UNPKG

@drincs/pixi-vn-ink

Version:

Pixi'VN gives you the ability to write your own narrative using Ink

46 lines 296 kB
'use strict';var pixiVn=require('@drincs/pixi-vn');var Fu=Object.create;var Po=Object.defineProperty;var Vu=Object.getOwnPropertyDescriptor;var Ru=Object.getOwnPropertyNames;var ku=Object.getPrototypeOf,Du=Object.prototype.hasOwnProperty;var p=(s,t)=>()=>(t||s((t={exports:{}}).exports,t),t.exports);var Wu=(s,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ru(t))!Du.call(s,i)&&i!==e&&Po(s,i,{get:()=>t[i],enumerable:!(n=Vu(t,i))||n.enumerable});return s};var Lu=(s,t,e)=>(e=s!=null?Fu(ku(s)):{},Wu(Po(e,"default",{value:s,enumerable:true}),s));var Kr=p(bn=>{Object.defineProperty(bn,"__esModule",{value:true});bn.CompilerOptions=void 0;var Hr=class{constructor(t=null,e=[],n=false,i=null,a=null){this.sourceFilename=t,this.pluginNames=e,this.countAllVisits=n,this.errorHandler=i,this.fileHandler=a;}};bn.CompilerOptions=Hr;});var wo=p(_n=>{Object.defineProperty(_n,"__esModule",{value:true});_n.DebugSourceRange=void 0;var zr=class{constructor(t,e,n){this.length=t,this.debugMetadata=e,this.text=n;}};_n.DebugSourceRange=zr;});var Pn=p(En=>{Object.defineProperty(En,"__esModule",{value:true});En.ErrorType=void 0;var xo;(function(s){s[s.Author=0]="Author",s[s.Warning=1]="Warning",s[s.Error=2]="Error";})(xo||(En.ErrorType=xo={}));});var To=p(wn=>{Object.defineProperty(wn,"__esModule",{value:true});wn.Argument=void 0;var Xr=class{constructor(t=null,e=null,n=null){this.identifier=t,this.isByReference=e,this.isDivertTarget=n;}get typeName(){return "Argument"}};wn.Argument=Xr;});var O=p(G=>{Object.defineProperty(G,"__esModule",{value:true});G.filterUndef=G.isEquatable=G.nullIfUndefined=G.asINamedContentOrNull=G.asBooleanOrThrows=G.asNumberOrThrows=G.asOrThrows=G.asOrNull=void 0;function qu(s,t){return s instanceof t?Oo(s):null}G.asOrNull=qu;function ju(s,t){if(s instanceof t)return Oo(s);throw new Error(`${s} is not of type ${t}`)}G.asOrThrows=ju;function Mu(s){if(typeof s=="number")return s;throw new Error(`${s} is not a number`)}G.asNumberOrThrows=Mu;function Bu(s){if(typeof s=="boolean")return s;throw new Error(`${s} is not a boolean`)}G.asBooleanOrThrows=Bu;function Gu(s){return s.hasValidName&&s.name?s:null}G.asINamedContentOrNull=Gu;function $u(s){return typeof s>"u"?null:s}G.nullIfUndefined=$u;function Ju(s){return typeof s=="object"&&typeof s.Equals=="function"}G.isEquatable=Ju;function Oo(s,t){return s}function Uu(s){return s!=null}G.filterUndef=Uu;});var R=p(xn=>{Object.defineProperty(xn,"__esModule",{value:true});xn.ParsedObject=void 0;var No=O(),Yr=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=t=>{this.content===null&&(this.content=[]);let e=Array.isArray(t)?t:[t];for(let n of e)n.hasOwnProperty("parent")&&(n.parent=this),this.content.push(n);if(!Array.isArray(t))return t},this.InsertContent=(t,e)=>(this.content===null&&(this.content=[]),e.parent=this,this.content.splice(t,0,e),e),this.Find=t=>(e=null)=>{let n=(0, No.asOrNull)(this,t);if(n!==null&&(e===null||e(n)===true))return n;if(this.content===null)return null;for(let i of this.content){let a=i.Find&&i.Find(t)(e);if(a)return a}return null},this.FindAll=t=>(e,n)=>{let i=Array.isArray(n)?n:[],a=(0, No.asOrNull)(this,t);if(a!==null&&(!e||e(a)===true)&&i.push(a),this.content===null)return [];for(let r of this.content)r.FindAll&&r.FindAll(t)(e,i);return i},this.Warning=(t,e=null)=>{this.Error(t,e,true);};}get debugMetadata(){return this._debugMetadata===null&&this.parent?this.parent.debugMetadata:this._debugMetadata}set debugMetadata(t){this._debugMetadata=t;}get hasOwnDebugMetadata(){return !!this.debugMetadata}get typeName(){return "ParsedObject"}get story(){let t=this;for(;t.parent;)t=t.parent;return t}get runtimeObject(){return this._runtimeObject||(this._runtimeObject=this.GenerateRuntimeObject(),this._runtimeObject&&(this._runtimeObject.debugMetadata=this.debugMetadata)),this._runtimeObject}set runtimeObject(t){this._runtimeObject=t;}get runtimePath(){if(!this.runtimeObject.path)throw new Error;return this.runtimeObject.path}get containerForCounting(){return this.runtimeObject}get ancestry(){let t=[],e=this.parent;for(;e;)t.push(e),e=e.parent;return t=t.reverse(),t}ResolveReferences(t){if(this.content!==null)for(let e of this.content)e.ResolveReferences(t);}Error(t,e=null,n=false){if(e===null&&(e=this),!(e._alreadyHadError&&!n||e._alreadyHadWarning&&n)){if(this.parent)this.parent.Error(t,e,n);else throw new Error(`No parent object to send error to: ${t}`);n?e._alreadyHadWarning=true:e._alreadyHadError=true;}}};xn.ParsedObject=Yr;});var On=p(Tn=>{Object.defineProperty(Tn,"__esModule",{value:true});Tn.AuthorWarning=void 0;var Hu=R(),Zr=class extends Hu.ParsedObject{constructor(t){super(),this.warningMessage=t,this.GenerateRuntimeObject=()=>(this.Warning(this.warningMessage),null);}get typeName(){return "AuthorWarning"}};Tn.AuthorWarning=Zr;});var it=p(Re=>{Object.defineProperty(Re,"__esModule",{value:true});Re.Path=void 0;var ae=class s{constructor(){if(this._components=[],this._componentsString=null,this._isRelative=false,typeof arguments[0]=="string"){let t=arguments[0];this.componentsString=t;}else if(arguments[0]instanceof s.Component&&arguments[1]instanceof s){let t=arguments[0],e=arguments[1];this._components.push(t),this._components=this._components.concat(e._components);}else if(arguments[0]instanceof Array){let t=arguments[0],e=!!arguments[1];this._components=this._components.concat(t),this._isRelative=e;}}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 t=this._components.slice(1,this._components.length);return new s(t)}else return s.self}get length(){return this._components.length}get lastComponent(){let t=this._components.length-1;return t>=0?this._components[t]:null}get containsNamedComponent(){for(let t=0,e=this._components.length;t<e;t++)if(!this._components[t].isIndex)return  true;return  false}static get self(){let t=new s;return t._isRelative=true,t}GetComponent(t){return this._components[t]}PathByAppendingPath(t){let e=new s,n=0;for(let i=0;i<t._components.length&&t._components[i].isParent;++i)n++;for(let i=0;i<this._components.length-n;++i)e._components.push(this._components[i]);for(let i=n;i<t._components.length;++i)e._components.push(t._components[i]);return e}get componentsString(){return this._componentsString==null&&(this._componentsString=this._components.join("."),this.isRelative&&(this._componentsString="."+this._componentsString)),this._componentsString}set componentsString(t){if(this._components.length=0,this._componentsString=t,this._componentsString==null||this._componentsString=="")return;this._componentsString[0]=="."&&(this._isRelative=true,this._componentsString=this._componentsString.substring(1));let e=this._componentsString.split(".");for(let n of e)/^(\-|\+)?([0-9]+|Infinity)$/.test(n)?this._components.push(new s.Component(parseInt(n))):this._components.push(new s.Component(n));}toString(){return this.componentsString}Equals(t){if(t==null||t._components.length!=this._components.length||t.isRelative!=this.isRelative)return  false;for(let e=0,n=t._components.length;e<n;e++)if(!t._components[e].Equals(this._components[e]))return  false;return  true}PathByAppendingComponent(t){let e=new s;return e._components.push(...this._components),e._components.push(t),e}};Re.Path=ae;ae.parentId="^";(function(s){class t{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==s.parentId}static ToParent(){return new t(s.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}}s.Component=t;})(ae||(Re.Path=ae={}));});var ke=p(Nn=>{Object.defineProperty(Nn,"__esModule",{value:true});Nn.Debug=void 0;var Ao;(function(s){function t(n,i,a){e(n instanceof i,a);}s.AssertType=t;function e(n,i){if(!n)throw typeof i<"u"&&console.warn(i),console.trace&&console.trace(),new Error("")}s.Assert=e;})(Ao||(Nn.Debug=Ao={}));});var K=p(oe=>{Object.defineProperty(oe,"__esModule",{value:true});oe.throwNullException=oe.NullException=void 0;var An=class extends Error{};oe.NullException=An;function Ku(s){throw new An(`${s} is null or undefined`)}oe.throwNullException=Ku;});var rt=p(Fn=>{Object.defineProperty(Fn,"__esModule",{value:true});Fn.InkObject=void 0;var le=it(),De=L(),Qr=ke(),ue=O(),In=K(),ts=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(t){this._debugMetadata=t;}get ownDebugMetadata(){return this._debugMetadata}DebugLineNumberOfPath(t){if(t===null)return null;let e=this.rootContentContainer;if(e){let n=e.ContentAtPath(t).obj;if(n){let i=n.debugMetadata;if(i!==null)return i.startLineNumber}}return null}get path(){if(this._path==null)if(this.parent==null)this._path=new le.Path;else {let t=[],e=this,n=(0, ue.asOrNull)(e.parent,De.Container);for(;n!==null;){let i=(0, ue.asINamedContentOrNull)(e);if(i!=null&&i.hasValidName){if(i.name===null)return (0, In.throwNullException)("namedChild.name");t.unshift(new le.Path.Component(i.name));}else t.unshift(new le.Path.Component(n.content.indexOf(e)));e=n,n=(0, ue.asOrNull)(n.parent,De.Container);}this._path=new le.Path(t);}return this._path}ResolvePath(t){if(t===null)return (0, In.throwNullException)("path");if(t.isRelative){let e=(0, ue.asOrNull)(this,De.Container);return e===null&&(Qr.Debug.Assert(this.parent!==null,"Can't resolve relative path because we don't have a parent"),e=(0, ue.asOrNull)(this.parent,De.Container),Qr.Debug.Assert(e!==null,"Expected parent to be a container"),Qr.Debug.Assert(t.GetComponent(0).isParent),t=t.tail),e===null?(0, In.throwNullException)("nearestContainer"):e.ContentAtPath(t)}else {let e=this.rootContentContainer;return e===null?(0, In.throwNullException)("contentContainer"):e.ContentAtPath(t)}}ConvertPathToRelative(t){let e=this.path,n=Math.min(t.length,e.length),i=-1;for(let l=0;l<n;++l){let u=e.GetComponent(l),h=t.GetComponent(l);if(u.Equals(h))i=l;else break}if(i==-1)return t;let a=e.componentCount-1-i,r=[];for(let l=0;l<a;++l)r.push(le.Path.Component.ToParent());for(let l=i+1;l<t.componentCount;++l)r.push(t.GetComponent(l));return new le.Path(r,true)}CompactPathString(t){let e=null,n=null;return t.isRelative?(n=t.componentsString,e=this.path.PathByAppendingPath(t).componentsString):(n=this.ConvertPathToRelative(t).componentsString,e=t.componentsString),n.length<e.length?n:e}get rootContentContainer(){let t=this;for(;t.parent;)t=t.parent;return (0, ue.asOrNull)(t,De.Container)}Copy(){throw Error("Not Implemented: Doesn't support copying")}SetChild(t,e,n){t[e]&&(t[e]=null),t[e]=n,t[e]&&(t[e].parent=this);}Equals(t){return t===this}};Fn.InkObject=ts;});var Kt=p(Vn=>{Object.defineProperty(Vn,"__esModule",{value:true});Vn.StringBuilder=void 0;var es=class{constructor(t){t=typeof t<"u"?t.toString():"",this.string=t;}get Length(){return this.string.length}Append(t){t!==null&&(this.string+=t);}AppendLine(t){typeof t<"u"&&this.Append(t),this.string+=`
`;}AppendFormat(t,...e){this.string+=t.replace(/{(\d+)}/g,(n,i)=>typeof e[i]<"u"?e[i]:n);}toString(){return this.string}Clear(){this.string="";}};Vn.StringBuilder=es;});var at=p(he=>{Object.defineProperty(he,"__esModule",{value:true});he.InkList=he.InkListItem=void 0;var St=K(),zu=Kt(),st=class s{constructor(){if(this.originName=null,this.itemName=null,typeof arguments[1]<"u"){let t=arguments[0],e=arguments[1];this.originName=t,this.itemName=e;}else if(arguments[0]){let e=arguments[0].toString().split(".");this.originName=e[0],this.itemName=e[1];}}static get Null(){return new s(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(t){if(t instanceof s){let e=t;return e.itemName==this.itemName&&e.originName==this.originName}return  false}copy(){return new s(this.originName,this.itemName)}serialized(){return JSON.stringify({originName:this.originName,itemName:this.itemName})}static fromSerializedKey(t){let e=JSON.parse(t);if(!s.isLikeInkListItem(e))return s.Null;let n=e;return new s(n.originName,n.itemName)}static isLikeInkListItem(t){return !(typeof t!="object"||!t.hasOwnProperty("originName")||!t.hasOwnProperty("itemName")||typeof t.originName!="string"&&typeof t.originName!==null||typeof t.itemName!="string"&&typeof t.itemName!==null)}};he.InkListItem=st;var ns=class s extends Map{constructor(){if(super(arguments[0]instanceof s?arguments[0]:[]),this.origins=null,this._originNames=[],arguments[0]instanceof s){let t=arguments[0],e=t.originNames;e!==null&&(this._originNames=e.slice()),t.origins!==null&&(this.origins=t.origins.slice());}else if(typeof arguments[0]=="string"){let t=arguments[0],e=arguments[1];if(this.SetInitialOriginName(t),e.listDefinitions===null)return (0, St.throwNullException)("originStory.listDefinitions");let n=e.listDefinitions.TryListGetDefinition(t,null);if(n.exists){if(n.result===null)return (0, St.throwNullException)("def.result");this.origins=[n.result];}else throw new Error("InkList origin could not be found in story when constructing new list: "+t)}else if(typeof arguments[0]=="object"&&arguments[0].hasOwnProperty("Key")&&arguments[0].hasOwnProperty("Value")){let t=arguments[0];this.Add(t.Key,t.Value);}}static FromString(t,e){var n;if(t==null||t=="")return new s;let i=(n=e.listDefinitions)===null||n===void 0?void 0:n.FindSingleItemListWithName(t);if(i)return i.value===null?(0, St.throwNullException)("listValue.value"):new s(i.value);throw new Error("Could not find the InkListItem from the string '"+t+"' to create an InkList because it doesn't exist in the original list definition in ink.")}AddItem(t,e=null){if(t instanceof st){let n=t;if(n.originName==null){this.AddItem(n.itemName);return}if(this.origins===null)return (0, St.throwNullException)("this.origins");for(let i of this.origins)if(i.name==n.originName){let a=i.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(t!==null){let n=t,i=null;if(this.origins===null)return (0, St.throwNullException)("this.origins");for(let a of this.origins){if(n===null)return (0, St.throwNullException)("itemName");if(a.ContainsItemWithName(n)){if(i!=null)throw new Error("Could not add the item "+n+" to this list because it could come from either "+a.name+" or "+i.name);i=a;}}if(i==null){if(e==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=s.FromString(n,e).orderedItems[0];this.Add(a.Key,a.Value);}}else {let a=new st(i.name,n),r=i.ValueForItem(a);this.Add(a,r);}}}ContainsItemNamed(t){for(let[e]of this)if(st.fromSerializedKey(e).itemName==t)return  true;return  false}ContainsKey(t){return this.has(t.serialized())}Add(t,e){let n=t.serialized();if(this.has(n))throw new Error(`The Map already contains an entry for ${t}`);this.set(n,e);}Remove(t){return this.delete(t.serialized())}get Count(){return this.size}get originOfMaxItem(){if(this.origins==null)return null;let t=this.maxItem.Key.originName,e=null;return this.origins.every(n=>n.name==t?(e=n,false):true),e}get originNames(){if(this.Count>0){this._originNames==null&&this.Count>0?this._originNames=[]:(this._originNames||(this._originNames=[]),this._originNames.length=0);for(let[t]of this){let e=st.fromSerializedKey(t);if(e.originName===null)return (0, St.throwNullException)("item.originName");this._originNames.push(e.originName);}}return this._originNames}SetInitialOriginName(t){this._originNames=[t];}SetInitialOriginNames(t){t==null?this._originNames=null:this._originNames=t.slice();}get maxItem(){let t={Key:st.Null,Value:0};for(let[e,n]of this){let i=st.fromSerializedKey(e);(t.Key.isNull||n>t.Value)&&(t={Key:i,Value:n});}return t}get minItem(){let t={Key:st.Null,Value:0};for(let[e,n]of this){let i=st.fromSerializedKey(e);(t.Key.isNull||n<t.Value)&&(t={Key:i,Value:n});}return t}get inverse(){let t=new s;if(this.origins!=null)for(let e of this.origins)for(let[n,i]of e.items){let a=st.fromSerializedKey(n);this.ContainsKey(a)||t.Add(a,i);}return t}get all(){let t=new s;if(this.origins!=null)for(let e of this.origins)for(let[n,i]of e.items){let a=st.fromSerializedKey(n);t.set(a.serialized(),i);}return t}Union(t){let e=new s(this);for(let[n,i]of t)e.set(n,i);return e}Intersect(t){let e=new s;for(let[n,i]of this)t.has(n)&&e.set(n,i);return e}HasIntersection(t){for(let[e]of this)if(t.has(e))return  true;return  false}Without(t){let e=new s(this);for(let[n]of t)e.delete(n);return e}Contains(t){if(typeof t=="string")return this.ContainsItemNamed(t);let e=t;if(e.size==0||this.size==0)return  false;for(let[n]of e)if(!this.has(n))return  false;return  true}GreaterThan(t){return this.Count==0?false:t.Count==0?true:this.minItem.Value>t.maxItem.Value}GreaterThanOrEquals(t){return this.Count==0?false:t.Count==0?true:this.minItem.Value>=t.minItem.Value&&this.maxItem.Value>=t.maxItem.Value}LessThan(t){return t.Count==0?false:this.Count==0?true:this.maxItem.Value<t.minItem.Value}LessThanOrEquals(t){return t.Count==0?false:this.Count==0?true:this.maxItem.Value<=t.maxItem.Value&&this.minItem.Value<=t.minItem.Value}MaxAsList(){return this.Count>0?new s(this.maxItem):new s}MinAsList(){return this.Count>0?new s(this.minItem):new s}ListWithSubRange(t,e){if(this.Count==0)return new s;let n=this.orderedItems,i=0,a=Number.MAX_SAFE_INTEGER;Number.isInteger(t)?i=t:t instanceof s&&t.Count>0&&(i=t.minItem.Value),Number.isInteger(e)?a=e:e instanceof s&&e.Count>0&&(a=e.maxItem.Value);let r=new s;r.SetInitialOriginNames(this.originNames);for(let o of n)o.Value>=i&&o.Value<=a&&r.Add(o.Key,o.Value);return r}Equals(t){if(!(t instanceof s)||t.Count!=this.Count)return  false;for(let[e]of this)if(!t.has(e))return  false;return  true}get orderedItems(){let t=new Array;for(let[e,n]of this){let i=st.fromSerializedKey(e);t.push({Key:i,Value:n});}return t.sort((e,n)=>e.Key.originName===null?(0, St.throwNullException)("x.Key.originName"):n.Key.originName===null?(0, St.throwNullException)("y.Key.originName"):e.Value==n.Value?e.Key.originName.localeCompare(n.Key.originName):e.Value<n.Value?-1:e.Value>n.Value?1:0),t}get singleItem(){for(let t of this.orderedItems)return t.Key;return null}toString(){let t=this.orderedItems,e=new zu.StringBuilder;for(let n=0;n<t.length;n++){n>0&&e.Append(", ");let i=t[n].Key;if(i.itemName===null)return (0, St.throwNullException)("item.itemName");e.Append(i.itemName);}return e.toString()}valueOf(){return NaN}};he.InkList=ns;});var We=p(Rn=>{Object.defineProperty(Rn,"__esModule",{value:true});Rn.StoryException=void 0;var is=class extends Error{constructor(t){super(t),this.useEndLineNumber=false,this.message=t,this.name="StoryException";}};Rn.StoryException=is;});var ce=p(Dt=>{Object.defineProperty(Dt,"__esModule",{value:true});Dt.tryParseFloat=Dt.tryParseInt=Dt.tryGetValueFromMap=void 0;function Xu(s,t,e){if(s===null)return {result:e,exists:false};let n=s.get(t);return typeof n>"u"?{result:e,exists:false}:{result:n,exists:true}}Dt.tryGetValueFromMap=Xu;function Yu(s,t=0){let e=parseInt(s);return Number.isNaN(e)?{result:t,exists:false}:{result:e,exists:true}}Dt.tryParseInt=Yu;function Zu(s,t=0){let e=parseFloat(s);return Number.isNaN(e)?{result:t,exists:false}:{result:e,exists:true}}Dt.tryParseFloat=Zu;});var k=p(W=>{Object.defineProperty(W,"__esModule",{value:true});W.ValueType=W.ListValue=W.VariablePointerValue=W.DivertTargetValue=W.StringValue=W.FloatValue=W.IntValue=W.BoolValue=W.Value=W.AbstractValue=void 0;var Io=rt(),Fo=it(),zt=at(),Qu=We(),Le=O(),Vo=ce(),ht=K(),kn=class s extends Io.InkObject{static Create(t,e){if(e){if(e===V.Int&&Number.isInteger(Number(t)))return new bt(Number(t));if(e===V.Float&&!isNaN(t))return new _t(Number(t))}if(typeof t=="boolean")return new de(!!t);if(typeof t=="string")return new It(String(t));if(Number.isInteger(Number(t)))return new bt(Number(t));if(isNaN(t)){if(t instanceof Fo.Path)return new Dn((0, Le.asOrThrows)(t,Fo.Path));if(t instanceof zt.InkList)return new Wn((0, Le.asOrThrows)(t,zt.InkList))}else return new _t(Number(t));return null}Copy(){return (0, Le.asOrThrows)(s.Create(this.valueObject),Io.InkObject)}BadCastException(t){return new Qu.StoryException("Can't cast "+this.valueObject+" from "+this.valueType+" to "+t)}};W.AbstractValue=kn;var yt=class extends kn{constructor(t){super(),this.value=t;}get valueObject(){return this.value}toString(){return this.value===null?(0, ht.throwNullException)("Value.value"):this.value.toString()}};W.Value=yt;var de=class extends yt{constructor(t){super(t||false);}get isTruthy(){return !!this.value}get valueType(){return V.Bool}Cast(t){if(this.value===null)return (0, ht.throwNullException)("Value.value");if(t==this.valueType)return this;if(t==V.Int)return new bt(this.value?1:0);if(t==V.Float)return new _t(this.value?1:0);if(t==V.String)return new It(this.value?"true":"false");throw this.BadCastException(t)}toString(){return this.value?"true":"false"}};W.BoolValue=de;var bt=class extends yt{constructor(t){super(t||0);}get isTruthy(){return this.value!=0}get valueType(){return V.Int}Cast(t){if(this.value===null)return (0, ht.throwNullException)("Value.value");if(t==this.valueType)return this;if(t==V.Bool)return new de(this.value!==0);if(t==V.Float)return new _t(this.value);if(t==V.String)return new It(""+this.value);throw this.BadCastException(t)}};W.IntValue=bt;var _t=class extends yt{constructor(t){super(t||0);}get isTruthy(){return this.value!=0}get valueType(){return V.Float}Cast(t){if(this.value===null)return (0, ht.throwNullException)("Value.value");if(t==this.valueType)return this;if(t==V.Bool)return new de(this.value!==0);if(t==V.Int)return new bt(this.value);if(t==V.String)return new It(""+this.value);throw this.BadCastException(t)}};W.FloatValue=_t;var It=class extends yt{constructor(t){if(super(t||""),this._isNewline=this.value==`
`,this._isInlineWhitespace=true,this.value===null)return (0, ht.throwNullException)("Value.value");this.value.length>0&&this.value.split("").every(e=>e!=" "&&e!="	"?(this._isInlineWhitespace=false,false):true);}get valueType(){return V.String}get isTruthy(){return this.value===null?(0, ht.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(t){if(t==this.valueType)return this;if(t==V.Int){let e=(0, Vo.tryParseInt)(this.value);if(e.exists)return new bt(e.result);throw this.BadCastException(t)}if(t==V.Float){let e=(0, Vo.tryParseFloat)(this.value);if(e.exists)return new _t(e.result);throw this.BadCastException(t)}throw this.BadCastException(t)}};W.StringValue=It;var Dn=class extends yt{constructor(t=null){super(t);}get valueType(){return V.DivertTarget}get targetPath(){return this.value===null?(0, ht.throwNullException)("Value.value"):this.value}set targetPath(t){this.value=t;}get isTruthy(){throw new Error("Shouldn't be checking the truthiness of a divert target")}Cast(t){if(t==this.valueType)return this;throw this.BadCastException(t)}toString(){return "DivertTargetValue("+this.targetPath+")"}};W.DivertTargetValue=Dn;var rs=class s extends yt{constructor(t,e=-1){super(t),this._contextIndex=e;}get contextIndex(){return this._contextIndex}set contextIndex(t){this._contextIndex=t;}get variableName(){return this.value===null?(0, ht.throwNullException)("Value.value"):this.value}set variableName(t){this.value=t;}get valueType(){return V.VariablePointer}get isTruthy(){throw new Error("Shouldn't be checking the truthiness of a variable pointer")}Cast(t){if(t==this.valueType)return this;throw this.BadCastException(t)}toString(){return "VariablePointerValue("+this.variableName+")"}Copy(){return new s(this.variableName,this.contextIndex)}};W.VariablePointerValue=rs;var Wn=class s extends yt{get isTruthy(){return this.value===null?(0, ht.throwNullException)("this.value"):this.value.Count>0}get valueType(){return V.List}Cast(t){if(this.value===null)return (0, ht.throwNullException)("Value.value");if(t==V.Int){let e=this.value.maxItem;return e.Key.isNull?new bt(0):new bt(e.Value)}else if(t==V.Float){let e=this.value.maxItem;return e.Key.isNull?new _t(0):new _t(e.Value)}else if(t==V.String){let e=this.value.maxItem;return e.Key.isNull?new It(""):new It(e.Key.toString())}if(t==this.valueType)return this;throw this.BadCastException(t)}constructor(t,e){super(null),!t&&!e?this.value=new zt.InkList:t instanceof zt.InkList?this.value=new zt.InkList(t):t instanceof zt.InkListItem&&typeof e=="number"&&(this.value=new zt.InkList({Key:t,Value:e}));}static RetainListOriginsForAssignment(t,e){let n=(0, Le.asOrNull)(t,s),i=(0, Le.asOrNull)(e,s);if(i&&i.value===null)return (0, ht.throwNullException)("newList.value");if(n&&n.value===null)return (0, ht.throwNullException)("oldList.value");n&&i&&i.value.Count==0&&i.value.SetInitialOriginNames(n.value.originNames);}};W.ListValue=Wn;var V;(function(s){s[s.Bool=-1]="Bool",s[s.Int=0]="Int",s[s.Float=1]="Float",s[s.List=2]="List",s[s.String=3]="String",s[s.DivertTarget=4]="DivertTarget",s[s.VariablePointer=5]="VariablePointer";})(V||(W.ValueType=V={}));});var Ro=p(Ln=>{Object.defineProperty(Ln,"__esModule",{value:true});Ln.SearchResult=void 0;var th=L(),ss=class s{constructor(){this.obj=null,this.approximate=false;}get correctObj(){return this.approximate?null:this.obj}get container(){return this.obj instanceof th.Container?this.obj:null}copy(){let t=new s;return t.obj=this.obj,t.approximate=this.approximate,t}};Ln.SearchResult=ss;});var L=p(je=>{Object.defineProperty(je,"__esModule",{value:true});je.Container=void 0;var eh=k(),ko=K(),nh=Kt(),fe=rt(),ih=Ro(),Do=it(),Wo=ke(),rh=ce(),Wt=O(),qe=class s extends fe.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(t){this.AddContent(t);}get namedOnlyContent(){let t=new Map;for(let[e,n]of this.namedContent){let i=(0, Wt.asOrThrows)(n,fe.InkObject);t.set(e,i);}for(let e of this.content){let n=(0, Wt.asINamedContentOrNull)(e);n!=null&&n.hasValidName&&t.delete(n.name);}return t.size==0&&(t=null),t}set namedOnlyContent(t){let e=this.namedOnlyContent;if(e!=null)for(let[n]of e)this.namedContent.delete(n);if(t!=null)for(let[,n]of t){let i=(0, Wt.asINamedContentOrNull)(n);i!=null&&this.AddToNamedContentOnly(i);}}get countFlags(){let t=0;return this.visitsShouldBeCounted&&(t|=s.CountFlags.Visits),this.turnIndexShouldBeCounted&&(t|=s.CountFlags.Turns),this.countingAtStartOnly&&(t|=s.CountFlags.CountStartOnly),t==s.CountFlags.CountStartOnly&&(t=0),t}set countFlags(t){let e=t;(e&s.CountFlags.Visits)>0&&(this.visitsShouldBeCounted=true),(e&s.CountFlags.Turns)>0&&(this.turnIndexShouldBeCounted=true),(e&s.CountFlags.CountStartOnly)>0&&(this.countingAtStartOnly=true);}get pathToFirstLeafContent(){return this._pathToFirstLeafContent==null&&(this._pathToFirstLeafContent=this.path.PathByAppendingPath(this.internalPathToFirstLeafContent)),this._pathToFirstLeafContent}get internalPathToFirstLeafContent(){let t=[],e=this;for(;e instanceof s;)e.content.length>0&&(t.push(new Do.Path.Component(0)),e=e.content[0]);return new Do.Path(t)}AddContent(t){if(t instanceof Array){let e=t;for(let n of e)this.AddContent(n);}else {let e=t;if(this._content.push(e),e.parent)throw new Error("content is already in "+e.parent);e.parent=this,this.TryAddNamedContent(e);}}TryAddNamedContent(t){let e=(0, Wt.asINamedContentOrNull)(t);e!=null&&e.hasValidName&&this.AddToNamedContentOnly(e);}AddToNamedContentOnly(t){Wo.Debug.AssertType(t,fe.InkObject,"Can only add Runtime.Objects to a Runtime.Container");let e=(0, Wt.asOrThrows)(t,fe.InkObject);if(e.parent=this,t.name===null)return (0, ko.throwNullException)("namedContentObj.name");this.namedContent.set(t.name,t);}ContentAtPath(t,e=0,n=-1){n==-1&&(n=t.length);let i=new ih.SearchResult;i.approximate=false;let a=this,r=this;for(let o=e;o<n;++o){let l=t.GetComponent(o);if(a==null){i.approximate=true;break}let u=a.ContentWithPathComponent(l);if(u==null){i.approximate=true;break}let h=(0, Wt.asOrNull)(u,s);if(o<n-1&&h==null){i.approximate=true;break}r=u,a=h;}return i.obj=r,i}InsertContent(t,e){if(this.content.splice(e,0,t),t.parent)throw new Error("content is already in "+t.parent);t.parent=this,this.TryAddNamedContent(t);}AddContentsOfContainer(t){this.content.push(...t.content);for(let e of t.content)e.parent=this,this.TryAddNamedContent(e);}ContentWithPathComponent(t){if(t.isIndex)return t.index>=0&&t.index<this.content.length?this.content[t.index]:null;if(t.isParent)return this.parent;{if(t.name===null)return (0, ko.throwNullException)("component.name");let e=(0, rh.tryGetValueFromMap)(this.namedContent,t.name,null);return e.exists?(0, Wt.asOrThrows)(e.result,fe.InkObject):null}}BuildStringOfHierarchy(){let t;if(arguments.length==0)return t=new nh.StringBuilder,this.BuildStringOfHierarchy(t,0,null),t.toString();t=arguments[0];let e=arguments[1],n=arguments[2];function i(){for(let o=0;o<4*e;++o)t.Append(" ");}i(),t.Append("["),this.hasValidName&&t.AppendFormat(" ({0})",this.name),this==n&&t.Append("  <---"),t.AppendLine(),e++;for(let r=0;r<this.content.length;++r){let o=this.content[r];o instanceof s?o.BuildStringOfHierarchy(t,e,n):(i(),o instanceof eh.StringValue?(t.Append('"'),t.Append(o.toString().replace(`
`,"\\n")),t.Append('"')):t.Append(o.toString())),r!=this.content.length-1&&t.Append(","),!(o instanceof s)&&o==n&&t.Append("  <---"),t.AppendLine();}let a=new Map;for(let[r,o]of this.namedContent)this.content.indexOf((0, Wt.asOrThrows)(o,fe.InkObject))>=0||a.set(r,o);if(a.size>0){i(),t.AppendLine("-- named: --");for(let[,r]of a)Wo.Debug.AssertType(r,s,"Can only print out named Containers"),r.BuildStringOfHierarchy(t,e,n),t.AppendLine();}e--,i(),t.Append("]");}};je.Container=qe;(function(s){(function(e){e[e.Start=0]="Start",e[e.Visits=1]="Visits",e[e.Turns=2]="Turns",e[e.CountStartOnly=4]="CountStartOnly";})(s.CountFlags||(s.CountFlags={}));})(qe||(je.Container=qe={}));});var z=p(Be=>{Object.defineProperty(Be,"__esModule",{value:true});Be.ControlCommand=void 0;var sh=rt(),Me=class s extends sh.InkObject{get commandType(){return this._commandType}constructor(t=s.CommandType.NotSet){super(),this._commandType=t;}Copy(){return new s(this.commandType)}static EvalStart(){return new s(s.CommandType.EvalStart)}static EvalOutput(){return new s(s.CommandType.EvalOutput)}static EvalEnd(){return new s(s.CommandType.EvalEnd)}static Duplicate(){return new s(s.CommandType.Duplicate)}static PopEvaluatedValue(){return new s(s.CommandType.PopEvaluatedValue)}static PopFunction(){return new s(s.CommandType.PopFunction)}static PopTunnel(){return new s(s.CommandType.PopTunnel)}static BeginString(){return new s(s.CommandType.BeginString)}static EndString(){return new s(s.CommandType.EndString)}static NoOp(){return new s(s.CommandType.NoOp)}static ChoiceCount(){return new s(s.CommandType.ChoiceCount)}static Turns(){return new s(s.CommandType.Turns)}static TurnsSince(){return new s(s.CommandType.TurnsSince)}static ReadCount(){return new s(s.CommandType.ReadCount)}static Random(){return new s(s.CommandType.Random)}static SeedRandom(){return new s(s.CommandType.SeedRandom)}static VisitIndex(){return new s(s.CommandType.VisitIndex)}static SequenceShuffleIndex(){return new s(s.CommandType.SequenceShuffleIndex)}static StartThread(){return new s(s.CommandType.StartThread)}static Done(){return new s(s.CommandType.Done)}static End(){return new s(s.CommandType.End)}static ListFromInt(){return new s(s.CommandType.ListFromInt)}static ListRange(){return new s(s.CommandType.ListRange)}static ListRandom(){return new s(s.CommandType.ListRandom)}static BeginTag(){return new s(s.CommandType.BeginTag)}static EndTag(){return new s(s.CommandType.EndTag)}toString(){return "ControlCommand "+this.commandType.toString()}};Be.ControlCommand=Me;(function(s){(function(e){e[e.NotSet=-1]="NotSet",e[e.EvalStart=0]="EvalStart",e[e.EvalOutput=1]="EvalOutput",e[e.EvalEnd=2]="EvalEnd",e[e.Duplicate=3]="Duplicate",e[e.PopEvaluatedValue=4]="PopEvaluatedValue",e[e.PopFunction=5]="PopFunction",e[e.PopTunnel=6]="PopTunnel",e[e.BeginString=7]="BeginString",e[e.EndString=8]="EndString",e[e.NoOp=9]="NoOp",e[e.ChoiceCount=10]="ChoiceCount",e[e.Turns=11]="Turns",e[e.TurnsSince=12]="TurnsSince",e[e.ReadCount=13]="ReadCount",e[e.Random=14]="Random",e[e.SeedRandom=15]="SeedRandom",e[e.VisitIndex=16]="VisitIndex",e[e.SequenceShuffleIndex=17]="SequenceShuffleIndex",e[e.StartThread=18]="StartThread",e[e.Done=19]="Done",e[e.End=20]="End",e[e.ListFromInt=21]="ListFromInt",e[e.ListRange=22]="ListRange",e[e.ListRandom=23]="ListRandom",e[e.BeginTag=24]="BeginTag",e[e.EndTag=25]="EndTag",e[e.TOTAL_VALUES=26]="TOTAL_VALUES";})(s.CommandType||(s.CommandType={}));})(Me||(Be.ControlCommand=Me={}));});var ct=p(qn=>{Object.defineProperty(qn,"__esModule",{value:true});qn.Expression=void 0;var Lo=L(),as=z(),ah=R(),os=class extends ah.ParsedObject{constructor(){super(...arguments),this._prototypeRuntimeConstantExpression=null,this.outputWhenComplete=false,this.GenerateRuntimeObject=()=>{let t=new Lo.Container;return t.AddContent(as.ControlCommand.EvalStart()),this.GenerateIntoContainer(t),this.outputWhenComplete&&t.AddContent(as.ControlCommand.EvalOutput()),t.AddContent(as.ControlCommand.EvalEnd()),t},this.GenerateConstantIntoContainer=t=>{this._prototypeRuntimeConstantExpression===null&&(this._prototypeRuntimeConstantExpression=new Lo.Container,this.GenerateIntoContainer(this._prototypeRuntimeConstantExpression));for(let e of this._prototypeRuntimeConstantExpression.content){let n=e.Copy();n&&t.AddContent(n);}},this.toString=()=>"No string value in JavaScript.";}get typeName(){return "Expression"}Equals(t){return  false}};qn.Expression=os;});var Xt=p(jn=>{Object.defineProperty(jn,"__esModule",{value:true});jn.Void=void 0;var oh=rt(),ls=class extends oh.InkObject{toString(){return "Void"}};jn.Void=ls;});var Et=p(Bn=>{Object.defineProperty(Bn,"__esModule",{value:true});Bn.NativeFunctionCall=void 0;var v=k(),Ge=We(),lh=Xt(),Mn=at(),uh=rt(),dt=O(),ot=K(),w=class s extends uh.InkObject{static CallWithName(t){return new s(t)}static CallExistsWithName(t){return this.GenerateNativeFunctionsIfNecessary(),this._nativeFunctions.get(t)}get name(){return this._name===null?(0, ot.throwNullException)("NativeFunctionCall._name"):this._name}set name(t){this._name=t,this._isPrototype||(s._nativeFunctions===null?(0, ot.throwNullException)("NativeFunctionCall._nativeFunctions"):this._prototype=s._nativeFunctions.get(this._name)||null);}get numberOfParameters(){return this._prototype?this._prototype.numberOfParameters:this._numberOfParameters}set numberOfParameters(t){this._numberOfParameters=t;}Call(t){if(this._prototype)return this._prototype.Call(t);if(this.numberOfParameters!=t.length)throw new Error("Unexpected number of parameters");let e=false;for(let a of t){if(a instanceof lh.Void)throw new Ge.StoryException("Attempting to perform "+this.name+' on a void value. Did you forget to "return" a value from a function you called here?');a instanceof v.ListValue&&(e=true);}if(t.length==2&&e)return this.CallBinaryListOperation(t);let n=this.CoerceValuesToSingleType(t),i=n[0].valueType;return i==v.ValueType.Int?this.CallType(n):i==v.ValueType.Float?this.CallType(n):i==v.ValueType.String?this.CallType(n):i==v.ValueType.DivertTarget?this.CallType(n):i==v.ValueType.List?this.CallType(n):null}CallType(t){let e=(0, dt.asOrThrows)(t[0],v.Value),n=e.valueType,i=e,a=t.length;if(a==2||a==1){if(this._operationFuncs===null)return (0, ot.throwNullException)("NativeFunctionCall._operationFuncs");let r=this._operationFuncs.get(n);if(!r){let o=v.ValueType[n];throw new Ge.StoryException("Cannot perform operation "+this.name+" on "+o)}if(a==2){let l=(0, dt.asOrThrows)(t[1],v.Value),u=r;if(i.value===null||l.value===null)return (0, ot.throwNullException)("NativeFunctionCall.Call BinaryOp values");let h=u(i.value,l.value);return v.Value.Create(h)}else {let o=r;if(i.value===null)return (0, ot.throwNullException)("NativeFunctionCall.Call UnaryOp value");let l=o(i.value);return this.name===s.Int?v.Value.Create(l,v.ValueType.Int):this.name===s.Float?v.Value.Create(l,v.ValueType.Float):v.Value.Create(l,e.valueType)}}else throw new Error("Unexpected number of parameters to NativeFunctionCall: "+t.length)}CallBinaryListOperation(t){if((this.name=="+"||this.name=="-")&&t[0]instanceof v.ListValue&&t[1]instanceof v.IntValue)return this.CallListIncrementOperation(t);let e=(0, dt.asOrThrows)(t[0],v.Value),n=(0, dt.asOrThrows)(t[1],v.Value);if((this.name=="&&"||this.name=="||")&&(e.valueType!=v.ValueType.List||n.valueType!=v.ValueType.List)){if(this._operationFuncs===null)return (0, ot.throwNullException)("NativeFunctionCall._operationFuncs");let i=this._operationFuncs.get(v.ValueType.Int);if(i===null)return (0, ot.throwNullException)("NativeFunctionCall.CallBinaryListOperation op");let a=(0, dt.asBooleanOrThrows)(i(e.isTruthy?1:0,n.isTruthy?1:0));return new v.BoolValue(a)}if(e.valueType==v.ValueType.List&&n.valueType==v.ValueType.List)return this.CallType([e,n]);throw new Ge.StoryException("Can not call use "+this.name+" operation on "+v.ValueType[e.valueType]+" and "+v.ValueType[n.valueType])}CallListIncrementOperation(t){let e=(0, dt.asOrThrows)(t[0],v.ListValue),n=(0, dt.asOrThrows)(t[1],v.IntValue),i=new Mn.InkList;if(e.value===null)return (0, ot.throwNullException)("NativeFunctionCall.CallListIncrementOperation listVal.value");for(let[a,r]of e.value){let o=Mn.InkListItem.fromSerializedKey(a);if(this._operationFuncs===null)return (0, ot.throwNullException)("NativeFunctionCall._operationFuncs");let l=this._operationFuncs.get(v.ValueType.Int);if(n.value===null)return (0, ot.throwNullException)("NativeFunctionCall.CallListIncrementOperation intVal.value");let u=l(r,n.value),h=null;if(e.value.origins===null)return (0, ot.throwNullException)("NativeFunctionCall.CallListIncrementOperation listVal.value.origins");for(let c of e.value.origins)if(c.name==o.originName){h=c;break}if(h!=null){let c=h.TryGetItemWithValue(u,Mn.InkListItem.Null);c.exists&&i.Add(c.result,u);}}return new v.ListValue(i)}CoerceValuesToSingleType(t){let e=v.ValueType.Int,n=null;for(let a of t){let r=(0, dt.asOrThrows)(a,v.Value);r.valueType>e&&(e=r.valueType),r.valueType==v.ValueType.List&&(n=(0, dt.asOrNull)(r,v.ListValue));}let i=[];if(v.ValueType[e]==v.ValueType[v.ValueType.List])for(let a of t){let r=(0, dt.asOrThrows)(a,v.Value);if(r.valueType==v.ValueType.List)i.push(r);else if(r.valueType==v.ValueType.Int){let o=parseInt(r.valueObject);if(n=(0, dt.asOrThrows)(n,v.ListValue),n.value===null)return (0, ot.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType specialCaseList.value");let l=n.value.originOfMaxItem;if(l===null)return (0, ot.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType list");let u=l.TryGetItemWithValue(o,Mn.InkListItem.Null);if(u.exists){let h=new v.ListValue(u.result,o);i.push(h);}else throw new Ge.StoryException("Could not find List item with the value "+o+" in "+l.name)}else {let o=v.ValueType[r.valueType];throw new Ge.StoryException("Cannot mix Lists and "+o+" values in this operation")}}else for(let a of t){let o=(0, dt.asOrThrows)(a,v.Value).Cast(e);i.push(o);}return i}constructor(){if(super(),this._name=null,this._numberOfParameters=0,this._prototype=null,this._isPrototype=false,this._operationFuncs=null,arguments.length===0)s.GenerateNativeFunctionsIfNecessary();else if(arguments.length===1){let t=arguments[0];s.GenerateNativeFunctionsIfNecessary(),this.name=t;}else if(arguments.length===2){let t=arguments[0],e=arguments[1];this._isPrototype=true,this.name=t,this.numberOfParameters=e;}}static Identity(t){return t}static GenerateNativeFunctionsIfNecessary(){if(this._nativeFunctions==null){this._nativeFunctions=new Map,this.AddIntBinaryOp(this.Add,(n,i)=>n+i),this.AddIntBinaryOp(this.Subtract,(n,i)=>n-i),this.AddIntBinaryOp(this.Multiply,(n,i)=>n*i),this.AddIntBinaryOp(this.Divide,(n,i)=>Math.floor(n/i)),this.AddIntBinaryOp(this.Mod,(n,i)=>n%i),this.AddIntUnaryOp(this.Negate,n=>-n),this.AddIntBinaryOp(this.Equal,(n,i)=>n==i),this.AddIntBinaryOp(this.Greater,(n,i)=>n>i),this.AddIntBinaryOp(this.Less,(n,i)=>n<i),this.AddIntBinaryOp(this.GreaterThanOrEquals,(n,i)=>n>=i),this.AddIntBinaryOp(this.LessThanOrEquals,(n,i)=>n<=i),this.AddIntBinaryOp(this.NotEquals,(n,i)=>n!=i),this.AddIntUnaryOp(this.Not,n=>n==0),this.AddIntBinaryOp(this.And,(n,i)=>n!=0&&i!=0),this.AddIntBinaryOp(this.Or,(n,i)=>n!=0||i!=0),this.AddIntBinaryOp(this.Max,(n,i)=>Math.max(n,i)),this.AddIntBinaryOp(this.Min,(n,i)=>Math.min(n,i)),this.AddIntBinaryOp(this.Pow,(n,i)=>Math.pow(n,i)),this.AddIntUnaryOp(this.Floor,s.Identity),this.AddIntUnaryOp(this.Ceiling,s.Identity),this.AddIntUnaryOp(this.Int,s.Identity),this.AddIntUnaryOp(this.Float,n=>n),this.AddFloatBinaryOp(this.Add,(n,i)=>n+i),this.AddFloatBinaryOp(this.Subtract,(n,i)=>n-i),this.AddFloatBinaryOp(this.Multiply,(n,i)=>n*i),this.AddFloatBinaryOp(this.Divide,(n,i)=>n/i),this.AddFloatBinaryOp(this.Mod,(n,i)=>n%i),this.AddFloatUnaryOp(this.Negate,n=>-n),this.AddFloatBinaryOp(this.Equal,(n,i)=>n==i),this.AddFloatBinaryOp(this.Greater,(n,i)=>n>i),this.AddFloatBinaryOp(this.Less,(n,i)=>n<i),this.AddFloatBinaryOp(this.GreaterThanOrEquals,(n,i)=>n>=i),this.AddFloatBinaryOp(this.LessThanOrEquals,(n,i)=>n<=i),this.AddFloatBinaryOp(this.NotEquals,(n,i)=>n!=i),this.AddFloatUnaryOp(this.Not,n=>n==0),this.AddFloatBinaryOp(this.And,(n,i)=>n!=0&&i!=0),this.AddFloatBinaryOp(this.Or,(n,i)=>n!=0||i!=0),this.AddFloatBinaryOp(this.Max,(n,i)=>Math.max(n,i)),this.AddFloatBinaryOp(this.Min,(n,i)=>Math.min(n,i)),this.AddFloatBinaryOp(this.Pow,(n,i)=>Math.pow(n,i)),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,s.Identity),this.AddStringBinaryOp(this.Add,(n,i)=>n+i),this.AddStringBinaryOp(this.Equal,(n,i)=>n===i),this.AddStringBinaryOp(this.NotEquals,(n,i)=>n!==i),this.AddStringBinaryOp(this.Has,(n,i)=>n.includes(i)),this.AddStringBinaryOp(this.Hasnt,(n,i)=>!n.includes(i)),this.AddListBinaryOp(this.Add,(n,i)=>n.Union(i)),this.AddListBinaryOp(this.Subtract,(n,i)=>n.Without(i)),this.AddListBinaryOp(this.Has,(n,i)=>n.Contains(i)),this.AddListBinaryOp(this.Hasnt,(n,i)=>!n.Contains(i)),this.AddListBinaryOp(this.Intersect,(n,i)=>n.Intersect(i)),this.AddListBinaryOp(this.Equal,(n,i)=>n.Equals(i)),this.AddListBinaryOp(this.Greater,(n,i)=>n.GreaterThan(i)),this.AddListBinaryOp(this.Less,(n,i)=>n.LessThan(i)),this.AddListBinaryOp(this.GreaterThanOrEquals,(n,i)=>n.GreaterThanOrEquals(i)),this.AddListBinaryOp(this.LessThanOrEquals,(n,i)=>n.LessThanOrEquals(i)),this.AddListBinaryOp(this.NotEquals,(n,i)=>!n.Equals(i)),this.AddListBinaryOp(this.And,(n,i)=>n.Count>0&&i.Count>0),this.AddListBinaryOp(this.Or,(n,i)=>n.Count>0||i.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 t=(n,i)=>n.Equals(i),e=(n,i)=>!n.Equals(i);this.AddOpToNativeFunc(this.Equal,2,v.ValueType.DivertTarget,t),this.AddOpToNativeFunc(this.NotEquals,2,v.ValueType.DivertTarget,e);}}AddOpFuncForType(t,e){this._operationFuncs==null&&(this._operationFuncs=new Map),this._operationFuncs.set(t,e);}static AddOpToNativeFunc(t,e,n,i){if(this._nativeFunctions===null)return (0, ot.throwNullException)("NativeFunctionCall._nativeFunctions");let a=this._nativeFunctions.get(t);a||(a=new s(t,e),this._nativeFunctions.set(t,a)),a.AddOpFuncForType(n,i);}static AddIntBinaryOp(t,e){this.AddOpToNativeFunc(t,2,v.ValueType.Int,e);}static AddIntUnaryOp(t,e){this.AddOpToNativeFunc(t,1,v.ValueType.Int,e);}static AddFloatBinaryOp(t,e){this.AddOpToNativeFunc(t,2,v.ValueType.Float,e);}static AddFloatUnaryOp(t,e){this.AddOpToNativeFunc(t,1,v.ValueType.Float,e);}static AddStringBinaryOp(t,e){this.AddOpToNativeFunc(t,2,v.ValueType.String,e);}static AddListBinaryOp(t,e){this.AddOpToNativeFunc(t,2,v.ValueType.List,e);}static AddListUnaryOp(t,e){this.AddOpToNativeFunc(t,1,v.ValueType.List,e);}toString(){return 'Native "'+this.name+'"'}};Bn.NativeFunctionCall=w;w.Add="+";w.Subtract="-";w.Divide="/";w.Multiply="*";w.Mod="%";w.Negate="_";w.Equal="==";w.Greater=">";w.Less="<";w.GreaterThanOrEquals=">=";w.LessThanOrEquals="<=";w.NotEquals="!=";w.Not="!";w.And="&&";w.Or="||";w.Min="MIN";w.Max="MAX";w.Pow="POW";w.Floor="FLOOR";w.Ceiling="CEILING";w.Int="INT";w.Float="FLOAT";w.Has="?";w.Hasnt="!?";w.Intersect="^";w.ListMin="LIST_MIN";w.ListMax="LIST_MAX";w.All="LIST_ALL";w.Count="LIST_COUNT";w.ValueOfList="LIST_VALUE";w.Invert="LIST_INVERT";w._nativeFunctions=null;});var $n=p(Gn=>{Object.defineProperty(Gn,"__esModule",{value:true});Gn.NumberExpression=void 0;var hh=ct(),us=k(),ch=O(),hs=class s extends hh.Expression{constructor(t,e){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 us.IntValue(this.value)):this.isFloat()?n.AddContent(new us.FloatValue(this.value)):this.isBool()&&n.AddContent(new us.BoolValue(this.value));},this.toString=()=>String(this.value),typeof t=="number"&&!Number.isNaN(t)||typeof t=="boolean")this.value=t,this.subtype=e;else throw new Error("Unexpected object type in NumberExpression.")}get typeName(){return "Number"}Equals(t){let e=(0, ch.asOrNull)(t,s);return e?e.subtype==this.subtype&&e.value==this.value:false}};Gn.NumberExpression=hs;});var cs=p(Jn=>{Object.defineProperty(Jn,"__esModule",{value:true});Jn.UnaryExpression=void 0;var dh=ct(),fh=Et(),pe=$n(),ph=O(),$e=class extends dh.Expression{get nativeNameForOp(){return this.op==="-"?"_":this.op==="not"?"!":this.op}constructor(t,e){super(),this.op=e,this.GenerateIntoContainer=n=>{this.innerExpression.GenerateIntoContainer(n),n.AddContent(fh.NativeFunctionCall.CallWithName(this.nativeNameForOp));},this.toString=()=>this.nativeNameForOp+this.innerExpression,this.innerExpression=this.AddContent(t);}get typeName(){return "UnaryExpression"}};Jn.UnaryExpression=$e;$e.WithInner=(s,t)=>{let e=(0, ph.asOrNull)(s,pe.NumberExpression);if(e){if(t==="-"){if(e.isInt())return new pe.NumberExpression(-e.value,"int");if(e.isFloat())return new pe.NumberExpression(-e.value,"float")}else if(t=="!"||t=="not"){if(e.isInt())return new pe.NumberExpression(e.value==0,"bool");if(e.isFloat())return new pe.NumberExpression(e.value==0,"bool");if(e.isBool())return new pe.NumberExpression(!e.value,"bool")}throw new Error("Unexpected operation or number type")}return new $e(s,t)};});var fs=p(Un=>{Object.defineProperty(Un,"__esModule",{value:true});Un.BinaryExpression=void 0;var mh=ct(),gh=Et(),Ch=cs(),vh=O(),ds=class extends mh.Expression{constructor(t,e,n){super(),this.opName=n,this.GenerateIntoContainer=i=>{this.leftExpression.GenerateIntoContainer(i),this.rightExpression.GenerateIntoContainer(i),this.opName=this.NativeNameForOp(this.opName),i.AddContent(gh.NativeFunctionCall.CallWithName(this.opName));},this.NativeNameForOp=i=>i==="and"?"&&":i==="or"?"||":i==="mod"?"%":i==="has"?"?":i==="hasnt"?"!?":i,this.toString=()=>`(${this.leftExpression} ${this.opName} ${this.rightExpression})`,this.leftExpression=this.AddContent(t),this.rightExpression=this.AddContent(e),this.opName=n;}get typeName(){return "BinaryExpression"}ResolveReferences(t){if(super.ResolveReferences(t),this.NativeNameForOp(this.opName)==="?"){let e=(0, vh.asOrNull)(this.leftExpression,Ch.UnaryExpression);e!==null&&(e.op==="not"||e.op==="!")&&this.Error(`Using 'not' or '!' here negates '${e.innerExpression}' rather than the result of the '?' or 'has' operator. You need to add parentheses around the (A ? B) expression.`);}}};Un.BinaryExpression=ds;});var Ue=p(Hn=>{Object.defineProperty(Hn,"__esModule",{value:true});Hn.CharacterSet=void 0;var Je=class{constructor(t){this.set=new Set,this.Add=e=>this.set.add(e),this.AddRange=(e,n)=>{for(let i=e.charCodeAt(0);i<=n.charCodeAt(0);++i)this.Add(String.fromCharCode(i));return this},this.AddCharacters=e=>{if(typeof e=="string"||Array.isArray(e))for(let n of e)this.Add(n);else for(let n of e.set)this.Add(n);return this},t&&this.AddCharacters(t);}};Hn.CharacterSet=Je;Je.FromRange=(s,t)=>new Je().AddRange(s,t);});var jo=p(Kn=>{Object.defineProperty(Kn,"__esModule",{value:true});Kn.CharacterRange=void 0;var qo=Ue(),He=class{constructor(t,e,n=[]){if(this._start=t,this._end=e,this._correspondingCharSet=new qo.CharacterSet,this._excludes=new Set,this.ToCharacterSet=()=>{if(this._correspondingCharSet.set.size===0)for(let i=this.start.charCodeAt(0),a;i<=this.end.charCodeAt(0);i+=1)a=String.fromCharCode(i),this._excludes.has(a)||this._correspondingCharSet.AddCharacters(a);return this._correspondingCharSet},n instanceof qo.CharacterSet)this._excludes=n.set;else for(let i of n)this._excludes.add(i);}get start(){return this._start}get end(){return this._end}};Kn.CharacterRange=He;He.Define=(s,t,e=[])=>new He(s,t,e);});var Xn=p(zn=>{Object.defineProperty(zn,"__esModule",{value:true});zn.ChoicePoint=void 0;var Sh=rt(),yh=it(),ps=K(),ms=class extends Sh.InkObject{constructor(t=true){super(),this._pathOnChoice=null,this.hasCondition=false,this.hasStartContent=false,this.hasChoiceOnlyContent=false,this.isInvisibleDefault=false,this.onceOnly=true,this.onceOnly=t;}get pathOnChoice(){if(this._pathOnChoice!=null&&this._pathOnChoice.isRelative){let t=this.choiceTarget;t&&(this._pathOnChoice=t.path);}return this._pathOnChoice}set pathOnChoice(t){this._pathOnChoice=t;}get choiceTarget(){return this._pathOnChoice===null?(0, ps.throwNullException)("ChoicePoint._pathOnChoice"):this.ResolvePath(this._pathOnChoice).container}get pathStringOnChoice(){return this.pathOnChoice===null?(0, ps.throwNullException)("ChoicePoint.pathOnChoice"):this.CompactPathString(this.pathOnChoice)}set pathStringOnChoice(t){this.pathOnChoice=new yh.Path(t);}get flags(){let t=0;return this.hasCondition&&(t|=1),this.hasStartContent&&(t|=2),this.hasChoiceOnlyContent&&(t|=4),this.isInvisibleDefault&&(t|=8),this.onceOnly&&(t|=16),t}set flags(t){this.hasCondition=(t&1)>0,this.hasStartContent=(t&2)>0,this.hasChoiceOnlyContent=(t&4)>0,this.isInvisibleDefault=(t&8)>0,this.onceOnly=(t&16)>0;}toString(){if(this.pathOnChoice===null)return (0, ps.throwNullException)("ChoicePoint.pathOnChoice");let e=this.pathOnChoice.toString();return "Choice: -> "+e}};zn.ChoicePoint=ms;});var Yt=p(Yn=>{Object.defineProperty(Yn,"__esModule",{value:true});Yn.PushPopType=void 0;var Mo;(function(s){s[s.Tunnel=0]="Tunnel",s[s.Function=1]="Function",s[s.FunctionEvaluationFromGame=2]="FunctionEvaluationFromGame";})(Mo||(Yn.PushPopType=Mo={}));});var Ke=p(Zn=>{Object.defineProperty(Zn,"__esModule",{value:true});Zn.Pointer=void 0;var bh=it(),gs=class s{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 bh.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 s(this.container,this.index)}static StartOf(t){return new s(t,0)}static get Null(){return new s(null,-1)}};Zn.Pointer=gs;});var Pt=p(ti=>{Object.defineProperty(ti,"__esModule",{value:true});ti.Divert=void 0;var _h=it(),Eh=Yt(),Ph=Kt(),wh=rt(),Cs=Ke(),Bo=L(),Qn=K(),vs=class s extends wh.InkObject{get targetPath(){if(this._targetPath!=null&&this._targetPath.isRelative){let t=this.targetPointer.Resolve();t&&(this._targetPath=t.path);}return this._targetPath}set targetPath(t){this._targetPath=t,this._targetPointer=Cs.Pointer.Null;}get targetPointer(){if(this._targetPointer.isNull){let t=this.ResolvePath(this._targetPath).obj;if(this._targetPath===null)return (0, Qn.throwNullException)("this._targetPath");if(this._targetPath.lastComponent===null)return (0, Qn.throwNullException)("this._targetPath.lastComponent");if(this._targetPath.lastComponent.isIndex){if(t===null)return (0, Qn.throwNullException)("targetObj");this._targetPointer.container=t.parent instanceof Bo.Container?t.parent:null,this._targetPointer.index=this._targetPath.lastComponent.index;}else this._targetPointer=Cs.Pointer.StartOf(t instanceof Bo.Container?t:null);}return this._targetPointer.copy()}get targetPathString(){return this.targetPath==null?null:this.CompactPathString(this.targetPath)}set targetPathString(t){t==null?this.targetPath=null:this.targetPath=new _h.Path(t);}get hasVariableTarget(){return this.variableDivertName!=null}constructor(t){super(),this._targetPath=null,this._targetPointer=Cs.Pointer.Null,this.variableDivertName=null,this.pushesToStack=false,this.stackPushType=0,this.isExternal=false,this.externalArgs=0,this.isConditional=false,this.pushesToStack=false,typeof t<"u"&&(this.pushesToStack=true,this.stackPushType=t);}Equals(t){let e=t;return e instanceof s&&this.hasVariableTarget==e.hasVariableTarget?this.hasVariableTarget?this.variableDivertName==e.variableDivertName:this.targetPath===null?(0, Qn.throwNullException)("this.targetPath"):this.targetPath.Equals(e.targetPath):false}toString(){if(this.hasVariableTarget)return "Divert(variable: "+this.variableDivertName+")";if(this.targetPath==null)return "Divert(null)";{let t=new Ph.StringBuilder,e=this.targetPath.toString();return t.Append("Divert"),this.isConditional&&t.Append("?"),this.pushesToStack&&(this.stackPushType==Eh.PushPopType.Function?t.Append(" function"):t.Append(" tunnel")),t.Append(" -> "),t.Append(this.targetPathString),t.Append(" ("),t.Append(e),t.Append(")"),t.toString()}}};ti.Divert=vs;});var Ft=p(ei=>{Object.defineProperty(ei,"__esModule",{value:true});ei.SymbolType=void 0;var Go;(function(s){s[s.Knot=0]="Knot",s[s.List=1]="List",s[s.ListItem=2]="ListItem",s[s.Var=3]="Var",s[s.SubFlowAndWeave=4]="SubFlowAndWeave",s[s.Arg=5]="Arg",s[s.Temp=6]="Temp";})(Go||(ei.SymbolType=Go={}));});var Lt=p(ni=>{Object.defineProperty(ni,"__esModule",{value:true});ni.VariableAssignment=void 0;var xh=rt(),Ss=class extends xh.InkObject{constructor(t,e){super(),this.variableName=t||null,this.isNewDeclaration=!!e,this.isGlobal=false;}toString(){return "VarAssign to "+this.variableName}};ni.VariableAssignment=Ss;});var me=p(ri=>{Object.defineProperty(ri,"__esModule",{value:true});ri.Choice=void 0;var Th=Xn(),ii=L(),qt=z(),ys=Pt(),$o=k(),Oh=R(),Nh=Ft(),Jo=Lt(),bs=class extends Oh.ParsedObject{get runtimeChoice(){if(!this._runtimeChoice)throw new Error;return this._runtimeChoice}get name(){var t;return ((t=this.identifier)===null||t===void 0?void 0:t.name)||null}get condition(){return this._condition}set condition(t){this._condition=t,t&&this.AddContent(t);}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(t,e,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 ii.Container,this._runtimeChoice=new Th.ChoicePoint(this.onceOnly),this._runtimeChoice.isInvisibleDefault=this.isInvisibleDefault,(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(qt.ControlCommand.EvalStart()),this.startContent){this._returnToR1=new $o.DivertTargetValue,this._outerContainer.AddContent(this._returnToR1);let i=new Jo.VariableAssignment("$r",true);this._outerContainer.AddContent(i),this._outerContainer.AddContent(qt.ControlCommand.BeginString()),this._divertToStartContentOuter=new ys.Divert,this._outerContainer.AddContent(this._divertToStartContentOuter),this._startContentRuntimeContainer=this.startContent.GenerateRuntimeObject(),this._startContentRuntimeContainer.name="s";let a=new ys.Divert;a.variableDivertName="$r",this._startContentRuntimeContainer.AddContent(a),this._outerContainer.AddToNamedContentOnly(this._startContentRuntimeContainer),this._r1Label=new ii.Container,this._r1Label.name="$r1",this._outerContainer.AddContent(this._r1Label),this._outerContainer.AddContent(qt.ControlCommand.EndString()),this._runtimeChoice.hasStartContent=true;}if(this.choiceOnlyContent){this._outerContainer.AddContent(qt.ControlCommand.BeginString());let i=this.choiceOnlyContent.GenerateRuntimeObject();this._outerContainer.AddContentsOfContainer(i),this._outerContainer.AddContent(qt.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(qt.ControlCommand.EvalEnd()),this._outerContainer.AddContent(this._runtimeChoice),this._innerContentContainer=new ii.Container,this.startContent){this._returnToR2=new $o.DivertTargetValue,this._innerContentContainer.AddContent(qt.ControlCommand.EvalStart()),this._innerContentContainer.AddContent(this._returnToR2),this._innerContentContainer.AddContent(qt.ControlCommand.EvalEnd());let i=new Jo.VariableAssignment("$r",true);this._innerContentContainer.AddContent(i),this._divertToStartContentInner=new ys.Divert,this._innerContentContainer.AddContent(this._divertToStartContentInner),this._r2Label=new ii.Container,this._r2Label.name="$r2",this._innerContentContainer.AddContent(this._r2Label);}if(this.innerContent){let i=this.innerContent.GenerateRuntimeObject();this._innerContentContainer.AddContentsOfContainer(i);}return this.story.countAllVisits&&(this._innerContentContainer.visitsShouldBeCounted=true),this._innerContentContainer.countingAtStartOnly=true,this._outerContainer},this.toString=()=>this.choiceOnlyContent!==null?`* ${this.startContent}[${this.choiceOnlyContent}]...`:`* ${this.startContent}...`,this.startContent=t,this.choiceOnlyContent=e,this.innerContent=n,this.indentationDepth=1,t&&this.AddContent(this.startContent),e&&this.AddContent(this.choiceOnlyContent),n&&this.AddContent(this.innerContent),this.onceOnly=true;}get typeName(){return "Choice"}ResolveReferences(t){var e;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(t),this.identifier&&(((e=this.identifier)===null||e===void 0?void 0:e.name)||"").length>0&&t.CheckForNamingCollisions(this,this.identifier,Nh.SymbolType.SubFlowAndWeave);}};ri.Choice=bs;});var Uo=p(ai=>{Object.defineProperty(ai,"__esModule",{value:true});ai.StringParserElement=void 0;var si=class s{constructor(){this.characterIndex=0,this.characterInLineIndex=0,this.lineIndex=0,this.reportedErrorInScope=false,this.uniqueId=0,this.customFlags=0,this.CopyFrom=t=>{s._uniqueIdCounter++,this.uniqueId=s._uniqueIdCounter,this.characterIndex=t.characterIndex,this.characterInLineIndex=t.characterInLineIndex,this.lineIndex=t.lineIndex,this.customFlags=t.customFlags,this.reportedErrorInScope=false;},this.SquashFrom=t=>{this.characterIndex=t.characterIndex,this.characterInLineIndex=t.characterInLineIndex,this.lineIndex=t.lineIndex,this.reportedErrorInScope=t.reportedErrorInScope,this.customFlags=t.customFlags;};}};ai.StringParserElement=si;si._uniqueIdCounter=1e3;});var Ko=p(oi=>{Object.defineProperty(oi,"__esModule",{value:true});oi.StringParserState=void 0;var Ho=Uo(),_s=class{get currentElement(){return this._stack[this._numElements-1]}get lineIndex(){return this.currentElement.lineIndex}set lineIndex(t){this.currentElement.lineIndex=t;}get characterIndex(){return this.currentElement.characterIndex}set characterIndex(t){this.currentElement.characterIndex=t;}get characterInLineIndex(){return this.currentElement.characterInLineIndex}set characterInLineIndex(t){this.currentElement.characterInLineIndex=t;}get customFlags(){return this.currentElement.customFlags}set customFlags(t){this.currentElement.customFlags=t;}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 Ho.StringParserElement;this._numElements=1;},this.Push=()=>{if(this._numElements>=this._stack.length&&this._numElements>0)throw new Error("Stack overflow in parser state.");let e=this._stack[this._numElements-1],n=this._stack[this._numElements];return this._numElements++,n.CopyFrom(e),n.uniqueId},this.Pop=e=>{if(this._numElements==1)throw new Error("Attempting to remove final stack element is illegal! Mismatched Begin/Succceed/Fail?");if(this.currentElement.uniqueId!=e)throw new Error("Mismatched rule IDs while Poping - do you have mismatched Begin/Succeed/Fail?");this._numElements-=1;},this.Peek=e=>{if(this.currentElement.uniqueId!=e)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 e=this._stack[this._numElements-2],n=this._stack[this._numElements-1];e.SquashFrom(n),this._numElements-=1;},this.NoteErrorReported=()=>{for(let e of this._stack)e.reportedErrorInScope=true;};let t=200;for(let e=0;e<t;e++)this._stack[e]=new Ho.StringParserElement;this._numElements=1;}};oi.StringParserState=_s;});var Ps=p(Zt=>{Object.defineProperty(Zt,"__esModule",{value:true});Zt.StringParser=Zt.ParseSuccess=void 0;var Es=Ue(),Ah=Ko();Zt.ParseSuccess=Symbol("ParseSuccessStruct");var ze=class s{constructor(t){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,i=null)=>{let a=this.state.Peek(n),r=this.state.PeekPenultimate();this.RuleDidSucceed&&this.RuleDidSucceed(i,r,a),this.state.Squash();let o=i;return o===null&&(o=s.ParseSuccess),o},this.Expect=(n,i=null,a=null)=>{let r=this.ParseObject(n);if(r===null){i===null&&(i=n.name);let o,l=this.LineRemainder();l===null||l.length===0?o="end of line":o=`'${l}'`,this.Error(`Expected ${i} but saw ${o}`),a!==null&&(r=a());}return r},this.Error=(n,i=false)=>{this.ErrorOnLine(n,this.lineIndex+1,i);},this.ErrorWithParsedObject=(n,i,a=false)=>{this.ErrorOnLine(n,i.debugMetadata?i.debugMetadata.startLineNumber:-1,a);},this.ErrorOnLine=(n,i,a)=>{if(!this.state.errorReportedAlreadyInScope){let r=a?"Warning":"Error";if(this.errorHandler)this.errorHandler(n,this.index,i-1,a);else throw new Error(`${r} on line ${i}: ${n}`);this.state.NoteErrorReported();}a||(this.hadError=true);},this.Warning=n=>this.Error(n,true),this.LineRemainder=()=>this.Peek(()=>this.ParseUntilCharactersFromString(`
\r`)),this.SetFlag=(n,i)=>{i?this.state.customFlags|=n:this.state.customFlags&=~n;},this.GetFlag=n=>!!(this.state.customFlags&n),this.ParseObject=n=>{let i=this.BeginRule(),a=this.state.stackHeight,r=n();if(a!==this.state.stackHeight)throw new Error("Mismatched Begin/Fail/Succeed rules");return r===null?this.FailRule(i):(this.SucceedRule(i,r),r)},this.Parse=n=>{let i=this.BeginRule(),a=n();return a===null?(this.FailRule(i),null):(this.SucceedRule(i,a),a)},this.OneOf=n=>{for(let i of n){let a=this.ParseObject(i);if(a!==null)return a}return null},this.OneOrMore=n=>{let i=[],a=null;do a=this.ParseObject(n),a!==null&&i.push(a);while(a!==null);return i.length>0?i:null},this.Optional=n=>()=>{let i=this.ParseObject(n);return i===null?s.ParseSuccess:i},this.Exclude=n=>()=>this.ParseObject(n)&&s.ParseSuccess,this.OptionalExclude=n=>()=>(this.ParseObject(n),s.ParseSuccess),this.String=n=>()=>this.ParseString(n),this.TryAddResultToList=(n,i,a=true)=>{if(n!==s.ParseSuccess){if(a&&Array.isArray(n)){let r=n;if(r!==null){for(let o of r)i.push(o);return}}i.push(n);}},this.Interleave=(n,i,a=null,r=true)=>{let o=this.BeginRule(),l=[],u=this.ParseObject(n);if(u===null)return this.FailRule(o);this.TryAddResultToList(u,l,r);let h=null,c=null;do{if(a!==null&&this.Peek(a)!==null||(h=this.ParseObject(i),h===null))break;if(this.TryAddResultToList(h,l,r),c=null,h!==null){if(c=this.ParseObject(n),c===null)break;this.TryAddResultToList(c,l,r);}}while((h!==null||c!==null)&&!(h===s.ParseSuccess&&c==s.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 i=this.BeginRule(),a=this.index,r=this.characterInLineIndex,o=this.lineIndex,l=true;for(let u=0;u<n.length;u+=1){let h=n[u];if(this._chars[a]!==h){l=false;break}h===`
`&&(o++,r=-1),a++,r++;}return this.index=a,this.characterInLineIndex=r,this.lineIndex=o,l?this.SucceedRule(i,n):this.FailRule(i)},this.ParseSingleCharacter=()=>{if(this.remainingLength>0){let n=this._chars[this.index];return n===`
`&&(this.lineIndex+=1,this.characterInLineIndex=-1),this.index+=1,this.characterInLineIndex+=1,n}return "0"},this.ParseUntilCharactersFromString=(n,i=-1)=>this.ParseCharactersFromString(n,false,i),this.ParseUntilCharactersFromCharSet=(n,i=-1)=>this.ParseCharactersFromCharSet(n,false,i),this.ParseCharactersFromString=(n,i=-1,a=-1)=>{let r=new Es.CharacterSet(n);return typeof i=="number"?this.ParseCharactersFromCharSet(r,true,i):this.ParseCharactersFromCharSet(r,i,a)},this.ParseCharactersFromCharSet=(n,i=true,a=-1)=>{a===-1&&(a=Number.MAX_SAFE_INTEGER);let r=this.index,o=this.index,l=this.characterInLineIndex,u=this.lineIndex,h=0;for(;o<this._chars.length&&n.set.has(this._chars[o])===i&&h<a;)this._chars[o]===`
`&&(u+=1,l=-1),o+=1,l+=1,h+=1;return this.index=o,this.characterInLineIndex=l,this.lineIndex=u,this.index>r?this._chars.slice(r,this.index).join(""):null},this.Peek=n=>{let i=this.BeginRule(),a=n();return this.CancelRule(i),a},this.ParseInt=()=>{let n=this.index,i=this.characterInLineIndex,a=this.ParseString("-")!==null;this.ParseCharactersFromString(" 	");let r=this.ParseCharactersFromCharSet(s.numbersCharacterSet);if(r===null)return this.index=n,this.characterInLineIndex=i,null;let o;return Number.isNaN(Number(r))?(this.Error("Failed to read integer value: "+r+". Perhaps it's out of the range of acceptable numbers ink supports? ("+Number.MIN_SAFE_INTEGER+" to "+Number.MAX_SAFE_INTEGER+")"),null):(o=Number(r),a?-o:o)},this.ParseFloat=()=>{let n=this.index,i=this.characterInLineIndex,a=this.ParseInt();if(a!==null&&this.ParseString(".")!==null){let r=this.ParseCharactersFromCharSet(s.numbersCharacterSet);return +`${a}.${r}`}return this.index=n,this.characterInLineIndex=i,null},this.ParseNewline=()=>{let n=this.BeginRule();return this.ParseString("\r"),this.ParseString(`
`)===null?this.FailRule(n):this.SucceedRule(n,`
`)};let e=this.PreProcessInputString(t);this.state=new Ah.StringParserState,t?this._chars=e.split(""):this._chars=[],this.inputString=e;}get currentCharacter(){return this.index>=0&&this.remainingLength>0?this._chars[this.index]:"0"}PreProcessInputString(t){return t}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(t){this.state.lineIndex=t;}set characterInLineIndex(t){this.state.characterInLineIndex=t;}get characterInLineIndex(){return this.state.characterInLineIndex}get index(){return this.state.characterIndex}set index(t){this.state.characterIndex=t;}ParseUntil(t,e=null,n=null){let i=this.BeginRule(),a=new Es.CharacterSet;e!==null&&(a.set=new Set([...a.set.values(),...e.set.values()])),n!==null&&(a.set=new Set([...a.set.values(),...n.set.values()]));let r="",o=null;do{let l=this.ParseUntilCharactersFromCharSet(a);if(l&&(r+=l),o=this.Peek(t),o!==null)break;{if(this.endOfInput)break;let u=this.currentCharacter;if(e!==null&&e.set.has(u)){r+=u,u===`
`&&(this.lineIndex+=1,this.characterInLineIndex=-1),this.index+=1,this.characterInLineIndex+=1;continue}else break}}while(true);return r.length>0?this.SucceedRule(i,String(r)):this.FailRule(i)}};Zt.StringParser=ze;ze.ParseSuccess=Zt.ParseSuccess;ze.numbersCharacterSet=new Es.CharacterSet("0123456789");});var zo=p(li=>{Object.defineProperty(li,"__esModule",{value:true});li.CommentEliminator=void 0;var ws=Ue(),Ih=Ps(),xs=class extends Ih.StringParser{constructor(){super(...arguments),this._commentOrNewlineStartCharacter=new ws.CharacterSet(`/\r
`),this._commentBlockEndCharacter=new ws.CharacterSet("*"),this._newlineCharacters=new ws.CharacterSet(`
\r`),this.Process=()=>{let t=this.Interleave(this.Optional(this.CommentsAndNewlines),this.Optional(this.MainInk));return t!==null?t.join(""):""},this.MainInk=()=>this.ParseUntil(this.CommentsAndNewlines,this._commentOrNewlineStartCharacter,null),this.CommentsAndNewlines=()=>{let t=this.Interleave(this.Optional(this.ParseNewline),this.Optional(this.ParseSingleComment));return t!==null?t.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 t=this.lineIndex,e=this.ParseUntil(this.String("*/"),this._commentBlockEndCharacter,null);return this.endOfInput||this.ParseString("*/"),e!=null?`
`.repeat(this.lineIndex-t):null};}PreProcessInputString(t){return t}};li.CommentEliminator=xs;});var hi=p(ui=>{Object.defineProperty(ui,"__esModule",{value:true});ui.Conditional=void 0;var Fh=L(),Xo=z(),Vh=R(),Ts=class extends Vh.ParsedObject{constructor(t,e){super(),this.initialCondition=t,this.branches=e,this._reJoinTarget=null,this.GenerateRuntimeObject=()=>{let n=new Fh.Container;this.initialCondition&&n.AddContent(this.initialCondition.runtimeObject);for(let i of this.branches){let a=i.runtimeObject;n.AddContent(a);}return this.initialCondition!==null&&this.branches[0].ownExpression!==null&&!this.branches[this.branches.length-1].isElse&&n.AddContent(Xo.ControlCommand.PopEvaluatedValue()),this._reJoinTarget=Xo.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(t){let e=this._reJoinTarget.path;for(let n of this.branches){if(!n.returnDivert)throw new Error;n.returnDivert.targetPath=e;}super.ResolveReferences(t);}};ui.Conditional=Ts;});var jt=p(ci=>{Object.defineProperty(ci,"__esModule",{value:true});ci.Text=void 0;var Rh=R(),kh=k(),Os=class extends Rh.ParsedObject{constructor(t){super(),this.text=t,this.GenerateRuntimeObject=()=>new kh.StringValue(this.text),this.toString=()=>this.text;}get typeName(){return "Text"}};ci.Text=Os;});var fi=p(di=>{Object.defineProperty(di,"__esModule",{value:true});di.ConstantDeclaration=void 0;var Dh=R(),Wh=Ft(),Ns=class extends Dh.ParsedObject{get constantName(){var t;return (t=this.constantIdentifier)===null||t===void 0?void 0:t.name}get expression(){if(!this._expression)throw new Error;return this._expression}constructor(t,e){super(),this._expression=null,this.GenerateRuntimeObject=()=>null,this.constantIdentifier=t,e&&(this._expression=this.AddContent(e));}get typeName(){return "CONST"}ResolveReferences(t){super.ResolveReferences(t),t.CheckForNamingCollisions(this,this.constantIdentifier,Wh.SymbolType.Var);}};di.ConstantDeclaration=Ns;});var ge=p(pi=>{Object.defineProperty(pi,"__esModule",{value:true});pi.FlowLevel=void 0;var Yo;(function(s){s[s.Story=0]="Story",s[s.Knot=1]="Knot",s[s.Stitch=2]="Stitch",s[s.WeavePoint=3]="WeavePoint";})(Yo||(pi.FlowLevel=Yo={}));});var Xe=p(mi=>{Object.defineProperty(mi,"__esModule",{value:true});mi.Gather=void 0;var Lh=L(),qh=R(),jh=Ft(),As=class extends qh.ParsedObject{get name(){var t;return ((t=this.identifier)===null||t===void 0?void 0:t.name)||null}get runtimeContainer(){return this.runtimeObject}constructor(t,e){super(),this.indentationDepth=e,this.GenerateRuntimeObject=()=>{let n=new Lh.Container;if(n.name=this.name,this.story.countAllVisits&&(n.visitsShouldBeCounted=true),n.countingAtStartOnly=true,this.content)for(let i of this.content)n.AddContent(i.runtimeObject);return n},this.toString=()=>{var n,i;return `- ${!((n=this.identifier)===null||n===void 0)&&n.name?"("+((i=this.identifier)===null||i===void 0?void 0:i.name)+")":"gather"}`},t&&(this.identifier=t);}get typeName(){return "Gather"}ResolveReferences(t){super.ResolveReferences(t),this.identifier&&(this.identifier.name||"").length>0&&t.CheckForNamingCollisions(this,this.identifier,jh.SymbolType.SubFlowAndWeave);}};mi.Gather=As;});var Qt=p(Ci=>{Object.defineProperty(Ci,"__esModule",{value:true});Ci.Path=void 0;var gi=O(),Zo=wt(),Ce=ge(),Mh=te(),Is=class{get baseTargetLevel(){return this.baseLevelIsAmbiguous?Ce.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(t=>t.name).filter(gi.filterUndef).join(".")),this._dotSeparatedComponents}constructor(t,e){this._dotSeparatedComponents=null,this.toString=()=>this.components===null||this.components.length===0?this.baseTargetLevel===Ce.FlowLevel.WeavePoint?"-> <next gather point>":"<invalid Path>":`-> ${this.dotSeparatedComponents}`,this.ResolveFromContext=n=>{if(this.components==null||this.components.length==0)return null;let i=this.ResolveBaseTarget(n);return i===null?null:this.components.length>1?this.ResolveTailComponents(i):i},this.ResolveBaseTarget=n=>{let i=this.firstComponent,a=n;for(;a;){let r=a===n,o=this.GetChildFromContext(a,i,null,r);if(o)return o;a=a.parent;}return null},this.ResolveTailComponents=n=>{let i=n;if(!this.components)return null;for(let a=1;a<this.components.length;++a){let r=this.components[a].name,o,l=(0, gi.asOrNull)(i,Zo.FlowBase);if(l!==null?o=l.flowLevel+1:o=Ce.FlowLevel.WeavePoint,i=this.GetChildFromContext(i,r,o),i===null)break}return i},this.GetChildFromContext=(n,i,a,r=false)=>{let o=a===null,l=(0, gi.asOrNull)(n,Mh.Weave);if(i&&l!==null&&(o||a===Ce.FlowLevel.WeavePoint))return l.WeavePointNamed(i);let u=(0, gi.asOrNull)(n,Zo.FlowBase);if(i&&u!==null){let h=r||u.flowLevel===Ce.FlowLevel.Knot;return u.ContentWithNameAtLevel(i,a,h)}return null},Object.values(Ce.FlowLevel).includes(t)?(this._baseTargetLevel=t,this.components=e||[]):Array.isArray(t)?(this._baseTargetLevel=null,this.components=t||[]):(this._baseTargetLevel=null,this.components=[t]);}get typeName(){return "Path"}};Ci.Path=Is;});var Rs=p(vi=>{Object.defineProperty(vi,"__esModule",{value:true});vi.ReturnType=void 0;var Bh=R(),Gh=L(),Fs=z(),$h=Xt(),Vs=class extends Bh.ParsedObject{constructor(t=null){super(),this.returnedExpression=null,this.GenerateRuntimeObject=()=>{let e=new Gh.Container;return this.returnedExpression?e.AddContent(this.returnedExpression.runtimeObject):(e.AddContent(Fs.ControlCommand.EvalStart()),e.AddContent(new $h.Void),e.AddContent(Fs.ControlCommand.EvalEnd())),e.AddContent(Fs.ControlCommand.PopFunction()),e},t&&(this.returnedExpression=this.AddContent(t));}get typeName(){return "ReturnType"}};vi.ReturnType=Vs;});var Ye=p(Si=>{Object.defineProperty(Si,"__esModule",{value:true});Si.ClosestFlowBase=void 0;function Jh(s){let t=s.parent;for(;t;){if(t.hasOwnProperty("iamFlowbase")&&t.iamFlowbase())return t;t=t.parent;}return null}Si.ClosestFlowBase=Jh;});var bi=p(yi=>{Object.defineProperty(yi,"__esModule",{value:true});yi.Identifier=void 0;var ks=class s{constructor(t){this.debugMetadata=null,this.toString=()=>this.name||"undefined identifer",this.name=t;}get typeName(){return "Identifier"}static Done(){return new s("DONE")}};yi.Identifier=ks;});var wt=p(_i=>{Object.defineProperty(_i,"__esModule",{value:true});_i.FlowBase=void 0;var Uh=me(),Ds=Se(),Hh=ve(),xt=ge(),Kh=Xe(),zh=R(),Xh=Qt(),Yh=Rs(),Zh=L(),Qh=Pt(),tc=Lt(),Ws=Ft(),ec=te(),nc=Ye(),ic=bi(),Qo=O(),Ls=class s extends zh.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 t;return ((t=this.identifier)===null||t===void 0?void 0:t.name)||null}constructor(t,e=null,n=null,i=false,a=false){super(),this.isFunction=i,this._rootWeave=null,this._subFlowsByName=new Map,this._startingSubFlowDivert=null,this._startingSubFlowRuntime=null,this._firstChildFlow=null,this.variableDeclarations=new Map,this.identifier=null,this.args=null,this.iamFlowbase=()=>true,this.SplitWeaveAndSubFlowContent=(r,o)=>{var l,u;let h=[],c=[];this._subFlowsByName=new Map;for(let m of r){let g=(0, Qo.asOrNull)(m,s);g?(this._firstChildFlow===null&&(this._firstChildFlow=g),c.push(m),!((l=g.identifier)===null||l===void 0)&&l.name&&this._subFlowsByName.set((u=g.identifier)===null||u===void 0?void 0:u.name,g)):h.push(m);}o&&h.push(new Kh.Gather(null,1),new Ds.Divert(new Xh.Path(ic.Identifier.Done())));let d=[];return h.length>0&&(this._rootWeave=new ec.Weave(h,0),d.push(this._rootWeave)),c.length>0&&d.push(...c),d},this.ResolveVariableWithName=(r,o)=>{var l;let u={},h=o===null?this:(0, nc.ClosestFlowBase)(o);if(h){if(h.args!==null){for(let c of h.args)if(((l=c.identifier)===null||l===void 0?void 0:l.name)===r)return u.found=true,u.isArgument=true,u.ownerFlow=h,u}if(h!==this.story&&h.variableDeclarations.has(r))return u.found=true,u.ownerFlow=h,u.isTemporary=true,u}return this.story.variableDeclarations.has(r)?(u.found=true,u.ownerFlow=this.story,u.isGlobal=true,u):(u.found=false,u)},this.AddNewVariableDeclaration=r=>{let o=r.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}`,r,false);return}this.variableDeclarations.set(r.variableName,r);},this.ResolveWeavePointNaming=()=>{this._rootWeave&&this._rootWeave.ResolveWeavePointNaming();for(let[,r]of this._subFlowsByName)r.hasOwnProperty("ResolveWeavePointNaming")&&r.ResolveWeavePointNaming();},this.GenerateRuntimeObject=()=>{var r;let o=null;this.isFunction?this.CheckForDisallowedFunctionFlowControl():(this.flowLevel===xt.FlowLevel.Knot||this.flowLevel===xt.FlowLevel.Stitch)&&(o=this.Find(Yh.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 Zh.Container;l.name=(r=this.identifier)===null||r===void 0?void 0:r.name,this.story.countAllVisits&&(l.visitsShouldBeCounted=true),this.GenerateArgumentVariableAssignments(l);let u=0;for(;this.content!==null&&u<this.content.length;){let h=this.content[u];if(h instanceof s){let c=h,d=c.runtimeObject;u===0&&!c.hasParameters&&this.flowLevel===xt.FlowLevel.Knot&&(this._startingSubFlowDivert=new Qh.Divert,l.AddContent(this._startingSubFlowDivert),this._startingSubFlowRuntime=d);let m=d,g=l.namedContent.get(m.name)||null;if(g){let S=`${this.GetType()} already contains flow named '${m.name}' (at ${g.debugMetadata})`;this.Error(S,c);}l.AddToNamedContentOnly(m);}else h&&l.AddContent(h.runtimeObject);u+=1;}return this.flowLevel!==xt.FlowLevel.Story&&!this.isFunction&&this._rootWeave!==null&&o===null&&this._rootWeave.ValidateTermination(this.WarningInTermination),l},this.GenerateArgumentVariableAssignments=r=>{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,h=new tc.VariableAssignment(u,true);r.AddContent(h);}},this.ContentWithNameAtLevel=(r,o=null,l=false)=>{var u;if((o===this.flowLevel||o===null)&&r===((u=this.identifier)===null||u===void 0?void 0:u.name))return this;if(o===xt.FlowLevel.WeavePoint||o===null){let c=null;if(this._rootWeave&&(c=this._rootWeave.WeavePointNamed(r),c))return c;if(o===xt.FlowLevel.WeavePoint)return l?this.DeepSearchForAnyLevelContent(r):null}if(o!==null&&o<this.flowLevel)return null;let h=this._subFlowsByName.get(r)||null;return h&&(o===null||o===h.flowLevel)?h:l?this.DeepSearchForAnyLevelContent(r):null},this.DeepSearchForAnyLevelContent=r=>{let o=this.ContentWithNameAtLevel(r,xt.FlowLevel.WeavePoint,false);if(o)return o;for(let[,l]of this._subFlowsByName){let u=l.ContentWithNameAtLevel(r,null,true);if(u)return u}return null},this.CheckForDisallowedFunctionFlowControl=()=>{this.flowLevel!==xt.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 r=this._rootWeave.FindAll(Ds.Divert)();for(let l of r)!l.isFunctionCall&&!(l.parent instanceof Hh.DivertTarget)&&this.Error(`Functions may not contain diverts, but saw '${l}'`,l);let o=this._rootWeave.FindAll(Uh.Choice)();for(let l of o)this.Error(`Functions may not contain choices, but saw '${l}'`,l);},this.WarningInTermination=r=>{let o="Apparent loose end exists where the flow runs out. Do you need a '-> DONE' statement, choice or divert?";r.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, Qo.asOrNull)(r,Ds.Divert);l&&l.isTunnel&&(o+=` When final tunnel to '${l.target} ->' returns it won't have anywhere to go.`),this.Warning(o,r);},this.toString=()=>`${this.typeName} '${this.identifier}'`,this.identifier=t,this.args=n,e===null&&(e=[]),this.PreProcessTopLevelObjects(e),e=this.SplitWeaveAndSubFlowContent(e,this.GetType()=="Story"&&!a),this.AddContent(e);}PreProcessTopLevelObjects(t){}ResolveReferences(t){var e,n;if(this._startingSubFlowDivert){if(!this._startingSubFlowRuntime)throw new Error;this._startingSubFlowDivert.targetPath=this._startingSubFlowRuntime.path;}if(super.ResolveReferences(t),this.args!==null){for(let i of this.args)t.CheckForNamingCollisions(this,i.identifier,Ws.SymbolType.Arg,"argument");for(let i=0;i<this.args.length;i+=1)for(let a=i+1;a<this.args.length;a+=1)((e=this.args[i].identifier)===null||e===void 0?void 0:e.name)==((n=this.args[a].identifier)===null||n===void 0?void 0:n.name)&&this.Error(`Multiple arguments with the same name: '${this.args[i].identifier}'`);}if(this.flowLevel!==xt.FlowLevel.Story){let i=this.flowLevel===xt.FlowLevel.Knot?Ws.SymbolType.Knot:Ws.SymbolType.SubFlowAndWeave;t.CheckForNamingCollisions(this,this.identifier,i);}}};_i.FlowBase=Ls;});var Pi=p(Ei=>{Object.defineProperty(Ei,"__esModule",{value:true});Ei.ContentList=void 0;var rc=L(),sc=R(),ac=jt(),oc=O(),qs=class extends sc.ParsedObject{get runtimeContainer(){return this.runtimeObject}constructor(t,...e){super(),this.dontFlatten=false,this.TrimTrailingWhitespace=()=>{for(let n=this.content.length-1;n>=0;--n){let i=(0, oc.asOrNull)(this.content[n],ac.Text);if(i===null)break;if(i.text=i.text.replace(new RegExp(/[ \t]/g),""),i.text.length===0)this.content.splice(n,1);else break}},this.GenerateRuntimeObject=()=>{let n=new rc.Container;if(this.content!==null)for(let i of this.content){let a=i.runtimeObject;a&&n.AddContent(a);}return this.dontFlatten&&this.story.DontFlattenContainer(n),n},this.toString=()=>`ContentList(${this.content.join(", ")})`,t&&this.AddContent(t),e&&this.AddContent(e);}get typeName(){return "ContentList"}};Ei.ContentList=qs;});var ye=p(wi=>{Object.defineProperty(wi,"__esModule",{value:true});wi.VariableReference=void 0;var lc=rt(),uc=it(),js=class extends lc.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(t){t===null?this.pathForCount=null:this.pathForCount=new uc.Path(t);}constructor(t=null){super(),this.pathForCount=null,this.name=t;}toString(){return this.name!=null?"var("+this.name+")":"read_count("+this.pathStringForCount+")"}};wi.VariableReference=js;});var be=p(xi=>{Object.defineProperty(xi,"__esModule",{value:true});xi.VariableReference=void 0;var hc=Pi(),cc=ct(),tl=wt(),dc=Qt(),fc=ye(),pc=te(),mc=bi(),el=O(),Ms=class extends cc.Expression{get name(){return this.path.join(".")}get path(){return this.pathIdentifiers.map(t=>t.name).filter(el.filterUndef)}get identifier(){if(!this.pathIdentifiers||this.pathIdentifiers.length==0)return null;let t=this.path.join(".");return new mc.Identifier(t)}get runtimeVarRef(){return this._runtimeVarRef}constructor(t){super(),this.pathIdentifiers=t,this._runtimeVarRef=null,this.isConstantReference=false,this.isListItemReference=false,this.GenerateIntoContainer=e=>{let n=this.story.constants.get(this.name);if(n){n.GenerateConstantIntoContainer(e),this.isConstantReference=true;return}if(this._runtimeVarRef=new fc.VariableReference(this.name),this.path.length===1||this.path.length===2){let i="",a="";this.path.length===1?i=this.path[0]:(a=this.path[0],i=this.path[1]),this.story.ResolveListItem(a,i,this)&&(this.isListItemReference=true);}e.AddContent(this._runtimeVarRef);},this.toString=()=>`{${this.path.join(".")}}`;}get typeName(){return "ref"}ResolveReferences(t){if(super.ResolveReferences(t),this.isConstantReference||this.isListItemReference)return;let e=new dc.Path(this.pathIdentifiers),n=e.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 i=(0, el.asOrNull)(n,tl.FlowBase);i&&i.isFunction&&(this.parent instanceof pc.Weave||this.parent instanceof hc.ContentList||this.parent instanceof tl.FlowBase)&&this.Warning(`'${i.identifier}' being used as read count rather than being called as function. Perhaps you intended to write ${i.identifier}()`);return}if(this.path.length>1){let i=`Could not find target for read count: ${e}`;this.path.length<=2&&(i+=`, or couldn't find list item with the name ${this.path.join(",")}`),this.Error(i);return}t.ResolveVariableWithName(this.name,this).found||this.Error(`Unresolved variable: ${this.name}`,this);}};xi.VariableReference=Ms;});var Ze=p(Ai=>{Object.defineProperty(Ai,"__esModule",{value:true});Ai.FunctionCall=void 0;var Tt=z(),gc=Se(),Cc=ve(),vc=ct(),Sc=at(),yc=k(),Oi=Et(),nl=$n(),bc=Qt(),_c=k(),Ec=be(),Ti=O(),Ni=class s extends vc.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(t,e){super(),this._divertTargetToCount=null,this._variableReferenceToCount=null,this.shouldPopReturnedValue=false,this.GenerateIntoContainer=n=>{let i=this.story.ResolveList(this.name),a=false;if(this.isChoiceCount)this.args.length>0&&this.Error("The CHOICE_COUNT() function shouldn't take any arguments"),n.AddContent(Tt.ControlCommand.ChoiceCount());else if(this.isTurns)this.args.length>0&&this.Error("The TURNS() function shouldn't take any arguments"),n.AddContent(Tt.ControlCommand.Turns());else if(this.isTurnsSince||this.isReadCount){let r=(0, Ti.asOrNull)(this.args[0],Cc.DivertTarget),o=(0, Ti.asOrNull)(this.args[0],Ec.VariableReference);if(this.args.length!==1||r===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}r?(this._divertTargetToCount=r,this.AddContent(this._divertTargetToCount),this._divertTargetToCount.GenerateIntoContainer(n)):o&&(this._variableReferenceToCount=o,this.AddContent(this._variableReferenceToCount),this._variableReferenceToCount.GenerateIntoContainer(n)),this.isTurnsSince?n.AddContent(Tt.ControlCommand.TurnsSince()):n.AddContent(Tt.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 r=0;r<this.args.length;r+=1){let o=(0, Ti.asOrNull)(this.args[r],nl.NumberExpression);if(o&&!o.isInt()){let l=r===0?"minimum":"maximum";this.Error(`RANDOM's ${l} parameter should be an integer`);}this.args[r].GenerateIntoContainer(n);}n.AddContent(Tt.ControlCommand.Random());}else if(this.isSeedRandom){this.args.length!==1&&this.Error("SEED_RANDOM should take 1 parameter - an integer seed");let r=(0, Ti.asOrNull)(this.args[0],nl.NumberExpression);r&&!r.isInt()&&this.Error("SEED_RANDOM's parameter should be an integer seed"),this.args[0].GenerateIntoContainer(n),n.AddContent(Tt.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 r=0;r<this.args.length;r+=1)this.args[r].GenerateIntoContainer(n);n.AddContent(Tt.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(Tt.ControlCommand.ListRandom());else if(Oi.NativeFunctionCall.CallExistsWithName(this.name)){let r=Oi.NativeFunctionCall.CallWithName(this.name);if(r.numberOfParameters!==this.args.length){let o=`${s.name} should take ${r.numberOfParameters} parameter`;r.numberOfParameters>1&&(o+="s"),this.Error(o);}for(let o=0;o<this.args.length;o+=1)this.args[o].GenerateIntoContainer(n);n.AddContent(Oi.NativeFunctionCall.CallWithName(this.name));}else if(i!==null)if(this.args.length>1&&this.Error("Can currently only construct a list from one integer (or an empty list from a given list definition)"),this.args.length===1)n.AddContent(new _c.StringValue(this.name)),this.args[0].GenerateIntoContainer(n),n.AddContent(Tt.ControlCommand.ListFromInt());else {let r=new Sc.InkList;r.SetInitialOriginName(this.name),n.AddContent(new yc.ListValue(r));}else n.AddContent(this._proxyDivert.runtimeObject),a=true;a||this.content.splice(this.content.indexOf(this._proxyDivert),1),this.shouldPopReturnedValue&&n.AddContent(Tt.ControlCommand.PopEvaluatedValue());},this.toString=()=>{let n=this.args.join(", ");return `${this.name}(${n})`},this._proxyDivert=new gc.Divert(new bc.Path(t),e),this._proxyDivert.isFunctionCall=true,this.AddContent(this._proxyDivert);}get typeName(){return "FunctionCall"}ResolveReferences(t){if(super.ResolveReferences(t),!this.content.includes(this._proxyDivert)&&this.args!==null)for(let e of this.args)e.ResolveReferences(t);if(this._divertTargetToCount){let e=this._divertTargetToCount.divert,n=e.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(${e.runtimeDivert.variableDivertName})`);return}let i=e.targetContent;if(i===null)n||this.Error(`Failed to find target for TURNS_SINCE: '${e.target}'`);else {if(!i.containerForCounting)throw new Error;i.containerForCounting.turnIndexShouldBeCounted=true;}}else if(this._variableReferenceToCount){let e=this._variableReferenceToCount.runtimeVarRef;if(!e)throw new Error;e.pathForCount!==null&&this.Error(`Should be '${s.name}'(-> '${this._variableReferenceToCount.name}). Usage without the '->' only makes sense for variable targets.`);}}};Ai.FunctionCall=Ni;Ni.IsBuiltIn=s=>Oi.NativeFunctionCall.CallExistsWithName(s)?true:s==="CHOICE_COUNT"||s==="TURNS_SINCE"||s==="TURNS"||s==="RANDOM"||s==="SEED_RANDOM"||s==="LIST_VALUE"||s==="LIST_RANDOM"||s==="READ_COUNT";});var Gs=p(Ii=>{Object.defineProperty(Ii,"__esModule",{value:true});Ii.MultipleConditionExpression=void 0;var Pc=ct(),wc=Et(),Bs=class extends Pc.Expression{get subExpressions(){return this.content}constructor(t){super(),this.GenerateIntoContainer=e=>{let n=true;for(let i of this.subExpressions)i.GenerateIntoContainer(e),n||e.AddContent(wc.NativeFunctionCall.CallWithName("&&")),n=false;},this.AddContent(t);}get typeName(){return "MultipleConditionExpression"}};Ii.MultipleConditionExpression=Bs;});var ve=p(Fi=>{Object.defineProperty(Fi,"__esModule",{value:true});Fi.DivertTarget=void 0;var xc=fs(),Tc=me(),Oc=hi(),Nc=Hs(),Ac=k(),$s=ct(),Ic=wt(),il=Ze(),Fc=Gs(),rl=be(),Js=O(),Us=class s extends $s.Expression{get runtimeDivert(){if(!this._runtimeDivert)throw new Error;return this._runtimeDivert}get runtimeDivertTargetValue(){if(!this._runtimeDivertTargetValue)throw new Error;return this._runtimeDivertTargetValue}constructor(t){super(),this._runtimeDivert=null,this._runtimeDivertTargetValue=null,this.GenerateIntoContainer=e=>{this.divert.GenerateRuntimeObject(),this._runtimeDivert=this.divert.runtimeDivert,this._runtimeDivertTargetValue=new Ac.DivertTargetValue,e.AddContent(this.runtimeDivertTargetValue);},this.Equals=e=>{let n=(0, Js.asOrNull)(e,s);if(!n||!this.divert.target||!n.divert.target)return  false;let i=this.divert.target.dotSeparatedComponents,a=n.divert.target.dotSeparatedComponents;return i===a},this.divert=this.AddContent(t);}get typeName(){return "DivertTarget"}ResolveReferences(t){if(super.ResolveReferences(t),this.divert.isDone||this.divert.isEnd){this.Error("Can't use -> DONE or -> END as variable divert targets",this);return}let e=this;for(;e&&e instanceof $s.Expression;){let i=false,a=false,r=e.parent;if(r instanceof xc.BinaryExpression){let o=r;o.opName!=="=="&&o.opName!=="!="?i=true:(o.leftExpression instanceof s||o.leftExpression instanceof rl.VariableReference)&&(o.rightExpression instanceof s||o.rightExpression instanceof rl.VariableReference)||(i=true),a=true;}else if(r instanceof il.FunctionCall){let o=r;!o.isTurnsSince&&!o.isReadCount&&(i=true),a=true;}else (r instanceof $s.Expression||r instanceof Fc.MultipleConditionExpression||r instanceof Tc.Choice&&r.condition===e||r instanceof Oc.Conditional||r instanceof Nc.ConditionalSingleBranch)&&(i=true,a=true);if(i&&this.Error(`Can't use a divert target like that. Did you intend to call '${this.divert.target}' as a function: likeThis(), or check the read count: likeThis, with no arrows?`,this),a)break;e=r;}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 i=n.containerForCounting;if(i!==null){let r=(0, Js.asOrNull)(this.parent,il.FunctionCall);r&&r.isTurnsSince||(i.visitsShouldBeCounted=true),i.turnIndexShouldBeCounted=true;}let a=(0, Js.asOrNull)(n,Ic.FlowBase);if(a!=null&&a.args!==null)for(let r of a.args)r.isByReference&&this.Error(`Can't store a divert target to a knot or function that has by-reference arguments ('${a.identifier}' has 'ref ${r.identifier}').`);}}};Fi.DivertTarget=Us;});var Se=p(Vi=>{Object.defineProperty(Vi,"__esModule",{value:true});Vi.Divert=void 0;var Vc=L(),Qe=z(),Rc=Pt(),Ks=ve(),zs=wt(),kc=Ze(),Dc=R(),sl=Qt(),Wc=it(),al=Yt(),Lc=k(),ol=be(),qc=Ye(),tn=O(),Xs=class extends Dc.ParsedObject{get runtimeDivert(){if(!this._runtimeDivert)throw new Error;return this._runtimeDivert}set runtimeDivert(t){this._runtimeDivert=t;}get isEnd(){return !!(this.target&&this.target.dotSeparatedComponents==="END")}get isDone(){return !!(this.target&&this.target.dotSeparatedComponents==="DONE")}constructor(t,e){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 Qe.ControlCommand.End();if(this.isDone)return Qe.ControlCommand.Done();this.runtimeDivert=new Rc.Divert,this.ResolveTargetContent(),this.CheckArgumentValidity();let n=this.args!==null&&this.args.length>0;if(n||this.isFunctionCall||this.isTunnel||this.isThread){let i=new Vc.Container;if(n){this.isFunctionCall||i.AddContent(Qe.ControlCommand.EvalStart());let a=null;this.targetContent&&(a=this.targetContent.args);for(let r=0;r<this.args.length;++r){let o=this.args[r],l=null;if(a&&r<a.length&&(l=a[r]),l&&l.isByReference){let u=(0, tn.asOrNull)(o,ol.VariableReference);if(!u){this.Error(`Expected variable name to pass by reference to 'ref ${l.identifier}' but saw ${o}`);break}let h=new sl.Path(u.pathIdentifiers);if(h.ResolveFromContext(this)){this.Error(`can't pass a read count by reference. '${h.dotSeparatedComponents}' is a knot/stitch/label, but '${this.target.dotSeparatedComponents}' requires the name of a VAR to be passed.`);break}let d=new Lc.VariablePointerValue(u.name);i.AddContent(d);}else o.GenerateIntoContainer(i);}this.isFunctionCall||i.AddContent(Qe.ControlCommand.EvalEnd());}return this.isThread?i.AddContent(Qe.ControlCommand.StartThread()):(this.isFunctionCall||this.isTunnel)&&(this.runtimeDivert.pushesToStack=true,this.runtimeDivert.stackPushType=this.isFunctionCall?al.PushPopType.Function:al.PushPopType.Tunnel),i.AddContent(this.runtimeDivert),i}return this.runtimeDivert},this.PathAsVariableName=()=>this.target?this.target.firstComponent:null,this.ResolveTargetContent=()=>{if(!(this.isEmpty||this.isEnd)&&this.targetContent===null){let n=this.PathAsVariableName();if(n!==null){let i=(0, tn.asOrNull)((0, qc.ClosestFlowBase)(this),zs.FlowBase);if(i){let a=i.ResolveVariableWithName(n,this);if(a.found){if(a.isArgument&&a.ownerFlow&&a.ownerFlow.args){let r=a.ownerFlow.args.find(o=>{var l;return ((l=o.identifier)===null||l===void 0?void 0:l.name)==n});r&&!r.isDivertTarget&&this.Error(`Since '${r.identifier}' is used as a variable divert target (on ${this.debugMetadata}), it should be marked as: -> ${r.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 i=(0, tn.asOrNull)(this.targetContent,zs.FlowBase);if(n===0&&(i===null||!i.hasParameters))return;if(i===null&&n>0){this.Error("target needs to be a knot or stitch in order to pass arguments");return}else if(i!==null&&(i.args===null||!i.args&&n>0)){this.Error(`target (${i.name}) doesn't take parameters`);return}else if(this.parent instanceof Ks.DivertTarget){n>0&&this.Error("can't store arguments in a divert target variable");return}let a=i.args.length;if(a!==n){let r;n===0?r="but there weren't any passed to it":n<a?r=`but only got ${n}`:r=`but got ${n}`,this.Error(`to '${i.identifier}' requires ${a} arguments, ${r}`);return}for(let r=0;r<a;++r){let o=i.args[r],l=this.args[r];if(o.isDivertTarget){let u=(0, tn.asOrNull)(l,ol.VariableReference);if(!(l instanceof Ks.DivertTarget)&&u===null)this.Error(`Target '${i.identifier}' expects a divert target for the parameter named -> ${o.identifier} but saw ${l}`,l);else if(u){let h=new sl.Path(u.pathIdentifiers);h.ResolveFromContext(u)&&this.Error(`Passing read count of '${h.dotSeparatedComponents}' instead of a divert target. You probably meant '${h}'`);}}}if(i===null){this.Error("Can't call as a function or with arguments unless it's a knot or stitch");return}},this.CheckExternalArgumentValidity=n=>{let i=this.target?this.target.firstComponent:null,a=n.externals.get(i);if(!a)throw new Error("external not found");let r=a.argumentNames.length,o=0;this.args&&(o=this.args.length),o!==r&&this.Error(`incorrect number of arguments sent to external function '${i}'. Expected ${r} 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},t&&(this.target=t),e&&(this.args=e,this.AddContent(e));}get typeName(){return "Divert"}ResolveReferences(t){if(this.isEmpty||this.isEnd||this.isDone)return;if(!this.runtimeDivert)throw new Error;this.targetContent&&(this.runtimeDivert.targetPath=this.targetContent.runtimePath),super.ResolveReferences(t);let e=(0, tn.asOrNull)(this.targetContent,zs.FlowBase);e&&(!e.isFunction&&this.isFunctionCall?super.Error(`${e.identifier} hasn't been marked as a function, but it's being called as one. Do you need to declare the knot as '== function ${e.identifier} =='?`):e.isFunction&&!this.isFunctionCall&&!(this.parent instanceof Ks.DivertTarget)&&super.Error(e.identifier+" can't be diverted to. It can only be called as a function since it's been marked as such: '"+e.identifier+"(...)'"));let n=this.targetContent!==null,i=false,a=false;if(this.target){if(this.target.numberOfComponents===1){if(!this.target.firstComponent)throw new Error;if(i=kc.FunctionCall.IsBuiltIn(this.target.firstComponent),a=t.IsExternal(this.target.firstComponent),i||a){this.isFunctionCall||super.Error(`${this.target.firstComponent} must be called as a function: ~ ${this.target.firstComponent}()`),a&&(this.runtimeDivert.isExternal=true,this.args!==null&&(this.runtimeDivert.externalArgs=this.args.length),this.runtimeDivert.pushesToStack=false,this.runtimeDivert.targetPath=new Wc.Path(this.target.firstComponent),this.CheckExternalArgumentValidity(t));return}}}else throw new Error;this.runtimeDivert.variableDivertName==null&&!n&&!i&&!a&&this.Error(`target not found: '${this.target}'`);}Error(t,e=null,n=false){if(e!==this&&e){super.Error(t,e);return}this.isFunctionCall?super.Error(`Function call ${t}`,e,n):super.Error(`Divert ${t}`,e,n);}};Vi.Divert=Xs;});var ll=p(Ri=>{Object.defineProperty(Ri,"__esModule",{value:true});Ri.GatherPointToResolve=void 0;var Ys=class{constructor(t,e){this.divert=t,this.targetRuntimeObj=e;}};Ri.GatherPointToResolve=Ys;});var ul=p(ki=>{Object.defineProperty(ki,"__esModule",{value:true});ki.SequenceDivertToResolve=void 0;var Zs=class{constructor(t,e){this.divert=t,this.targetContent=e;}};ki.SequenceDivertToResolve=Zs;});var Qs=p(Di=>{Object.defineProperty(Di,"__esModule",{value:true});Di.SequenceType=void 0;var hl;(function(s){s[s.Stopping=1]="Stopping",s[s.Cycle=2]="Cycle",s[s.Shuffle=4]="Shuffle",s[s.Once=8]="Once";})(hl||(Di.SequenceType=hl={}));});var na=p(qi=>{Object.defineProperty(qi,"__esModule",{value:true});qi.Sequence=void 0;var cl=L(),Ct=z(),ta=Pt(),en=k(),Wi=Et(),jc=R(),Mc=ul(),Li=Qs(),Bc=te(),ea=class extends jc.ParsedObject{constructor(t,e){super(),this.sequenceType=e,this._sequenceDivertsToResolve=[],this.GenerateRuntimeObject=()=>{let n=new cl.Container;n.visitsShouldBeCounted=true,n.countingAtStartOnly=true,this._sequenceDivertsToResolve=[],n.AddContent(Ct.ControlCommand.EvalStart()),n.AddContent(Ct.ControlCommand.VisitIndex());let i=(this.sequenceType&Li.SequenceType.Once)>0,a=(this.sequenceType&Li.SequenceType.Cycle)>0,r=(this.sequenceType&Li.SequenceType.Stopping)>0,o=(this.sequenceType&Li.SequenceType.Shuffle)>0,l=this.sequenceElements.length;if(i&&(l+=1),r||i?(n.AddContent(new en.IntValue(l-1)),n.AddContent(Wi.NativeFunctionCall.CallWithName("MIN"))):a&&(n.AddContent(new en.IntValue(this.sequenceElements.length)),n.AddContent(Wi.NativeFunctionCall.CallWithName("%"))),o){let h=Ct.ControlCommand.NoOp();if(i||r){let d=r?this.sequenceElements.length-1:this.sequenceElements.length;n.AddContent(Ct.ControlCommand.Duplicate()),n.AddContent(new en.IntValue(d)),n.AddContent(Wi.NativeFunctionCall.CallWithName("=="));let m=new ta.Divert;m.isConditional=true,n.AddContent(m),this.AddDivertToResolve(m,h);}let c=this.sequenceElements.length;r&&(c-=1),n.AddContent(new en.IntValue(c)),n.AddContent(Ct.ControlCommand.SequenceShuffleIndex()),(i||r)&&n.AddContent(h);}n.AddContent(Ct.ControlCommand.EvalEnd());let u=Ct.ControlCommand.NoOp();for(let h=0;h<l;h+=1){n.AddContent(Ct.ControlCommand.EvalStart()),n.AddContent(Ct.ControlCommand.Duplicate()),n.AddContent(new en.IntValue(h)),n.AddContent(Wi.NativeFunctionCall.CallWithName("==")),n.AddContent(Ct.ControlCommand.EvalEnd());let c=new ta.Divert;c.isConditional=true,n.AddContent(c);let d;h<this.sequenceElements.length?d=this.sequenceElements[h].runtimeObject:d=new cl.Container,d.name=`s${h}`,d.InsertContent(Ct.ControlCommand.PopEvaluatedValue(),0);let m=new ta.Divert;d.AddContent(m),n.AddToNamedContentOnly(d),this.AddDivertToResolve(c,d),this.AddDivertToResolve(m,u);}return n.AddContent(u),n},this.AddDivertToResolve=(n,i)=>{this._sequenceDivertsToResolve.push(new Mc.SequenceDivertToResolve(n,i));},this.sequenceType=e,this.sequenceElements=[];for(let n of t){let i=n.content,a=null;i===null||i.length===0?a=n:a=new Bc.Weave(i),this.sequenceElements.push(a),this.AddContent(a);}}get typeName(){return "Sequence"}ResolveReferences(t){super.ResolveReferences(t);for(let e of this._sequenceDivertsToResolve)e.divert.targetPath=e.targetContent.path;}};qi.Sequence=ea;});var ra=p(ji=>{Object.defineProperty(ji,"__esModule",{value:true});ji.TunnelOnwards=void 0;var Gc=L(),nn=z(),$c=Pt(),Jc=k(),Uc=R(),Hc=Xt(),Kc=O(),zc=ye(),ia=class extends Uc.ParsedObject{constructor(){super(...arguments),this._overrideDivertTarget=null,this._divertAfter=null,this.GenerateRuntimeObject=()=>{let t=new Gc.Container;if(t.AddContent(nn.ControlCommand.EvalStart()),this.divertAfter){let e=this.divertAfter.GenerateRuntimeObject(),n=e;if(n){let a=this.divertAfter.args;if(a!==null&&a.length>0){let r=-1,o=-1;for(let l=0;l<n.content.length;l+=1){let u=n.content[l];u&&(r==-1&&u.commandType===nn.ControlCommand.CommandType.EvalStart?r=l:u.commandType===nn.ControlCommand.CommandType.EvalEnd&&(o=l));}for(let l=r+1;l<o;l+=1){let u=n.content[l];u.parent=null,t.AddContent(n.content[l]);}}}let i=(0, Kc.asOrNull)(e,$c.Divert);if(i!=null&&i.hasVariableTarget){let a=new zc.VariableReference(i.variableDivertName);t.AddContent(a);}else this._overrideDivertTarget=new Jc.DivertTargetValue,t.AddContent(this._overrideDivertTarget);}else t.AddContent(new Hc.Void);return t.AddContent(nn.ControlCommand.EvalEnd()),t.AddContent(nn.ControlCommand.PopTunnel()),t},this.toString=()=>` -> ${this._divertAfter}`;}get divertAfter(){return this._divertAfter}set divertAfter(t){this._divertAfter=t,this._divertAfter&&this.AddContent(this._divertAfter);}get typeName(){return "TunnelOnwards"}ResolveReferences(t){super.ResolveReferences(t),this.divertAfter&&this.divertAfter.targetContent&&(this._overrideDivertTarget.targetPath=this.divertAfter.targetContent.runtimePath);}};ji.TunnelOnwards=ia;});var oa=p(Mi=>{Object.defineProperty(Mi,"__esModule",{value:true});Mi.ListDefinition=void 0;var sa=at(),aa=class{constructor(t,e){this._name=t||"",this._items=null,this._itemNameToValues=e||new Map;}get name(){return this._name}get items(){if(this._items==null){this._items=new Map;for(let[t,e]of this._itemNameToValues){let n=new sa.InkListItem(this.name,t);this._items.set(n.serialized(),e);}}return this._items}ValueForItem(t){if(!t.itemName)return 0;let e=this._itemNameToValues.get(t.itemName);return typeof e<"u"?e:0}ContainsItem(t){return !t.itemName||t.originName!=this.name?false:this._itemNameToValues.has(t.itemName)}ContainsItemWithName(t){return this._itemNameToValues.has(t)}TryGetItemWithValue(t,e){for(let[n,i]of this._itemNameToValues)if(i==t)return e=new sa.InkListItem(this.name,n),{result:e,exists:true};return e=sa.InkListItem.Null,{result:e,exists:false}}TryGetValueForItem(t,e){if(!t.itemName)return {result:0,exists:false};let n=this._itemNameToValues.get(t.itemName);return n?{result:n,exists:true}:{result:0,exists:false}}};Mi.ListDefinition=aa;});var Gi=p(Bi=>{Object.defineProperty(Bi,"__esModule",{value:true});Bi.ListDefinition=void 0;var Xc=at(),Yc=at(),Zc=oa(),Qc=k(),td=R(),ed=Ft(),la=class extends td.ParsedObject{get typeName(){return "ListDefinition"}get runtimeListDefinition(){var t;let e=new Map;for(let n of this.itemDefinitions)e.has(n.name)?this.Error(`List '${this.identifier}' contains duplicate items called '${n.name}'`):e.set(n.name,n.seriesValue);return new Zc.ListDefinition(((t=this.identifier)===null||t===void 0?void 0:t.name)||"",e)}constructor(t){super(),this.itemDefinitions=t,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,i;let a=new Xc.InkList;for(let r of this.itemDefinitions)if(r.inInitialList){let o=new Yc.InkListItem(((n=this.identifier)===null||n===void 0?void 0:n.name)||null,r.name||null);a.Add(o,r.seriesValue);}return a.SetInitialOriginName(((i=this.identifier)===null||i===void 0?void 0:i.name)||""),new Qc.ListValue(a)};let e=1;for(let n of this.itemDefinitions)n.explicitValue!==null&&(e=n.explicitValue),n.seriesValue=e,e+=1;this.AddContent(t);}ResolveReferences(t){super.ResolveReferences(t),t.CheckForNamingCollisions(this,this.identifier,ed.SymbolType.List);}};Bi.ListDefinition=la;});var ha=p($i=>{Object.defineProperty($i,"__esModule",{value:true});$i.VariableAssignment=void 0;var nd=L(),id=Ye(),rd=Gi(),sd=R(),dl=Ft(),ad=Lt(),od=be(),ld=O(),ua=class extends sd.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:t,isGlobalDeclaration:e,isTemporaryNewDeclaration:n,listDef:i,variableIdentifier:a}){super(),this._runtimeAssignment=null,this.expression=null,this.listDefinition=null,this.GenerateRuntimeObject=()=>{let r=null;if(this.isGlobalDeclaration?r=this.story:this.isNewTemporaryDeclaration&&(r=(0, id.ClosestFlowBase)(this)),r&&r.AddNewVariableDeclaration(this),this.isGlobalDeclaration)return null;let o=new nd.Container;return this.expression?o.AddContent(this.expression.runtimeObject):this.listDefinition&&o.AddContent(this.listDefinition.runtimeObject),this._runtimeAssignment=new ad.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=!!e,this.isNewTemporaryDeclaration=!!n,i instanceof rd.ListDefinition?(this.listDefinition=this.AddContent(i),this.listDefinition.variableAssignment=this,this.isGlobalDeclaration=true):t&&(this.expression=this.AddContent(t));}ResolveReferences(t){if(super.ResolveReferences(t),this.isDeclaration&&this.listDefinition===null&&t.CheckForNamingCollisions(this,this.variableIdentifier,this.isGlobalDeclaration?dl.SymbolType.Var:dl.SymbolType.Temp),this.isGlobalDeclaration){let e=(0, ld.asOrNull)(this.expression,od.VariableReference);e&&!e.isConstantReference&&!e.isListItemReference&&this.Error("global variable assignments cannot refer to other variables, only literal values, constants and list items");}if(!this.isNewTemporaryDeclaration){let e=t.ResolveVariableWithName(this.variableName,this);e.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=e.isGlobal);}}};$i.VariableAssignment=ua;});var te=p(Hi=>{Object.defineProperty(Hi,"__esModule",{value:true});Hi.Weave=void 0;var fl=On(),ft=me(),Ji=hi(),ud=fi(),hd=L(),Ui=Se(),cd=Pt(),dd=ve(),fd=wt(),Ot=Xe(),pd=ll(),md=R(),ca=na(),gd=jt(),Cd=ra(),vd=ha(),pt=O(),da=class s extends md.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 t=null;for(let n=this.content.length-1;n>=0;--n){t=this.content[n];let i=(0, pt.asOrNull)(t,gd.Text);if(!(i&&i.text===`
`)&&!this.IsGlobalDeclaration(t))break}let e=(0, pt.asOrNull)(t,s);return e&&(t=e.lastParsedSignificantObject),t}constructor(t,e=-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,i,a;let r=[...this.FindAll(Ot.Gather)(o=>!(o.name===null||o.name===void 0)),...this.FindAll(ft.Choice)(o=>!(o.name===null||o.name===void 0))];this._namedWeavePoints=new Map;for(let o of r){let l=this.namedWeavePoints.get(((n=o.identifier)===null||n===void 0?void 0:n.name)||"");if(l){let u=l instanceof Ot.Gather?"gather":"choice",h=l;this.Error(`A ${u} with the same label name '${o.name}' already exists in this context on line ${h.debugMetadata?h.debugMetadata.startLineNumber:"NO DEBUG METADATA AVAILABLE"}`,o);}!((i=o.identifier)===null||i===void 0)&&i.name&&this.namedWeavePoints.set((a=o.identifier)===null||a===void 0?void 0:a.name,o);}},this.ConstructWeaveHierarchyFromIndentation=()=>{let n=0;for(;n<this.content.length;){let i=this.content[n];if(i instanceof ft.Choice||i instanceof Ot.Gather){let r=i.indentationDepth-1;if(r>this.baseIndentIndex){let o=n;for(;n<this.content.length;){let c=(0, pt.asOrNull)(this.content[n],ft.Choice)||(0, pt.asOrNull)(this.content[n],Ot.Gather);if(c!==null&&c.indentationDepth-1<=this.baseIndentIndex)break;n+=1;}let l=n-o,u=this.content.slice(o,o+l);this.content.splice(o,l);let h=new s(u,r);this.InsertContent(o,h),n=o;}}n+=1;}},this.DetermineBaseIndentationFromContent=n=>{for(let i of n)if(i instanceof ft.Choice||i instanceof Ot.Gather)return i.indentationDepth-1;return 0},this.GenerateRuntimeObject=()=>{this._rootContainer=new hd.Container,this.currentContainer=this._rootContainer,this.looseEnds=[],this.gatherPointsToResolve=[];for(let n of this.content)if(n instanceof ft.Choice||n instanceof Ot.Gather)this.AddRuntimeForWeavePoint(n);else if(n instanceof s){let i=n;this.AddRuntimeForNestedWeave(i),this.gatherPointsToResolve.splice(0,0,...i.gatherPointsToResolve);}else this.AddGeneralRuntimeContent(n.runtimeObject);return this.PassLooseEndsToAncestors(),this._rootContainer},this.AddRuntimeForGather=n=>{let i=!this.hasSeenChoiceInSection;this.hasSeenChoiceInSection=false;let a=n.runtimeContainer;if(n.name||(a.name=`g-${this._unnamedGatherCount}`,this._unnamedGatherCount+=1),i){if(!this.currentContainer)throw new Error;this.currentContainer.AddContent(a);}else this.rootContainer.AddToNamedContentOnly(a);for(let r of this.looseEnds){let o=r;if(o instanceof Ot.Gather&&o.indentationDepth==n.indentationDepth)continue;let l=null;if(o instanceof Ui.Divert)l=o.runtimeObject;else {l=new cd.Divert;let u=o;if(!u.runtimeContainer)throw new Error;u.runtimeContainer.AddContent(l);}this.gatherPointsToResolve.push(new pd.GatherPointToResolve(l,a));}this.looseEnds=[],this.currentContainer=a;},this.AddRuntimeForWeavePoint=n=>{if(n instanceof Ot.Gather)this.AddRuntimeForGather(n);else if(n instanceof ft.Choice){if(!this.currentContainer)throw new Error;this.previousWeavePoint instanceof Ot.Gather&&this.looseEnds.splice(this.looseEnds.indexOf(this.previousWeavePoint),1);let i=n;if(this.currentContainer.AddContent(i.runtimeObject),!i.innerContentContainer)throw new Error;i.innerContentContainer.name=`c-${this._choiceCount}`,this.currentContainer.AddToNamedContentOnly(i.innerContentContainer),this._choiceCount+=1,this.hasSeenChoiceInSection=true;}this.addContentToPreviousWeavePoint=false,this.WeavePointHasLooseEnd(n)&&(this.looseEnds.push(n),(0, pt.asOrNull)(n,ft.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,i=null,a=false;for(let r=this.parent;r!==null;r=r.parent){let o=(0, pt.asOrNull)(r,s);o&&(!a&&n===null&&(n=o),a&&i===null&&(i=o)),(r instanceof ca.Sequence||r instanceof Ji.Conditional)&&(a=true);}if(!(n===null&&i===null))for(let r=this.looseEnds.length-1;r>=0;r-=1){let o=this.looseEnds[r],l=false;if(a){if(o instanceof ft.Choice&&n!==null)n.ReceiveLooseEnd(o),l=true;else if(!(o instanceof ft.Choice)){let u=n||i;u!==null&&(u.ReceiveLooseEnd(o),l=true);}}else n?.hasOwnProperty("ReceiveLooseEnd")&&n.ReceiveLooseEnd(o),l=true;l&&this.looseEnds.splice(r,1);}},this.ReceiveLooseEnd=n=>{this.looseEnds.push(n);},this.WeavePointNamed=n=>{if(!this.namedWeavePoints)return null;let i=this.namedWeavePoints.get(n);return i||null},this.IsGlobalDeclaration=n=>{let i=(0, pt.asOrNull)(n,vd.VariableAssignment);return !!(i&&i.isGlobalDeclaration&&i.isDeclaration||(0, pt.asOrNull)(n,ud.ConstantDeclaration))},this.ContentThatFollowsWeavePoint=n=>{let i=[],a=n;if(a.content!==null)for(let l of a.content)this.IsGlobalDeclaration(l)||i.push(l);let r=(0, pt.asOrNull)(a.parent,s);if(r===null)throw new Error("Expected weave point parent to be weave?");let o=r.content.indexOf(a);for(let l=o+1;l<r.content.length;l+=1){let u=r.content[l];if(!this.IsGlobalDeclaration(u)){if(u instanceof ft.Choice||u instanceof Ot.Gather||u instanceof s)break;i.push(u);}}return i},this.ValidateTermination=n=>{if(this.lastParsedSignificantObject instanceof fl.AuthorWarning)return;if(this.looseEnds!==null&&this.looseEnds.length>0)for(let a of this.looseEnds){let r=this.ContentThatFollowsWeavePoint(a);this.ValidateFlowOfObjectsTerminates(r,a,n);}else {for(let a of this.content)if(a instanceof ft.Choice||a instanceof Ui.Divert)return;this.ValidateFlowOfObjectsTerminates(this.content,this,n);}},this.BadNestedTerminationHandler=n=>{let i=null;for(let r=n.parent;r!==null;r=r.parent)if(r instanceof ca.Sequence||r instanceof Ji.Conditional){i=(0, pt.asOrNull)(r,Ji.Conditional);break}let a="Choices nested in conditionals or sequences need to explicitly divert afterwards.";i!==null&&i.FindAll(ft.Choice)().length===1&&(a=`Choices with conditions should be written: '* {condition} choice'. Otherwise, ${a.toLowerCase()}`),this.Error(a,n);},this.ValidateFlowOfObjectsTerminates=(n,i,a)=>{let r=false,o=i;for(let l of n){if(l.Find(Ui.Divert)(h=>!h.isThread&&!h.isTunnel&&!h.isFunctionCall&&!(h.parent instanceof dd.DivertTarget))!==null&&(r=true),l.Find(Cd.TunnelOnwards)()!=null){r=true;break}o=l;}if(!r){if(o instanceof fl.AuthorWarning)return;a(o);}},this.WeavePointHasLooseEnd=n=>{if(n.content===null)return  true;for(let i=n.content.length-1;i>=0;--i){let a=(0, pt.asOrNull)(n.content[i],Ui.Divert);if(a&&!(a.isThread||a.isTunnel||a.isFunctionCall))return  false}return  true},this.CheckForWeavePointNamingCollisions=()=>{if(!this.namedWeavePoints)return;let n=[];for(let i of this.ancestry){let a=(0, pt.asOrNull)(i,fd.FlowBase);if(a)n.push(a);else break}for(let[i,a]of this.namedWeavePoints)for(let r of n){let o=r.ContentWithNameAtLevel(i);if(o&&o!==a){let l=`${a.GetType()} '${i}' has the same label name as a ${o.GetType()} (on ${o.debugMetadata})`;this.Error(l,a);}}},e==-1?this.baseIndentIndex=this.DetermineBaseIndentationFromContent(t):this.baseIndentIndex=e,this.AddContent(t),this.ConstructWeaveHierarchyFromIndentation();}get typeName(){return "Weave"}ResolveReferences(t){if(super.ResolveReferences(t),this.looseEnds!==null&&this.looseEnds.length>0){let e=false;for(let n=this.parent;n!==null;n=n.parent)if(n instanceof ca.Sequence||n instanceof Ji.Conditional){e=true;break}e&&this.ValidateTermination(this.BadNestedTerminationHandler);}for(let e of this.gatherPointsToResolve)e.divert.targetPath=e.targetRuntimeObj.path;this.CheckForWeavePointNamingCollisions();}};Hi.Weave=da;});var Hs=p(zi=>{Object.defineProperty(zi,"__esModule",{value:true});zi.ConditionalSingleBranch=void 0;var pl=L(),Ki=z(),ml=Pt(),Sd=R(),yd=Et(),bd=k(),_d=jt(),Ed=te(),Pd=O(),fa=class extends Sd.ParsedObject{get ownExpression(){return this._ownExpression}set ownExpression(t){this._ownExpression=t,this._ownExpression&&this.AddContent(this._ownExpression);}constructor(t){super(),this._contentContainer=null,this._conditionalDivert=null,this._ownExpression=null,this._innerWeave=null,this.isTrueBranch=false,this.matchingEquality=false,this.isElse=false,this.isInline=false,this.returnDivert=null,this.GenerateRuntimeObject=()=>{if(this._innerWeave)for(let i of this._innerWeave.content){let a=(0, Pd.asOrNull)(i,_d.Text);a&&a.text.startsWith("else:")&&this.Warning("Saw the text 'else:' which is being treated as content. Did you mean '- else:'?",a);}let e=new pl.Container,n=this.matchingEquality&&!this.isElse;if(n&&e.AddContent(Ki.ControlCommand.Duplicate()),this._conditionalDivert=new ml.Divert,this._conditionalDivert.isConditional=!this.isElse,!this.isTrueBranch&&!this.isElse){let i=this.ownExpression!==null;i&&e.AddContent(Ki.ControlCommand.EvalStart()),this.ownExpression&&this.ownExpression.GenerateIntoContainer(e),this.matchingEquality&&e.AddContent(yd.NativeFunctionCall.CallWithName("==")),i&&e.AddContent(Ki.ControlCommand.EvalEnd());}return e.AddContent(this._conditionalDivert),this._contentContainer=this.GenerateRuntimeForContent(),this._contentContainer.name="b",this.isInline||this._contentContainer.InsertContent(new bd.StringValue(`
`),0),(n||this.isElse&&this.matchingEquality)&&this._contentContainer.InsertContent(Ki.ControlCommand.PopEvaluatedValue(),0),e.AddToNamedContentOnly(this._contentContainer),this.returnDivert=new ml.Divert,this._contentContainer.AddContent(this.returnDivert),e},this.GenerateRuntimeForContent=()=>this._innerWeave===null?new pl.Container:this._innerWeave.rootContainer,t&&(this._innerWeave=new Ed.Weave(t),this.AddContent(this._innerWeave));}get typeName(){return "ConditionalSingleBranch"}ResolveReferences(t){if(!this._conditionalDivert||!this._contentContainer)throw new Error;this._conditionalDivert.targetPath=this._contentContainer.path,super.ResolveReferences(t);}};zi.ConditionalSingleBranch=fa;});var Cl=p(Xi=>{Object.defineProperty(Xi,"__esModule",{value:true});Xi.CustomFlags=void 0;var gl;(function(s){s[s.ParsingString=1]="ParsingString",s[s.TagActive=2]="TagActive";})(gl||(Xi.CustomFlags=gl={}));});var vl=p(Yi=>{Object.defineProperty(Yi,"__esModule",{value:true});Yi.DebugMetadata=void 0;var pa=class s{constructor(){this.startLineNumber=0,this.endLineNumber=0,this.startCharacterNumber=0,this.endCharacterNumber=0,this.fileName=null,this.sourceName=null;}Merge(t){let e=new s;return e.fileName=this.fileName,e.sourceName=this.sourceName,this.startLineNumber<t.startLineNumber?(e.startLineNumber=this.startLineNumber,e.startCharacterNumber=this.startCharacterNumber):this.startLineNumber>t.startLineNumber?(e.startLineNumber=t.startLineNumber,e.startCharacterNumber=t.startCharacterNumber):(e.startLineNumber=this.startLineNumber,e.startCharacterNumber=Math.min(this.startCharacterNumber,t.startCharacterNumber)),this.endLineNumber>t.endLineNumber?(e.endLineNumber=this.endLineNumber,e.endCharacterNumber=this.endCharacterNumber):this.endLineNumber<t.endLineNumber?(e.endLineNumber=t.endLineNumber,e.endCharacterNumber=t.endCharacterNumber):(e.endLineNumber=this.endLineNumber,e.endCharacterNumber=Math.max(this.endCharacterNumber,t.endCharacterNumber)),e}toString(){return this.fileName!==null?`line ${this.startLineNumber} of ${this.fileName}"`:"line "+this.startLineNumber}};Yi.DebugMetadata=pa;});var Sl=p(Zi=>{Object.defineProperty(Zi,"__esModule",{value:true});Zi.ExternalDeclaration=void 0;var wd=R(),ma=class extends wd.ParsedObject{get name(){var t;return ((t=this.identifier)===null||t===void 0?void 0:t.name)||null}constructor(t,e){super(),this.identifier=t,this.argumentNames=e,this.GenerateRuntimeObject=()=>(this.story.AddExternal(this),null);}get typeName(){return "EXTERNAL"}toString(){var t;return `EXTERNAL ${(t=this.identifier)===null||t===void 0?void 0:t.name}`}};Zi.ExternalDeclaration=ma;});var yl=p(Qi=>{Object.defineProperty(Qi,"__esModule",{value:true});Qi.FlowDecl=void 0;var ga=class{constructor(t,e,n){this.name=t,this.args=e,this.isFunction=n;}};Qi.FlowDecl=ga;});var va=p(tr=>{Object.defineProperty(tr,"__esModule",{value:true});tr.Wrap=void 0;var xd=R(),Ca=class extends xd.ParsedObject{constructor(t){super(),this._objToWrap=t,this.GenerateRuntimeObject=()=>this._objToWrap;}};tr.Wrap=Ca;});var bl=p(er=>{Object.defineProperty(er,"__esModule",{value:true});er.Glue=void 0;var Td=va(),Sa=class extends Td.Wrap{constructor(t){super(t);}get typeName(){return "Glue"}};er.Glue=Sa;});var ir=p(nr=>{Object.defineProperty(nr,"__esModule",{value:true});nr.Glue=void 0;var Od=rt(),ya=class extends Od.InkObject{toString(){return "Glue"}};nr.Glue=ya;});var El=p(rr=>{Object.defineProperty(rr,"__esModule",{value:true});rr.IncDecExpression=void 0;var Nd=Pi(),_l=ct(),Ad=wt(),Id=Et(),Fd=k(),Vd=Lt(),Rd=ye(),kd=te(),ba=class extends _l.Expression{constructor(t,e,n){super(),this.varIdentifier=t,this._runtimeAssignment=null,this.expression=null,this.GenerateIntoContainer=i=>{var a,r;i.AddContent(new Rd.VariableReference(((a=this.varIdentifier)===null||a===void 0?void 0:a.name)||null)),this.expression?this.expression.GenerateIntoContainer(i):i.AddContent(new Fd.IntValue(1)),i.AddContent(Id.NativeFunctionCall.CallWithName(this.isInc?"+":"-")),this._runtimeAssignment=new Vd.VariableAssignment(((r=this.varIdentifier)===null||r===void 0?void 0:r.name)||null,false),i.AddContent(this._runtimeAssignment);},this.toString=()=>{var i,a;return this.expression?`${(i=this.varIdentifier)===null||i===void 0?void 0:i.name}${this.isInc?" += ":" -= "}${this.expression}`:`${(a=this.varIdentifier)===null||a===void 0?void 0:a.name}`+(this.isInc?"++":"--")},e instanceof _l.Expression?(this.expression=e,this.AddContent(this.expression),this.isInc=!!n):this.isInc=e;}get typeName(){return "IncDecExpression"}ResolveReferences(t){var e;super.ResolveReferences(t);let n=t.ResolveVariableWithName(((e=this.varIdentifier)===null||e===void 0?void 0:e.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 kd.Weave)&&!(this.parent instanceof Ad.FlowBase)&&!(this.parent instanceof Nd.ContentList)&&this.Error(`Can't use ${this.incrementDecrementWord} as sub-expression`);}get incrementDecrementWord(){return this.isInc?"increment":"decrement"}};rr.IncDecExpression=ba;});var Ea=p(sr=>{Object.defineProperty(sr,"__esModule",{value:true});sr.IncludedFile=void 0;var Dd=R(),_a=class extends Dd.ParsedObject{constructor(t){super(),this.includedStory=t,this.GenerateRuntimeObject=()=>null;}get typeName(){return "IncludedFile"}};sr.IncludedFile=_a;});var Pl=p(ar=>{Object.defineProperty(ar,"__esModule",{value:true});ar.InfixOperator=void 0;var Pa=class{constructor(t,e,n){this.type=t,this.precedence=e,this.requireWhitespace=n,this.toString=()=>this.type;}};ar.InfixOperator=Pa;});var xa=p(or=>{Object.defineProperty(or,"__esModule",{value:true});or.Knot=void 0;var Wd=wt(),wl=ge(),wa=class extends Wd.FlowBase{get flowLevel(){return wl.FlowLevel.Knot}constructor(t,e,n,i){super(t,e,n,i);}get typeName(){return this.isFunction?"Function":"Knot"}ResolveReferences(t){super.ResolveReferences(t);let e=this.story;for(let n in this.subFlowsByName){let i=e.ContentWithNameAtLevel(n,wl.FlowLevel.Knot,false);if(i){let a=this.subFlowsByName.get(n),r=`Stitch '${a?a.name:"NO STITCH FOUND"}' has the same name as a knot (on ${i.debugMetadata})`;this.Error(r,a);}}}};or.Knot=wa;});var xl=p(lr=>{Object.defineProperty(lr,"__esModule",{value:true});lr.List=void 0;var Ld=ct(),qd=at(),jd=at(),Md=k(),Ta=class extends Ld.Expression{constructor(t){super(),this.itemIdentifierList=t,this.GenerateIntoContainer=e=>{var n,i;let a=new qd.InkList;if(this.itemIdentifierList!=null)for(let r of this.itemIdentifierList){let o=((n=r?.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 h=this.story.ResolveListItem(l,u,this);if(h===null)l===null?this.Error(`Could not find list definition that contains item '${r}'`):this.Error(`Could not find list item ${r}`);else {if(h.parent==null){this.Error(`Could not find list definition for item ${r}`);return}l||(l=((i=h.parent.identifier)===null||i===void 0?void 0:i.name)||null);let c=new jd.InkListItem(l,h.name||null);a.has(c.serialized())?this.Warning(`Duplicate of item '${r}' in list.`):a.Add(c,h.seriesValue);}}e.AddContent(new Md.ListValue(a));};}get typeName(){return "List"}};lr.List=Ta;});var Na=p(ur=>{Object.defineProperty(ur,"__esModule",{value:true});ur.ListElementDefinition=void 0;var Bd=R(),Gd=Ft(),Oa=class extends Bd.ParsedObject{get fullName(){var t;let e=this.parent;if(e===null)throw new Error("Can't get full name without a parent list.");return `${(t=e.identifier)===null||t===void 0?void 0:t.name}.${this.name}`}get typeName(){return "ListElement"}get name(){var t;return ((t=this.indentifier)===null||t===void 0?void 0:t.name)||null}constructor(t,e,n=null){super(),this.indentifier=t,this.inInitialList=e,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(t){super.ResolveReferences(t),t.CheckForNamingCollisions(this,this.indentifier,Gd.SymbolType.ListItem);}};ur.ListElementDefinition=Oa;});var Aa=p(hr=>{Object.defineProperty(hr,"__esModule",{value:true});hr.StatementLevel=void 0;var Tl;(function(s){s[s.InnerBlock=0]="InnerBlock",s[s.Stitch=1]="Stitch",s[s.Knot=2]="Knot",s[s.Top=3]="Top";})(Tl||(hr.StatementLevel=Tl={}));});var Fa=p(cr=>{Object.defineProperty(cr,"__esModule",{value:true});cr.Stitch=void 0;var $d=wt(),Jd=ge(),Ia=class extends $d.FlowBase{get flowLevel(){return Jd.FlowLevel.Stitch}constructor(t,e,n,i){super(t,e,n,i),this.baseToString=this.toString,this.toString=()=>`${this.parent!==null?this.parent+" > ":""}${this.baseToString()}`;}get typeName(){return "Stitch"}};cr.Stitch=Ia;});var fr=p(dr=>{Object.defineProperty(dr,"__esModule",{value:true});dr.Tag=void 0;var Ud=rt(),Va=class extends Ud.InkObject{constructor(t){super(),this.text=t.toString()||"";}toString(){return "# "+this.text}};dr.Tag=Va;});var ka=p(pr=>{Object.defineProperty(pr,"__esModule",{value:true});pr.Choice=void 0;var Hd=it(),Kd=K(),zd=rt(),Ra=class s extends zd.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, Kd.throwNullException)("Choice.targetPath"):this.targetPath.toString()}set pathStringOnChoice(t){this.targetPath=new Hd.Path(t);}Clone(){let t=new s;return t.text=this.text,t.sourcePath=this.sourcePath,t.index=this.index,t.targetPath=this.targetPath,t.originalThreadIndex=this.originalThreadIndex,t.isInvisibleDefault=this.isInvisibleDefault,this.threadAtGeneration!==null&&(t.threadAtGeneration=this.threadAtGeneration.Copy()),t}};pr.Choice=Ra;});var Wa=p(mr=>{Object.defineProperty(mr,"__esModule",{value:true});mr.ListDefinitionsOrigin=void 0;var Xd=at(),Yd=k(),Zd=K(),Da=class{constructor(t){this._lists=new Map,this._allUnambiguousListValueCache=new Map;for(let e of t){this._lists.set(e.name,e);for(let[n,i]of e.items){let a=Xd.InkListItem.fromSerializedKey(n),r=new Yd.ListValue(a,i);if(!a.itemName)throw new Error("item.itemName is null or undefined.");this._allUnambiguousListValueCache.set(a.itemName,r),this._allUnambiguousListValueCache.set(a.fullName,r);}}}get lists(){let t=[];for(let[,e]of this._lists)t.push(e);return t}TryListGetDefinition(t,e){if(t===null)return {result:e,exists:false};let n=this._lists.get(t);return n?{result:n,exists:true}:{result:e,exists:false}}FindSingleItemListWithName(t){if(t===null)return (0, Zd.throwNullException)("name");let e=this._allUnambiguousListValueCache.get(t);return typeof e<"u"?e:null}};mr.ListDefinitionsOrigin=Da;});var Ee=p(Sr=>{Object.defineProperty(Sr,"__esModule",{value:true});Sr.JsonSerialisation=void 0;var gr=L(),lt=k(),Ol=ir(),x=z(),_e=Yt(),Nl=Pt(),Al=Xn(),La=ye(),Il=Lt(),qa=Et(),Fl=Xt(),Vl=fr(),Qd=it(),Rl=ka(),tf=oa(),ef=Wa(),Cr=at(),q=O(),ee=K(),vr=class s{static JArrayToRuntimeObjList(t,e=false){let n=t.length;e&&n--;let i=[];for(let a=0;a<n;a++){let r=t[a],o=this.JTokenToRuntimeObject(r);if(o===null)return (0, ee.throwNullException)("runtimeObj");i.push(o);}return i}static WriteDictionaryRuntimeObjs(t,e){t.WriteObjectStart();for(let[n,i]of e)t.WritePropertyStart(n),this.WriteRuntimeObject(t,i),t.WritePropertyEnd();t.WriteObjectEnd();}static WriteListRuntimeObjs(t,e){t.WriteArrayStart();for(let n of e)this.WriteRuntimeObject(t,n);t.WriteArrayEnd();}static WriteIntDictionary(t,e){t.WriteObjectStart();for(let[n,i]of e)t.WriteIntProperty(n,i);t.WriteObjectEnd();}static WriteRuntimeObject(t,e){let n=(0, q.asOrNull)(e,gr.Container);if(n){this.WriteRuntimeContainer(t,n);return}let i=(0, q.asOrNull)(e,Nl.Divert);if(i){let C="->";i.isExternal?C="x()":i.pushesToStack&&(i.stackPushType==_e.PushPopType.Function?C="f()":i.stackPushType==_e.PushPopType.Tunnel&&(C="->t->"));let _;i.hasVariableTarget?_=i.variableDivertName:_=i.targetPathString,t.WriteObjectStart(),t.WriteProperty(C,_),i.hasVariableTarget&&t.WriteProperty("var",true),i.isConditional&&t.WriteProperty("c",true),i.externalArgs>0&&t.WriteIntProperty("exArgs",i.externalArgs),t.WriteObjectEnd();return}let a=(0, q.asOrNull)(e,Al.ChoicePoint);if(a){t.WriteObjectStart(),t.WriteProperty("*",a.pathStringOnChoice),t.WriteIntProperty("flg",a.flags),t.WriteObjectEnd();return}let r=(0, q.asOrNull)(e,lt.BoolValue);if(r){t.WriteBool(r.value);return}let o=(0, q.asOrNull)(e,lt.IntValue);if(o){t.WriteInt(o.value);return}let l=(0, q.asOrNull)(e,lt.FloatValue);if(l){t.WriteFloat(l.value);return}let u=(0, q.asOrNull)(e,lt.StringValue);if(u){u.isNewline?t.Write(`
`,false):(t.WriteStringStart(),t.WriteStringInner("^"),t.WriteStringInner(u.value),t.WriteStringEnd());return}let h=(0, q.asOrNull)(e,lt.ListValue);if(h){this.WriteInkList(t,h);return}let c=(0, q.asOrNull)(e,lt.DivertTargetValue);if(c){if(t.WriteObjectStart(),c.value===null)return (0, ee.throwNullException)("divTargetVal.value");t.WriteProperty("^->",c.value.componentsString),t.WriteObjectEnd();return}let d=(0, q.asOrNull)(e,lt.VariablePointerValue);if(d){t.WriteObjectStart(),t.WriteProperty("^var",d.value),t.WriteIntProperty("ci",d.contextIndex),t.WriteObjectEnd();return}if((0, q.asOrNull)(e,Ol.Glue)){t.Write("<>");return}let g=(0, q.asOrNull)(e,x.ControlCommand);if(g){t.Write(s._controlCommandNames[g.commandType]);return}let S=(0, q.asOrNull)(e,qa.NativeFunctionCall);if(S){let C=S.name;C=="^"&&(C="L^"),t.Write(C);return}let D=(0, q.asOrNull)(e,La.VariableReference);if(D){t.WriteObjectStart();let C=D.pathStringForCount;C!=null?t.WriteProperty("CNT?",C):t.WriteProperty("VAR?",D.name),t.WriteObjectEnd();return}let N=(0, q.asOrNull)(e,Il.VariableAssignment);if(N){t.WriteObjectStart();let C=N.isGlobal?"VAR=":"temp=";t.WriteProperty(C,N.variableName),N.isNewDeclaration||t.WriteProperty("re",true),t.WriteObjectEnd();return}if((0, q.asOrNull)(e,Fl.Void)){t.Write("void");return}let A=(0, q.asOrNull)(e,Vl.Tag);if(A){t.WriteObjectStart(),t.WriteProperty("#",A.text),t.WriteObjectEnd();return}let y=(0, q.asOrNull)(e,Rl.Choice);if(y){this.WriteChoice(t,y);return}throw new Error("Failed to convert runtime object to Json token: "+e)}static JObjectToDictionaryRuntimeObjs(t){let e=new Map;for(let n in t)if(t.hasOwnProperty(n)){let i=this.JTokenToRuntimeObject(t[n]);if(i===null)return (0, ee.throwNullException)("inkObject");e.set(n,i);}return e}static JObjectToIntDictionary(t){let e=new Map;for(let n in t)t.hasOwnProperty(n)&&e.set(n,parseInt(t[n]));return e}static JTokenToRuntimeObject(t){if(typeof t=="number"&&!isNaN(t)||typeof t=="boolean")return lt.Value.Create(t);if(typeof t=="string"){let e=t.toString(),n=/^([0-9]+.[0-9]+f)$/.exec(e);if(n)return new lt.FloatValue(parseFloat(n[0]));let i=e[0];if(i=="^")return new lt.StringValue(e.substring(1));if(i==`
`&&e.length==1)return new lt.StringValue(`
`);if(e=="<>")return new Ol.Glue;for(let a=0;a<s._controlCommandNames.length;++a){let r=s._controlCommandNames[a];if(e==r)return new x.ControlCommand(a)}if(e=="L^"&&(e="^"),qa.NativeFunctionCall.CallExistsWithName(e))return qa.NativeFunctionCall.CallWithName(e);if(e=="->->")return x.ControlCommand.PopTunnel();if(e=="~ret")return x.ControlCommand.PopFunction();if(e=="void")return new Fl.Void}if(typeof t=="object"&&!Array.isArray(t)){let e=t,n;if(e["^->"])return n=e["^->"],new lt.DivertTargetValue(new Qd.Path(n.toString()));if(e["^var"]){n=e["^var"];let h=new lt.VariablePointerValue(n.toString());return "ci"in e&&(n=e.ci,h.contextIndex=parseInt(n)),h}let i=false,a=false,r=_e.PushPopType.Function,o=false;if((n=e["->"])?i=true:(n=e["f()"])?(i=true,a=true,r=_e.PushPopType.Function):(n=e["->t->"])?(i=true,a=true,r=_e.PushPopType.Tunnel):(n=e["x()"])&&(i=true,o=true,a=false,r=_e.PushPopType.Function),i){let h=new Nl.Divert;h.pushesToStack=a,h.stackPushType=r,h.isExternal=o;let c=n.toString();return (n=e.var)?h.variableDivertName=c:h.targetPathString=c,h.isConditional=!!e.c,o&&(n=e.exArgs)&&(h.externalArgs=parseInt(n)),h}if(n=e["*"]){let h=new Al.ChoicePoint;return h.pathStringOnChoice=n.toString(),(n=e.flg)&&(h.flags=parseInt(n)),h}if(n=e["VAR?"])return new La.VariableReference(n.toString());if(n=e["CNT?"]){let h=new La.VariableReference;return h.pathStringForCount=n.toString(),h}let l=false,u=false;if((n=e["VAR="])?(l=true,u=true):(n=e["temp="])&&(l=true,u=false),l){let h=n.toString(),c=!e.re,d=new Il.VariableAssignment(h,c);return d.isGlobal=u,d}if(e["#"]!==void 0)return n=e["#"],new Vl.Tag(n.toString());if(n=e.list){let h=n,c=new Cr.InkList;if(n=e.origins){let d=n;c.SetInitialOriginNames(d);}for(let d in h)if(h.hasOwnProperty(d)){let m=h[d],g=new Cr.InkListItem(d),S=parseInt(m);c.Add(g,S);}return new lt.ListValue(c)}if(e.originalChoicePath!=null)return this.JObjectToChoice(e)}if(Array.isArray(t))return this.JArrayToContainer(t);if(t==null)return null;throw new Error("Failed to convert token to runtime object: "+this.toJson(t,["parent"]))}static toJson(t,e,n){return JSON.stringify(t,(i,a)=>e?.some(r=>r===i)?void 0:a,n)}static WriteRuntimeContainer(t,e,n=false){if(t.WriteArrayStart(),e===null)return (0, ee.throwNullException)("container");for(let l of e.content)this.WriteRuntimeObject(t,l);let i=e.namedOnlyContent,a=e.countFlags,r=e.name!=null&&!n,o=i!=null||a>0||r;if(o&&t.WriteObjectStart(),i!=null)for(let[l,u]of i){let h=l,c=(0, q.asOrNull)(u,gr.Container);t.WritePropertyStart(h),this.WriteRuntimeContainer(t,c,true),t.WritePropertyEnd();}a>0&&t.WriteIntProperty("#f",a),r&&t.WriteProperty("#n",e.name),o?t.WriteObjectEnd():t.WriteNull(),t.WriteArrayEnd();}static JArrayToContainer(t){let e=new gr.Container;e.content=this.JArrayToRuntimeObjList(t,true);let n=t[t.length-1];if(n!=null){let i=new Map;for(let a in n)if(a=="#f")e.countFlags=parseInt(n[a]);else if(a=="#n")e.name=n[a].toString();else {let r=this.JTokenToRuntimeObject(n[a]),o=(0, q.asOrNull)(r,gr.Container);o&&(o.name=a),i.set(a,r);}e.namedOnlyContent=i;}return e}static JObjectToChoice(t){let e=new Rl.Choice;return e.text=t.text.toString(),e.index=parseInt(t.index),e.sourcePath=t.originalChoicePath.toString(),e.originalThreadIndex=parseInt(t.originalThreadIndex),e.pathStringOnChoice=t.targetPath.toString(),e.tags=this.JArrayToTags(t),e}static JArrayToTags(t){return t.tags?t.tags:null}static WriteChoice(t,e){t.WriteObjectStart(),t.WriteProperty("text",e.text),t.WriteIntProperty("index",e.index),t.WriteProperty("originalChoicePath",e.sourcePath),t.WriteIntProperty("originalThreadIndex",e.originalThreadIndex),t.WriteProperty("targetPath",e.pathStringOnChoice),this.WriteChoiceTags(t,e),t.WriteObjectEnd();}static WriteChoiceTags(t,e){if(e.tags&&e.tags.length>0){t.WritePropertyStart("tags"),t.WriteArrayStart();for(let n of e.tags)t.Write(n);t.WriteArrayEnd(),t.WritePropertyEnd();}}static WriteInkList(t,e){let n=e.value;if(n===null)return (0, ee.throwNullException)("rawList");t.WriteObjectStart(),t.WritePropertyStart("list"),t.WriteObjectStart();for(let[i,a]of n){let r=Cr.InkListItem.fromSerializedKey(i),o=a;if(r.itemName===null)return (0, ee.throwNullException)("item.itemName");t.WritePropertyNameStart(),t.WritePropertyNameInner(r.originName?r.originName:"?"),t.WritePropertyNameInner("."),t.WritePropertyNameInner(r.itemName),t.WritePropertyNameEnd(),t.Write(o),t.WritePropertyEnd();}if(t.WriteObjectEnd(),t.WritePropertyEnd(),n.Count==0&&n.originNames!=null&&n.originNames.length>0){t.WritePropertyStart("origins"),t.WriteArrayStart();for(let i of n.originNames)t.Write(i);t.WriteArrayEnd(),t.WritePropertyEnd();}t.WriteObjectEnd();}static ListDefinitionsToJToken(t){let e={};for(let n of t.lists){let i={};for(let[a,r]of n.items){let o=Cr.InkListItem.fromSerializedKey(a);if(o.itemName===null)return (0, ee.throwNullException)("item.itemName");i[o.itemName]=r;}e[n.name]=i;}return e}static JTokenToListDefinitions(t){let e=t,n=[];for(let i in e)if(e.hasOwnProperty(i)){let a=i.toString(),r=e[i],o=new Map;for(let u in r)if(e.hasOwnProperty(i)){let h=r[u];o.set(u,parseInt(h));}let l=new tf.ListDefinition(a,o);n.push(l);}return new ef.ListDefinitionsOrigin(n)}};Sr.JsonSerialisation=vr;vr._controlCommandNames=(()=>{let s=[];s[x.ControlCommand.CommandType.EvalStart]="ev",s[x.ControlCommand.CommandType.EvalOutput]="out",s[x.ControlCommand.CommandType.EvalEnd]="/ev",s[x.ControlCommand.CommandType.Duplicate]="du",s[x.ControlCommand.CommandType.PopEvaluatedValue]="pop",s[x.ControlCommand.CommandType.PopFunction]="~ret",s[x.ControlCommand.CommandType.PopTunnel]="->->",s[x.ControlCommand.CommandType.BeginString]="str",s[x.ControlCommand.CommandType.EndString]="/str",s[x.ControlCommand.CommandType.NoOp]="nop",s[x.ControlCommand.CommandType.ChoiceCount]="choiceCnt",s[x.ControlCommand.CommandType.Turns]="turn",s[x.ControlCommand.CommandType.TurnsSince]="turns",s[x.ControlCommand.CommandType.ReadCount]="readc",s[x.ControlCommand.CommandType.Random]="rnd",s[x.ControlCommand.CommandType.SeedRandom]="srnd",s[x.ControlCommand.CommandType.VisitIndex]="visit",s[x.ControlCommand.CommandType.SequenceShuffleIndex]="seq",s[x.ControlCommand.CommandType.StartThread]="thread",s[x.ControlCommand.CommandType.Done]="done",s[x.ControlCommand.CommandType.End]="end",s[x.ControlCommand.CommandType.ListFromInt]="listInt",s[x.ControlCommand.CommandType.ListRange]="range",s[x.ControlCommand.CommandType.ListRandom]="lrnd",s[x.ControlCommand.CommandType.BeginTag]="#",s[x.ControlCommand.CommandType.EndTag]="/#";for(let t=0;t<x.ControlCommand.CommandType.TOTAL_VALUES;++t)if(s[t]==null)throw new Error("Control command not accounted for in serialisation");return s})();});var Ba=p(an=>{Object.defineProperty(an,"__esModule",{value:true});an.CallStack=void 0;var ja=Yt(),kl=it(),nf=on(),Dl=Ee(),rf=k(),sf=Kt(),rn=Ke(),af=ke(),Wl=ce(),Ma=K(),sn=class s{get elements(){return this.callStack}get depth(){return this.elements.length}get currentElement(){let e=this._threads[this._threads.length-1].callstack;return e[e.length-1]}get currentElementIndex(){return this.callStack.length-1}get currentThread(){return this._threads[this._threads.length-1]}set currentThread(t){af.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(t);}get canPop(){return this.callStack.length>1}constructor(){if(this._threadCounter=0,this._startOfRoot=rn.Pointer.Null,arguments[0]instanceof nf.Story){let t=arguments[0];this._startOfRoot=rn.Pointer.StartOf(t.rootContentContainer),this.Reset();}else {let t=arguments[0];this._threads=[];for(let e of t._threads)this._threads.push(e.Copy());this._threadCounter=t._threadCounter,this._startOfRoot=t._startOfRoot.copy();}}Reset(){this._threads=[],this._threads.push(new s.Thread),this._threads[0].callstack.push(new s.Element(ja.PushPopType.Tunnel,this._startOfRoot));}SetJsonToken(t,e){this._threads.length=0;let n=t.threads;for(let i of n){let a=i,r=new s.Thread(a,e);this._threads.push(r);}this._threadCounter=parseInt(t.threadCounter),this._startOfRoot=rn.Pointer.StartOf(e.rootContentContainer);}WriteJson(t){t.WriteObject(e=>{e.WritePropertyStart("threads"),e.WriteArrayStart();for(let n of this._threads)n.WriteJson(e);e.WriteArrayEnd(),e.WritePropertyEnd(),e.WritePropertyStart("threadCounter"),e.WriteInt(this._threadCounter),e.WritePropertyEnd();});}PushThread(){let t=this.currentThread.Copy();this._threadCounter++,t.threadIndex=this._threadCounter,this._threads.push(t);}ForkThread(){let t=this.currentThread.Copy();return this._threadCounter++,t.threadIndex=this._threadCounter,t}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==ja.PushPopType.FunctionEvaluationFromGame}Push(t,e=0,n=0){let i=new s.Element(t,this.currentElement.currentPointer,false);i.evaluationStackHeightWhenPushed=e,i.functionStartInOutputStream=n,this.callStack.push(i);}CanPop(t=null){return this.canPop?t==null?true:this.currentElement.type==t:false}Pop(t=null){if(this.CanPop(t)){this.callStack.pop();return}else throw new Error("Mismatched push/pop in Callstack")}GetTemporaryVariableWithName(t,e=-1){e==-1&&(e=this.currentElementIndex+1);let n=this.callStack[e-1],i=(0, Wl.tryGetValueFromMap)(n.temporaryVariables,t,null);return i.exists?i.result:null}SetTemporaryVariable(t,e,n,i=-1){i==-1&&(i=this.currentElementIndex+1);let a=this.callStack[i-1];if(!n&&!a.temporaryVariables.get(t))throw new Error("Could not find temporary variable to set: "+t);let r=(0, Wl.tryGetValueFromMap)(a.temporaryVariables,t,null);r.exists&&rf.ListValue.RetainListOriginsForAssignment(r.result,e),a.temporaryVariables.set(t,e);}ContextForVariableNamed(t){return this.currentElement.temporaryVariables.get(t)?this.currentElementIndex+1:0}ThreadWithIndex(t){let e=this._threads.filter(n=>{if(n.threadIndex==t)return n});return e.length>0?e[0]:null}get callStack(){return this.currentThread.callstack}get callStackTrace(){let t=new sf.StringBuilder;for(let e=0;e<this._threads.length;e++){let n=this._threads[e],i=e==this._threads.length-1;t.AppendFormat(`=== THREAD {0}/{1} {2}===
`,e+1,this._threads.length,i?"(current) ":"");for(let a=0;a<n.callstack.length;a++){n.callstack[a].type==ja.PushPopType.Function?t.Append("  [FUNCTION] "):t.Append("  [TUNNEL] ");let r=n.callstack[a].currentPointer;if(!r.isNull){if(t.Append("<SOMEWHERE IN "),r.container===null)return (0, Ma.throwNullException)("pointer.container");t.Append(r.container.path.toString()),t.AppendLine(">");}}}return t.toString()}};an.CallStack=sn;(function(s){class t{constructor(i,a,r=false){this.evaluationStackHeightWhenPushed=0,this.functionStartInOutputStream=0,this.currentPointer=a.copy(),this.inExpressionEvaluation=r,this.temporaryVariables=new Map,this.type=i;}Copy(){let i=new t(this.type,this.currentPointer,this.inExpressionEvaluation);return i.temporaryVariables=new Map(this.temporaryVariables),i.evaluationStackHeightWhenPushed=this.evaluationStackHeightWhenPushed,i.functionStartInOutputStream=this.functionStartInOutputStream,i}}s.Element=t;class e{constructor(){if(this.threadIndex=0,this.previousPointer=rn.Pointer.Null,this.callstack=[],arguments[0]&&arguments[1]){let i=arguments[0],a=arguments[1];this.threadIndex=parseInt(i.threadIndex);let r=i.callstack;for(let l of r){let u=l,h=parseInt(u.type),c=rn.Pointer.Null,d,m=u.cPath;if(typeof m<"u"){d=m.toString();let N=a.ContentAtPath(new kl.Path(d));if(c.container=N.container,c.index=parseInt(u.idx),N.obj==null)throw new Error("When loading state, internal story location couldn't be found: "+d+". Has the story changed since this save data was created?");N.approximate&&(c.container!==null?a.Warning("When loading state, exact internal story location couldn't be found: '"+d+"', so it was approximated to '"+c.container.path.toString()+"' to recover. Has the story changed since this save data was created?"):a.Warning("When loading state, exact internal story location couldn't be found: '"+d+"' and it may not be recoverable. Has the story changed since this save data was created?"));}let g=!!u.exp,S=new t(h,c,g),D=u.temp;typeof D<"u"?S.temporaryVariables=Dl.JsonSerialisation.JObjectToDictionaryRuntimeObjs(D):S.temporaryVariables.clear(),this.callstack.push(S);}let o=i.previousContentObject;if(typeof o<"u"){let l=new kl.Path(o.toString());this.previousPointer=a.PointerAtPath(l);}}}Copy(){let i=new e;i.threadIndex=this.threadIndex;for(let a of this.callstack)i.callstack.push(a.Copy());return i.previousPointer=this.previousPointer.copy(),i}WriteJson(i){i.WriteObjectStart(),i.WritePropertyStart("callstack"),i.WriteArrayStart();for(let a of this.callstack){if(i.WriteObjectStart(),!a.currentPointer.isNull){if(a.currentPointer.container===null)return (0, Ma.throwNullException)("el.currentPointer.container");i.WriteProperty("cPath",a.currentPointer.container.path.componentsString),i.WriteIntProperty("idx",a.currentPointer.index);}i.WriteProperty("exp",a.inExpressionEvaluation),i.WriteIntProperty("type",a.type),a.temporaryVariables.size>0&&(i.WritePropertyStart("temp"),Dl.JsonSerialisation.WriteDictionaryRuntimeObjs(i,a.temporaryVariables),i.WritePropertyEnd()),i.WriteObjectEnd();}if(i.WriteArrayEnd(),i.WritePropertyEnd(),i.WriteIntProperty("threadIndex",this.threadIndex),!this.previousPointer.isNull){let a=this.previousPointer.Resolve();if(a===null)return (0, Ma.throwNullException)("this.previousPointer.Resolve()");i.WriteProperty("previousContentObject",a.path.toString());}i.WriteObjectEnd();}}s.Thread=e;})(sn||(an.CallStack=sn={}));});var ql=p(br=>{Object.defineProperty(br,"__esModule",{value:true});br.VariablesState=void 0;var H=k(),of=We(),Ll=Ee(),X=O(),ln=ce(),Mt=K();function lf(){return class{}}var yr=class s extends lf(){variableChangedEvent(t,e){for(let n of this.variableChangedEventCallbacks)n(t,e);}StartVariableObservation(){this._batchObservingVariableChanges=true,this._changedVariablesForBatchObs=new Set;}CompleteVariableObservation(){this._batchObservingVariableChanges=false;let t=new Map;if(this._changedVariablesForBatchObs!=null)for(let e of this._changedVariablesForBatchObs){let n=this._globalVariables.get(e);this.variableChangedEvent(e,n);}if(this.patch!=null)for(let e of this.patch.changedVariables){let n=this.patch.TryGetGlobal(e,null);n.exists&&t.set(e,n);}return this._changedVariablesForBatchObs=null,t}NotifyObservers(t){for(let[e,n]of t)this.variableChangedEvent(e,n);}get callStack(){return this._callStack}set callStack(t){this._callStack=t;}$(t,e){if(typeof e>"u"){let n=null;return this.patch!==null&&(n=this.patch.TryGetGlobal(t,null),n.exists)?n.result.valueObject:(n=this._globalVariables.get(t),typeof n>"u"&&(n=this._defaultGlobalVariables.get(t)),typeof n<"u"?n.valueObject:null)}else {if(typeof this._defaultGlobalVariables.get(t)>"u")throw new of.StoryException("Cannot assign to a variable ("+t+") that hasn't been declared in the story");let n=H.Value.Create(e);if(n==null)throw e==null?new Error("Cannot pass null to VariableState"):new Error("Invalid value passed to VariableState: "+e.toString());this.SetGlobal(t,n);}}constructor(t,e){super(),this.variableChangedEventCallbacks=[],this.patch=null,this._defaultGlobalVariables=new Map,this._changedVariablesForBatchObs=new Set,this._batchObservingVariableChanges=false,this._globalVariables=new Map,this._callStack=t,this._listDefsOrigin=e;try{return new Proxy(this,{get(i,a){return a in i?i[a]:i.$(a)},set(i,a,r){return a in i?i[a]=r:i.$(a,r),!0},ownKeys(i){return [...new Set([...i._defaultGlobalVariables.keys(),...i._globalVariables.keys()])]},getOwnPropertyDescriptor(i,a){return {enumerable:!0,configurable:!0,value:i.$(a)}}})}catch{}}ApplyPatch(){if(this.patch===null)return (0, Mt.throwNullException)("this.patch");for(let[t,e]of this.patch.globals)this._globalVariables.set(t,e);if(this._changedVariablesForBatchObs!==null)for(let t of this.patch.changedVariables)this._changedVariablesForBatchObs.add(t);this.patch=null;}SetJsonToken(t){this._globalVariables.clear();for(let[e,n]of this._defaultGlobalVariables){let i=t[e];if(typeof i<"u"){let a=Ll.JsonSerialisation.JTokenToRuntimeObject(i);if(a===null)return (0, Mt.throwNullException)("tokenInkObject");this._globalVariables.set(e,a);}else this._globalVariables.set(e,n);}}WriteJson(t){t.WriteObjectStart();for(let[e,n]of this._globalVariables){let i=e,a=n;if(s.dontSaveDefaultValues&&this._defaultGlobalVariables.has(i)){let r=this._defaultGlobalVariables.get(i);if(this.RuntimeObjectsEqual(a,r))continue}t.WritePropertyStart(i),Ll.JsonSerialisation.WriteRuntimeObject(t,a),t.WritePropertyEnd();}t.WriteObjectEnd();}RuntimeObjectsEqual(t,e){if(t===null)return (0, Mt.throwNullException)("obj1");if(e===null)return (0, Mt.throwNullException)("obj2");if(t.constructor!==e.constructor)return  false;let n=(0, X.asOrNull)(t,H.BoolValue);if(n!==null)return n.value===(0, X.asOrThrows)(e,H.BoolValue).value;let i=(0, X.asOrNull)(t,H.IntValue);if(i!==null)return i.value===(0, X.asOrThrows)(e,H.IntValue).value;let a=(0, X.asOrNull)(t,H.FloatValue);if(a!==null)return a.value===(0, X.asOrThrows)(e,H.FloatValue).value;let r=(0, X.asOrNull)(t,H.Value),o=(0, X.asOrNull)(e,H.Value);if(r!==null&&o!==null)return (0, X.isEquatable)(r.valueObject)&&(0, X.isEquatable)(o.valueObject)?r.valueObject.Equals(o.valueObject):r.valueObject===o.valueObject;throw new Error("FastRoughDefinitelyEquals: Unsupported runtime object type: "+t.constructor.name)}GetVariableWithName(t,e=-1){let n=this.GetRawVariableWithName(t,e),i=(0, X.asOrNull)(n,H.VariablePointerValue);return i!==null&&(n=this.ValueAtVariablePointer(i)),n}TryGetDefaultVariableValue(t){let e=(0, ln.tryGetValueFromMap)(this._defaultGlobalVariables,t,null);return e.exists?e.result:null}GlobalVariableExistsWithName(t){return this._globalVariables.has(t)||this._defaultGlobalVariables!==null&&this._defaultGlobalVariables.has(t)}GetRawVariableWithName(t,e){let n=null;if(e==0||e==-1){let i=null;if(this.patch!==null&&(i=this.patch.TryGetGlobal(t,null),i.exists)||(i=(0, ln.tryGetValueFromMap)(this._globalVariables,t,null),i.exists)||this._defaultGlobalVariables!==null&&(i=(0, ln.tryGetValueFromMap)(this._defaultGlobalVariables,t,null),i.exists))return i.result;if(this._listDefsOrigin===null)return (0, Mt.throwNullException)("VariablesState._listDefsOrigin");let a=this._listDefsOrigin.FindSingleItemListWithName(t);if(a)return a}return n=this._callStack.GetTemporaryVariableWithName(t,e),n}ValueAtVariablePointer(t){return this.GetVariableWithName(t.variableName,t.contextIndex)}Assign(t,e){let n=t.variableName;if(n===null)return (0, Mt.throwNullException)("name");let i=-1,a=false;if(t.isNewDeclaration?a=t.isGlobal:a=this.GlobalVariableExistsWithName(n),t.isNewDeclaration){let r=(0, X.asOrNull)(e,H.VariablePointerValue);r!==null&&(e=this.ResolveVariablePointer(r));}else {let r=null;do r=(0, X.asOrNull)(this.GetRawVariableWithName(n,i),H.VariablePointerValue),r!=null&&(n=r.variableName,i=r.contextIndex,a=i==0);while(r!=null)}a?this.SetGlobal(n,e):this._callStack.SetTemporaryVariable(n,e,t.isNewDeclaration,i);}SnapshotDefaultGlobals(){this._defaultGlobalVariables=new Map(this._globalVariables);}RetainListOriginsForAssignment(t,e){let n=(0, X.asOrThrows)(t,H.ListValue),i=(0, X.asOrThrows)(e,H.ListValue);n.value&&i.value&&i.value.Count==0&&i.value.SetInitialOriginNames(n.value.originNames);}SetGlobal(t,e){let n=null;if(this.patch===null&&(n=(0, ln.tryGetValueFromMap)(this._globalVariables,t,null)),this.patch!==null&&(n=this.patch.TryGetGlobal(t,null),n.exists||(n=(0, ln.tryGetValueFromMap)(this._globalVariables,t,null))),H.ListValue.RetainListOriginsForAssignment(n.result,e),t===null)return (0, Mt.throwNullException)("variableName");if(this.patch!==null?this.patch.SetGlobal(t,e):this._globalVariables.set(t,e),this.variableChangedEvent!==null&&n!==null&&e!==n.result)if(this._batchObservingVariableChanges){if(this._changedVariablesForBatchObs===null)return (0, Mt.throwNullException)("this._changedVariablesForBatchObs");this.patch!==null?this.patch.AddChangedVariable(t):this._changedVariablesForBatchObs!==null&&this._changedVariablesForBatchObs.add(t);}else this.variableChangedEvent(t,e);}ResolveVariablePointer(t){let e=t.contextIndex;e==-1&&(e=this.GetContextIndexOfVariableNamed(t.variableName));let n=this.GetRawVariableWithName(t.variableName,e),i=(0, X.asOrNull)(n,H.VariablePointerValue);return i??new H.VariablePointerValue(t.variableName,e)}GetContextIndexOfVariableNamed(t){return this.GlobalVariableExistsWithName(t)?0:this._callStack.currentElementIndex}ObserveVariableChange(t){this.variableChangedEventCallbacks.push(t);}};br.VariablesState=yr;yr.dontSaveDefaultValues=true;});var $a=p(_r=>{Object.defineProperty(_r,"__esModule",{value:true});_r.PRNG=void 0;var Ga=class{constructor(t){this.seed=t%2147483647,this.seed<=0&&(this.seed+=2147483646);}next(){return this.seed=this.seed*48271%2147483647}nextFloat(){return (this.next()-1)/2147483646}};_r.PRNG=Ga;});var jl=p(Er=>{Object.defineProperty(Er,"__esModule",{value:true});Er.StatePatch=void 0;var Ja=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 t=arguments[0];this._globals=new Map(t._globals),this._changedVariables=new Set(t._changedVariables),this._visitCounts=new Map(t._visitCounts),this._turnIndices=new Map(t._turnIndices);}else this._globals=new Map,this._changedVariables=new Set,this._visitCounts=new Map,this._turnIndices=new Map;}TryGetGlobal(t,e){return t!==null&&this._globals.has(t)?{result:this._globals.get(t),exists:true}:{result:e,exists:false}}SetGlobal(t,e){this._globals.set(t,e);}AddChangedVariable(t){return this._changedVariables.add(t)}TryGetVisitCount(t,e){return this._visitCounts.has(t)?{result:this._visitCounts.get(t),exists:true}:{result:e,exists:false}}SetVisitCount(t,e){this._visitCounts.set(t,e);}SetTurnIndex(t,e){this._turnIndices.set(t,e);}TryGetTurnIndex(t,e){return this._turnIndices.has(t)?{result:this._turnIndices.get(t),exists:true}:{result:e,exists:false}}};Er.StatePatch=Ja;});var Ua=p(hn=>{Object.defineProperty(hn,"__esModule",{value:true});hn.SimpleJson=void 0;var un=class s{static TextToDictionary(t){return new s.Reader(t).ToDictionary()}static TextToArray(t){return new s.Reader(t).ToArray()}};hn.SimpleJson=un;(function(s){class t{constructor(i){if(JSON.parse("0",(r,o,l)=>l!=null)){let r=(o,l,u)=>Number.isInteger(l)&&u.source.endsWith(".0")?u.source+"f":l;this._rootObject=JSON.parse(i,r);}else {let r=i.replace(/(,\s*)([0-9]+\.[0]+)([,]*)/g,'$1"$2f"$3');this._rootObject=JSON.parse(r);}}ToDictionary(){return this._rootObject}ToArray(){return this._rootObject}}s.Reader=t;class e{constructor(){this._currentPropertyName=null,this._currentString=null,this._stateStack=[],this._collectionStack=[],this._propertyNameStack=[],this._jsonObject=null;}WriteObject(i){this.WriteObjectStart(),i(this),this.WriteObjectEnd();}WriteObjectStart(){this.StartNewObject(true);let i={};if(this.state===s.Writer.State.Property){this.Assert(this.currentCollection!==null),this.Assert(this.currentPropertyName!==null);let a=this._propertyNameStack.pop();this.currentCollection[a]=i,this._collectionStack.push(i);}else this.state===s.Writer.State.Array?(this.Assert(this.currentCollection!==null),this.currentCollection.push(i),this._collectionStack.push(i)):(this.Assert(this.state===s.Writer.State.None),this._jsonObject=i,this._collectionStack.push(i));this._stateStack.push(new s.Writer.StateElement(s.Writer.State.Object));}WriteObjectEnd(){this.Assert(this.state===s.Writer.State.Object),this._collectionStack.pop(),this._stateStack.pop();}WriteProperty(i,a){if(this.WritePropertyStart(i),arguments[1]instanceof Function){let r=arguments[1];r(this);}else {let r=arguments[1];this.Write(r);}this.WritePropertyEnd();}WriteIntProperty(i,a){this.WritePropertyStart(i),this.WriteInt(a),this.WritePropertyEnd();}WriteFloatProperty(i,a){this.WritePropertyStart(i),this.WriteFloat(a),this.WritePropertyEnd();}WritePropertyStart(i){this.Assert(this.state===s.Writer.State.Object),this._propertyNameStack.push(i),this.IncrementChildCount(),this._stateStack.push(new s.Writer.StateElement(s.Writer.State.Property));}WritePropertyEnd(){this.Assert(this.state===s.Writer.State.Property),this.Assert(this.childCount===1),this._stateStack.pop();}WritePropertyNameStart(){this.Assert(this.state===s.Writer.State.Object),this.IncrementChildCount(),this._currentPropertyName="",this._stateStack.push(new s.Writer.StateElement(s.Writer.State.Property)),this._stateStack.push(new s.Writer.StateElement(s.Writer.State.PropertyName));}WritePropertyNameEnd(){this.Assert(this.state===s.Writer.State.PropertyName),this.Assert(this._currentPropertyName!==null),this._propertyNameStack.push(this._currentPropertyName),this._currentPropertyName=null,this._stateStack.pop();}WritePropertyNameInner(i){this.Assert(this.state===s.Writer.State.PropertyName),this.Assert(this._currentPropertyName!==null),this._currentPropertyName+=i;}WriteArrayStart(){this.StartNewObject(true);let i=[];if(this.state===s.Writer.State.Property){this.Assert(this.currentCollection!==null),this.Assert(this.currentPropertyName!==null);let a=this._propertyNameStack.pop();this.currentCollection[a]=i,this._collectionStack.push(i);}else this.state===s.Writer.State.Array?(this.Assert(this.currentCollection!==null),this.currentCollection.push(i),this._collectionStack.push(i)):(this.Assert(this.state===s.Writer.State.None),this._jsonObject=i,this._collectionStack.push(i));this._stateStack.push(new s.Writer.StateElement(s.Writer.State.Array));}WriteArrayEnd(){this.Assert(this.state===s.Writer.State.Array),this._collectionStack.pop(),this._stateStack.pop();}Write(i,a=true){if(i===null){console.error("Warning: trying to write a null value");return}this.StartNewObject(false),this._addToCurrentObject(i);}WriteBool(i){i!==null&&(this.StartNewObject(false),this._addToCurrentObject(i));}WriteInt(i){i!==null&&(this.StartNewObject(false),this._addToCurrentObject(Math.floor(i)));}WriteFloat(i){i!==null&&(this.StartNewObject(false),i==Number.POSITIVE_INFINITY?this._addToCurrentObject(34e37):i==Number.NEGATIVE_INFINITY?this._addToCurrentObject(-34e37):isNaN(i)?this._addToCurrentObject(0):this._addToCurrentObject(i));}WriteNull(){this.StartNewObject(false),this._addToCurrentObject(null);}WriteStringStart(){this.StartNewObject(false),this._currentString="",this._stateStack.push(new s.Writer.StateElement(s.Writer.State.String));}WriteStringEnd(){this.Assert(this.state==s.Writer.State.String),this._stateStack.pop(),this._addToCurrentObject(this._currentString),this._currentString=null;}WriteStringInner(i,a=true){if(this.Assert(this.state===s.Writer.State.String),i===null){console.error("Warning: trying to write a null string");return}this._currentString+=i;}toString(){return this._jsonObject===null?"":JSON.stringify(this._jsonObject)}StartNewObject(i){i?this.Assert(this.state===s.Writer.State.None||this.state===s.Writer.State.Property||this.state===s.Writer.State.Array):this.Assert(this.state===s.Writer.State.Property||this.state===s.Writer.State.Array),this.state===s.Writer.State.Property&&this.Assert(this.childCount===0),(this.state===s.Writer.State.Array||this.state===s.Writer.State.Property)&&this.IncrementChildCount();}get state(){return this._stateStack.length>0?this._stateStack[this._stateStack.length-1].type:s.Writer.State.None}get childCount(){return this._stateStack.length>0?this._stateStack[this._stateStack.length-1].childCount:0}get currentCollection(){return this._collectionStack.length>0?this._collectionStack[this._collectionStack.length-1]:null}get currentPropertyName(){return this._propertyNameStack.length>0?this._propertyNameStack[this._propertyNameStack.length-1]:null}IncrementChildCount(){this.Assert(this._stateStack.length>0);let i=this._stateStack.pop();i.childCount++,this._stateStack.push(i);}Assert(i){if(!i)throw Error("Assert failed while writing JSON")}_addToCurrentObject(i){this.Assert(this.currentCollection!==null),this.state===s.Writer.State.Array?(this.Assert(Array.isArray(this.currentCollection)),this.currentCollection.push(i)):this.state===s.Writer.State.Property&&(this.Assert(!Array.isArray(this.currentCollection)),this.Assert(this.currentPropertyName!==null),this.currentCollection[this.currentPropertyName]=i,this._propertyNameStack.pop());}}s.Writer=e,function(n){(function(r){r[r.None=0]="None",r[r.Object=1]="Object",r[r.Array=2]="Array",r[r.Property=3]="Property",r[r.PropertyName=4]="PropertyName",r[r.String=5]="String";})(n.State||(n.State={}));class a{constructor(o){this.type=s.Writer.State.None,this.childCount=0,this.type=o;}}n.StateElement=a;}(e=s.Writer||(s.Writer={}));})(un||(hn.SimpleJson=un={}));});var Bl=p(wr=>{Object.defineProperty(wr,"__esModule",{value:true});wr.Flow=void 0;var Ml=Ba(),Pr=Ee(),uf=K(),Ha=class{constructor(){let t=arguments[0],e=arguments[1];if(this.name=t,this.callStack=new Ml.CallStack(e),arguments[2]){let n=arguments[2];this.callStack.SetJsonToken(n.callstack,e),this.outputStream=Pr.JsonSerialisation.JArrayToRuntimeObjList(n.outputStream),this.currentChoices=Pr.JsonSerialisation.JArrayToRuntimeObjList(n.currentChoices);let i=n.choiceThreads;typeof i<"u"&&this.LoadFlowChoiceThreads(i,e);}else this.outputStream=[],this.currentChoices=[];}WriteJson(t){t.WriteObjectStart(),t.WriteProperty("callstack",n=>this.callStack.WriteJson(n)),t.WriteProperty("outputStream",n=>Pr.JsonSerialisation.WriteListRuntimeObjs(n,this.outputStream));let e=false;for(let n of this.currentChoices){if(n.threadAtGeneration===null)return (0, uf.throwNullException)("c.threadAtGeneration");n.originalThreadIndex=n.threadAtGeneration.threadIndex,this.callStack.ThreadWithIndex(n.originalThreadIndex)===null&&(e||(e=true,t.WritePropertyStart("choiceThreads"),t.WriteObjectStart()),t.WritePropertyStart(n.originalThreadIndex),n.threadAtGeneration.WriteJson(t),t.WritePropertyEnd());}e&&(t.WriteObjectEnd(),t.WritePropertyEnd()),t.WriteProperty("currentChoices",n=>{n.WriteArrayStart();for(let i of this.currentChoices)Pr.JsonSerialisation.WriteChoice(n,i);n.WriteArrayEnd();}),t.WriteObjectEnd();}LoadFlowChoiceThreads(t,e){for(let n of this.currentChoices){let i=this.callStack.ThreadWithIndex(n.originalThreadIndex);if(i!==null)n.threadAtGeneration=i.Copy();else {let a=t[`${n.originalThreadIndex}`];n.threadAtGeneration=new Ml.CallStack.Thread(a,e);}}}};wr.Flow=Ha;});var Jl=p(Tr=>{Object.defineProperty(Tr,"__esModule",{value:true});Tr.StoryState=void 0;var hf=Ba(),cf=ql(),$=k(),Bt=Yt(),df=fr(),Ka=ir(),Gl=it(),et=z(),za=Kt(),Gt=Ee(),ff=$a(),pf=Xt(),Pe=Ke(),cn=ce(),M=O(),mf=ke(),mt=K(),gf=on(),Cf=jl(),$l=Ua(),xr=Bl(),vf=at(),Xa=class s{ToJson(t=false){let e=new $l.SimpleJson.Writer;return this.WriteJson(e),e.toString()}toJson(t=false){return this.ToJson(t)}LoadJson(t){let e=$l.SimpleJson.TextToDictionary(t);this.LoadJsonObj(e),this.onDidLoadState!==null&&this.onDidLoadState();}VisitCountAtPathString(t){let e;if(this._patch!==null){let n=this.story.ContentAtPath(new Gl.Path(t)).container;if(n===null)throw new Error("Content at path not found: "+t);if(e=this._patch.TryGetVisitCount(n,0),e.exists)return e.result}return e=(0, cn.tryGetValueFromMap)(this._visitCounts,t,null),e.exists?e.result:0}VisitCountForContainer(t){if(t===null)return (0, mt.throwNullException)("container");if(!t.visitsShouldBeCounted)return this.story.Error("Read count for target ("+t.name+" - on "+t.debugMetadata+") unknown. The story may need to be compiled with countAllVisits flag (-c)."),0;if(this._patch!==null){let i=this._patch.TryGetVisitCount(t,0);if(i.exists)return i.result}let e=t.path.toString(),n=(0, cn.tryGetValueFromMap)(this._visitCounts,e,null);return n.exists?n.result:0}IncrementVisitCountForContainer(t){if(this._patch!==null){let i=this.VisitCountForContainer(t);i++,this._patch.SetVisitCount(t,i);return}let e=t.path.toString(),n=(0, cn.tryGetValueFromMap)(this._visitCounts,e,null);n.exists?this._visitCounts.set(e,n.result+1):this._visitCounts.set(e,1);}RecordTurnIndexVisitToContainer(t){if(this._patch!==null){this._patch.SetTurnIndex(t,this.currentTurnIndex);return}let e=t.path.toString();this._turnIndices.set(e,this.currentTurnIndex);}TurnsSinceForContainer(t){if(t.turnIndexShouldBeCounted||this.story.Error("TURNS_SINCE() for target ("+t.name+" - on "+t.debugMetadata+") unknown. The story may need to be compiled with countAllVisits flag (-c)."),this._patch!==null){let i=this._patch.TryGetTurnIndex(t,0);if(i.exists)return this.currentTurnIndex-i.result}let e=t.path.toString(),n=(0, cn.tryGetValueFromMap)(this._turnIndices,e,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(t){this._variablesState=t;}get callStack(){return this._currentFlow.callStack}get evaluationStack(){return this._evaluationStack}get currentTurnIndex(){return this._currentTurnIndex}set currentTurnIndex(t){this._currentTurnIndex=t;}get currentPathString(){let t=this.currentPointer;return t.isNull?null:t.path===null?(0, mt.throwNullException)("pointer.path"):t.path.toString()}get previousPathString(){let t=this.previousPointer;return t.isNull?null:t.path===null?(0, mt.throwNullException)("previousPointer.path"):t.path.toString()}get currentPointer(){return this.callStack.currentElement.currentPointer.copy()}set currentPointer(t){this.callStack.currentElement.currentPointer=t.copy();}get previousPointer(){return this.callStack.currentThread.previousPointer.copy()}set previousPointer(t){this.callStack.currentThread.previousPointer=t.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 t=new za.StringBuilder,e=false;for(let n of this.outputStream){let i=(0, M.asOrNull)(n,$.StringValue);if(!e&&i!==null)t.Append(i.value);else {let a=(0, M.asOrNull)(n,et.ControlCommand);a!==null&&(a.commandType==et.ControlCommand.CommandType.BeginTag?e=true:a.commandType==et.ControlCommand.CommandType.EndTag&&(e=false));}}this._currentText=this.CleanOutputWhitespace(t.toString()),this._outputStreamTextDirty=false;}return this._currentText}CleanOutputWhitespace(t){let e=new za.StringBuilder,n=-1,i=0;for(let a=0;a<t.length;a++){let r=t.charAt(a),o=r==" "||r=="	";o&&n==-1&&(n=a),o||(r!=`
`&&n>0&&n!=i&&e.Append(" "),n=-1),r==`
`&&(i=a+1),o||e.Append(r);}return e.toString()}get currentTags(){if(this._outputStreamTagsDirty){this._currentTags=[];let t=false,e=new za.StringBuilder;for(let n of this.outputStream){let i=(0, M.asOrNull)(n,et.ControlCommand);if(i!=null){if(i.commandType==et.ControlCommand.CommandType.BeginTag){if(t&&e.Length>0){let a=this.CleanOutputWhitespace(e.toString());this._currentTags.push(a),e.Clear();}t=true;}else if(i.commandType==et.ControlCommand.CommandType.EndTag){if(e.Length>0){let a=this.CleanOutputWhitespace(e.toString());this._currentTags.push(a),e.Clear();}t=false;}}else if(t){let a=(0, M.asOrNull)(n,$.StringValue);a!==null&&e.Append(a.value);}else {let a=(0, M.asOrNull)(n,df.Tag);a!=null&&a.text!=null&&a.text.length>0&&this._currentTags.push(a.text);}}if(e.Length>0){let n=this.CleanOutputWhitespace(e.toString());this._currentTags.push(n),e.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 t of this._namedFlows.keys())t!=this.kDefaultFlowName&&this._aliveFlowNames.push(t);this._aliveFlowNamesDirty=false;}return this._aliveFlowNames}get inExpressionEvaluation(){return this.callStack.currentElement.inExpressionEvaluation}set inExpressionEvaluation(t){this.callStack.currentElement.inExpressionEvaluation=t;}constructor(t){this.kInkSaveStateVersion=10,this.kMinCompatibleLoadVersion=8,this.onDidLoadState=null,this._currentErrors=null,this._currentWarnings=null,this.divertedPointer=Pe.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=t,this._currentFlow=new xr.Flow(this.kDefaultFlowName,t),this.OutputStreamDirty(),this._aliveFlowNamesDirty=true,this._evaluationStack=[],this._variablesState=new cf.VariablesState(this.callStack,t.listDefinitions),this._visitCounts=new Map,this._turnIndices=new Map,this.currentTurnIndex=-1;let e=new Date().getTime();this.storySeed=new ff.PRNG(e).next()%100,this.previousRandom=0,this.GoToStart();}GoToStart(){this.callStack.currentElement.currentPointer=Pe.Pointer.StartOf(this.story.mainContentContainer);}SwitchFlow_Internal(t){if(t===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)),t===this._currentFlow.name)return;let e,n=(0, cn.tryGetValueFromMap)(this._namedFlows,t,null);n.exists?e=n.result:(e=new xr.Flow(t,this.story),this._namedFlows.set(t,e),this._aliveFlowNamesDirty=true),this._currentFlow=e,this.variablesState.callStack=this._currentFlow.callStack,this.OutputStreamDirty();}SwitchToDefaultFlow_Internal(){this._namedFlows!==null&&this.SwitchFlow_Internal(this.kDefaultFlowName);}RemoveFlow_Internal(t){if(t===null)throw new Error("Must pass a non-null string to Story.DestroyFlow");if(t===this.kDefaultFlowName)throw new Error("Cannot destroy default flow");if(this._currentFlow.name===t&&this.SwitchToDefaultFlow_Internal(),this._namedFlows===null)return (0, mt.throwNullException)("this._namedFlows");this._namedFlows.delete(t),this._aliveFlowNamesDirty=true;}CopyAndStartPatching(t){let e=new s(this.story);if(e._patch=new Cf.StatePatch(this._patch),e._currentFlow.name=this._currentFlow.name,e._currentFlow.callStack=new hf.CallStack(this._currentFlow.callStack),e._currentFlow.outputStream.push(...this._currentFlow.outputStream),e.OutputStreamDirty(),t)for(let n of this._currentFlow.currentChoices)e._currentFlow.currentChoices.push(n.Clone());else e._currentFlow.currentChoices.push(...this._currentFlow.currentChoices);if(this._namedFlows!==null){e._namedFlows=new Map;for(let[n,i]of this._namedFlows)e._namedFlows.set(n,i),e._aliveFlowNamesDirty=true;e._namedFlows.set(this._currentFlow.name,e._currentFlow);}return this.hasError&&(e._currentErrors=[],e._currentErrors.push(...this.currentErrors||[])),this.hasWarning&&(e._currentWarnings=[],e._currentWarnings.push(...this.currentWarnings||[])),e.variablesState=this.variablesState,e.variablesState.callStack=e.callStack,e.variablesState.patch=e._patch,e.evaluationStack.push(...this.evaluationStack),this.divertedPointer.isNull||(e.divertedPointer=this.divertedPointer.copy()),e.previousPointer=this.previousPointer.copy(),e._visitCounts=this._visitCounts,e._turnIndices=this._turnIndices,e.currentTurnIndex=this.currentTurnIndex,e.storySeed=this.storySeed,e.previousRandom=this.previousRandom,e.didSafeExit=this.didSafeExit,e}RestoreAfterPatch(){this.variablesState.callStack=this.callStack,this.variablesState.patch=this._patch;}ApplyAnyPatch(){if(this._patch!==null){this.variablesState.ApplyPatch();for(let[t,e]of this._patch.visitCounts)this.ApplyCountChanges(t,e,true);for(let[t,e]of this._patch.turnIndices)this.ApplyCountChanges(t,e,false);this._patch=null;}}ApplyCountChanges(t,e,n){(n?this._visitCounts:this._turnIndices).set(t.path.toString(),e);}WriteJson(t){if(t.WriteObjectStart(),t.WritePropertyStart("flows"),t.WriteObjectStart(),this._namedFlows!==null)for(let[e,n]of this._namedFlows)t.WriteProperty(e,i=>n.WriteJson(i));else t.WriteProperty(this._currentFlow.name,e=>this._currentFlow.WriteJson(e));if(t.WriteObjectEnd(),t.WritePropertyEnd(),t.WriteProperty("currentFlowName",this._currentFlow.name),t.WriteProperty("variablesState",e=>this.variablesState.WriteJson(e)),t.WriteProperty("evalStack",e=>Gt.JsonSerialisation.WriteListRuntimeObjs(e,this.evaluationStack)),!this.divertedPointer.isNull){if(this.divertedPointer.path===null)return (0, mt.throwNullException)("divertedPointer");t.WriteProperty("currentDivertTarget",this.divertedPointer.path.componentsString);}t.WriteProperty("visitCounts",e=>Gt.JsonSerialisation.WriteIntDictionary(e,this._visitCounts)),t.WriteProperty("turnIndices",e=>Gt.JsonSerialisation.WriteIntDictionary(e,this._turnIndices)),t.WriteIntProperty("turnIdx",this.currentTurnIndex),t.WriteIntProperty("storySeed",this.storySeed),t.WriteIntProperty("previousRandom",this.previousRandom),t.WriteIntProperty("inkSaveVersion",this.kInkSaveStateVersion),t.WriteIntProperty("inkFormatVersion",gf.Story.inkVersionCurrent),t.WriteObjectEnd();}LoadJsonObj(t){let e=t,n=e.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 i=e.flows;if(i!=null){let r=i;Object.keys(r).length===1?this._namedFlows=null:this._namedFlows===null?this._namedFlows=new Map:this._namedFlows.clear();let o=Object.entries(r);for(let[l,u]of o){let h=l,c=u,d=new xr.Flow(h,this.story,c);if(Object.keys(r).length===1)this._currentFlow=new xr.Flow(h,this.story,c);else {if(this._namedFlows===null)return (0, mt.throwNullException)("this._namedFlows");this._namedFlows.set(h,d);}}if(this._namedFlows!=null&&this._namedFlows.size>1){let l=e.currentFlowName;this._currentFlow=this._namedFlows.get(l);}}else {this._namedFlows=null,this._currentFlow.name=this.kDefaultFlowName,this._currentFlow.callStack.SetJsonToken(e.callstackThreads,this.story),this._currentFlow.outputStream=Gt.JsonSerialisation.JArrayToRuntimeObjList(e.outputStream),this._currentFlow.currentChoices=Gt.JsonSerialisation.JArrayToRuntimeObjList(e.currentChoices);let r=e.choiceThreads;this._currentFlow.LoadFlowChoiceThreads(r,this.story);}this.OutputStreamDirty(),this._aliveFlowNamesDirty=true,this.variablesState.SetJsonToken(e.variablesState),this.variablesState.callStack=this._currentFlow.callStack,this._evaluationStack=Gt.JsonSerialisation.JArrayToRuntimeObjList(e.evalStack);let a=e.currentDivertTarget;if(a!=null){let r=new Gl.Path(a.toString());this.divertedPointer=this.story.PointerAtPath(r);}this._visitCounts=Gt.JsonSerialisation.JObjectToIntDictionary(e.visitCounts),this._turnIndices=Gt.JsonSerialisation.JObjectToIntDictionary(e.turnIndices),this.currentTurnIndex=parseInt(e.turnIdx),this.storySeed=parseInt(e.storySeed),this.previousRandom=parseInt(e.previousRandom);}ResetErrors(){this._currentErrors=null,this._currentWarnings=null;}ResetOutput(t=null){this.outputStream.length=0,t!==null&&this.outputStream.push(...t),this.OutputStreamDirty();}PushToOutputStream(t){let e=(0, M.asOrNull)(t,$.StringValue);if(e!==null){let n=this.TrySplittingHeadTailWhitespace(e);if(n!==null){for(let i of n)this.PushToOutputStreamIndividual(i);this.OutputStreamDirty();return}}this.PushToOutputStreamIndividual(t),this.OutputStreamDirty();}PopFromOutputStream(t){this.outputStream.splice(this.outputStream.length-t,t),this.OutputStreamDirty();}TrySplittingHeadTailWhitespace(t){let e=t.value;if(e===null)return (0, mt.throwNullException)("single.value");let n=-1,i=-1;for(let h=0;h<e.length;h++){let c=e[h];if(c==`
`)n==-1&&(n=h),i=h;else {if(c==" "||c=="	")continue;break}}let a=-1,r=-1;for(let h=e.length-1;h>=0;h--){let c=e[h];if(c==`
`)a==-1&&(a=h),r=h;else {if(c==" "||c=="	")continue;break}}if(n==-1&&a==-1)return null;let o=[],l=0,u=e.length;if(n!=-1){if(n>0){let h=new $.StringValue(e.substring(0,n));o.push(h);}o.push(new $.StringValue(`
`)),l=i+1;}if(a!=-1&&(u=r),u>l){let h=e.substring(l,u);o.push(new $.StringValue(h));}if(a!=-1&&r>i&&(o.push(new $.StringValue(`
`)),a<e.length-1)){let h=e.length-a-1,c=new $.StringValue(e.substring(a+1,a+1+h));o.push(c);}return o}PushToOutputStreamIndividual(t){let e=(0, M.asOrNull)(t,Ka.Glue),n=(0, M.asOrNull)(t,$.StringValue),i=true;if(e)this.TrimNewlinesFromOutputStream(),i=true;else if(n){let a=-1,r=this.callStack.currentElement;r.type==Bt.PushPopType.Function&&(a=r.functionStartInOutputStream);let o=-1;for(let u=this.outputStream.length-1;u>=0;u--){let h=this.outputStream[u],c=h instanceof et.ControlCommand?h:null;if((h instanceof Ka.Glue?h:null)!=null){o=u;break}else if(c!=null&&c.commandType==et.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)i=false;else if(n.isNonWhitespace&&(o>-1&&this.RemoveExistingGlue(),a>-1)){let u=this.callStack.elements;for(let h=u.length-1;h>=0;h--){let c=u[h];if(c.type==Bt.PushPopType.Function)c.functionStartInOutputStream=-1;else break}}}else n.isNewline&&(this.outputStreamEndsInNewline||!this.outputStreamContainsContent)&&(i=false);}if(i){if(t===null)return (0, mt.throwNullException)("obj");this.outputStream.push(t),this.OutputStreamDirty();}}TrimNewlinesFromOutputStream(){let t=-1,e=this.outputStream.length-1;for(;e>=0;){let n=this.outputStream[e],i=(0, M.asOrNull)(n,et.ControlCommand),a=(0, M.asOrNull)(n,$.StringValue);if(i!=null||a!=null&&a.isNonWhitespace)break;a!=null&&a.isNewline&&(t=e),e--;}if(t>=0)for(e=t;e<this.outputStream.length;)(0, M.asOrNull)(this.outputStream[e],$.StringValue)?this.outputStream.splice(e,1):e++;this.OutputStreamDirty();}RemoveExistingGlue(){for(let t=this.outputStream.length-1;t>=0;t--){let e=this.outputStream[t];if(e instanceof Ka.Glue)this.outputStream.splice(t,1);else if(e instanceof et.ControlCommand)break}this.OutputStreamDirty();}get outputStreamEndsInNewline(){if(this.outputStream.length>0)for(let t=this.outputStream.length-1;t>=0&&!(this.outputStream[t]instanceof et.ControlCommand);t--){let n=this.outputStream[t];if(n instanceof $.StringValue){if(n.isNewline)return  true;if(n.isNonWhitespace)break}}return  false}get outputStreamContainsContent(){for(let t of this.outputStream)if(t instanceof $.StringValue)return  true;return  false}get inStringEvaluation(){for(let t=this.outputStream.length-1;t>=0;t--){let e=(0, M.asOrNull)(this.outputStream[t],et.ControlCommand);if(e instanceof et.ControlCommand&&e.commandType==et.ControlCommand.CommandType.BeginString)return  true}return  false}PushEvaluationStack(t){let e=(0, M.asOrNull)(t,$.ListValue);if(e){let n=e.value;if(n===null)return (0, mt.throwNullException)("rawList");if(n.originNames!=null){n.origins||(n.origins=[]),n.origins.length=0;for(let i of n.originNames){if(this.story.listDefinitions===null)return (0, mt.throwNullException)("StoryState.story.listDefinitions");let a=this.story.listDefinitions.TryListGetDefinition(i,null);if(a.result===null)return (0, mt.throwNullException)("StoryState def.result");n.origins.indexOf(a.result)<0&&n.origins.push(a.result);}}}if(t===null)return (0, mt.throwNullException)("obj");this.evaluationStack.push(t);}PopEvaluationStack(t){if(typeof t>"u"){let e=this.evaluationStack.pop();return (0, M.nullIfUndefined)(e)}else {if(t>this.evaluationStack.length)throw new Error("trying to pop too many objects");let e=this.evaluationStack.splice(this.evaluationStack.length-t,t);return (0, M.nullIfUndefined)(e)}}PeekEvaluationStack(){return this.evaluationStack[this.evaluationStack.length-1]}ForceEnd(){this.callStack.Reset(),this._currentFlow.currentChoices.length=0,this.currentPointer=Pe.Pointer.Null,this.previousPointer=Pe.Pointer.Null,this.didSafeExit=true;}TrimWhitespaceFromFunctionEnd(){mf.Debug.Assert(this.callStack.currentElement.type==Bt.PushPopType.Function);let t=this.callStack.currentElement.functionStartInOutputStream;t==-1&&(t=0);for(let e=this.outputStream.length-1;e>=t;e--){let n=this.outputStream[e],i=(0, M.asOrNull)(n,$.StringValue),a=(0, M.asOrNull)(n,et.ControlCommand);if(i!=null){if(a)break;if(i.isNewline||i.isInlineWhitespace)this.outputStream.splice(e,1),this.OutputStreamDirty();else break}}}PopCallStack(t=null){this.callStack.currentElement.type==Bt.PushPopType.Function&&this.TrimWhitespaceFromFunctionEnd(),this.callStack.Pop(t);}SetChosenPath(t,e){this._currentFlow.currentChoices.length=0;let n=this.story.PointerAtPath(t);!n.isNull&&n.index==-1&&(n.index=0),this.currentPointer=n,e&&this.currentTurnIndex++;}StartFunctionEvaluationFromGame(t,e){this.callStack.Push(Bt.PushPopType.FunctionEvaluationFromGame,this.evaluationStack.length),this.callStack.currentElement.currentPointer=Pe.Pointer.StartOf(t),this.PassArgumentsToEvaluationStack(e);}PassArgumentsToEvaluationStack(t){if(t!==null)for(let e=0;e<t.length;e++){if(!(typeof t[e]=="number"||typeof t[e]=="string"||typeof t[e]=="boolean"||t[e]instanceof vf.InkList))throw new Error("ink arguments when calling EvaluateFunction / ChoosePathStringWithParameters must benumber, string, bool or InkList. Argument was "+((0, M.nullIfUndefined)(t[e])===null?"null":t[e].constructor.name));this.PushEvaluationStack($.Value.Create(t[e]));}}TryExitFunctionEvaluationFromGame(){return this.callStack.currentElement.type==Bt.PushPopType.FunctionEvaluationFromGame?(this.currentPointer=Pe.Pointer.Null,this.didSafeExit=true,true):false}CompleteFunctionEvaluationFromGame(){if(this.callStack.currentElement.type!=Bt.PushPopType.FunctionEvaluationFromGame)throw new Error("Expected external function evaluation to be complete. Stack trace: "+this.callStack.callStackTrace);let t=this.callStack.currentElement.evaluationStackHeightWhenPushed,e=null;for(;this.evaluationStack.length>t;){let n=this.PopEvaluationStack();e===null&&(e=n);}if(this.PopCallStack(Bt.PushPopType.FunctionEvaluationFromGame),e){if(e instanceof pf.Void)return null;let n=(0, M.asOrThrows)(e,$.Value);return n.valueType==$.ValueType.DivertTarget?"-> "+n.valueObject.toString():n.valueObject}return null}AddError(t,e){e?(this._currentWarnings==null&&(this._currentWarnings=[]),this._currentWarnings.push(t)):(this._currentErrors==null&&(this._currentErrors=[]),this._currentErrors.push(t));}OutputStreamDirty(){this._outputStreamTextDirty=true,this._outputStreamTagsDirty=true;}};Tr.StoryState=Xa;});var Ul=p(Or=>{Object.defineProperty(Or,"__esModule",{value:true});Or.Stopwatch=void 0;var Ya=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;}};Or.Stopwatch=Ya;});var Kl=p(Nr=>{Object.defineProperty(Nr,"__esModule",{value:true});Nr.ErrorType=void 0;var Hl;(function(s){s[s.Author=0]="Author",s[s.Warning=1]="Warning",s[s.Error=2]="Error";})(Hl||(Nr.ErrorType=Hl={}));});var on=p(re=>{Object.defineProperty(re,"__esModule",{value:true});re.Story=re.InkList=void 0;var Y=L(),Za=rt(),Qa=Ee(),Sf=Jl(),E=z(),gt=Yt(),yf=Xn(),bf=ka(),zl=Pt(),b=k(),to=it(),dn=Xt(),Ar=fr(),_f=Lt(),Ef=ye(),Pf=Et(),ne=We(),eo=$a(),ie=Kt(),wf=Wa(),xf=Ul(),$t=Ke(),fn=at(),P=O(),T=K(),Xl=Ua(),Yl=Kl(),Tf=at();Object.defineProperty(re,"InkList",{enumerable:true,get:function(){return Tf.InkList}});Number.isInteger||(Number.isInteger=function(t){return typeof t=="number"&&isFinite(t)&&t>-9007199254740992&&t<9007199254740992&&Math.floor(t)===t});var we=class s extends Za.InkObject{get currentChoices(){let t=[];if(this._state===null)return (0, T.throwNullException)("this._state");for(let e of this._state.currentChoices)e.isInvisibleDefault||(e.index=t.length,t.push(e));return t}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 t,e=null,n=null;if(arguments[0]instanceof Y.Container)t=arguments[0],typeof arguments[1]<"u"&&(e=arguments[1]),this._mainContentContainer=t;else if(typeof arguments[0]=="string"){let i=arguments[0];n=Xl.SimpleJson.TextToDictionary(i);}else n=arguments[0];if(e!=null&&(this._listDefinitions=new wf.ListDefinitionsOrigin(e)),this._externals=new Map,n!==null){let i=n,a=i.inkVersion;if(a==null)throw new Error("ink version number not found. Are you sure it's a valid .ink.json file?");let r=parseInt(a);if(r>s.inkVersionCurrent)throw new Error("Version of ink used to build story was newer than the current version of the engine");if(r<this.inkVersionMinimumCompatible)throw new Error("Version of ink used to build story is too old to be loaded by this version of the engine");r!=s.inkVersionCurrent&&console.warn(`WARNING: Version of ink ${s.inkVersionCurrent} used to build story doesn't match current version of engine (${r}). Non-critical, but recommend synchronising.`);let o=i.root;if(o==null)throw new Error("Root node for ink not found. Are you sure it's a valid .ink.json file?");let l;(l=i.listDefs)&&(this._listDefinitions=Qa.JsonSerialisation.JTokenToListDefinitions(l)),this._mainContentContainer=(0, P.asOrThrows)(Qa.JsonSerialisation.JTokenToRuntimeObject(o),Y.Container),this.ResetState();}}ToJson(t){let e=false;if(t||(e=true,t=new Xl.SimpleJson.Writer),t.WriteObjectStart(),t.WriteIntProperty("inkVersion",s.inkVersionCurrent),t.WriteProperty("root",n=>Qa.JsonSerialisation.WriteRuntimeContainer(n,this._mainContentContainer)),this._listDefinitions!=null){t.WritePropertyStart("listDefs"),t.WriteObjectStart();for(let n of this._listDefinitions.lists){t.WritePropertyStart(n.name),t.WriteObjectStart();for(let[i,a]of n.items){let r=fn.InkListItem.fromSerializedKey(i),o=a;t.WriteIntProperty(r.itemName,o);}t.WriteObjectEnd(),t.WritePropertyEnd();}t.WriteObjectEnd(),t.WritePropertyEnd();}if(t.WriteObjectEnd(),e)return t.toString()}ResetState(){this.IfAsyncWeCant("ResetState"),this._state=new Sf.StoryState(this),this._state.variablesState.ObserveVariableChange(this.VariableStateDidChangeEvent.bind(this)),this.ResetGlobals();}ResetErrors(){if(this._state===null)return (0, T.throwNullException)("this._state");this._state.ResetErrors();}ResetCallstack(){if(this.IfAsyncWeCant("ResetCallstack"),this._state===null)return (0, T.throwNullException)("this._state");this._state.ForceEnd();}ResetGlobals(){if(this._mainContentContainer.namedContent.get("global decl")){let t=this.state.currentPointer.copy();this.ChoosePath(new to.Path("global decl"),false),this.ContinueInternal(),this.state.currentPointer=t;}this.state.variablesState.SnapshotDefaultGlobals();}SwitchFlow(t){if(this.IfAsyncWeCant("switch flow"),this._asyncSaving)throw new Error("Story is already in background saving mode, can't switch flow to "+t);this.state.SwitchFlow_Internal(t);}RemoveFlow(t){this.state.RemoveFlow_Internal(t);}SwitchToDefaultFlow(){this.state.SwitchToDefaultFlow_Internal();}Continue(){return this.ContinueAsync(0),this.currentText}get canContinue(){return this.state.canContinue}get asyncContinueComplete(){return !this._asyncContinueActive}ContinueAsync(t){this._hasValidatedExternals||this.ValidateExternalBindings(),this.ContinueInternal(t);}ContinueInternal(t=0){this._profiler!=null&&this._profiler.PreContinue();let e=t>0;if(this._recursiveContinueCount++,this._asyncContinueActive)this._asyncContinueActive&&!e&&(this._asyncContinueActive=false);else {if(this._asyncContinueActive=e,!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 xf.Stopwatch;n.Start();let i=false;this._sawLookaheadUnsafeFunctionAfterNewline=false;do{try{i=this.ContinueSingleStep();}catch(r){if(!(r instanceof ne.StoryException))throw r;this.AddError(r.message,void 0,r.useEndLineNumber);break}if(i||this._asyncContinueActive&&n.ElapsedMilliseconds>t)break}while(this.canContinue);n.Stop();let a=null;if((i||!this.canContinue)&&(this._stateSnapshotAtLastNewline!==null&&this.RestoreStateSnapshot(),this.canContinue||(this.state.callStack.canPopThread&&this.AddError("Thread available to pop, threads should always be flat by the end of evaluation?"),this.state.generatedChoices.length==0&&!this.state.didSafeExit&&this._temporaryEvaluationContainer==null&&(this.state.callStack.CanPop(gt.PushPopType.Tunnel)?this.AddError("unexpectedly reached end of content. Do you need a '->->' to return from a tunnel?"):this.state.callStack.CanPop(gt.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 r of this.state.currentErrors)this.onError(r,Yl.ErrorType.Error);if(this.state.hasWarning)for(let r of this.state.currentWarnings)this.onError(r,Yl.ErrorType.Warning);this.ResetErrors();}else {let r=new ie.StringBuilder;throw r.Append("Ink had "),this.state.hasError&&(r.Append(`${this.state.currentErrors.length}`),r.Append(this.state.currentErrors.length==1?" error":" errors"),this.state.hasWarning&&r.Append(" and ")),this.state.hasWarning&&(r.Append(`${this.state.currentWarnings.length}`),r.Append(this.state.currentWarnings.length==1?" warning":" warnings"),this.state.hasWarning&&r.Append(" and ")),r.Append(". It is strongly suggested that you assign an error handler to story.onError. The first issue was: "),r.Append(this.state.hasError?this.state.currentErrors[0]:this.state.currentWarnings[0]),new ne.StoryException(r.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, T.throwNullException)("this._stateAtLastNewline.currentTags");if(this.state.currentTags===null)return (0, T.throwNullException)("this.state.currentTags");let t=this.CalculateNewlineOutputStateChange(this._stateSnapshotAtLastNewline.currentText,this.state.currentText,this._stateSnapshotAtLastNewline.currentTags.length,this.state.currentTags.length);if(t==s.OutputStateChange.ExtendedBeyondNewline||this._sawLookaheadUnsafeFunctionAfterNewline)return this.RestoreStateSnapshot(),true;t==s.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(t,e,n,i){if(t===null)return (0, T.throwNullException)("prevText");if(e===null)return (0, T.throwNullException)("currText");let a=e.length>=t.length&&t.length>0&&e.charAt(t.length-1)==`
`;if(n==i&&t.length==e.length&&a)return s.OutputStateChange.NoChange;if(!a)return s.OutputStateChange.NewlineRemoved;if(i>n)return s.OutputStateChange.ExtendedBeyondNewline;for(let r=t.length;r<e.length;r++){let o=e.charAt(r);if(o!=" "&&o!="	")return s.OutputStateChange.ExtendedBeyondNewline}return s.OutputStateChange.NoChange}ContinueMaximally(){this.IfAsyncWeCant("ContinueMaximally");let t=new ie.StringBuilder;for(;this.canContinue;)t.Append(this.Continue());return t.toString()}ContentAtPath(t){return this.mainContentContainer.ContentAtPath(t)}KnotContainerWithName(t){let e=this.mainContentContainer.namedContent.get(t);return e instanceof Y.Container?e:null}PointerAtPath(t){if(t.length==0)return $t.Pointer.Null;let e=new $t.Pointer,n=t.length,i=null;return t.lastComponent===null?(0, T.throwNullException)("path.lastComponent"):(t.lastComponent.isIndex?(n=t.length-1,i=this.mainContentContainer.ContentAtPath(t,void 0,n),e.container=i.container,e.index=t.lastComponent.index):(i=this.mainContentContainer.ContentAtPath(t),e.container=i.container,e.index=-1),i.obj==null||i.obj==this.mainContentContainer&&n>0?this.Error("Failed to find content at path '"+t+"', and no approximation of it was possible."):i.approximate&&this.Warning("Failed to find content at path '"+t+"', so it was approximated to: '"+i.obj.path+"'."),e)}StateSnapshot(){this._stateSnapshotAtLastNewline=this._state,this._state=this._state.CopyAndStartPatching(false);}RestoreStateSnapshot(){this._stateSnapshotAtLastNewline===null&&(0, T.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 t=this._state;return this._state=this._state.CopyAndStartPatching(true),this._asyncSaving=true,t}BackgroundSaveComplete(){this._stateSnapshotAtLastNewline===null&&this._state.ApplyAnyPatch(),this._asyncSaving=false;}Step(){let t=true,e=this.state.currentPointer.copy();if(e.isNull)return;let n=(0, P.asOrNull)(e.Resolve(),Y.Container);for(;n&&(this.VisitContainer(n,true),n.content.length!=0);)e=$t.Pointer.StartOf(n),n=(0, P.asOrNull)(e.Resolve(),Y.Container);this.state.currentPointer=e.copy(),this._profiler!=null&&this._profiler.Step(this.state.callStack);let i=e.Resolve(),a=this.PerformLogicAndFlowControl(i);if(this.state.currentPointer.isNull)return;a&&(t=false);let r=(0, P.asOrNull)(i,yf.ChoicePoint);if(r){let l=this.ProcessChoice(r);l&&this.state.generatedChoices.push(l),i=null,t=false;}if(i instanceof Y.Container&&(t=false),t){let l=(0, P.asOrNull)(i,b.VariablePointerValue);if(l&&l.contextIndex==-1){let u=this.state.callStack.ContextForVariableNamed(l.variableName);i=new b.VariablePointerValue(l.variableName,u);}this.state.inExpressionEvaluation?this.state.PushEvaluationStack(i):this.state.PushToOutputStream(i);}this.NextContent();let o=(0, P.asOrNull)(i,E.ControlCommand);o&&o.commandType==E.ControlCommand.CommandType.StartThread&&this.state.callStack.PushThread();}VisitContainer(t,e){(!t.countingAtStartOnly||e)&&(t.visitsShouldBeCounted&&this.state.IncrementVisitCountForContainer(t),t.turnIndexShouldBeCounted&&this.state.RecordTurnIndexVisitToContainer(t));}VisitChangedContainersDueToDivert(){let t=this.state.previousPointer.copy(),e=this.state.currentPointer.copy();if(e.isNull||e.index==-1)return;if(this._prevContainers.length=0,!t.isNull){let r=t.Resolve(),o=(0, P.asOrNull)(r,Y.Container)||(0, P.asOrNull)(t.container,Y.Container);for(;o;)this._prevContainers.push(o),o=(0, P.asOrNull)(o.parent,Y.Container);}let n=e.Resolve();if(n==null)return;let i=(0, P.asOrNull)(n.parent,Y.Container),a=true;for(;i&&(this._prevContainers.indexOf(i)<0||i.countingAtStartOnly);){let r=i.content.length>0&&n==i.content[0]&&a;r||(a=false),this.VisitContainer(i,r),n=i,i=(0, P.asOrNull)(i.parent,Y.Container);}}PopChoiceStringAndTags(t){let e=(0, P.asOrThrows)(this.state.PopEvaluationStack(),b.StringValue);for(;this.state.evaluationStack.length>0&&(0, P.asOrNull)(this.state.PeekEvaluationStack(),Ar.Tag)!=null;){let n=(0, P.asOrNull)(this.state.PopEvaluationStack(),Ar.Tag);n&&t.push(n.text);}return e.value}ProcessChoice(t){let e=true;if(t.hasCondition){let o=this.state.PopEvaluationStack();this.IsTruthy(o)||(e=false);}let n="",i="",a=[];if(t.hasChoiceOnlyContent&&(i=this.PopChoiceStringAndTags(a)||""),t.hasStartContent&&(n=this.PopChoiceStringAndTags(a)||""),t.onceOnly&&this.state.VisitCountForContainer(t.choiceTarget)>0&&(e=false),!e)return null;let r=new bf.Choice;return r.targetPath=t.pathOnChoice,r.sourcePath=t.path.toString(),r.isInvisibleDefault=t.isInvisibleDefault,r.threadAtGeneration=this.state.callStack.ForkThread(),r.tags=a.reverse(),r.text=(n+i).replace(/^[ \t]+|[ \t]+$/g,""),r}IsTruthy(t){let e=false;if(t instanceof b.Value){let n=t;if(n instanceof b.DivertTargetValue){let i=n;return this.Error("Shouldn't use a divert target (to "+i.targetPath+") as a conditional value. Did you intend a function call 'likeThis()' or a read count check 'likeThis'? (no arrows)"),false}return n.isTruthy}return e}PerformLogicAndFlowControl(t){if(t==null)return  false;if(t instanceof zl.Divert){let e=t;if(e.isConditional){let n=this.state.PopEvaluationStack();if(!this.IsTruthy(n))return  true}if(e.hasVariableTarget){let n=e.variableDivertName,i=this.state.variablesState.GetVariableWithName(n);if(i==null)this.Error("Tried to divert using a target from a variable that could not be found ("+n+")");else if(!(i instanceof b.DivertTargetValue)){let r=(0, P.asOrNull)(i,b.IntValue),o="Tried to divert to a target from a variable, but the variable ("+n+") didn't contain a divert target, it ";r instanceof b.IntValue&&r.value==0?o+="was empty/null (the value 0).":o+="contained '"+i+"'.",this.Error(o);}let a=(0, P.asOrThrows)(i,b.DivertTargetValue);this.state.divertedPointer=this.PointerAtPath(a.targetPath);}else {if(e.isExternal)return this.CallExternalFunction(e.targetPathString,e.externalArgs),true;this.state.divertedPointer=e.targetPointer.copy();}return e.pushesToStack&&this.state.callStack.Push(e.stackPushType,void 0,this.state.outputStream.length),this.state.divertedPointer.isNull&&!e.isExternal&&(e&&e.debugMetadata&&e.debugMetadata.sourceName!=null?this.Error("Divert target doesn't exist: "+e.debugMetadata.sourceName):this.Error("Divert resolution failed: "+e)),true}else if(t instanceof E.ControlCommand){let e=t;switch(e.commandType){case E.ControlCommand.CommandType.EvalStart:this.Assert(this.state.inExpressionEvaluation===false,"Already in expression evaluation?"),this.state.inExpressionEvaluation=true;break;case E.ControlCommand.CommandType.EvalEnd:this.Assert(this.state.inExpressionEvaluation===true,"Not in expression evaluation mode"),this.state.inExpressionEvaluation=false;break;case E.ControlCommand.CommandType.EvalOutput:if(this.state.evaluationStack.length>0){let C=this.state.PopEvaluationStack();if(!(C instanceof dn.Void)){let _=new b.StringValue(C.toString());this.state.PushToOutputStream(_);}}break;case E.ControlCommand.CommandType.NoOp:break;case E.ControlCommand.CommandType.Duplicate:this.state.PushEvaluationStack(this.state.PeekEvaluationStack());break;case E.ControlCommand.CommandType.PopEvaluatedValue:this.state.PopEvaluationStack();break;case E.ControlCommand.CommandType.PopFunction:case E.ControlCommand.CommandType.PopTunnel:let n=e.commandType==E.ControlCommand.CommandType.PopFunction?gt.PushPopType.Function:gt.PushPopType.Tunnel,i=null;if(n==gt.PushPopType.Tunnel){let C=this.state.PopEvaluationStack();i=(0, P.asOrNull)(C,b.DivertTargetValue),i===null&&this.Assert(C instanceof dn.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(gt.PushPopType.Function,"function return statement (~ return)"),C.set(gt.PushPopType.Tunnel,"tunnel onwards statement (->->)");let _=C.get(this.state.callStack.currentElement.type);this.state.callStack.canPop||(_="end of flow (-> END or choice)");let B="Found "+C.get(n)+", when expected "+_;this.Error(B);}else this.state.PopCallStack(),i&&(this.state.divertedPointer=this.PointerAtPath(i.targetPath));break;case E.ControlCommand.CommandType.BeginString:this.state.PushToOutputStream(e),this.Assert(this.state.inExpressionEvaluation===true,"Expected to be in an expression when evaluating a string"),this.state.inExpressionEvaluation=false;break;case E.ControlCommand.CommandType.BeginTag:this.state.PushToOutputStream(e);break;case E.ControlCommand.CommandType.EndTag:{if(this.state.inStringEvaluation){let C=[],_=0;for(let Q=this.state.outputStream.length-1;Q>=0;--Q){let tt=this.state.outputStream[Q];_++;let At=(0, P.asOrNull)(tt,E.ControlCommand);if(At!=null){if(At.commandType==E.ControlCommand.CommandType.BeginTag)break;this.Error("Unexpected ControlCommand while extracting tag from choice");break}tt instanceof b.StringValue&&C.push(tt);}this.state.PopFromOutputStream(_);let B=new ie.StringBuilder;for(let Q of C.reverse())B.Append(Q.toString());let kt=new Ar.Tag(this.state.CleanOutputWhitespace(B.toString()));this.state.PushEvaluationStack(kt);}else this.state.PushToOutputStream(e);break}case E.ControlCommand.CommandType.EndString:{let C=[],_=[],B=0;for(let Q=this.state.outputStream.length-1;Q>=0;--Q){let tt=this.state.outputStream[Q];B++;let At=(0, P.asOrNull)(tt,E.ControlCommand);if(At&&At.commandType==E.ControlCommand.CommandType.BeginString)break;tt instanceof Ar.Tag&&_.push(tt),tt instanceof b.StringValue&&C.push(tt);}this.state.PopFromOutputStream(B);for(let Q of _)this.state.PushToOutputStream(Q);C=C.reverse();let kt=new ie.StringBuilder;for(let Q of C)kt.Append(Q.toString());this.state.inExpressionEvaluation=true,this.state.PushEvaluationStack(new b.StringValue(kt.toString()));break}case E.ControlCommand.CommandType.ChoiceCount:let a=this.state.generatedChoices.length;this.state.PushEvaluationStack(new b.IntValue(a));break;case E.ControlCommand.CommandType.Turns:this.state.PushEvaluationStack(new b.IntValue(this.state.currentTurnIndex+1));break;case E.ControlCommand.CommandType.TurnsSince:case E.ControlCommand.CommandType.ReadCount:let r=this.state.PopEvaluationStack();if(!(r instanceof b.DivertTargetValue)){let C="";r instanceof b.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 "+r+C);break}let o=(0, P.asOrThrows)(r,b.DivertTargetValue),l=(0, P.asOrNull)(this.ContentAtPath(o.targetPath).correctObj,Y.Container),u;l!=null?e.commandType==E.ControlCommand.CommandType.TurnsSince?u=this.state.TurnsSinceForContainer(l):u=this.state.VisitCountForContainer(l):(e.commandType==E.ControlCommand.CommandType.TurnsSince?u=-1:u=0,this.Warning("Failed to find container for "+e.toString()+" lookup at "+o.targetPath.toString())),this.state.PushEvaluationStack(new b.IntValue(u));break;case E.ControlCommand.CommandType.Random:{let C=(0, P.asOrNull)(this.state.PopEvaluationStack(),b.IntValue),_=(0, P.asOrNull)(this.state.PopEvaluationStack(),b.IntValue);if(_==null||!(_ instanceof b.IntValue))return this.Error("Invalid value for minimum parameter of RANDOM(min, max)");if(C==null||!(C instanceof b.IntValue))return this.Error("Invalid value for maximum parameter of RANDOM(min, max)");if(C.value===null)return (0, T.throwNullException)("maxInt.value");if(_.value===null)return (0, T.throwNullException)("minInt.value");let B=C.value-_.value+1;(!isFinite(B)||B>Number.MAX_SAFE_INTEGER)&&(B=Number.MAX_SAFE_INTEGER,this.Error("RANDOM was called with a range that exceeds the size that ink numbers can use.")),B<=0&&this.Error("RANDOM was called with minimum as "+_.value+" and maximum as "+C.value+". The maximum must be larger");let kt=this.state.storySeed+this.state.previousRandom,tt=new eo.PRNG(kt).next(),At=tt%B+_.value;this.state.PushEvaluationStack(new b.IntValue(At)),this.state.previousRandom=tt;break}case E.ControlCommand.CommandType.SeedRandom:let h=(0, P.asOrNull)(this.state.PopEvaluationStack(),b.IntValue);if(h==null||!(h instanceof b.IntValue))return this.Error("Invalid value passed to SEED_RANDOM");if(h.value===null)return (0, T.throwNullException)("minInt.value");this.state.storySeed=h.value,this.state.previousRandom=0,this.state.PushEvaluationStack(new dn.Void);break;case E.ControlCommand.CommandType.VisitIndex:let c=this.state.VisitCountForContainer(this.state.currentPointer.container)-1;this.state.PushEvaluationStack(new b.IntValue(c));break;case E.ControlCommand.CommandType.SequenceShuffleIndex:let d=this.NextSequenceShuffleIndex();this.state.PushEvaluationStack(new b.IntValue(d));break;case E.ControlCommand.CommandType.StartThread:break;case E.ControlCommand.CommandType.Done:this.state.callStack.canPopThread?this.state.callStack.PopThread():(this.state.didSafeExit=true,this.state.currentPointer=$t.Pointer.Null);break;case E.ControlCommand.CommandType.End:this.state.ForceEnd();break;case E.ControlCommand.CommandType.ListFromInt:let m=(0, P.asOrNull)(this.state.PopEvaluationStack(),b.IntValue),g=(0, P.asOrThrows)(this.state.PopEvaluationStack(),b.StringValue);if(m===null)throw new ne.StoryException("Passed non-integer when creating a list element from a numerical value.");let S=null;if(this.listDefinitions===null)return (0, T.throwNullException)("this.listDefinitions");let D=this.listDefinitions.TryListGetDefinition(g.value,null);if(D.exists){if(m.value===null)return (0, T.throwNullException)("minInt.value");let C=D.result.TryGetItemWithValue(m.value,fn.InkListItem.Null);C.exists&&(S=new b.ListValue(C.result,m.value));}else throw new ne.StoryException("Failed to find LIST called "+g.value);S==null&&(S=new b.ListValue),this.state.PushEvaluationStack(S);break;case E.ControlCommand.CommandType.ListRange:let N=(0, P.asOrNull)(this.state.PopEvaluationStack(),b.Value),f=(0, P.asOrNull)(this.state.PopEvaluationStack(),b.Value),A=(0, P.asOrNull)(this.state.PopEvaluationStack(),b.ListValue);if(A===null||f===null||N===null)throw new ne.StoryException("Expected list, minimum and maximum for LIST_RANGE");if(A.value===null)return (0, T.throwNullException)("targetList.value");let y=A.value.ListWithSubRange(f.valueObject,N.valueObject);this.state.PushEvaluationStack(new b.ListValue(y));break;case E.ControlCommand.CommandType.ListRandom:{let C=this.state.PopEvaluationStack();if(C===null)throw new ne.StoryException("Expected list for LIST_RANDOM");let _=C.value,B=null;if(_===null)throw (0, T.throwNullException)("list");if(_.Count==0)B=new fn.InkList;else {let kt=this.state.storySeed+this.state.previousRandom,tt=new eo.PRNG(kt).next(),At=tt%_.Count,bo=_.entries();for(let Eo=0;Eo<=At-1;Eo++)bo.next();let _o=bo.next().value,yn={Key:fn.InkListItem.fromSerializedKey(_o[0]),Value:_o[1]};if(yn.Key.originName===null)return (0, T.throwNullException)("randomItem.Key.originName");B=new fn.InkList(yn.Key.originName,this),B.Add(yn.Key,yn.Value),this.state.previousRandom=tt;}this.state.PushEvaluationStack(new b.ListValue(B));break}default:this.Error("unhandled ControlCommand: "+e);break}return  true}else if(t instanceof _f.VariableAssignment){let e=t,n=this.state.PopEvaluationStack();return this.state.variablesState.Assign(e,n),true}else if(t instanceof Ef.VariableReference){let e=t,n=null;if(e.pathForCount!=null){let i=e.containerForCount,a=this.state.VisitCountForContainer(i);n=new b.IntValue(a);}else n=this.state.variablesState.GetVariableWithName(e.name),n==null&&(this.Warning("Variable not found: '"+e.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 b.IntValue(0));return this.state.PushEvaluationStack(n),true}else if(t instanceof Pf.NativeFunctionCall){let e=t,n=this.state.PopEvaluationStack(e.numberOfParameters),i=e.Call(n);return this.state.PushEvaluationStack(i),true}return  false}ChoosePathString(t,e=true,n=[]){if(this.IfAsyncWeCant("call ChoosePathString right now"),this.onChoosePathString!==null&&this.onChoosePathString(t,n),e)this.ResetCallstack();else if(this.state.callStack.currentElement.type==gt.PushPopType.Function){let i="",a=this.state.callStack.currentElement.currentPointer.container;throw a!=null&&(i="("+a.path.toString()+") "),new Error("Story was running a function "+i+"when you called ChoosePathString("+t+`) - this is almost certainly not not what you want! Full stack trace: 
`+this.state.callStack.callStackTrace)}this.state.PassArgumentsToEvaluationStack(n),this.ChoosePath(new to.Path(t));}IfAsyncWeCant(t){if(this._asyncContinueActive)throw new Error("Can't "+t+". Story is in the middle of a ContinueAsync(). Make more ContinueAsync() calls or a single Continue() call beforehand.")}ChoosePath(t,e=true){this.state.SetChosenPath(t,e),this.VisitChangedContainersDueToDivert();}ChooseChoiceIndex(t){t=t;let e=this.currentChoices;this.Assert(t>=0&&t<e.length,"choice out of range");let n=e[t];if(this.onMakeChoice!==null&&this.onMakeChoice(n),n.threadAtGeneration===null)return (0, T.throwNullException)("choiceToChoose.threadAtGeneration");if(n.targetPath===null)return (0, T.throwNullException)("choiceToChoose.targetPath");this.state.callStack.currentThread=n.threadAtGeneration,this.ChoosePath(n.targetPath);}HasFunction(t){try{return this.KnotContainerWithName(t)!=null}catch{return  false}}EvaluateFunction(t,e=[],n=false){if(this.onEvaluateFunction!==null&&this.onEvaluateFunction(t,e),this.IfAsyncWeCant("evaluate a function"),t==null)throw new Error("Function is null");if(t==""||t.trim()=="")throw new Error("Function is empty or white space.");let i=this.KnotContainerWithName(t);if(i==null)throw new Error("Function doesn't exist: '"+t+"'");let a=[];a.push(...this.state.outputStream),this._state.ResetOutput(),this.state.StartFunctionEvaluationFromGame(i,e);let r=new ie.StringBuilder;for(;this.canContinue;)r.Append(this.Continue());let o=r.toString();this._state.ResetOutput(a);let l=this.state.CompleteFunctionEvaluationFromGame();return this.onCompleteEvaluateFunction!=null&&this.onCompleteEvaluateFunction(t,e,o,l),n?{returned:l,output:o}:l}EvaluateExpression(t){let e=this.state.callStack.elements.length;this.state.callStack.Push(gt.PushPopType.Tunnel),this._temporaryEvaluationContainer=t,this.state.GoToStart();let n=this.state.evaluationStack.length;return this.Continue(),this._temporaryEvaluationContainer=null,this.state.callStack.elements.length>e&&this.state.PopCallStack(),this.state.evaluationStack.length>n?this.state.PopEvaluationStack():null}CallExternalFunction(t,e){if(t===null)return (0, T.throwNullException)("funcName");let n=this._externals.get(t),i=null,a=typeof n<"u";if(a&&!n.lookAheadSafe&&this._state.inStringEvaluation&&this.Error("External function "+t+` 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 = `+t+"()"),a&&!n.lookAheadSafe&&this._stateSnapshotAtLastNewline!==null){this._sawLookaheadUnsafeFunctionAfterNewline=true;return}if(!a)if(this.allowExternalFunctionFallbacks){i=this.KnotContainerWithName(t),this.Assert(i!==null,"Trying to call EXTERNAL function '"+t+"' which has not been bound, and fallback ink function could not be found."),this.state.callStack.Push(gt.PushPopType.Function,void 0,this.state.outputStream.length),this.state.divertedPointer=$t.Pointer.StartOf(i);return}else this.Assert(false,"Trying to call EXTERNAL function '"+t+"' which has not been bound (and ink fallbacks disabled).");let r=[];for(let u=0;u<e;++u){let c=(0, P.asOrThrows)(this.state.PopEvaluationStack(),b.Value).valueObject;r.push(c);}r.reverse();let o=n.function(r),l=null;o!=null?(l=b.Value.Create(o),this.Assert(l!==null,"Could not create ink value from returned object of type "+typeof o)):l=new dn.Void,this.state.PushEvaluationStack(l);}BindExternalFunctionGeneral(t,e,n=true){this.IfAsyncWeCant("bind an external function"),this.Assert(!this._externals.has(t),"Function '"+t+"' has already been bound."),this._externals.set(t,{function:e,lookAheadSafe:n});}TryCoerce(t){return t}BindExternalFunction(t,e,n=false){this.Assert(e!=null,"Can't bind a null function"),this.BindExternalFunctionGeneral(t,i=>{this.Assert(i.length>=e.length,"External function expected "+e.length+" arguments");let a=[];for(let r=0,o=i.length;r<o;r++)a[r]=this.TryCoerce(i[r]);return e.apply(null,a)},n);}UnbindExternalFunction(t){this.IfAsyncWeCant("unbind an external a function"),this.Assert(this._externals.has(t),"Function '"+t+"' has not been bound."),this._externals.delete(t);}ValidateExternalBindings(){let t=null,e=null,n=arguments[1]||new Set;if(arguments[0]instanceof Y.Container&&(t=arguments[0]),arguments[0]instanceof Za.InkObject&&(e=arguments[0]),t===null&&e===null)if(this.ValidateExternalBindings(this._mainContentContainer,n),this._hasValidatedExternals=true,n.size==0)this._hasValidatedExternals=true;else {let i="Error: Missing function binding for external";i+=n.size>1?"s":"",i+=": '",i+=Array.from(n).join("', '"),i+="' ",i+=this.allowExternalFunctionFallbacks?", and no fallback ink function found.":" (ink fallbacks disabled)",this.Error(i);}else if(t!=null){for(let i of t.content){let a=i;(a==null||!a.hasValidName)&&this.ValidateExternalBindings(i,n);}for(let[,i]of t.namedContent)this.ValidateExternalBindings((0, P.asOrNull)(i,Za.InkObject),n);}else if(e!=null){let i=(0, P.asOrNull)(e,zl.Divert);if(i&&i.isExternal){let a=i.targetPathString;if(a===null)return (0, T.throwNullException)("name");this._externals.has(a)||this.allowExternalFunctionFallbacks&&this.mainContentContainer.namedContent.has(a)||n.add(a);}}}ObserveVariable(t,e){if(this.IfAsyncWeCant("observe a new variable"),this._variableObservers===null&&(this._variableObservers=new Map),!this.state.variablesState.GlobalVariableExistsWithName(t))throw new Error("Cannot observe variable '"+t+"' because it wasn't declared in the ink story.");this._variableObservers.has(t)?this._variableObservers.get(t).push(e):this._variableObservers.set(t,[e]);}ObserveVariables(t,e){for(let n=0,i=t.length;n<i;n++)this.ObserveVariable(t[n],e[n]);}RemoveVariableObserver(t,e){if(this.IfAsyncWeCant("remove a variable observer"),this._variableObservers!==null){if(e!=null){if(this._variableObservers.has(e))if(t!=null){let n=this._variableObservers.get(e);n!=null&&(n.splice(n.indexOf(t),1),n.length===0&&this._variableObservers.delete(e));}else this._variableObservers.delete(e);}else if(t!=null){let n=this._variableObservers.keys();for(let i of n){let a=this._variableObservers.get(i);a!=null&&(a.splice(a.indexOf(t),1),a.length===0&&this._variableObservers.delete(i));}}}}VariableStateDidChangeEvent(t,e){if(this._variableObservers===null)return;let n=this._variableObservers.get(t);if(typeof n<"u"){if(!(e instanceof b.Value))throw new Error("Tried to get the value of a variable that isn't a standard type");let i=(0, P.asOrThrows)(e,b.Value);for(let a of n)a(t,i.valueObject);}}get globalTags(){return this.TagsAtStartOfFlowContainerWithPathString("")}TagsForContentAtPath(t){return this.TagsAtStartOfFlowContainerWithPathString(t)}TagsAtStartOfFlowContainerWithPathString(t){let e=new to.Path(t),n=this.ContentAtPath(e).container;if(n===null)return (0, T.throwNullException)("flowContainer");for(;;){let r=n.content[0];if(r instanceof Y.Container)n=r;else break}let i=false,a=null;for(let r of n.content){let o=(0, P.asOrNull)(r,E.ControlCommand);if(o!=null)o.commandType==E.ControlCommand.CommandType.BeginTag?i=true:o.commandType==E.ControlCommand.CommandType.EndTag&&(i=false);else if(i){let l=(0, P.asOrNull)(r,b.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 t=new ie.StringBuilder;return this.mainContentContainer.BuildStringOfHierarchy(t,0,this.state.currentPointer.Resolve()),t.toString()}BuildStringOfContainer(t){let e=new ie.StringBuilder;return t.BuildStringOfHierarchy(e,0,this.state.currentPointer.Resolve()),e.toString()}NextContent(){if(this.state.previousPointer=this.state.currentPointer.copy(),!this.state.divertedPointer.isNull&&(this.state.currentPointer=this.state.divertedPointer.copy(),this.state.divertedPointer=$t.Pointer.Null,this.VisitChangedContainersDueToDivert(),!this.state.currentPointer.isNull))return;if(!this.IncrementContentPointer()){let e=false;this.state.callStack.CanPop(gt.PushPopType.Function)?(this.state.PopCallStack(gt.PushPopType.Function),this.state.inExpressionEvaluation&&this.state.PushEvaluationStack(new dn.Void),e=true):this.state.callStack.canPopThread?(this.state.callStack.PopThread(),e=true):this.state.TryExitFunctionEvaluationFromGame(),e&&!this.state.currentPointer.isNull&&this.NextContent();}}IncrementContentPointer(){let t=true,e=this.state.callStack.currentElement.currentPointer.copy();if(e.index++,e.container===null)return (0, T.throwNullException)("pointer.container");for(;e.index>=e.container.content.length;){t=false;let n=(0, P.asOrNull)(e.container.parent,Y.Container);if(!(n instanceof Y.Container))break;let i=n.content.indexOf(e.container);if(i==-1)break;if(e=new $t.Pointer(n,i),e.index++,t=true,e.container===null)return (0, T.throwNullException)("pointer.container")}return t||(e=$t.Pointer.Null),this.state.callStack.currentElement.currentPointer=e.copy(),t}TryFollowDefaultInvisibleChoice(){let t=this._state.currentChoices,e=t.filter(i=>i.isInvisibleDefault);if(e.length==0||t.length>e.length)return  false;let n=e[0];return n.targetPath===null?(0, T.throwNullException)("choice.targetPath"):n.threadAtGeneration===null?(0, T.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 t=(0, P.asOrNull)(this.state.PopEvaluationStack(),b.IntValue);if(!(t instanceof b.IntValue))return this.Error("expected number of elements in sequence for shuffle index"),0;let e=this.state.currentPointer.container;if(e===null)return (0, T.throwNullException)("seqContainer");if(t.value===null)return (0, T.throwNullException)("numElementsIntVal.value");let n=t.value,a=(0, P.asOrThrows)(this.state.PopEvaluationStack(),b.IntValue).value;if(a===null)return (0, T.throwNullException)("seqCount");let r=a/n,o=a%n,l=e.path.toString(),u=0;for(let m=0,g=l.length;m<g;m++)u+=l.charCodeAt(m)||0;let h=u+r+this.state.storySeed,c=new eo.PRNG(Math.floor(h)),d=[];for(let m=0;m<n;++m)d.push(m);for(let m=0;m<=o;++m){let g=c.next()%d.length,S=d[g];if(d.splice(g,1),m==o)return S}throw new Error("Should never reach here")}Error(t,e=false){let n=new ne.StoryException(t);throw n.useEndLineNumber=e,n}Warning(t){this.AddError(t,true);}AddError(t,e=false,n=false){let i=this.currentDebugMetadata,a=e?"WARNING":"ERROR";if(i!=null){let r=n?i.endLineNumber:i.startLineNumber;t="RUNTIME "+a+": '"+i.fileName+"' line "+r+": "+t;}else this.state.currentPointer.isNull?t="RUNTIME "+a+": "+t:t="RUNTIME "+a+": ("+this.state.currentPointer+"): "+t;this.state.AddError(t,e),e||this.state.ForceEnd();}Assert(t,e=null){if(t==false)throw e==null&&(e="Story assert"),new Error(e+" "+this.currentDebugMetadata)}get currentDebugMetadata(){let t,e=this.state.currentPointer;if(!e.isNull&&e.Resolve()!==null&&(t=e.Resolve().debugMetadata,t!==null))return t;for(let n=this.state.callStack.elements.length-1;n>=0;--n)if(e=this.state.callStack.elements[n].currentPointer,!e.isNull&&e.Resolve()!==null&&(t=e.Resolve().debugMetadata,t!==null))return t;for(let n=this.state.outputStream.length-1;n>=0;--n)if(t=this.state.outputStream[n].debugMetadata,t!==null)return t;return null}get mainContentContainer(){return this._temporaryEvaluationContainer?this._temporaryEvaluationContainer:this._mainContentContainer}};re.Story=we;we.inkVersionCurrent=21;(function(s){(function(e){e[e.NoChange=0]="NoChange",e[e.ExtendedBeyondNewline=1]="ExtendedBeyondNewline",e[e.NewlineRemoved=2]="NewlineRemoved";})(s.OutputStateChange||(s.OutputStateChange={}));})(we||(re.Story=we={}));});var Ql=p(kr=>{Object.defineProperty(kr,"__esModule",{value:true});kr.Story=void 0;var Of=On(),Nf=fi(),Ir=L(),Fr=z(),pn=Pn(),Vr=wt(),Zl=ge(),Af=Ea(),If=Gi(),Ff=Na(),Vf=on(),xe=Ft(),Rf=jt(),kf=Lt(),mn=O(),Df=Ye(),Wf=Ze(),Lf=Qt(),Rr=class s extends Vr.FlowBase{get flowLevel(){return Zl.FlowLevel.Story}get hadError(){return this._hadError}get hadWarning(){return this._hadWarning}constructor(t,e=false){super(null,t,null,false,e),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 i,a;this._errorHandler=n,this.constants=new Map;for(let h of this.FindAll(Nf.ConstantDeclaration)()){let c=this.constants.get(h.constantName);if(c&&!c.Equals(h.expression)){let d=`CONST '${h.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 ${c.debugMetadata}.`;this.Error(d,h,false);}this.constants.set(h.constantName,h.expression);}this._listDefs=new Map;for(let h of this.FindAll(If.ListDefinition)())!((i=h.identifier)===null||i===void 0)&&i.name&&this._listDefs.set((a=h.identifier)===null||a===void 0?void 0:a.name,h);this.externals=new Map,this.ResolveWeavePointNaming();let r=this.runtimeObject,o=new Ir.Container;o.AddContent(Fr.ControlCommand.EvalStart());let l=[];for(let[h,c]of this.variableDeclarations)if(c.isGlobalDeclaration){if(c.listDefinition)this._listDefs.set(h,c.listDefinition),o.AddContent(c.listDefinition.runtimeObject),l.push(c.listDefinition.runtimeListDefinition);else {if(!c.expression)throw new Error;c.expression.GenerateIntoContainer(o);}let d=new kf.VariableAssignment(h,true);d.isGlobal=true,o.AddContent(d);}o.AddContent(Fr.ControlCommand.EvalEnd()),o.AddContent(Fr.ControlCommand.End()),this.variableDeclarations.size>0&&(o.name="global decl",r.AddToNamedContentOnly(o)),r.AddContent(Fr.ControlCommand.Done());let u=new Vf.Story(r,l);return this.runtimeObject=u,this.hadError||(this.FlattenContainersIn(r),this.ResolveReferences(this),this.hadError)?null:(u.ResetState(),u)},this.ResolveList=n=>{let i=this._listDefs.get(n);return i||null},this.ResolveListItem=(n,i,a=null)=>{let r=null;if(n)return (r=this._listDefs.get(n))?r.ItemNamed(i):null;{let o=null,l=null;for(let[,u]of this._listDefs.entries()){let h=u.ItemNamed(i);h&&(o?this.Error(`Ambiguous item name '${i}' found in multiple sets, including ${l.identifier} and ${u.identifier}`,a,false):(o=h,l=u));}return o}},this.FlattenContainersIn=n=>{let i=new Set;if(n.content)for(let a of n.content){let r=(0, mn.asOrNull)(a,Ir.Container);r&&i.add(r);}if(n.namedContent)for(let[,a]of n.namedContent){let r=(0, mn.asOrNull)(a,Ir.Container);r&&i.add(r);}for(let a of i)this.TryFlattenContainer(a),this.FlattenContainersIn(a);},this.TryFlattenContainer=n=>{if(n.namedContent&&n.namedContent.size>0||n.hasValidName||this._dontFlattenContainers.has(n))return;let i=(0, mn.asOrNull)(n.parent,Ir.Container);if(i){let a=i.content.indexOf(n);i.content.splice(a,1);let r=n.ownDebugMetadata;if(n.content)for(let o of n.content)o.parent=null,r!==null&&o.ownDebugMetadata===null&&(o.debugMetadata=r),i.InsertContent(o,a),a+=1;}},this.Error=(n,i,a)=>{let r=a?pn.ErrorType.Warning:pn.ErrorType.Error,o="";if(i instanceof Of.AuthorWarning?(o+="TODO: ",r=pn.ErrorType.Author):a?o+="WARNING: ":o+="ERROR: ",i&&i.debugMetadata!==null&&i.debugMetadata.startLineNumber>=1&&(i.debugMetadata.fileName!=null&&(o+=`'${i.debugMetadata.fileName}' `),o+=`line ${i.debugMetadata.startLineNumber}: `),o+=n,n=o,this._errorHandler!==null)this._errorHandler(n,r);else throw new Error(n);this._hadError=r===pn.ErrorType.Error,this._hadWarning=r===pn.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,i,a,r)=>{n.Error(`${r} '${i}': name has already been used for a ${a.typeName.toLowerCase()} on ${a.debugMetadata}`);},this.CheckForNamingCollisions=(n,i,a,r="")=>{var o;let l=r||n.typeName;if(s.IsReservedKeyword(i?.name)){n.Error(`'${i}' cannot be used for the name of a ${l.toLowerCase()} because it's a reserved keyword`);return}else if(Wf.FunctionCall.IsBuiltIn(i?.name||"")){n.Error(`'${i}' cannot be used for the name of a ${l.toLowerCase()} because it's a built in function`);return}let u=this.ContentWithNameAtLevel(i?.name||"",Zl.FlowLevel.Knot),h=(0, mn.asOrNull)(u,Vr.FlowBase);if(h&&(h!==n||a===xe.SymbolType.Arg)){this.NameConflictError(n,i?.name||"",h,l);return}if(a<xe.SymbolType.List)return;for(let[g,S]of this._listDefs)if(i?.name===g&&n!==S&&S.variableAssignment!==n&&this.NameConflictError(n,i?.name,S,l),!(n instanceof Ff.ListElementDefinition))for(let D of S.itemDefinitions)i?.name===D.name&&this.NameConflictError(n,i?.name||"",D,l);if(a<=xe.SymbolType.Var)return;let c=i?.name&&this.variableDeclarations.get(i?.name)||null;if(c&&c!==n&&c.isGlobalDeclaration&&c.listDefinition==null&&this.NameConflictError(n,i?.name||"",c,l),a<xe.SymbolType.SubFlowAndWeave)return;let m=new Lf.Path(i).ResolveFromContext(n);if(m&&m!==n){this.NameConflictError(n,i?.name||"",m,l);return}if(!(a<xe.SymbolType.Arg)&&a!==xe.SymbolType.Arg){let g=(0, mn.asOrNull)(n,Vr.FlowBase);if(g||(g=(0, Df.ClosestFlowBase)(n)),g&&g.hasParameters&&g.args){for(let S of g.args)if(((o=S.identifier)===null||o===void 0?void 0:o.name)===i?.name){n.Error(`${l} '${i}': name has already been used for a argument to ${g.identifier} on ${g.debugMetadata}`);return}}}};}get typeName(){return "Story"}PreProcessTopLevelObjects(t){super.PreProcessTopLevelObjects(t);let e=[];for(let n of t)if(n instanceof Af.IncludedFile){let i=n,a=t.indexOf(n);if(t.splice(a,1),i.includedStory){let r=[],o=i.includedStory;if(o.content!=null){for(let l of o.content)l instanceof Vr.FlowBase?e.push(l):r.push(l);r.push(new Rf.Text(`
`)),t.splice(a,0,...r);}}continue}t.splice(0,0,...e);}};kr.Story=Rr;Rr.IsReservedKeyword=s=>{switch(s){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 eu=p(Dr=>{Object.defineProperty(Dr,"__esModule",{value:true});Dr.StringExpression=void 0;var tu=z(),qf=ct(),jf=jt(),Mf=O(),no=class s extends qf.Expression{get isSingleString(){return !(this.content.length!==1||!(this.content[0]instanceof jf.Text))}constructor(t){super(),this.GenerateIntoContainer=e=>{e.AddContent(tu.ControlCommand.BeginString());for(let n of this.content)e.AddContent(n.runtimeObject);e.AddContent(tu.ControlCommand.EndString());},this.toString=()=>{let e="";for(let n of this.content)e+=n;return e},this.AddContent(t);}get typeName(){return "String"}Equals(t){let e=(0, Mf.asOrNull)(t,s);if(e===null||!this.isSingleString||!e.isSingleString)return  false;let n=this.toString(),i=e.toString();return n===i}};Dr.StringExpression=no;});var iu=p(Te=>{Object.defineProperty(Te,"__esModule",{value:true});Te.LegacyTag=Te.Tag=void 0;var Bf=R(),nu=z(),io=class extends Bf.ParsedObject{constructor(t,e=false){super(),this.GenerateRuntimeObject=()=>this.isStart?nu.ControlCommand.BeginTag():nu.ControlCommand.EndTag(),this.toString=()=>this.isStart?"#StartTag":"#EndTag",this.isStart=t,this.inChoice=e;}get typeName(){return "Tag"}};Te.Tag=io;var Gf=va(),ro=class extends Gf.Wrap{constructor(t){super(t);}get typeName(){return "Tag"}};Te.LegacyTag=ro;});var ru=p(Wr=>{Object.defineProperty(Wr,"__esModule",{value:true});Wr.DefaultFileHandler=void 0;var so=class{constructor(t){this.rootPath=t,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.")};}};Wr.DefaultFileHandler=so;});var uo=p(Mr=>{Object.defineProperty(Mr,"__esModule",{value:true});Mr.InkParser=void 0;var $f=To(),Jf=On(),Uf=fs(),vt=jo(),U=Ue(),Hf=me(),Kf=zo(),zf=hi(),gn=Hs(),ut=Pi(),Xf=fi(),Lr=Cl(),Yf=vl(),se=Se(),ao=ve(),Zf=ct(),Qf=Sl(),su=yl(),qr=Ze(),tp=Xe(),ep=bl(),np=ir(),jr=El(),au=Ea(),ip=Pl(),rp=xa(),ou=xl(),sp=Gi(),ap=Na(),op=Gs(),lu=R(),lp=Qt(),uu=Rs(),hu=na(),J=Qs(),nt=Aa(),up=Fa(),cu=Ql(),Cn=eu(),Vt=Ps(),Oe=iu(),Rt=jt(),du=ra(),oo=ha(),lo=be(),hp=cs(),Jt=O(),vn=bi(),Ne=$n(),fu=Pn(),cp=ru(),I=class s extends Vt.StringParser{get fileHandler(){if(!this._fileHandler)throw new Error("No FileHandler defined");return this._fileHandler}set fileHandler(t){this._fileHandler=t;}constructor(t,e=null,n=null,i=null,a=null){if(super(t),this.ParseStory=()=>{let r=this.StatementsAtLevel(nt.StatementLevel.Top);return new cu.Story(r,this._rootParser!==this)},this.SeparatedList=(r,o)=>{let l=this.Parse(r);if(l===null)return null;let u=[];u.push(l);do{let h=this.BeginRule();if(o()===null){this.FailRule(h);break}let d=this.Parse(r);if(d===null){this.FailRule(h);break}this.SucceedRule(h),u.push(d);}while(true);return u},this.CreateDebugMetadata=(r,o)=>{let l=new Yf.DebugMetadata;return l.startLineNumber=(r?.lineIndex||0)+1,l.endLineNumber=o.lineIndex+1,l.startCharacterNumber=(r?.characterInLineIndex||0)+1,l.endCharacterNumber=o.characterInLineIndex+1,l.fileName=this._filename,l},this.RuleDidSucceed=(r,o,l)=>{let u=(0, Jt.asOrNull)(r,lu.ParsedObject);u&&(u.debugMetadata=this.CreateDebugMetadata(o,l));let h=Array.isArray(r)?r:null;if(h!==null)for(let d of h)(0, Jt.asOrNull)(d,lu.ParsedObject)&&(d.hasOwnDebugMetadata||(d.debugMetadata=this.CreateDebugMetadata(o,l)));let c=(0, Jt.asOrNull)(r,vn.Identifier);c!=null&&(c.debugMetadata=this.CreateDebugMetadata(o,l));},this.OnStringParserError=(r,o,l=0,u=false)=>{let c=u?"WARNING:":"ERROR:";if(this._filename!==null&&(c+=` '${this._filename}'`),c+=` line ${l+1}: ${r}`,this._externalErrorHandler!==null)this._externalErrorHandler(c,u?fu.ErrorType.Warning:fu.ErrorType.Error);else throw new Error(c)},this.AuthorWarning=()=>{this.Whitespace();let r=this.Parse(this.IdentifierWithMetadata);if(r===null||r.name!=="TODO")return null;this.Whitespace(),this.ParseString(":"),this.Whitespace();let o=this.ParseUntilCharactersFromString(`
\r`);return o?new Jf.AuthorWarning(o):null},this.ExtendIdentifierCharacterRanges=r=>{let o=s.ListAllCharacterRanges();for(let l of o)r.AddCharacters(l.ToCharacterSet());},this._parsingChoice=false,this.Choice=()=>{let r=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;r=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 h=null,c=this.Parse(this.MixedTextAndLogic);c&&(h=new ut.ContentList(c));let d=null,m=null,g=this.ParseString("[")!==null;if(g){this.EndTagIfNecessary(h);let f=this.Parse(this.MixedTextAndLogic);f!==null&&(d=new ut.ContentList(f)),this.Expect(this.String("]"),"closing ']' for weave-style option"),this.EndTagIfNecessary(d);let A=this.Parse(this.MixedTextAndLogic);A!==null&&(m=new ut.ContentList(A));}this.Whitespace(),this.EndTagIfNecessary(m??h);let S=this.Parse(this.MultiDivert);this._parsingChoice=false,this.Whitespace();let D=!h&&!m&&!d;if(D&&S===null&&this.Warning("Choice is completely empty. Interpretting as a default fallback choice. Add a divert arrow to remove this warning: * ->"),!h&&g&&!d&&this.Warning("Blank choice - if you intended a default fallback choice, use the `* ->` syntax"),m||(m=new ut.ContentList),this.EndTagIfNecessary(m),S!==null)for(let f of S){let A=(0, Jt.asOrNull)(f,se.Divert);A&&A.isEmpty||m.AddContent(f);}m.AddContent(new Rt.Text(`
`));let N=new Hf.Choice(h,d,m);return l&&(N.identifier=l),N.indentationDepth=o.length,N.hasWeaveStyleInlineBrackets=g,N.condition=u,N.onceOnly=r,N.isInvisibleDefault=D,N},this.ChoiceCondition=()=>{let r=this.Interleave(this.ChoiceSingleCondition,this.ChoiceConditionsSpace);return r===null?null:r.length===1?r[0]:new op.MultipleConditionExpression(r)},this.ChoiceConditionsSpace=()=>(this.Newline(),this.Whitespace(),Vt.ParseSuccess),this.ChoiceSingleCondition=()=>{if(this.ParseString("{")===null)return null;let r=this.Expect(this.Expression,"choice condition inside { }");return this.DisallowIncrement(r),this.Expect(this.String("}"),"closing '}' for choice condition"),r},this.Gather=()=>{let r=this.Parse(this.GatherDashes);if(r===null)return null;let o=Number(r),l=this.Parse(this.BracketedName),u=new tp.Gather(l,o);return this.Newline(),u},this.GatherDashes=()=>{this.Whitespace();let r=0;for(;this.ParseDashNotArrow()!==null;)r+=1,this.Whitespace();return r===0?null:r},this.ParseDashNotArrow=()=>{let r=this.BeginRule();return this.ParseString("->")===null&&this.ParseSingleCharacter()==="-"?this.SucceedRule(r):this.FailRule(r)},this.BracketedName=()=>{if(this.ParseString("(")===null)return null;this.Whitespace();let r=this.Parse(this.IdentifierWithMetadata);return r===null?null:(this.Whitespace(),this.Expect(this.String(")"),"closing ')' for bracketed name"),r)},this.InnerConditionalContent=r=>{if(r===void 0){let c=this.Parse(this.ConditionExpression),d=this.Parse(()=>this.InnerConditionalContent(c));return d===null?null:d}let o,l=r!==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(r){let c=this.StatementsAtLevel(nt.StatementLevel.InnerBlock);if(c!==null){o=[new gn.ConditionalSingleBranch(c)];let m=this.Parse(this.SingleMultilineCondition);m&&(m.isElse||(this.ErrorWithParsedObject("Expected an '- else:' clause here rather than an extra condition",m),m.isElse=true),o.push(m));}}if(o===null)return null}else if(o.length===1&&o[0].isElse&&r){let c=new gn.ConditionalSingleBranch(null);c.isTrueBranch=true,o.unshift(c);}if(r){let c=false;for(let d=0;d<o.length;++d){let m=o[d],g=d===o.length-1;m.ownExpression?(m.matchingEquality=true,c=true):c&&g?(m.matchingEquality=true,m.isElse=true):!g&&o.length>2?this.ErrorWithParsedObject("Only final branch can be an 'else'. Did you miss a ':'?",m):d===0?m.isTrueBranch=true:m.isElse=true;}}else {for(let c=0;c<o.length;++c){let d=o[c],m=c===o.length-1;if(d.ownExpression===null)if(m)d.isElse=true;else if(d.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",d);}else this.ErrorWithParsedObject("Branch doesn't have condition. Are you missing a ':'? ",d);}o.length===1&&o[0].ownExpression===null&&this.ErrorWithParsedObject("Condition block with no conditions",o[0]);}}if(o===null)return null;for(let c of o)c.isInline=u;return new zf.Conditional(r,o)},this.InlineConditionalBranches=()=>{let r=this.Interleave(this.MixedTextAndLogic,this.Exclude(this.String("|")),null,false);if(r===null||r.length===0)return null;let o=[];if(r.length>2)this.Error("Expected one or two alternatives separated by '|' in inline conditional");else {let l=new gn.ConditionalSingleBranch(r[0]);if(l.isTrueBranch=true,o.push(l),r.length>1){let u=new gn.ConditionalSingleBranch(r[1]);u.isElse=true,o.push(u);}}return o},this.MultilineConditionalBranches=()=>{this.MultilineWhitespace();let r=this.OneOrMore(this.SingleMultilineCondition);return r===null?null:(this.MultilineWhitespace(),r)},this.SingleMultilineCondition=()=>{if(this.Whitespace(),this.ParseString("->")!==null||this.ParseString("-")===null)return null;this.Whitespace();let r=null,o=this.Parse(this.ElseExpression)!==null;o||(r=this.Parse(this.ConditionExpression));let l=this.StatementsAtLevel(nt.StatementLevel.InnerBlock);r===null&&l===null&&(this.Error("expected content for the conditional branch following '-'"),l=[new Rt.Text("")]),this.MultilineWhitespace();let u=new gn.ConditionalSingleBranch(l);return u.ownExpression=r,u.isElse=o,u},this.ConditionExpression=()=>{let r=this.Parse(this.Expression);return r===null||(this.DisallowIncrement(r),this.Whitespace(),this.ParseString(":")===null)?null:r},this.ElseExpression=()=>this.ParseString("else")===null||(this.Whitespace(),this.ParseString(":")===null)?null:Vt.ParseSuccess,this._nonTextPauseCharacters=null,this._nonTextEndCharacters=null,this._notTextEndCharactersChoice=null,this._notTextEndCharactersString=null,this.TrimEndWhitespace=(r,o)=>{if(r.length>0){let l=r.length-1,u=r[l];if(u instanceof Rt.Text){let h=u;h.text=h.text.replace(new RegExp(/[ \t]+$/g),""),o?h.text+=" ":h.text.length===0&&(r.splice(l,1),this.TrimEndWhitespace(r,false));}}},this.LineOfMixedTextAndLogic=()=>{this.Parse(this.Whitespace);let r=this.Parse(this.MixedTextAndLogic);if(!r||!r.length)return null;let o=r[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?"),r.length===0?null:(r[r.length-1]instanceof se.Divert||this.TrimEndWhitespace(r,false),this.EndTagIfNecessary(r),r.length>0&&r[0]instanceof Oe.Tag&&r[0].isStart||r.push(new Rt.Text(`
`)),this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),r)},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 r=null;do{let o=this.Parse(this.ContentTextNoEscape),l=this.ParseString("\\")!==null;if(l||o!==null){if(r===null&&(r=""),o!==null&&(r+=String(o)),l){let u=this.ParseSingleCharacter();r+=u;}}else break}while(true);return r!==null?new Rt.Text(r):null},this.ContentTextNoEscape=()=>{this._nonTextPauseCharacters===null&&(this._nonTextPauseCharacters=new U.CharacterSet("-<")),this._nonTextEndCharacters===null&&(this._nonTextEndCharacters=new U.CharacterSet(`{}|
\r\\#`),this._notTextEndCharactersChoice=new U.CharacterSet(this._nonTextEndCharacters),this._notTextEndCharactersChoice.AddCharacters("[]"),this._notTextEndCharactersString=new U.CharacterSet(this._nonTextEndCharacters),this._notTextEndCharactersString.AddCharacters('"'));let r=()=>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(r,this._nonTextPauseCharacters,o);return l!==null?l:null},this.MultiDivert=()=>{this.Whitespace();let r=[],o=this.Parse(this.StartThread);if(o)return r=[o],r;let l=this.Interleave(this.ParseDivertArrowOrTunnelOnwards,this.DivertIdentifierWithArguments);if(!l)return null;r=[],this.EndTagIfNecessary(r);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 d=new du.TunnelOnwards;if(u<l.length-1){let m=(0, Jt.asOrNull)(l[u+1],se.Divert);d.divertAfter=m;}r.push(d);break}}else {let c=l[u];u<l.length-1&&(c.isTunnel=true),r.push(c);}if(r.length===0&&l.length===1){let u=new se.Divert(null);u.isEmpty=true,r.push(u),this._parsingChoice||this.Error("Empty diverts (->) are only valid on choices");}return r},this.StartThread=()=>{if(this.Whitespace(),this.ParseThreadArrow()===null)return null;this.Whitespace();let r=this.Expect(this.DivertIdentifierWithArguments,"target for new thread",()=>new se.Divert(null));return r.isThread=true,r},this.DivertIdentifierWithArguments=()=>{this.Whitespace();let r=this.Parse(this.DotSeparatedDivertPathComponents);if(!r)return null;this.Whitespace();let o=this.Parse(this.ExpressionFunctionCallArguments);this.Whitespace();let l=new lp.Path(r);return new se.Divert(l,o)},this.SingleDivert=()=>{let r=this.Parse(this.MultiDivert);if(!r||r.length!==1||r[0]instanceof du.TunnelOnwards)return null;let l=r[0];return l.isTunnel?null:l},this.DotSeparatedDivertPathComponents=()=>this.Interleave(this.Spaced(this.IdentifierWithMetadata),this.Exclude(this.String("."))),this.ParseDivertArrowOrTunnelOnwards=()=>{let r=0;for(;this.ParseString("->")!==null;)r+=1;return r===0?null:r===1?"->":(r===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 r=this.ParseTempKeyword();this.Whitespace();let o=null;if(r?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 r&&this.Error("Expected '='"),null;let h=this.Expect(this.Expression,"value expression to be assigned");return l||u?new jr.IncDecExpression(o,h,l):new oo.VariableAssignment({variableIdentifier:o,assignedExpression:h,isTemporaryNewDeclaration:r})},this.DisallowIncrement=r=>{r instanceof jr.IncDecExpression&&this.Error("Can't use increment/decrement here. It can only be used on a ~ line");},this.ParseTempKeyword=()=>{let r=this.BeginRule();return this.Parse(this.Identifier)==="temp"?(this.SucceedRule(r),true):(this.FailRule(r),false)},this.ReturnStatement=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="return")return null;this.Whitespace();let o=this.Parse(this.Expression);return new uu.ReturnType(o)},this.Expression=(r=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>r){let h=`right side of '${u.type}' expression`,c=this.Expect(()=>this.ExpressionInfixRight(o,u),h);if(c===null)return this.FailRule(l),null;o=this.SucceedRule(l,c);continue}this.FailRule(l);break}return this.Whitespace(),o},this.ExpressionUnary=()=>{let r=this.Parse(this.ExpressionDivertTarget);if(r!==null)return r;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=hp.UnaryExpression.WithInner(l,o)),this.Whitespace();let u=this.OneOf([this.String("++"),this.String("--")]);if(u!==null){let h=u==="++";if(!(l instanceof lo.VariableReference))this.Error(`can only increment and decrement variables, but saw '${l}'.`);else {let c=l;l=new jr.IncDecExpression(c.identifier,h);}}return l},this.ExpressionNot=()=>{let r=this.Identifier();return r==="not"?r:null},this.ExpressionLiteral=()=>this.OneOf([this.ExpressionFloat,this.ExpressionInt,this.ExpressionBool,this.ExpressionString]),this.ExpressionDivertTarget=()=>{this.Whitespace();let r=this.Parse(this.SingleDivert);return !r||r&&r.isThread?null:(this.Whitespace(),new ao.DivertTarget(r))},this.ExpressionInt=()=>{let r=this.ParseInt();return r===null?null:new Ne.NumberExpression(r,"int")},this.ExpressionFloat=()=>{let r=this.ParseFloat();return r===null?null:new Ne.NumberExpression(r,"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 Rt.Text("")]:o.find(l=>l instanceof se.Divert)&&this.Error("String expressions cannot contain diverts (->)"),new Cn.StringExpression(o)},this.ExpressionBool=()=>{let r=this.Parse(this.Identifier);return r==="true"?new Ne.NumberExpression(true,"bool"):r==="false"?new Ne.NumberExpression(false,"bool"):null},this.ExpressionFunctionCall=()=>{let r=this.Parse(this.IdentifierWithMetadata);if(r===null)return null;this.Whitespace();let o=this.Parse(this.ExpressionFunctionCallArguments);return o===null?null:new qr.FunctionCall(r,o)},this.ExpressionFunctionCallArguments=()=>{if(this.ParseString("(")===null)return null;let r=this.Exclude(this.String(",")),o=this.Interleave(this.Expression,r);return o===null&&(o=[]),this.Whitespace(),this.Expect(this.String(")"),"closing ')' for function call"),o},this.ExpressionVariableName=()=>{let r=this.Interleave(this.IdentifierWithMetadata,this.Exclude(this.Spaced(this.String("."))));return r===null||cu.Story.IsReservedKeyword(r[0].name)?null:new lo.VariableReference(r)},this.ExpressionParen=()=>{if(this.ParseString("(")===null)return null;let r=this.Parse(this.Expression);return r===null?null:(this.Whitespace(),this.Expect(this.String(")"),"closing parenthesis ')' for expression"),r)},this.ExpressionInfixRight=(r,o)=>{if(!r)return null;this.Whitespace();let l=this.Parse(()=>this.Expression(o.precedence));return l?new Uf.BinaryExpression(r,l,o.type):null},this.ParseInfixOperator=()=>{for(let r of this._binaryOperators){let o=this.BeginRule();if(this.ParseString(r.type)!==null){if(r.requireWhitespace&&this.Whitespace()===null){this.FailRule(o);continue}return this.SucceedRule(o,r)}this.FailRule(o);}return null},this.ExpressionList=()=>{if(this.Whitespace(),this.ParseString("(")===null)return null;this.Whitespace();let r=this.SeparatedList(this.ListMember,this.Spaced(this.String(",")));return this.Whitespace(),this.ParseString(")")===null?null:new ou.List(r)},this.ListMember=()=>{this.Whitespace();let r=this.Parse(this.IdentifierWithMetadata);if(r===null)return null;if(this.ParseString(".")!==null){let l=this.Expect(this.IdentifierWithMetadata,`element name within the set ${r}`);r.name+=`.${l?.name}`;}return this.Whitespace(),r},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=(r,o,l=false)=>{let u=new ip.InfixOperator(r,o,l);this._binaryOperators.push(u),this._maxBinaryOpLength=Math.max(this._maxBinaryOpLength,r.length);},this._openFilenames=[],this.IncludeStatement=()=>{if(this.Whitespace(),this.ParseString("INCLUDE")===null)return null;this.Whitespace();let r=this.Expect(()=>this.ParseUntilCharactersFromString(`
\r`),"filename for include statement");r=r.replace(new RegExp(/[ \t]+$/g),"");let o=this.fileHandler.ResolveInkFilename(r);if(this.FilenameIsAlreadyOpen(o))return this.Error(`Recursive INCLUDE detected: '${o}' is already open.`),this.ParseUntilCharactersFromString(`\r
`),new au.IncludedFile(null);this.AddOpenFilename(o);let l=null,u="";try{u=this._rootParser.fileHandler.LoadInkFileContents(o);}catch(h){this.Error(`Failed to load: '${r}'.
Error:${h}`);}return u!=null&&(l=new s(u,r,this._externalErrorHandler,this._rootParser,this.fileHandler).ParseStory()),this.RemoveOpenFilename(o),new au.IncludedFile(l)},this.FilenameIsAlreadyOpen=r=>this._rootParser._openFilenames.includes(r),this.AddOpenFilename=r=>{this._rootParser._openFilenames.push(r);},this.RemoveOpenFilename=r=>{this._rootParser._openFilenames.splice(this._rootParser._openFilenames.indexOf(r),1);},this.KnotDefinition=()=>{let r=this.Parse(this.KnotDeclaration);if(r===null)return null;this.Expect(this.EndOfLine,"end of line after knot name definition",this.SkipToNextLine);let o=()=>this.StatementsAtLevel(nt.StatementLevel.Knot),l=this.Expect(o,"at least one line within the knot",this.KnotStitchNoContentRecoveryRule);return new rp.Knot(r.name,l,r.args,r.isFunction)},this.KnotDeclaration=()=>{if(this.Whitespace(),this.KnotTitleEquals()===null)return null;this.Whitespace();let r=this.Parse(this.IdentifierWithMetadata),o,l=r?.name==="function";l?(this.Expect(this.Whitespace,"whitespace after the 'function' keyword"),o=this.Parse(this.IdentifierWithMetadata)):o=r,o===null&&(this.Error(`Expected the name of the ${l?"function":"knot"}`),o=new vn.Identifier("")),this.Whitespace();let u=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),this.Parse(this.KnotTitleEquals),new su.FlowDecl(o,u,l)},this.KnotTitleEquals=()=>{let r=this.ParseCharactersFromString("=");return r===null||r.length<=1?null:r},this.StitchDefinition=()=>{let r=this.Parse(this.StitchDeclaration);if(r===null)return null;this.Expect(this.EndOfLine,"end of line after stitch name",this.SkipToNextLine);let o=()=>this.StatementsAtLevel(nt.StatementLevel.Stitch),l=this.Expect(o,"at least one line within the stitch",this.KnotStitchNoContentRecoveryRule);return new up.Stitch(r.name,l,r.args,r.isFunction)},this.StitchDeclaration=()=>{if(this.Whitespace(),this.ParseString("=")===null||this.ParseString("=")!==null)return null;this.Whitespace();let r=this.ParseString("function")!==null;r&&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 su.FlowDecl(o,l,r)},this.KnotStitchNoContentRecoveryRule=()=>(this.ParseUntil(this.KnotDeclaration,new U.CharacterSet("="),null),[new Rt.Text("<ERROR IN FLOW>")]),this.BracketedKnotDeclArguments=()=>{if(this.ParseString("(")===null)return null;let r=this.Interleave(this.Spaced(this.FlowDeclArgument),this.Exclude(this.String(",")));return this.Expect(this.String(")"),"closing ')' for parameter list"),r===null&&(r=[]),r},this.FlowDeclArgument=()=>{let r=this.Parse(this.IdentifierWithMetadata);this.Whitespace();let o=this.ParseDivertArrow();this.Whitespace();let l=this.Parse(this.IdentifierWithMetadata);if(r==null&&l===null)return null;let u=new $f.Argument;return o!==null&&(u.isDivertTarget=true),r!==null&&r.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=r,u.identifier===null&&this.Error("Expected an parameter name"),u.isByReference=false),u},this.ExternalDeclaration=()=>{this.Whitespace();let r=this.Parse(this.IdentifierWithMetadata);if(r===null||r.name!="EXTERNAL")return null;this.Whitespace();let o=this.Expect(this.IdentifierWithMetadata,"name of external function")||new vn.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(h=>{var c;return (c=h.identifier)===null||c===void 0?void 0:c.name}).filter(Jt.filterUndef);return new Qf.ExternalDeclaration(o,u)},this._identifierCharSet=null,this.LogicLine=()=>{if(this.Whitespace(),this.ParseString("~")===null)return null;this.Whitespace();let r=()=>this.OneOf([this.ReturnStatement,this.TempDeclarationOrAssignment,this.Expression]),o=this.Expect(r,"expression after '~'",this.SkipToNextLine);if(o===null)return new ut.ContentList;o instanceof Zf.Expression&&!(o instanceof qr.FunctionCall||o instanceof jr.IncDecExpression)&&this.Error(`Logic following a '~' can't be that type of expression. It can only be something like:
	~ return
	~ var x = blah
	~ x++
	~ myFunction()`);let l=(0, Jt.asOrNull)(o,qr.FunctionCall);return l&&(l.shouldPopReturnedValue=true),o.Find(qr.FunctionCall)()!==null&&(o=new ut.ContentList(o,new Rt.Text(`
`))),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 Ne.NumberExpression||u instanceof Cn.StringExpression||u instanceof ao.DivertTarget||u instanceof lo.VariableReference||u instanceof ou.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 Cn.StringExpression&&(u.isSingleString||this.Error("Constant strings cannot contain any logic.")),new oo.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 vn.Identifier(o.name),new oo.VariableAssignment({variableIdentifier:o,listDef:l})):null},this.ListDefinition=()=>{this.AnyWhitespace();let r=this.SeparatedList(this.ListElementDefinition,this.ListElementDefinitionSeparator);return r===null?null:new sp.ListDefinition(r)},this.ListElementDefinitionSeparator=()=>(this.AnyWhitespace(),this.ParseString(",")===null?null:(this.AnyWhitespace(),",")),this.ListElementDefinition=()=>{let r=this.ParseString("(")!==null,o=r;this.Whitespace();let l=this.Parse(this.IdentifierWithMetadata);if(l===null)return null;this.Whitespace(),r&&this.ParseString(")")!=null&&(o=false,this.Whitespace());let u=null;if(this.ParseString("=")!==null){this.Whitespace();let h=this.Expect(this.ExpressionInt,"value to be assigned to list item");h!==null&&(u=h.value),o&&(this.Whitespace(),this.ParseString(")")!==null&&(o=false));}return o&&this.Error("Expected closing ')'"),new ap.ListElementDefinition(l,r,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 Ne.NumberExpression||l instanceof ao.DivertTarget||l instanceof Cn.StringExpression?l instanceof Cn.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 Xf.ConstantDeclaration(o,l)},this.InlineLogicOrGlueOrStartTag=()=>this.OneOf([this.InlineLogic,this.Glue,this.StartTag]),this.Glue=()=>this.ParseString("<>")!==null?new ep.Glue(new np.Glue):null,this.InlineLogic=()=>{if(this.ParseString("{")===null)return null;let r=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=r,null;this.DisallowIncrement(l);let u=(0, Jt.asOrNull)(l,ut.ContentList);return u||(u=new ut.ContentList(l)),this.Whitespace(),this.Expect(this.String("}"),"closing brace '}' for inline logic"),this.parsingStringExpression=r,o||this.EndTagIfNecessary(u),u},this.InnerLogic=()=>{this.Whitespace();let r=this.ParseObject(this.SequenceTypeAnnotation);if(r!==null){let u=this.Expect(this.InnerSequenceObjects,"sequence elements (for cycle/stoping etc)");return u===null?null:new hu.Sequence(u,r)}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 h=this.BeginRule(),c=this.ParseObject(u);if(c)if(this.Peek(this.Spaced(this.String("}")))===null)this.FailRule(h);else return this.SucceedRule(h,c);else this.FailRule(h);}return null},this.InnerExpression=()=>{let r=this.Parse(this.Expression);return r&&(r.outputWhenComplete=true),r},this.IdentifierWithMetadata=()=>{let r=this.Identifier();return r===null?null:new vn.Identifier(r)},this.Identifier=()=>{let r=this.ParseCharactersFromCharSet(this.identifierCharSet);if(r===null)return null;let o=true;for(let l of r)if(!(l>="0"&&l<="9")){o=false;break}return o?null:r},this._sequenceTypeSymbols=new U.CharacterSet("!&~$"),this.InnerSequence=()=>{this.Whitespace();let r=J.SequenceType.Stopping,o=this.Parse(this.SequenceTypeAnnotation);o!==null&&(r=o);let l=this.Parse(this.InnerSequenceObjects);return l===null||l.length<=1?null:new hu.Sequence(l,r)},this.SequenceTypeAnnotation=()=>{let r=this.Parse(this.SequenceTypeSymbolAnnotation);if(r===null&&(r=this.Parse(this.SequenceTypeWordAnnotation)),r===null)return null;switch(r){case J.SequenceType.Once:case J.SequenceType.Cycle:case J.SequenceType.Stopping:case J.SequenceType.Shuffle:case J.SequenceType.Shuffle|J.SequenceType.Stopping:case J.SequenceType.Shuffle|J.SequenceType.Once:break;default:return this.Error(`Sequence type combination not supported: ${r}`),J.SequenceType.Stopping}return r},this.SequenceTypeSymbolAnnotation=()=>{this._sequenceTypeSymbols===null&&(this._sequenceTypeSymbols=new U.CharacterSet("!&~$ "));let r=0,o=this.ParseCharactersFromCharSet(this._sequenceTypeSymbols);if(o===null)return null;for(let l of o)switch(l){case "!":r|=J.SequenceType.Once;break;case "&":r|=J.SequenceType.Cycle;break;case "~":r|=J.SequenceType.Shuffle;break;case "$":r|=J.SequenceType.Stopping;break}return r===0?null:r},this.SequenceTypeWordAnnotation=()=>{let r=this.Interleave(this.SequenceTypeSingleWord,this.Exclude(this.Whitespace));if(r===null||r.length===0||this.ParseString(":")===null)return null;let o=0;for(let l of r)o|=l;return o},this.SequenceTypeSingleWord=()=>{let r=null,o=this.Parse(this.IdentifierWithMetadata);if(o!==null)switch(o.name){case "once":r=J.SequenceType.Once;break;case "cycle":r=J.SequenceType.Cycle;break;case "shuffle":r=J.SequenceType.Shuffle;break;case "stopping":r=J.SequenceType.Stopping;break}return r===null?null:r},this.InnerSequenceObjects=()=>{let r=this.Parse(this.Newline)!==null,o=null;return r?o=this.Parse(this.InnerMultilineSequenceObjects):o=this.Parse(this.InnerInlineSequenceObjects),o},this.InnerInlineSequenceObjects=()=>{let r=this.Interleave(this.Optional(this.MixedTextAndLogic),this.String("|"),null,false);if(r===null)return null;let o=[],l=false;for(let u of r)if(u==="|")l||o.push(new ut.ContentList),l=false;else {let h=u;h===null?this.Error(`Expected content, but got ${u} (this is an ink compiler bug!)`):o.push(new ut.ContentList(h)),l=true;}return l||o.push(new ut.ContentList),o},this.InnerMultilineSequenceObjects=()=>{this.MultilineWhitespace();let r=this.OneOrMore(this.SingleMultilineSequenceElement);return r===null?null:r},this.SingleMultilineSequenceElement=()=>{if(this.Whitespace(),this.ParseString("->")!==null||this.ParseString("-")===null)return null;this.Whitespace();let r=this.StatementsAtLevel(nt.StatementLevel.InnerBlock);return r===null?this.MultilineWhitespace():r.unshift(new Rt.Text(`
`)),new ut.ContentList(r)},this._statementRulesAtLevel=[],this._statementBreakRulesAtLevel=[],this.StatementsAtLevel=r=>(r===nt.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(r),()=>this.StatementsBreakForLevel(r))),this.StatementAtLevel=r=>{let o=this._statementRulesAtLevel[r],l=this.OneOf(o);return r===nt.StatementLevel.Top&&l instanceof uu.ReturnType&&this.Error("should not have return statement outside of a knot"),l},this.StatementsBreakForLevel=r=>{this.Whitespace();let o=this._statementBreakRulesAtLevel[r],l=this.OneOf(o);return l===null?null:l},this.GenerateStatementLevelRules=()=>{let r=Object.values(nt.StatementLevel);this._statementRulesAtLevel="f".repeat(r.length).split("f").map(()=>[]),this._statementBreakRulesAtLevel="f".repeat(r.length).split("f").map(()=>[]);for(let o of r){let l=[],u=[];l.push(this.Line(this.MultiDivert)),o>=nt.StatementLevel.Top&&l.push(this.KnotDefinition),l.push(this.Line(this.Choice)),l.push(this.Line(this.AuthorWarning)),o>nt.StatementLevel.InnerBlock&&l.push(this.Gather),o>=nt.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<=nt.StatementLevel.Knot&&u.push(this.KnotDeclaration),o<=nt.StatementLevel.Stitch&&u.push(this.StitchDeclaration),o<=nt.StatementLevel.InnerBlock&&(u.push(this.ParseDashNotArrow),u.push(this.String("}"))),this._statementRulesAtLevel[o]=l,this._statementBreakRulesAtLevel[o]=u;}},this.SkipToNextLine=()=>(this.ParseUntilCharactersFromString(`
\r`),this.ParseNewline(),Vt.ParseSuccess),this.Line=r=>()=>{let o=this.ParseObject(r);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 r=null;if(this.tagActive){let o=new ut.ContentList;o.AddContent(new Oe.Tag(false)),o.AddContent(new Oe.Tag(true)),r=o;}else r=new Oe.Tag(true);return this.tagActive=true,this.Whitespace(),r},this._inlineWhitespaceChars=new U.CharacterSet(" 	"),this.EndOfLine=()=>this.OneOf([this.Newline,this.EndOfFile]),this.Newline=()=>(this.Whitespace(),this.ParseNewline()!==null?Vt.ParseSuccess:null),this.EndOfFile=()=>(this.Whitespace(),this.endOfInput?Vt.ParseSuccess:null),this.MultilineWhitespace=()=>{let r=this.OneOrMore(this.Newline);return r===null?null:r.length>=1?Vt.ParseSuccess:null},this.Whitespace=()=>this.ParseCharactersFromCharSet(this._inlineWhitespaceChars)!==null?Vt.ParseSuccess:null,this.Spaced=r=>()=>{this.Whitespace();let o=this.ParseObject(r);return o===null?null:(this.Whitespace(),o)},this.AnyWhitespace=()=>{let r=false;for(;this.OneOf([this.Whitespace,this.MultilineWhitespace])!==null;)r=true;return r?Vt.ParseSuccess:null},this.MultiSpaced=r=>()=>{this.AnyWhitespace();let o=this.ParseObject(r);return o===null?null:(this.AnyWhitespace(),o)},this._filename=null,this._externalErrorHandler=null,this._fileHandler=null,this._filename=e,this.RegisterExpressionOperators(),this.GenerateStatementLevelRules(),this.errorHandler=this.OnStringParserError,this._externalErrorHandler=n,a===null?this._fileHandler=new cp.DefaultFileHandler:this._fileHandler=a,i===null){if(this._rootParser=this,this._openFilenames=[],this._filename!==null){let r=this.fileHandler.ResolveInkFilename(this._filename);this._openFilenames.push(r);}}else this._rootParser=i;}PreProcessInputString(t){return new Kf.CommentEliminator(t).Process()}get parsingStringExpression(){return this.GetFlag(Number(Lr.CustomFlags.ParsingString))}set parsingStringExpression(t){this.SetFlag(Number(Lr.CustomFlags.ParsingString),t);}get tagActive(){return this.GetFlag(Number(Lr.CustomFlags.TagActive))}set tagActive(t){this.SetFlag(Number(Lr.CustomFlags.TagActive),t);}get identifierCharSet(){return this._identifierCharSet===null&&((this._identifierCharSet=new U.CharacterSet).AddRange("A","Z").AddRange("a","z").AddRange("0","9").Add("_"),this.ExtendIdentifierCharacterRanges(this._identifierCharSet)),this._identifierCharSet}EndTagIfNecessary(t){this.tagActive&&(t!=null&&(t instanceof ut.ContentList?t.AddContent(new Oe.Tag(false)):t.push(new Oe.Tag(false))),this.tagActive=false);}};Mr.InkParser=I;I.LatinBasic=vt.CharacterRange.Define("A","z",new U.CharacterSet().AddRange("[","`"));I.LatinExtendedA=vt.CharacterRange.Define("\u0100","\u017F");I.LatinExtendedB=vt.CharacterRange.Define("\u0180","\u024F");I.Greek=vt.CharacterRange.Define("\u0370","\u03FF",new U.CharacterSet().AddRange("\u0378","\u0385").AddCharacters("\u0374\u0375\u0378\u0387\u038B\u038D\u03A2"));I.Cyrillic=vt.CharacterRange.Define("\u0400","\u04FF",new U.CharacterSet().AddRange("\u0482","\u0489"));I.Armenian=vt.CharacterRange.Define("\u0530","\u058F",new U.CharacterSet().AddCharacters("\u0530").AddRange("\u0557","\u0560").AddRange("\u0588","\u058E"));I.Hebrew=vt.CharacterRange.Define("\u0590","\u05FF",new U.CharacterSet);I.Arabic=vt.CharacterRange.Define("\u0600","\u06FF",new U.CharacterSet);I.Korean=vt.CharacterRange.Define("\uAC00","\uD7AF",new U.CharacterSet);I.Latin1Supplement=vt.CharacterRange.Define("\x80","\xFF",new U.CharacterSet);I.Chinese=vt.CharacterRange.Define("\u4E00","\u9FFF",new U.CharacterSet);I.ListAllCharacterRanges=()=>[I.LatinBasic,I.LatinExtendedA,I.LatinExtendedB,I.Arabic,I.Armenian,I.Cyrillic,I.Greek,I.Hebrew,I.Korean,I.Latin1Supplement,I.Chinese];});var pu=p(Br=>{Object.defineProperty(Br,"__esModule",{value:true});Br.GenerateStoryStats=void 0;var dp=me(),fp=Se(),pp=Xe(),mp=xa(),gp=Fa(),Cp=jt();function vp(s){let t=s.FindAll(Cp.Text)(),e=0;for(let l of t){let u=0,h=true;for(let c of l.text)c==" "||c=="	"||c==`
`||c=="\r"?h=true:h&&(u++,h=false);e+=u;}let n=s.FindAll(mp.Knot)(),i=s.FindAll(gp.Stitch)(),a=s.FindAll(dp.Choice)(),r=s.FindAll(pp.Gather)(l=>l.debugMetadata!=null),o=s.FindAll(fp.Divert)();return {words:e,knots:n.length,functions:n.filter(l=>l.isFunction).length,stitches:i.length,gathers:r.length,diverts:o.length-1,choices:a.length}}Br.GenerateStoryStats=vp;});var mu=p(Gr=>{Object.defineProperty(Gr,"__esModule",{value:true});Gr.JsonFileHandler=void 0;var ho=class{constructor(t){this.fileHierarchy=t,this.ResolveInkFilename=e=>{if(Object.keys(this.fileHierarchy).includes(e))return e;throw new Error(`Cannot locate ${e}. Are you trying a relative import ? This is not yet implemented.`)},this.LoadInkFileContents=e=>{if(Object.keys(this.fileHierarchy).includes(e))return this.fileHierarchy[e];throw new Error(`Cannot open ${e}.`)};}};Gr.JsonFileHandler=ho;});var Cu=p(Z=>{Object.defineProperty(Z,"__esModule",{value:true});Z.Compiler=Z.Story=Z.InkList=Z.JsonFileHandler=Z.StatementLevel=Z.InkParser=Z.CompilerOptions=void 0;var Sp=Kr(),yp=wo(),co=Pn(),bp=uo(),_p=k(),Ep=O(),Pp=pu(),wp=Kr();Object.defineProperty(Z,"CompilerOptions",{enumerable:true,get:function(){return wp.CompilerOptions}});var xp=uo();Object.defineProperty(Z,"InkParser",{enumerable:true,get:function(){return xp.InkParser}});var Tp=Aa();Object.defineProperty(Z,"StatementLevel",{enumerable:true,get:function(){return Tp.StatementLevel}});var Op=mu();Object.defineProperty(Z,"JsonFileHandler",{enumerable:true,get:function(){return Op.JsonFileHandler}});var gu=on();Object.defineProperty(Z,"InkList",{enumerable:true,get:function(){return gu.InkList}});Object.defineProperty(Z,"Story",{enumerable:true,get:function(){return gu.Story}});var fo=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(t,e=null){this._errors=[],this._warnings=[],this._authorMessages=[],this._parsedStory=null,this._runtimeStory=null,this._parser=null,this._debugSourceRanges=[],this.Compile=()=>(this._parser=new bp.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 i of this.runtimeStory.state.outputStream){let a=(0, Ep.asOrNull)(i,_p.StringValue);if(a!==null){let r=new yp.DebugSourceRange(((n=a.value)===null||n===void 0?void 0:n.length)||0,a.debugMetadata,a.value||"unknown");this.debugSourceRanges.push(r);}}},this.GenerateStats=()=>this._parsedStory===null?null:(0, Pp.GenerateStoryStats)(this._parsedStory),this.DebugMetadataForContentAtOffset=n=>{let i=0,a=null;for(let r of this.debugSourceRanges){if(r.debugMetadata!==null&&(a=r.debugMetadata),n>=i&&n<i+r.length)return a;i+=r.length;}return null},this.OnError=(n,i)=>{switch(i){case co.ErrorType.Author:this._authorMessages.push(n);break;case co.ErrorType.Warning:this._warnings.push(n);break;case co.ErrorType.Error:this._errors.push(n);break}this.options.errorHandler!==null&&this.options.errorHandler(n,i);},this._inputString=t,this._options=e||new Sp.CompilerOptions;}};Z.Compiler=fo;});var Iu=Lu(Cu());var F="_|_",$r="global decl",Ut="___external_value___";function Sn(s,t){if(s.endsWith(".s"))return;if(new RegExp(/.*\.[0-9]+\..*$/).test(s)&&(s=s.split(".").filter(i=>!i.match(/^[0-9]+$/)).join("."),!s.startsWith(".")))return s.replaceAll(".",F);if(!new RegExp(/^\.\^.*$/).test(s)&&s.includes("g-")){let n=s.split("g-");return po(t)+F+"g-"+n[n.length-1]}let e=0;for(;new RegExp(/^\.\^.*$/).test(s);)e++,s=s.substring(2);if(e=e-1,new RegExp(/^\..*$/).test(s)&&t){let n=s.substring(1);return po(t,e)+F+n.replaceAll(".",F)}return s.replaceAll(".",F)||po(t,e).replaceAll(".",F)}function po(s,t=0){let e=s.split(F);for(;e.length>1&&t>0;)e.pop()?.includes("g-")&&t--,t--;return e.join(F)}var vu="\xA7DOUBLE_SLASH_CONVERTOR\xA7";function Nt(s){return s.startsWith("^")&&(s=s.substring(1)),s=s.replaceAll("\\\\",vu),s=s.replaceAll("\\n",`
`),s=s.replaceAll("\\t"," "),s=s.replaceAll("	"," "),s=s.replaceAll(vu,"\\\\"),s}var j;(i=>(i.log=(a,...r)=>console.log(`[Pixi\u2019VN Ink] ${a}`,...r),i.warn=(a,...r)=>console.warn(`[Pixi\u2019VN Ink] ${a}`,...r),i.error=(a,...r)=>console.error(`[Pixi\u2019VN Ink] ${a}`,...r),i.info=(a,...r)=>console.info(`[Pixi\u2019VN Ink] ${a}`,...r)))(j||={});var Su=["+","-","/","*","%","_","==",">","<",">=","<=","!=","!","&&","||","MIN","MAX"],yu=["+","-","/","*","%","POW","RANDOM"],bu=["INT","FLOOR","FLOAT"],_u=["==",">","<",">=","<=","!=","CONTAINS"];function Ae(s,t,e){s=s.map(i=>{if(typeof i=="string"){if(i==="rnd")return "RANDOM";if(i==="?")return "CONTAINS"}return i});let n=[];return s.forEach(i=>{if(typeof i=="object"&&"CNT?"in i)if(new RegExp(/.*\.[0-9]\..*/).test(i["CNT?"])){let a=i["CNT?"].split("."),r=a.pop(),o=a.pop();if(o===void 0||r===void 0){j.error("Error parsing ink file: Conditional statement is not valid",s);return}let l=parseInt(o),u=a.join(".");if(u.includes("^.")){let c=u.split("."),d=c[c.length-1].replaceAll(".",F);c.pop(),u=c.join(".")+"."+d,r.includes("c-")&&(u=u+F+r);}else u=u.replaceAll(".",F);let h=Sn(u,t);if(!h)return;n.push({type:"compare",leftValue:Eu(h),operator:">=",rightValue:{type:"value",value:l}});}else {let a=Sn(i["CNT?"],t);if(!a)return;n.push(Eu(a));}else if(typeof i=="object"&&"VAR?"in i)n.push(Ie(i["VAR?"],e));else if(i==="&&"||i==="||"){if(n.length>=2){let a={type:"union",unionType:i==="&&"?"and":"or",conditions:[n[n.length-2],n[n.length-1]]};n.pop(),n.pop(),n.push(a);}}else if(i==="!")if(n.length===0)j.error("Error parsing ink file: Conditional statement is not valid",s);else {let a={type:"union",unionType:"not",condition:n[n.length-1]};n[n.length-1]=a;}else if(i&&typeof i=="string"&&_u.includes(i))if(n.length<2)j.error("Error parsing ink file: Conditional statement is not valid",s);else {let a={type:"compare",operator:i,rightValue:n[n.length-1],leftValue:n[n.length-2]};n.pop(),n.pop(),n.push(a);}else if(i&&typeof i=="string"&&yu.includes(i))if(n.length<2)j.error("Error parsing ink file: Conditional statement is not valid",s);else {let a={type:"arithmetic",operator:i,rightValue:n[n.length-1],leftValue:n[n.length-2]};n.pop(),n.pop(),n.push(a);}else if(i&&typeof i=="string"&&bu.includes(i)){let a={type:"arithmeticsingle",operator:i,leftValue:n[n.length-1]};n.pop(),n.push(a);}else i&&typeof i=="string"?i.startsWith("^")&&n.push(Nt(i)):typeof i=="object"&&"^->"in i?i["^->"].includes("$r")||n.push(i["^->"]):n.push(i);}),n}function Eu(s){return {type:"value",storageType:"label",storageOperationType:"get",label:s}}function Pu(s,t,e){return Ae(s,t,e)}function Ie(s,t,e="storage"){let n=t.indexOf(s);return n>=0?{type:"value",storageType:"params",storageOperationType:"get",key:n}:{type:"value",storageOperationType:"get",storageType:e,key:s}}function mo(s,t,e,n="storage"){let i=t.indexOf(s);return i>=0?{type:"value",storageType:"params",storageOperationType:"set",key:i,value:e}:{type:"value",storageOperationType:"set",storageType:n,key:s,value:e}}function Jr(s,t){t&&(typeof t=="string"?t.startsWith("^")&&s.push(Nt(t)):typeof t=="object"&&"type"in t&&t.type!=="value"&&s.push(t));}function go(s,t,e,n,i=true,a=false){return Ap(s,t,e,n,i,a)}function Ap(s,t,e,n,i,a=false){if(t){if(a)Array.isArray(t)&&t.length>0&&s.push({operations:[{type:"operationtoconvert",values:t}],goNextStep:true});else if(typeof t=="string"&&t.startsWith("^")||t&&typeof t=="object"&&"type"in t&&t.type=="value"&&t.storageOperationType==="get"){if(!i&&s.length>0){let r=s[s.length-1];!r.glueEnabled&&!r.operations&&(r.glueEnabled=true,r.labelToOpen||(r.goNextStep=true)),s[s.length-1]=r;}typeof t=="string"?s.push(Ip(Nt(t))):s.push({dialogue:t});}else if(typeof t=="string"){if(t==="end")s.push({end:"game_end"});else if(t==="done")s.push({end:"label_end",goNextStep:true});else if(t=="<>")if(s.length>0){let r=s[s.length-1];r.glueEnabled=true,r.labelToOpen||(r.goNextStep=true),s[s.length-1]=r;}else s.push({glueEnabled:true,goNextStep:false});}else if(typeof t=="object"){if("type"in t&&t.type!=="value"){if(!i&&s.length>0){let r=s[s.length-1];!r.glueEnabled&&!r.operations&&(r.glueEnabled=true,r.labelToOpen||(r.goNextStep=true)),s[s.length-1]=r;}s.push({conditionalStep:t});}else if("->"in t){let r=i?void 0:true;if(!i&&s.length>0){let o=s[s.length-1];o.labelToOpen||(o.goNextStep=true),s[s.length-1]=o;}if(t.params&&t.params.length===0&&(t.params=void 0),t.var)s.push({labelToOpen:{label:Ie(t["->"],n),type:"jump",params:t.params},glueEnabled:r});else {let o=Sn(t["->"],e);if(!o)return;s.push({labelToOpen:{label:o,type:"jump",params:t.params},glueEnabled:r});}}"type"in t&&t.type=="value"&&t.storageOperationType==="set"&&(typeof t.value=="string"&&t.value.startsWith("^")&&(t.value=Nt(t.value)),s.push({goNextStep:true,operations:[t]}));}}}function Ip(s){let t;if(s.includes(": ")){let e=s.split(": "),n=e[0],i=e.slice(1).join(": ");pixiVn.getCharacterById(n)&&(t=n,s=i);}return t?{dialogue:{character:t,text:s}}:{dialogue:s}}function Co(s,t,e,n=true,i=false){return Fp(s,t,e,n,i)}function Fp(s,t,e,n,i=false){t&&(typeof t=="string"&&t.startsWith("^")||t&&typeof t=="object"&&"type"in t&&t.type=="value"&&t.storageOperationType==="get"?typeof t=="string"?s.push(Nt(t)):s.push(t):typeof t=="object"&&"type"in t&&s.push(t));}function Ur(s,t,e){if(s.length===0){j.error("Error parsing ink file: Arithmetic statement is not valid",s);return}let n=Ae(s,t,e);if(n.length===1){let i=n[0];return i&&typeof i=="object"&&"type"in i?{type:"value",storageType:"logic",storageOperationType:"get",operation:i}:i}}function Fe(s,t,e,n="",i,a,r=void 0){let o=[],l="sequential",u=false,h=true;s.forEach(m=>{m==="%"&&(l="loop"),m==="seq"&&(l="random"),m==="MIN"&&(u=true);});let c=s[s.length-1];return Object.keys(c).forEach(m=>{let g=c[m];if(Array.isArray(g)&&g.length>3){g=g.slice(1,g.length-2);let S=[];Ht(g,n,i,S,t,t,e,Ve,r,true,a),S.length===1?o.push(S[0]):o.push({type:"resulttocombine",combine:"cross",secondConditionalItem:S});}else Array.isArray(g)&&g.length===3&&(h=false);}),l==="sequential"?{type:"stepswitch",elements:o,choiceType:l,end:h?"lastItem":void 0,nestedId:r}:u&&l==="random"?{type:"stepswitch",elements:o,choiceType:"sequentialrandom",end:h?"lastItem":void 0,nestedId:r}:{type:"stepswitch",elements:o,choiceType:l}}function vo(s="",t=""){let e=Array.isArray(s)?s:[s],n=Array.isArray(t)?t:[t];return [...new Set([...e,...n])]}function Ve(s,t,e,n,i){if(s.length>0){let a={};wu(s,a,i);for(let[r,o]of Object.entries(a)){let l=e+F+r,u={text:o.text.length===1?o.text[0]:o.text,label:l,props:{},type:"jump",oneTime:o.onetime};o.text.length===0&&(u.onlyHaveNoChoice=true,u.autoSelect=true),u.oneTime===false&&delete u.oneTime;let h=So(u,o.conditions,i,e)||u,c=t[t.length-1];if(typeof c=="object"&&c&&"type"in c&&(c={conditionalStep:c}),t.length>0&&typeof c=="object"&&c&&"choices"in c&&c.choices){let d=c.choices;d&&Array.isArray(d)?d.push(h):j.error("Unhandled case: choices is PixiVNJsonConditionalStatements<PixiVNJsonChoices> | undefined",o,d),c.choices=d.sort((m,g)=>{try{let S=m.label.split("."),D=S[S.length-1].replaceAll(".",F),N=g.label.split("."),f=N[N.length-1].replaceAll(".",F);if(D.includes("c-")&&f.includes("c-")){let A=D.split("c-")[1],y=parseInt(A),C=f.split("c-")[1],_=parseInt(C);return y-_}}catch{}return 0});}else t.push({choices:[h]});o.preDialog&&(n.preDialog[l]={...o.preDialog});}}}function wu(s,t,e,n){let i=[],a="",r="",o=false,l=[];for(let u=0;u<s.length;u++){let h=s[u];if(typeof h=="string")h.startsWith("^")?i.push(Nt(h)):Su.includes(h)&&l.push(h);else if(Array.isArray(h)&&h.includes("visit")){let c=Fe(h,Jr,(d,m,g)=>{},n,{preDialog:{}},e);i.push(c);}else if(h&&typeof h=="object")if("*"in h&&typeof h["*"]&&typeof h["*"]=="string")h["*"].includes("c")&&(a="c"+h["*"].split("c")[1],h.flg&16&&(o=true));else if("s"in h&&h.s instanceof Array){let c=xu(h.s),d=h.s.includes("<>");c&&(n&&t[n]?(t[n].preDialog={text:c,glue:d},t[n].text=vo(c,t[n].text)):(i.push(c),r=c));}else "CNT?"in h&&l.push(h);else l.push(h);if(a){t[a]?t[a].text=vo(i,t[a].text):t[a]={text:i,onetime:o,conditions:l},r&&(t[a].preDialog={text:r,glue:false});let c=s.slice(u+1);wu(c,t,e,a);return}}}function xu(s){for(let t of s)if(typeof t=="string"){if(t.startsWith("^"))return Nt(t)}else if(t instanceof Array){let e=xu(t);if(e)return e}}function So(s,t,e,n,i){if(t.length===0)return;let a=Ae(t,n,e);if(a.length===1){let r={type:"ifelse",condition:a[0],then:s,else:i};return r.else||delete r.else,r}else if(a.length>1){let r={type:"ifelse",condition:{type:"union",unionType:"and",conditions:a},then:s,else:i};return r.else||delete r.else,r}}function Tu(s,t,e,n,i,a,r=void 0){if(s.length===0){j.error("Error parsing ink file: Conditional statement is not valid",s);return}let o=[],l=[];if(s.forEach(c=>{Array.isArray(c)?l.push(c):typeof c=="string"&&c==="du"?i.du?o.push(i.du):i.du=o[o.length-1]:(typeof c!="string"||c!=="/ev")&&o.push(c);}),l.length===0){j.error("Error parsing ink file: Conditional statement is not valid",l);return}let u=yo(l[0],t,e,n+F+"then",i,a,`${r||""}then`),h;return l.length===2?h=yo(l[1],t,e,n+F+"else",i,a,`${r||""}else`):l.length>2&&(l.shift(),l.push("nop"),l=[{b:l}],h=yo(l,t,e,n+F+"else",i,a,`${r||""}else`)),i.du=void 0,So(u,o,a,n,h)}function yo(s,t,e,n,i,a,r=void 0){let o=[];for(let u of s)typeof u=="object"&&"b"in u&&(u.b=u.b.filter(h=>h!==null&&!(typeof h=="object"&&"->"in h&&new RegExp(/.*\.[0-9]/).test(h["->"]))),Ht(u.b,n,i,o,t,t,e,Ve,r,true,a));return o.length===1?o[0]:{type:"resulttocombine",combine:"cross",secondConditionalItem:o}}function Ht(s,t,e,n=[],i,a,r,o,l=void 0,u=true,h=[]){let c=false,d=[],m=false,g=false,S=[],D=[];if(e.preDialog[t]&&(u=false,i(n,"^"+e.preDialog[t].text,t,h,u,g),e.preDialog[t].glue&&i(n,"<>",t,h,u,g),delete e.preDialog[t]),s.includes("visit")){let f=Fe(s,a,r,t,e,h,l);f&&(!u&&n.length>0&&i(n,"<>",t,h,u,g),i(n,f,t,h,u,g));return}let N=s[0];if(N&&typeof N=="object"&&"temp="in N){for(;s[0]&&typeof s[0]=="object"&&"temp="in s[0];)h.push(s[0]["temp="]),s.shift();h=h.reverse();}if(s.forEach((f,A)=>{if(g){if(typeof f=="string"&&f=="/#"){let y=[];Ht(D,t,e,y,Co,Co,r,o,l,u),i(n,y,t,h,u,g),g=false,D=[];}else D.push(f);return}else if(c)if(Array.isArray(f))d.push(f);else if(f&&typeof f=="object")if("CNT?"in f)A>0&&s[A-1]=="ev"?(m=true,S.push(f)):m?S.push(f):(d.push(f),u=false);else if("VAR="in f||"temp="in f){let y=mo("VAR="in f?f["VAR="]:f["temp="],h,s[A-1],"VAR="in f?"storage":"tempstorage");if(y.value&&typeof y.value=="string"&&y.value=="/str"&&(y.value=s[A-2]),y.value&&typeof y.value=="object"&&"^->"in y.value&&(y.value=y.value["^->"]),d.length>1){let C=Ur(d,t,h);d=[],C&&typeof C=="object"&&"type"in C&&C.type=="value"&&"storageType"in C&&C.storageType=="logic"&&(y.value=C.operation);}(typeof y.key!="string"||!y.key.includes("$r"))&&(i(n,y,t,h,u,g),u=true);}else "VAR?"in f?d.push(f):"^->"in f&&(f["^->"].includes("$r")||d.push(f));else if(typeof f=="string"&&f=="/ev")m&&S.push(f),c=false,d.push(f);else if(typeof f=="string"&&f=="out"){if(d.length>0){let y=d[d.length-1];if(y&&typeof y=="object"&&"VAR?"in y){d.pop();let C=Ie(y["VAR?"],h,"storage");i(n,C,t,h,u,g);}else {let C=[];for(;d.length>0&&d[d.length-1]!="/ev";)C.push(d.pop());C=C.reverse();let _=Ur(C,t,h);d=[],_&&typeof _=="object"&&"type"in _&&_.type=="value"&&"storageType"in _&&_.storageType=="logic"?i(n,{storageOperationType:"get",storageType:"logic",operation:_.operation,type:"value"},t,h,u,g):(i(n,"<>",t,h,u,g),_=`^${_}`,i(n,_,t,h,u,g));}u=false;}}else d.push(f);else if(typeof f=="string")if(f.startsWith("^"))i(n,f,t,h,u,g),u=false;else if(f=="ev")c=true;else if(f==`
`)u=true;else if(f=="done"||f=="end")i(n,f,t,h,u,g),u=false;else if(f=="<>")i(n,f,t,h,u,g),u=false;else if(f=="nop"&&m){let y=Tu(S,a,r,t,e,h,l);y&&i(n,y,t,h,u,g),m=false,S=[];}else f=="#"&&(g=true);else if(f instanceof Array)if(m)S.push(f);else if(f.length>1&&typeof f[f.length-2]=="object"&&f[f.length-2]&&"c"in f[f.length-2]&&typeof f[f.length-1]=="object"&&f[f.length-1]&&"b"in f[f.length-1]){d.pop();let y=[],C=[];for(;d.length>0&&d[d.length-1]!="/ev";)y.push(d.pop());S=[...S,...y.reverse()],m=true,C.push(f.pop()),C.push(f.pop()),S=[...S,...f],S.push(C);}else if(f.length>1&&typeof f[f.length-1]=="object"&&f[f.length-1]&&"#n"in f[f.length-1]){let y=f.pop();if(!y){j.error("Error parsing ink file: el is undefined");return}let C=y["#n"];delete y["#n"],f.push(y),i(n,{"->":t?t+F+C:C},t,h,u,g),r({[C]:f},t,e);}else Ht(f,t,e,n,i,a,r,o,l,u);else if(f&&typeof f=="object")if("->"in f&&typeof f["->"]=="string"&&!new RegExp(/^\.\^\.\^\.\d\.s$/).test(f["->"])){let y=[];d.length>0&&(y=Pu(["ev",...d],t,h)),f.params=y,i(n,f,t,h,u,g),u=false;}else if("*"in f&&typeof f["*"]=="string")f["*"].includes("c")&&(d.push(f),u=false);else if("s"in f&&f.s instanceof Array)d.push(f),u=false;else if("CNT?"in f)d.push(f),u=false;else if("VAR="in f||"temp="in f){let y=[],C=mo("VAR="in f?f["VAR="]:f["temp="],h,void 0,"VAR="in f?"storage":"tempstorage");if(C.key!=="$r"){for(d.pop(),d[d.length-1]=="/ev"&&d.pop();d.length>0&&d[d.length-1]!="/ev";)y.push(d.pop());y=y.reverse(),C.value=Ur(y,t,h),d=[],(C.value!==void 0||C.value!==null)&&i(n,C,t,h,u,g),u=false;}}else r(f,t,e);}),o(d,n,t,e,h),t.includes(F)&&n.length==2){let f=n[0],A=n[1];f&&A&&typeof f=="object"&&"dialogue"in f&&typeof A=="object"&&"labelToOpen"in A&&f.dialogue==" "&&A.labelToOpen&&(n.shift(),delete A.glueEnabled,n[0]=A);}}function Ou(s){try{let t={};return Nu(s,t),t}catch(t){j.error("Error parsing ink file",t);}}function Nu(s,t,e={externalSwitch:void 0}){for(let n of s)if(n)if(n instanceof Array)if(n.includes("visit")){let i=Fe(n,Jr,(a,r,o)=>{},"",{preDialog:{}},[]);i&&(e.externalSwitch=i);}else Nu(n,t,e);else typeof n=="object"&&(n&&"VAR="in n&&e.externalSwitch&&(t[Ut]||(t[Ut]=[]),t[Ut].push({operations:[{type:"value",value:e.externalSwitch,key:n["VAR="],storageType:"storage",storageOperationType:"set"}]})),Au(n,t));}function Au(s,t,e="",n={preDialog:{}}){if(s!==null){for(let[i,a]of Object.entries(s))if(a instanceof Array){let r=[],o={},l=(e?e+F:"")+i;Ht(a,l,n,r,go,go,(u,h,c)=>{Au(u,o,h,c);},Ve);for(let[u,h]of Object.entries(o))t[u]=h;r.length>0&&(t[l]=r);}}}function JC(s){let t={},e=Vp(s),n;try{n=JSON.parse(e);}catch{j.error("Error parsing ink file");return}if(t.labels=Ou(n.root),t.labels&&$r in t.labels){let i=t.labels[$r];delete t.labels[$r],i.forEach(a=>{a.operations&&(t.initialOperations=t.initialOperations?[...t.initialOperations,...a.operations]:[...a.operations]);});}if(t.labels&&Ut in t.labels){let i=t.labels[Ut];delete t.labels[Ut],i.forEach(a=>{a.operations&&(t.initialOperations=t.initialOperations?[...t.initialOperations,...a.operations]:[...a.operations]);});}return t}function Vp(s){try{return new Iu.Compiler(s).Compile().ToJson()||""}catch(t){return j.error("Error compiling ink file",t),""}}exports.convertInkText=JC;