diff --git a/Aetheria/Stories/Lucent Hostage Feed.md b/Aetheria/Stories/Lucent Hostage Feed.md
new file mode 100644
index 0000000..8c41cb5
--- /dev/null
+++ b/Aetheria/Stories/Lucent Hostage Feed.md
@@ -0,0 +1,23 @@
+---
+title: Lucent Hostage Feed
+description: "A playable Ghostlight branch-and-fold scene: negotiate a live hostage crisis on a Lucent media-eye station while influencers, security, and evidence custody all try to eat the room."
+---
+
+# Lucent Hostage Feed
+
+_A playable Ghostlight branch-and-fold scene._
+
+You are Mara Quell, a crisis negotiator working through Lucent's official feed controls. Sol Vant has taken Juno Ark hostage near the glass rail of a transfer lounge. The proof that might explain why is also the proof Lucent would very much like to turn into content, liability haze, or preferably both.
+
+This is not a finished game scene. It is a live artifact from Ghostlight's training-data machinery: a branching interactive-fiction scaffold built to test whether character pressure, institutional pressure, and state variables can survive contact with player choice without turning into decorative spreadsheet moss.
+
+
+
+## Source Note
+
+This scene is grounded in [[Worldbuilding/Pre-Elysium/Factions/Powers/Major/Lucent Media|Lucent Media]] and the [[Worldbuilding/Pre-Elysium/Factions/Movements/Reality Architects|Reality Architects]], with some room-scale crisis-feed procedure still marked as Ghostlight draft elaboration rather than settled canon.
+
diff --git a/Aetheria/Stories/index.md b/Aetheria/Stories/index.md
index 2e7304c..7ec3e59 100644
--- a/Aetheria/Stories/index.md
+++ b/Aetheria/Stories/index.md
@@ -13,6 +13,7 @@ Some of the pieces gathered here were written before the current canon settled i
## Current Stories
+- [[Lucent Hostage Feed]]
- [[Rain]]
- [[When We Get Home]]
diff --git a/Aetheria/static/interactive/aetheria-ink-player.js b/Aetheria/static/interactive/aetheria-ink-player.js
new file mode 100644
index 0000000..e35b42d
--- /dev/null
+++ b/Aetheria/static/interactive/aetheria-ink-player.js
@@ -0,0 +1,173 @@
+(function () {
+ let inkRuntimePromise = null
+
+ function createElement(tag, className, text) {
+ const element = document.createElement(tag)
+ if (className) element.className = className
+ if (text !== undefined) element.textContent = text
+ return element
+ }
+
+ function ensureInkRuntime() {
+ if (window.inkjs && window.inkjs.Story) return Promise.resolve()
+ if (inkRuntimePromise) return inkRuntimePromise
+
+ inkRuntimePromise = new Promise((resolve, reject) => {
+ const existing = document.querySelector('script[data-aetheria-ink-runtime="true"]')
+ if (existing) {
+ existing.addEventListener("load", resolve, { once: true })
+ existing.addEventListener("error", () => reject(new Error("inkjs runtime failed to load")), {
+ once: true,
+ })
+ return
+ }
+
+ const script = document.createElement("script")
+ script.src = "/static/interactive/ink.js"
+ script.defer = true
+ script.dataset.aetheriaInkRuntime = "true"
+ script.addEventListener("load", resolve, { once: true })
+ script.addEventListener("error", () => reject(new Error("inkjs runtime failed to load")), {
+ once: true,
+ })
+ document.head.appendChild(script)
+ })
+
+ return inkRuntimePromise
+ }
+
+ function formatVariableValue(value) {
+ if (value === true) return "true"
+ if (value === false) return "false"
+ if (value === null || value === undefined) return "unset"
+ return String(value)
+ }
+
+ function collectVariables(story) {
+ const state = story.variablesState || {}
+ return Object.keys(state)
+ .filter((name) => !name.startsWith("_") && name !== "$" && typeof state[name] !== "function")
+ .sort()
+ .map((name) => ({
+ name,
+ value: state[name],
+ }))
+ }
+
+ function renderVariables(story, target) {
+ const variables = collectVariables(story)
+ target.replaceChildren()
+ if (variables.length === 0) return
+
+ for (const variable of variables) {
+ const chip = createElement("span", "aetheria-ink-variable")
+ chip.append(createElement("span", "aetheria-ink-variable-name", variable.name))
+ chip.append(
+ createElement("span", "aetheria-ink-variable-value", formatVariableValue(variable.value)),
+ )
+ target.append(chip)
+ }
+ }
+
+ function appendParagraphs(story, transcript) {
+ let advanced = false
+ let safety = 0
+
+ while (story.canContinue && safety < 1000) {
+ const text = story.Continue().trim()
+ safety += 1
+ if (text.length > 0) {
+ transcript.append(createElement("p", "aetheria-ink-line", text))
+ advanced = true
+ }
+ }
+
+ if (safety >= 1000) {
+ transcript.append(
+ createElement(
+ "p",
+ "aetheria-ink-error",
+ "The story did not settle before the safety limit. Something in the Ink is looping.",
+ ),
+ )
+ }
+
+ if (advanced) {
+ transcript.scrollTop = transcript.scrollHeight
+ }
+ }
+
+ function renderChoices(story, choices, variables) {
+ choices.replaceChildren()
+
+ if (story.currentChoices.length === 0) {
+ choices.append(createElement("p", "aetheria-ink-end", "End of branch. The feed stops blinking."))
+ return
+ }
+
+ story.currentChoices.forEach((choice, index) => {
+ const button = createElement("button", "aetheria-ink-choice", choice.text)
+ button.type = "button"
+ button.addEventListener("click", () => {
+ story.ChooseChoiceIndex(index)
+ appendParagraphs(story, choices.closest(".aetheria-ink-player").querySelector(".aetheria-ink-transcript"))
+ renderVariables(story, variables)
+ renderChoices(story, choices, variables)
+ })
+ choices.append(button)
+ })
+ }
+
+ async function initialisePlayer(container) {
+ if (container.dataset.inkInitialised === "true") return
+ container.dataset.inkInitialised = "true"
+
+ const storySrc = container.dataset.inkStory
+ if (!storySrc) {
+ container.textContent = "Ink player is missing data-ink-story."
+ return
+ }
+
+ const status = createElement("p", "aetheria-ink-status", "Loading story...")
+ const transcript = createElement("div", "aetheria-ink-transcript")
+ const choices = createElement("div", "aetheria-ink-choices")
+ const variables = createElement("div", "aetheria-ink-variables")
+ const restart = createElement("button", "aetheria-ink-restart", "Restart")
+ restart.type = "button"
+
+ container.replaceChildren(status, transcript, choices, variables, restart)
+
+ try {
+ await ensureInkRuntime()
+
+ const response = await fetch(storySrc)
+ if (!response.ok) {
+ throw new Error(`could not fetch ${storySrc}: ${response.status}`)
+ }
+
+ const storyJson = await response.json()
+
+ function reset() {
+ const story = new window.inkjs.Story(JSON.stringify(storyJson))
+ status.textContent = container.dataset.inkTitle || "Interactive story"
+ transcript.replaceChildren()
+ appendParagraphs(story, transcript)
+ renderVariables(story, variables)
+ renderChoices(story, choices, variables)
+ }
+
+ restart.addEventListener("click", reset)
+ reset()
+ } catch (error) {
+ status.textContent = "Ink player failed to load."
+ transcript.append(createElement("p", "aetheria-ink-error", error.message || String(error)))
+ }
+ }
+
+ function initialiseAllPlayers() {
+ document.querySelectorAll(".aetheria-ink-player").forEach(initialisePlayer)
+ }
+
+ document.addEventListener("nav", initialiseAllPlayers)
+ if (document.readyState !== "loading") initialiseAllPlayers()
+})()
diff --git a/Aetheria/static/interactive/ink.js b/Aetheria/static/interactive/ink.js
new file mode 100644
index 0000000..70cfaa5
--- /dev/null
+++ b/Aetheria/static/interactive/ink.js
@@ -0,0 +1,2 @@
+!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).inkjs={})}(this,(function(t){"use strict";class e{constructor(){if(this._components=[],this._componentsString=null,this._isRelative=!1,"string"==typeof arguments[0]){let t=arguments[0];this.componentsString=t}else if(arguments[0]instanceof e.Component&&arguments[1]instanceof e){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 e(t)}return e.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=0}get isParent(){return this.name==t.parentId}static ToParent(){return new e(t.parentId)}toString(){return this.isIndex?this.index.toString():this.name}Equals(t){return null!=t&&t.isIndex==this.isIndex&&(this.isIndex?this.index==t.index:this.name==t.name)}}t.Component=e}(e||(e={})),function(t){function e(t,e){if(!t)throw void 0!==e&&console.warn(e),console.trace&&console.trace(),new Error("")}t.AssertType=function(t,n,i){e(t instanceof n,i)},t.Assert=e}(n||(n={}));class d extends Error{}function p(t){throw new d(`${t} is null or undefined`)}class m{constructor(){this.parent=null,this._debugMetadata=null,this._path=null}get debugMetadata(){return null===this._debugMetadata&&this.parent?this.parent.debugMetadata:this._debugMetadata}set debugMetadata(t){this._debugMetadata=t}get ownDebugMetadata(){return this._debugMetadata}DebugLineNumberOfPath(t){if(null===t)return null;let e=this.rootContentContainer;if(e){let n=e.ContentAtPath(t).obj;if(n){let t=n.debugMetadata;if(null!==t)return t.startLineNumber}}return null}get path(){if(null==this._path)if(null==this.parent)this._path=new e;else{let t=[],n=this,i=s(n.parent,x);for(;null!==i;){let r=o(n);if(null!=r&&r.hasValidName){if(null===r.name)return p("namedChild.name");t.unshift(new e.Component(r.name))}else t.unshift(new e.Component(i.content.indexOf(n)));n=i,i=s(i.parent,x)}this._path=new e(t)}return this._path}ResolvePath(t){if(null===t)return p("path");if(t.isRelative){let e=s(this,x);return null===e&&(n.Assert(null!==this.parent,"Can't resolve relative path because we don't have a parent"),e=s(this.parent,x),n.Assert(null!==e,"Expected parent to be a container"),n.Assert(t.GetComponent(0).isParent),t=t.tail),null===e?p("nearestContainer"):e.ContentAtPath(t)}{let e=this.rootContentContainer;return null===e?p("contentContainer"):e.ContentAtPath(t)}}ConvertPathToRelative(t){let n=this.path,i=Math.min(t.length,n.length),r=-1;for(let e=0;e1?e-1:0),i=1;ivoid 0!==n[e]?n[e]:t))}toString(){return this.string}Clear(){this.string=""}}class g{constructor(){if(this.originName=null,this.itemName=null,void 0!==arguments[1]){let t=arguments[0],e=arguments[1];this.originName=t,this.itemName=e}else if(arguments[0]){let t=arguments[0].toString().split(".");this.originName=t[0],this.itemName=t[1]}}static get Null(){return new g(null,null)}get isNull(){return null==this.originName&&null==this.itemName}get fullName(){return(null!==this.originName?this.originName:"?")+"."+this.itemName}toString(){return this.fullName}Equals(t){if(t instanceof g){let e=t;return e.itemName==this.itemName&&e.originName==this.originName}return!1}copy(){return new g(this.originName,this.itemName)}serialized(){return JSON.stringify({originName:this.originName,itemName:this.itemName})}static fromSerializedKey(t){let e=JSON.parse(t);if(!g.isLikeInkListItem(e))return g.Null;let n=e;return new g(n.originName,n.itemName)}static isLikeInkListItem(t){return"object"==typeof t&&(!(!t.hasOwnProperty("originName")||!t.hasOwnProperty("itemName"))&&(("string"==typeof t.originName||null===typeof t.originName)&&("string"==typeof t.itemName||null===typeof t.itemName)))}}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;null!==e&&(this._originNames=e.slice()),null!==t.origins&&(this.origins=t.origins.slice())}else if("string"==typeof arguments[0]){let t=arguments[0],e=arguments[1];if(this.SetInitialOriginName(t),null===e.listDefinitions)return p("originStory.listDefinitions");let n=e.listDefinitions.TryListGetDefinition(t,null);if(!n.exists)throw new Error("InkList origin could not be found in story when constructing new list: "+t);if(null===n.result)return p("def.result");this.origins=[n.result]}else if("object"==typeof arguments[0]&&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(null==t||""==t)return new S;let i=null===(n=e.listDefinitions)||void 0===n?void 0:n.FindSingleItemListWithName(t);if(i)return null===i.value?p("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){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;if(t instanceof g){let e=t;if(null==e.originName)return void this.AddItem(e.itemName);if(null===this.origins)return p("this.origins");for(let t of this.origins)if(t.name==e.originName){let n=t.TryGetValueForItem(e,0);if(n.exists)return void this.Add(e,n.result);throw new Error("Could not add the item "+e+" 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.")}if(null!==t){let n=t,i=null;if(null===this.origins)return p("this.origins");for(let t of this.origins){if(null===n)return p("itemName");if(t.ContainsItemWithName(n)){if(null!=i)throw new Error("Could not add the item "+n+" to this list because it could come from either "+t.name+" or "+i.name);i=t}}if(null==i){if(null==e)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 t=S.FromString(n,e).orderedItems[0];this.Add(t.Key,t.Value)}}else{let t=new g(i.name,n),e=i.ValueForItem(t);this.Add(t,e)}}}ContainsItemNamed(t){for(let[e]of this){if(g.fromSerializedKey(e).itemName==t)return!0}return!1}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(null==this.origins)return null;let t=this.maxItem.Key.originName,e=null;return this.origins.every((n=>n.name!=t||(e=n,!1))),e}get originNames(){if(this.Count>0){null==this._originNames&&this.Count>0?this._originNames=[]:(this._originNames||(this._originNames=[]),this._originNames.length=0);for(let[t]of this){let e=g.fromSerializedKey(t);if(null===e.originName)return p("item.originName");this._originNames.push(e.originName)}}return this._originNames}SetInitialOriginName(t){this._originNames=[t]}SetInitialOriginNames(t){this._originNames=null==t?null:t.slice()}get maxItem(){let t={Key:g.Null,Value:0};for(let[e,n]of this){let i=g.fromSerializedKey(e);(t.Key.isNull||n>t.Value)&&(t={Key:i,Value:n})}return t}get minItem(){let t={Key:g.Null,Value:0};for(let[e,n]of this){let i=g.fromSerializedKey(e);(t.Key.isNull||nt.maxItem.Value)}GreaterThanOrEquals(t){return 0!=this.Count&&(0==t.Count||this.minItem.Value>=t.minItem.Value&&this.maxItem.Value>=t.maxItem.Value)}LessThan(t){return 0!=t.Count&&(0==this.Count||this.maxItem.Value0?new S(this.maxItem):new S}MinAsList(){return this.Count>0?new S(this.minItem):new S}ListWithSubRange(t,e){if(0==this.Count)return new S;let n=this.orderedItems,i=0,r=Number.MAX_SAFE_INTEGER;Number.isInteger(t)?i=t:t instanceof S&&t.Count>0&&(i=t.minItem.Value),Number.isInteger(e)?r=e:e instanceof S&&e.Count>0&&(r=e.maxItem.Value);let a=new S;a.SetInitialOriginNames(this.originNames);for(let t of n)t.Value>=i&&t.Value<=r&&a.Add(t.Key,t.Value);return a}Equals(t){if(t instanceof S==!1)return!1;if(t.Count!=this.Count)return!1;for(let[e]of this)if(!t.has(e))return!1;return!0}get orderedItems(){let t=new Array;for(let[e,n]of this){let i=g.fromSerializedKey(e);t.push({Key:i,Value:n})}return t.sort(((t,e)=>null===t.Key.originName?p("x.Key.originName"):null===e.Key.originName?p("y.Key.originName"):t.Value==e.Value?t.Key.originName.localeCompare(e.Key.originName):t.Valuee.Value?1:0)),t}get singleItem(){for(let t of this.orderedItems)return t.Key;return null}toString(){let t=this.orderedItems,e=new f;for(let n=0;n0&&e.Append(", ");let i=t[n].Key;if(null===i.itemName)return p("item.itemName");e.Append(i.itemName)}return e.toString()}valueOf(){return NaN}}class y extends Error{constructor(t){super(t),this.useEndLineNumber=!1,this.message=t,this.name="StoryException"}}function v(t,e,n){if(null===t)return{result:n,exists:!1};let i=t.get(e);return void 0===i?{result:n,exists:!1}:{result:i,exists:!0}}class C extends m{static Create(t,n){if(n){if(n===i.Int&&Number.isInteger(Number(t)))return new w(Number(t));if(n===i.Float&&!isNaN(t))return new T(Number(t))}return"boolean"==typeof t?new _(Boolean(t)):"string"==typeof t?new E(String(t)):Number.isInteger(Number(t))?new w(Number(t)):isNaN(t)?t instanceof e?new P(l(t,e)):t instanceof S?new O(l(t,S)):null:new T(Number(t))}Copy(){return l(C.Create(this.valueObject),m)}BadCastException(t){return new y("Can't cast "+this.valueObject+" from "+this.valueType+" to "+t)}}class b extends C{constructor(t){super(),this.value=t}get valueObject(){return this.value}toString(){return null===this.value?p("Value.value"):this.value.toString()}}class _ extends b{constructor(t){super(t||!1)}get isTruthy(){return Boolean(this.value)}get valueType(){return i.Bool}Cast(t){if(null===this.value)return p("Value.value");if(t==this.valueType)return this;if(t==i.Int)return new w(this.value?1:0);if(t==i.Float)return new T(this.value?1:0);if(t==i.String)return new E(this.value?"true":"false");throw this.BadCastException(t)}toString(){return this.value?"true":"false"}}class w extends b{constructor(t){super(t||0)}get isTruthy(){return 0!=this.value}get valueType(){return i.Int}Cast(t){if(null===this.value)return p("Value.value");if(t==this.valueType)return this;if(t==i.Bool)return new _(0!==this.value);if(t==i.Float)return new T(this.value);if(t==i.String)return new E(""+this.value);throw this.BadCastException(t)}}class T extends b{constructor(t){super(t||0)}get isTruthy(){return 0!=this.value}get valueType(){return i.Float}Cast(t){if(null===this.value)return p("Value.value");if(t==this.valueType)return this;if(t==i.Bool)return new _(0!==this.value);if(t==i.Int)return new w(this.value);if(t==i.String)return new E(""+this.value);throw this.BadCastException(t)}}class E extends b{constructor(t){if(super(t||""),this._isNewline="\n"==this.value,this._isInlineWhitespace=!0,null===this.value)return p("Value.value");this.value.length>0&&this.value.split("").every((t=>" "==t||"\t"==t||(this._isInlineWhitespace=!1,!1)))}get valueType(){return i.String}get isTruthy(){return null===this.value?p("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==i.Int){let e=function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=parseInt(t);return Number.isNaN(n)?{result:e,exists:!1}:{result:n,exists:!0}}(this.value);if(e.exists)return new w(e.result);throw this.BadCastException(t)}if(t==i.Float){let e=function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=parseFloat(t);return Number.isNaN(n)?{result:e,exists:!1}:{result:n,exists:!0}}(this.value);if(e.exists)return new T(e.result);throw this.BadCastException(t)}throw this.BadCastException(t)}}class P extends b{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:null)}get valueType(){return i.DivertTarget}get targetPath(){return null===this.value?p("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+")"}}class N extends b{constructor(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1;super(t),this._contextIndex=e}get contextIndex(){return this._contextIndex}set contextIndex(t){this._contextIndex=t}get variableName(){return null===this.value?p("Value.value"):this.value}set variableName(t){this.value=t}get valueType(){return i.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 N(this.variableName,this.contextIndex)}}class O extends b{get isTruthy(){return null===this.value?p("this.value"):this.value.Count>0}get valueType(){return i.List}Cast(t){if(null===this.value)return p("Value.value");if(t==i.Int){let t=this.value.maxItem;return t.Key.isNull?new w(0):new w(t.Value)}if(t==i.Float){let t=this.value.maxItem;return t.Key.isNull?new T(0):new T(t.Value)}if(t==i.String){let t=this.value.maxItem;return t.Key.isNull?new E(""):new E(t.Key.toString())}if(t==this.valueType)return this;throw this.BadCastException(t)}constructor(t,e){super(null),t||e?t instanceof S?this.value=new S(t):t instanceof g&&"number"==typeof e&&(this.value=new S({Key:t,Value:e})):this.value=new S}static RetainListOriginsForAssignment(t,e){let n=s(t,O),i=s(e,O);return i&&null===i.value?p("newList.value"):n&&null===n.value?p("oldList.value"):void(n&&i&&0==i.value.Count&&i.value.SetInitialOriginNames(n.value.originNames))}}!function(t){t[t.Bool=-1]="Bool",t[t.Int=0]="Int",t[t.Float=1]="Float",t[t.List=2]="List",t[t.String=3]="String",t[t.DivertTarget=4]="DivertTarget",t[t.VariablePointer=5]="VariablePointer"}(i||(i={}));class A{constructor(){this.obj=null,this.approximate=!1}get correctObj(){return this.approximate?null:this.obj}get container(){return this.obj instanceof x?this.obj:null}copy(){let t=new A;return t.obj=this.obj,t.approximate=this.approximate,t}}class x extends m{constructor(){super(...arguments),this.name=null,this._content=[],this.namedContent=new Map,this.visitsShouldBeCounted=!1,this.turnIndexShouldBeCounted=!1,this.countingAtStartOnly=!1,this._pathToFirstLeafContent=null}get hasValidName(){return null!=this.name&&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=l(n,m);t.set(e,i)}for(let e of this.content){let n=o(e);null!=n&&n.hasValidName&&t.delete(n.name)}return 0==t.size&&(t=null),t}set namedOnlyContent(t){let e=this.namedOnlyContent;if(null!=e)for(let[t]of e)this.namedContent.delete(t);if(null!=t)for(let[,e]of t){let t=o(e);null!=t&&this.AddToNamedContentOnly(t)}}get countFlags(){let t=0;return this.visitsShouldBeCounted&&(t|=x.CountFlags.Visits),this.turnIndexShouldBeCounted&&(t|=x.CountFlags.Turns),this.countingAtStartOnly&&(t|=x.CountFlags.CountStartOnly),t==x.CountFlags.CountStartOnly&&(t=0),t}set countFlags(t){let e=t;(e&x.CountFlags.Visits)>0&&(this.visitsShouldBeCounted=!0),(e&x.CountFlags.Turns)>0&&(this.turnIndexShouldBeCounted=!0),(e&x.CountFlags.CountStartOnly)>0&&(this.countingAtStartOnly=!0)}get pathToFirstLeafContent(){return null==this._pathToFirstLeafContent&&(this._pathToFirstLeafContent=this.path.PathByAppendingPath(this.internalPathToFirstLeafContent)),this._pathToFirstLeafContent}get internalPathToFirstLeafContent(){let t=[],n=this;for(;n instanceof x;)n.content.length>0&&(t.push(new e.Component(0)),n=n.content[0]);return new e(t)}AddContent(t){if(t instanceof Array){let e=t;for(let t of e)this.AddContent(t)}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=o(t);null!=e&&e.hasValidName&&this.AddToNamedContentOnly(e)}AddToNamedContentOnly(t){if(n.AssertType(t,m,"Can only add Runtime.Objects to a Runtime.Container"),l(t,m).parent=this,null===t.name)return p("namedContentObj.name");this.namedContent.set(t.name,t)}ContentAtPath(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:-1;-1==n&&(n=t.length);let i=new A;i.approximate=!1;let r=this,a=this;for(let l=e;l=0&&t.index=0||a.set(t,e);if(a.size>0){r(),t.AppendLine("-- named: --");for(let[,r]of a){n.AssertType(r,x,"Can only print out named Containers"),r.BuildStringOfHierarchy(t,e,i),t.AppendLine()}}e--,r(),t.Append("]")}}!function(t){var e;(e=t.CountFlags||(t.CountFlags={}))[e.Start=0]="Start",e[e.Visits=1]="Visits",e[e.Turns=2]="Turns",e[e.CountStartOnly=4]="CountStartOnly"}(x||(x={}));class I extends m{toString(){return"Glue"}}class k extends m{get commandType(){return this._commandType}constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:k.CommandType.NotSet;super(),this._commandType=t}Copy(){return new k(this.commandType)}static EvalStart(){return new k(k.CommandType.EvalStart)}static EvalOutput(){return new k(k.CommandType.EvalOutput)}static EvalEnd(){return new k(k.CommandType.EvalEnd)}static Duplicate(){return new k(k.CommandType.Duplicate)}static PopEvaluatedValue(){return new k(k.CommandType.PopEvaluatedValue)}static PopFunction(){return new k(k.CommandType.PopFunction)}static PopTunnel(){return new k(k.CommandType.PopTunnel)}static BeginString(){return new k(k.CommandType.BeginString)}static EndString(){return new k(k.CommandType.EndString)}static NoOp(){return new k(k.CommandType.NoOp)}static ChoiceCount(){return new k(k.CommandType.ChoiceCount)}static Turns(){return new k(k.CommandType.Turns)}static TurnsSince(){return new k(k.CommandType.TurnsSince)}static ReadCount(){return new k(k.CommandType.ReadCount)}static Random(){return new k(k.CommandType.Random)}static SeedRandom(){return new k(k.CommandType.SeedRandom)}static VisitIndex(){return new k(k.CommandType.VisitIndex)}static SequenceShuffleIndex(){return new k(k.CommandType.SequenceShuffleIndex)}static StartThread(){return new k(k.CommandType.StartThread)}static Done(){return new k(k.CommandType.Done)}static End(){return new k(k.CommandType.End)}static ListFromInt(){return new k(k.CommandType.ListFromInt)}static ListRange(){return new k(k.CommandType.ListRange)}static ListRandom(){return new k(k.CommandType.ListRandom)}static BeginTag(){return new k(k.CommandType.BeginTag)}static EndTag(){return new k(k.CommandType.EndTag)}toString(){return"ControlCommand "+this.commandType.toString()}}!function(t){var e;(e=t.CommandType||(t.CommandType={}))[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"}(k||(k={})),function(t){t[t.Tunnel=0]="Tunnel",t[t.Function=1]="Function",t[t.FunctionEvaluationFromGame=2]="FunctionEvaluationFromGame"}(r||(r={}));class F{constructor(){this.container=null,this.index=-1,2===arguments.length&&(this.container=arguments[0],this.index=arguments[1])}Resolve(){return this.index<0?this.container:null==this.container?null:0==this.container.content.length?this.container:this.index>=this.container.content.length?null:this.container.content[this.index]}get isNull(){return null==this.container}get path(){return this.isNull?null:this.index>=0?this.container.path.PathByAppendingComponent(new e.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 F(this.container,this.index)}static StartOf(t){return new F(t,0)}static get Null(){return new F(null,-1)}}class W extends m{get targetPath(){if(null!=this._targetPath&&this._targetPath.isRelative){let t=this.targetPointer.Resolve();t&&(this._targetPath=t.path)}return this._targetPath}set targetPath(t){this._targetPath=t,this._targetPointer=F.Null}get targetPointer(){if(this._targetPointer.isNull){let t=this.ResolvePath(this._targetPath).obj;if(null===this._targetPath)return p("this._targetPath");if(null===this._targetPath.lastComponent)return p("this._targetPath.lastComponent");if(this._targetPath.lastComponent.isIndex){if(null===t)return p("targetObj");this._targetPointer.container=t.parent instanceof x?t.parent:null,this._targetPointer.index=this._targetPath.lastComponent.index}else this._targetPointer=F.StartOf(t instanceof x?t:null)}return this._targetPointer.copy()}get targetPathString(){return null==this.targetPath?null:this.CompactPathString(this.targetPath)}set targetPathString(t){this.targetPath=null==t?null:new e(t)}get hasVariableTarget(){return null!=this.variableDivertName}constructor(t){super(),this._targetPath=null,this._targetPointer=F.Null,this.variableDivertName=null,this.pushesToStack=!1,this.stackPushType=0,this.isExternal=!1,this.externalArgs=0,this.isConditional=!1,this.pushesToStack=!1,void 0!==t&&(this.pushesToStack=!0,this.stackPushType=t)}Equals(t){let e=t;return e instanceof W&&this.hasVariableTarget==e.hasVariableTarget&&(this.hasVariableTarget?this.variableDivertName==e.variableDivertName:null===this.targetPath?p("this.targetPath"):this.targetPath.Equals(e.targetPath))}toString(){if(this.hasVariableTarget)return"Divert(variable: "+this.variableDivertName+")";if(null==this.targetPath)return"Divert(null)";{let t=new f,e=this.targetPath.toString();return t.Append("Divert"),this.isConditional&&t.Append("?"),this.pushesToStack&&(this.stackPushType==r.Function?t.Append(" function"):t.Append(" tunnel")),t.Append(" -> "),t.Append(this.targetPathString),t.Append(" ("),t.Append(e),t.Append(")"),t.toString()}}}class V extends m{constructor(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];super(),this._pathOnChoice=null,this.hasCondition=!1,this.hasStartContent=!1,this.hasChoiceOnlyContent=!1,this.isInvisibleDefault=!1,this.onceOnly=!0,this.onceOnly=t}get pathOnChoice(){if(null!=this._pathOnChoice&&this._pathOnChoice.isRelative){let t=this.choiceTarget;t&&(this._pathOnChoice=t.path)}return this._pathOnChoice}set pathOnChoice(t){this._pathOnChoice=t}get choiceTarget(){return null===this._pathOnChoice?p("ChoicePoint._pathOnChoice"):this.ResolvePath(this._pathOnChoice).container}get pathStringOnChoice(){return null===this.pathOnChoice?p("ChoicePoint.pathOnChoice"):this.CompactPathString(this.pathOnChoice)}set pathStringOnChoice(t){this.pathOnChoice=new e(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=(1&t)>0,this.hasStartContent=(2&t)>0,this.hasChoiceOnlyContent=(4&t)>0,this.isInvisibleDefault=(8&t)>0,this.onceOnly=(16&t)>0}toString(){if(null===this.pathOnChoice)return p("ChoicePoint.pathOnChoice");return"Choice: -> "+this.pathOnChoice.toString()}}class L extends m{get containerForCount(){return null===this.pathForCount?null:this.ResolvePath(this.pathForCount).container}get pathStringForCount(){return null===this.pathForCount?null:this.CompactPathString(this.pathForCount)}set pathStringForCount(t){this.pathForCount=null===t?null:new e(t)}constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;super(),this.pathForCount=null,this.name=t}toString(){if(null!=this.name)return"var("+this.name+")";return"read_count("+this.pathStringForCount+")"}}class D extends m{constructor(t,e){super(),this.variableName=t||null,this.isNewDeclaration=!!e,this.isGlobal=!1}toString(){return"VarAssign to "+this.variableName}}class R extends m{toString(){return"Void"}}class j extends m{static CallWithName(t){return new j(t)}static CallExistsWithName(t){return this.GenerateNativeFunctionsIfNecessary(),this._nativeFunctions.get(t)}get name(){return null===this._name?p("NativeFunctionCall._name"):this._name}set name(t){this._name=t,this._isPrototype||(null===j._nativeFunctions?p("NativeFunctionCall._nativeFunctions"):this._prototype=j._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=!1;for(let n of t){if(n instanceof R)throw new y("Attempting to perform "+this.name+' on a void value. Did you forget to "return" a value from a function you called here?');n instanceof O&&(e=!0)}if(2==t.length&&e)return this.CallBinaryListOperation(t);let n=this.CoerceValuesToSingleType(t),r=n[0].valueType;return r==i.Int||r==i.Float||r==i.String||r==i.DivertTarget||r==i.List?this.CallType(n):null}CallType(t){let e=l(t[0],b),n=e.valueType,r=e,a=t.length;if(2==a||1==a){if(null===this._operationFuncs)return p("NativeFunctionCall._operationFuncs");let s=this._operationFuncs.get(n);if(!s){const t=i[n];throw new y("Cannot perform operation "+this.name+" on "+t)}if(2==a){let e=l(t[1],b),n=s;if(null===r.value||null===e.value)return p("NativeFunctionCall.Call BinaryOp values");let i=n(r.value,e.value);return b.Create(i)}{let t=s;if(null===r.value)return p("NativeFunctionCall.Call UnaryOp value");let n=t(r.value);return this.name===j.Int?b.Create(n,i.Int):this.name===j.Float?b.Create(n,i.Float):b.Create(n,e.valueType)}}throw new Error("Unexpected number of parameters to NativeFunctionCall: "+t.length)}CallBinaryListOperation(t){if(("+"==this.name||"-"==this.name)&&t[0]instanceof O&&t[1]instanceof w)return this.CallListIncrementOperation(t);let e=l(t[0],b),n=l(t[1],b);if(!("&&"!=this.name&&"||"!=this.name||e.valueType==i.List&&n.valueType==i.List)){if(null===this._operationFuncs)return p("NativeFunctionCall._operationFuncs");let t=this._operationFuncs.get(i.Int);if(null===t)return p("NativeFunctionCall.CallBinaryListOperation op");let r=function(t){if("boolean"==typeof t)return t;throw new Error(`${t} is not a boolean`)}(t(e.isTruthy?1:0,n.isTruthy?1:0));return new _(r)}if(e.valueType==i.List&&n.valueType==i.List)return this.CallType([e,n]);throw new y("Can not call use "+this.name+" operation on "+i[e.valueType]+" and "+i[n.valueType])}CallListIncrementOperation(t){let e=l(t[0],O),n=l(t[1],w),r=new S;if(null===e.value)return p("NativeFunctionCall.CallListIncrementOperation listVal.value");for(let[t,a]of e.value){let s=g.fromSerializedKey(t);if(null===this._operationFuncs)return p("NativeFunctionCall._operationFuncs");let l=this._operationFuncs.get(i.Int);if(null===n.value)return p("NativeFunctionCall.CallListIncrementOperation intVal.value");let o=l(a,n.value),h=null;if(null===e.value.origins)return p("NativeFunctionCall.CallListIncrementOperation listVal.value.origins");for(let t of e.value.origins)if(t.name==s.originName){h=t;break}if(null!=h){let t=h.TryGetItemWithValue(o,g.Null);t.exists&&r.Add(t.result,o)}}return new O(r)}CoerceValuesToSingleType(t){let e=i.Int,n=null;for(let r of t){let t=l(r,b);t.valueType>e&&(e=t.valueType),t.valueType==i.List&&(n=s(t,O))}let r=[];if(i[e]==i[i.List])for(let e of t){let t=l(e,b);if(t.valueType==i.List)r.push(t);else{if(t.valueType!=i.Int){const e=i[t.valueType];throw new y("Cannot mix Lists and "+e+" values in this operation")}{let e=parseInt(t.valueObject);if(n=l(n,O),null===n.value)return p("NativeFunctionCall.CoerceValuesToSingleType specialCaseList.value");let i=n.value.originOfMaxItem;if(null===i)return p("NativeFunctionCall.CoerceValuesToSingleType list");let a=i.TryGetItemWithValue(e,g.Null);if(!a.exists)throw new y("Could not find List item with the value "+e+" in "+i.name);{let t=new O(a.result,e);r.push(t)}}}}else for(let n of t){let t=l(n,b).Cast(e);r.push(t)}return r}constructor(){if(super(),this._name=null,this._numberOfParameters=0,this._prototype=null,this._isPrototype=!1,this._operationFuncs=null,0===arguments.length)j.GenerateNativeFunctionsIfNecessary();else if(1===arguments.length){let t=arguments[0];j.GenerateNativeFunctionsIfNecessary(),this.name=t}else if(2===arguments.length){let t=arguments[0],e=arguments[1];this._isPrototype=!0,this.name=t,this.numberOfParameters=e}}static Identity(t){return t}static GenerateNativeFunctionsIfNecessary(){if(null==this._nativeFunctions){this._nativeFunctions=new Map,this.AddIntBinaryOp(this.Add,((t,e)=>t+e)),this.AddIntBinaryOp(this.Subtract,((t,e)=>t-e)),this.AddIntBinaryOp(this.Multiply,((t,e)=>t*e)),this.AddIntBinaryOp(this.Divide,((t,e)=>Math.floor(t/e))),this.AddIntBinaryOp(this.Mod,((t,e)=>t%e)),this.AddIntUnaryOp(this.Negate,(t=>-t)),this.AddIntBinaryOp(this.Equal,((t,e)=>t==e)),this.AddIntBinaryOp(this.Greater,((t,e)=>t>e)),this.AddIntBinaryOp(this.Less,((t,e)=>tt>=e)),this.AddIntBinaryOp(this.LessThanOrEquals,((t,e)=>t<=e)),this.AddIntBinaryOp(this.NotEquals,((t,e)=>t!=e)),this.AddIntUnaryOp(this.Not,(t=>0==t)),this.AddIntBinaryOp(this.And,((t,e)=>0!=t&&0!=e)),this.AddIntBinaryOp(this.Or,((t,e)=>0!=t||0!=e)),this.AddIntBinaryOp(this.Max,((t,e)=>Math.max(t,e))),this.AddIntBinaryOp(this.Min,((t,e)=>Math.min(t,e))),this.AddIntBinaryOp(this.Pow,((t,e)=>Math.pow(t,e))),this.AddIntUnaryOp(this.Floor,j.Identity),this.AddIntUnaryOp(this.Ceiling,j.Identity),this.AddIntUnaryOp(this.Int,j.Identity),this.AddIntUnaryOp(this.Float,(t=>t)),this.AddFloatBinaryOp(this.Add,((t,e)=>t+e)),this.AddFloatBinaryOp(this.Subtract,((t,e)=>t-e)),this.AddFloatBinaryOp(this.Multiply,((t,e)=>t*e)),this.AddFloatBinaryOp(this.Divide,((t,e)=>t/e)),this.AddFloatBinaryOp(this.Mod,((t,e)=>t%e)),this.AddFloatUnaryOp(this.Negate,(t=>-t)),this.AddFloatBinaryOp(this.Equal,((t,e)=>t==e)),this.AddFloatBinaryOp(this.Greater,((t,e)=>t>e)),this.AddFloatBinaryOp(this.Less,((t,e)=>tt>=e)),this.AddFloatBinaryOp(this.LessThanOrEquals,((t,e)=>t<=e)),this.AddFloatBinaryOp(this.NotEquals,((t,e)=>t!=e)),this.AddFloatUnaryOp(this.Not,(t=>0==t)),this.AddFloatBinaryOp(this.And,((t,e)=>0!=t&&0!=e)),this.AddFloatBinaryOp(this.Or,((t,e)=>0!=t||0!=e)),this.AddFloatBinaryOp(this.Max,((t,e)=>Math.max(t,e))),this.AddFloatBinaryOp(this.Min,((t,e)=>Math.min(t,e))),this.AddFloatBinaryOp(this.Pow,((t,e)=>Math.pow(t,e))),this.AddFloatUnaryOp(this.Floor,(t=>Math.floor(t))),this.AddFloatUnaryOp(this.Ceiling,(t=>Math.ceil(t))),this.AddFloatUnaryOp(this.Int,(t=>Math.floor(t))),this.AddFloatUnaryOp(this.Float,j.Identity),this.AddStringBinaryOp(this.Add,((t,e)=>t+e)),this.AddStringBinaryOp(this.Equal,((t,e)=>t===e)),this.AddStringBinaryOp(this.NotEquals,((t,e)=>!(t===e))),this.AddStringBinaryOp(this.Has,((t,e)=>t.includes(e))),this.AddStringBinaryOp(this.Hasnt,((t,e)=>!t.includes(e))),this.AddListBinaryOp(this.Add,((t,e)=>t.Union(e))),this.AddListBinaryOp(this.Subtract,((t,e)=>t.Without(e))),this.AddListBinaryOp(this.Has,((t,e)=>t.Contains(e))),this.AddListBinaryOp(this.Hasnt,((t,e)=>!t.Contains(e))),this.AddListBinaryOp(this.Intersect,((t,e)=>t.Intersect(e))),this.AddListBinaryOp(this.Equal,((t,e)=>t.Equals(e))),this.AddListBinaryOp(this.Greater,((t,e)=>t.GreaterThan(e))),this.AddListBinaryOp(this.Less,((t,e)=>t.LessThan(e))),this.AddListBinaryOp(this.GreaterThanOrEquals,((t,e)=>t.GreaterThanOrEquals(e))),this.AddListBinaryOp(this.LessThanOrEquals,((t,e)=>t.LessThanOrEquals(e))),this.AddListBinaryOp(this.NotEquals,((t,e)=>!t.Equals(e))),this.AddListBinaryOp(this.And,((t,e)=>t.Count>0&&e.Count>0)),this.AddListBinaryOp(this.Or,((t,e)=>t.Count>0||e.Count>0)),this.AddListUnaryOp(this.Not,(t=>0==t.Count?1:0)),this.AddListUnaryOp(this.Invert,(t=>t.inverse)),this.AddListUnaryOp(this.All,(t=>t.all)),this.AddListUnaryOp(this.ListMin,(t=>t.MinAsList())),this.AddListUnaryOp(this.ListMax,(t=>t.MaxAsList())),this.AddListUnaryOp(this.Count,(t=>t.Count)),this.AddListUnaryOp(this.ValueOfList,(t=>t.maxItem.Value));let t=(t,e)=>t.Equals(e),e=(t,e)=>!t.Equals(e);this.AddOpToNativeFunc(this.Equal,2,i.DivertTarget,t),this.AddOpToNativeFunc(this.NotEquals,2,i.DivertTarget,e)}}AddOpFuncForType(t,e){null==this._operationFuncs&&(this._operationFuncs=new Map),this._operationFuncs.set(t,e)}static AddOpToNativeFunc(t,e,n,i){if(null===this._nativeFunctions)return p("NativeFunctionCall._nativeFunctions");let r=this._nativeFunctions.get(t);r||(r=new j(t,e),this._nativeFunctions.set(t,r)),r.AddOpFuncForType(n,i)}static AddIntBinaryOp(t,e){this.AddOpToNativeFunc(t,2,i.Int,e)}static AddIntUnaryOp(t,e){this.AddOpToNativeFunc(t,1,i.Int,e)}static AddFloatBinaryOp(t,e){this.AddOpToNativeFunc(t,2,i.Float,e)}static AddFloatUnaryOp(t,e){this.AddOpToNativeFunc(t,1,i.Float,e)}static AddStringBinaryOp(t,e){this.AddOpToNativeFunc(t,2,i.String,e)}static AddListBinaryOp(t,e){this.AddOpToNativeFunc(t,2,i.List,e)}static AddListUnaryOp(t,e){this.AddOpToNativeFunc(t,1,i.List,e)}toString(){return'Native "'+this.name+'"'}}j.Add="+",j.Subtract="-",j.Divide="/",j.Multiply="*",j.Mod="%",j.Negate="_",j.Equal="==",j.Greater=">",j.Less="<",j.GreaterThanOrEquals=">=",j.LessThanOrEquals="<=",j.NotEquals="!=",j.Not="!",j.And="&&",j.Or="||",j.Min="MIN",j.Max="MAX",j.Pow="POW",j.Floor="FLOOR",j.Ceiling="CEILING",j.Int="INT",j.Float="FLOAT",j.Has="?",j.Hasnt="!?",j.Intersect="^",j.ListMin="LIST_MIN",j.ListMax="LIST_MAX",j.All="LIST_ALL",j.Count="LIST_COUNT",j.ValueOfList="LIST_VALUE",j.Invert="LIST_INVERT",j._nativeFunctions=null;class B extends m{constructor(t){super(),this.text=t.toString()||""}toString(){return"# "+this.text}}class G extends m{constructor(){super(...arguments),this.text="",this.index=0,this.threadAtGeneration=null,this.sourcePath="",this.targetPath=null,this.isInvisibleDefault=!1,this.tags=null,this.originalThreadIndex=0}get pathStringOnChoice(){return null===this.targetPath?p("Choice.targetPath"):this.targetPath.toString()}set pathStringOnChoice(t){this.targetPath=new e(t)}Clone(){let t=new G;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,null!==this.threadAtGeneration&&(t.threadAtGeneration=this.threadAtGeneration.Copy()),t}}class M{constructor(t,e){this._name=t||"",this._items=null,this._itemNameToValues=e||new Map}get name(){return this._name}get items(){if(null==this._items){this._items=new Map;for(let[t,e]of this._itemNameToValues){let n=new g(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 void 0!==e?e:0}ContainsItem(t){return!!t.itemName&&(t.originName==this.name&&this._itemNameToValues.has(t.itemName))}ContainsItemWithName(t){return this._itemNameToValues.has(t)}TryGetItemWithValue(t,e){for(let[e,n]of this._itemNameToValues)if(n==t)return{result:new g(this.name,e),exists:!0};return{result:g.Null,exists:!1}}TryGetValueForItem(t,e){if(!t.itemName)return{result:0,exists:!1};let n=this._itemNameToValues.get(t.itemName);return n?{result:n,exists:!0}:{result:0,exists:!1}}}class J{constructor(t){this._lists=new Map,this._allUnambiguousListValueCache=new Map;for(let e of t){this._lists.set(e.name,e);for(let[t,n]of e.items){let e=g.fromSerializedKey(t),i=new O(e,n);if(!e.itemName)throw new Error("item.itemName is null or undefined.");this._allUnambiguousListValueCache.set(e.itemName,i),this._allUnambiguousListValueCache.set(e.fullName,i)}}}get lists(){let t=[];for(let[,e]of this._lists)t.push(e);return t}TryListGetDefinition(t,e){if(null===t)return{result:e,exists:!1};let n=this._lists.get(t);return n?{result:n,exists:!0}:{result:e,exists:!1}}FindSingleItemListWithName(t){if(null===t)return p("name");let e=this._allUnambiguousListValueCache.get(t);return void 0!==e?e:null}}class q{static JArrayToRuntimeObjList(t){let e=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=t.length;e&&n--;let i=[];for(let e=0;e";return i.isExternal?n="x()":i.pushesToStack&&(i.stackPushType==r.Function?n="f()":i.stackPushType==r.Tunnel&&(n="->t->")),e=i.hasVariableTarget?i.variableDivertName:i.targetPathString,t.WriteObjectStart(),t.WriteProperty(n,e),i.hasVariableTarget&&t.WriteProperty("var",!0),i.isConditional&&t.WriteProperty("c",!0),i.externalArgs>0&&t.WriteIntProperty("exArgs",i.externalArgs),void t.WriteObjectEnd()}let a=s(e,V);if(a)return t.WriteObjectStart(),t.WriteProperty("*",a.pathStringOnChoice),t.WriteIntProperty("flg",a.flags),void t.WriteObjectEnd();let l=s(e,_);if(l)return void t.WriteBool(l.value);let o=s(e,w);if(o)return void t.WriteInt(o.value);let h=s(e,T);if(h)return void t.WriteFloat(h.value);let u=s(e,E);if(u)return void(u.isNewline?t.Write("\n",!1):(t.WriteStringStart(),t.WriteStringInner("^"),t.WriteStringInner(u.value),t.WriteStringEnd()));let c=s(e,O);if(c)return void this.WriteInkList(t,c);let d=s(e,P);if(d)return t.WriteObjectStart(),null===d.value?p("divTargetVal.value"):(t.WriteProperty("^->",d.value.componentsString),void t.WriteObjectEnd());let m=s(e,N);if(m)return t.WriteObjectStart(),t.WriteProperty("^var",m.value),t.WriteIntProperty("ci",m.contextIndex),void t.WriteObjectEnd();if(s(e,I))return void t.Write("<>");let f=s(e,k);if(f)return void t.Write(q._controlCommandNames[f.commandType]);let g=s(e,j);if(g){let e=g.name;return"^"==e&&(e="L^"),void t.Write(e)}let S=s(e,L);if(S){t.WriteObjectStart();let e=S.pathStringForCount;return null!=e?t.WriteProperty("CNT?",e):t.WriteProperty("VAR?",S.name),void t.WriteObjectEnd()}let y=s(e,D);if(y){t.WriteObjectStart();let e=y.isGlobal?"VAR=":"temp=";return t.WriteProperty(e,y.variableName),y.isNewDeclaration||t.WriteProperty("re",!0),void t.WriteObjectEnd()}if(s(e,R))return void t.Write("void");let v=s(e,B);if(v)return t.WriteObjectStart(),t.WriteProperty("#",v.text),void t.WriteObjectEnd();let C=s(e,G);if(!C)throw new Error("Failed to convert runtime object to Json token: "+e);this.WriteChoice(t,C)}static JObjectToDictionaryRuntimeObjs(t){let e=new Map;for(let n in t)if(t.hasOwnProperty(n)){let i=this.JTokenToRuntimeObject(t[n]);if(null===i)return p("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("number"==typeof t&&!isNaN(t)||"boolean"==typeof t)return b.Create(t);if("string"==typeof t){let e=t.toString();const n=/^([0-9]+.[0-9]+f)$/.exec(e);if(n)return new T(parseFloat(n[0]));let i=e[0];if("^"==i)return new E(e.substring(1));if("\n"==i&&1==e.length)return new E("\n");if("<>"==e)return new I;for(let t=0;t->"==e)return k.PopTunnel();if("~ret"==e)return k.PopFunction();if("void"==e)return new R}if("object"==typeof t&&!Array.isArray(t)){let n,i=t;if(i["^->"])return n=i["^->"],new P(new e(n.toString()));if(i["^var"]){n=i["^var"];let t=new N(n.toString());return"ci"in i&&(n=i.ci,t.contextIndex=parseInt(n)),t}let a=!1,s=!1,l=r.Function,o=!1;if((n=i["->"])?a=!0:(n=i["f()"])?(a=!0,s=!0,l=r.Function):(n=i["->t->"])?(a=!0,s=!0,l=r.Tunnel):(n=i["x()"])&&(a=!0,o=!0,s=!1,l=r.Function),a){let t=new W;t.pushesToStack=s,t.stackPushType=l,t.isExternal=o;let e=n.toString();return(n=i.var)?t.variableDivertName=e:t.targetPathString=e,t.isConditional=!!i.c,o&&(n=i.exArgs)&&(t.externalArgs=parseInt(n)),t}if(n=i["*"]){let t=new V;return t.pathStringOnChoice=n.toString(),(n=i.flg)&&(t.flags=parseInt(n)),t}if(n=i["VAR?"])return new L(n.toString());if(n=i["CNT?"]){let t=new L;return t.pathStringForCount=n.toString(),t}let h=!1,u=!1;if((n=i["VAR="])?(h=!0,u=!0):(n=i["temp="])&&(h=!0,u=!1),h){let t=n.toString(),e=!i.re,r=new D(t,e);return r.isGlobal=u,r}if(void 0!==i["#"])return n=i["#"],new B(n.toString());if(n=i.list){let t=n,e=new S;if(n=i.origins){let t=n;e.SetInitialOriginNames(t)}for(let n in t)if(t.hasOwnProperty(n)){let i=t[n],r=new g(n),a=parseInt(i);e.Add(r,a)}return new O(e)}if(null!=i.originalChoicePath)return this.JObjectToChoice(i)}if(Array.isArray(t))return this.JArrayToContainer(t);if(null==t)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,((t,n)=>(null==e?void 0:e.some((e=>e===t)))?void 0:n),n)}static WriteRuntimeContainer(t,e){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(t.WriteArrayStart(),null===e)return p("container");for(let n of e.content)this.WriteRuntimeObject(t,n);let i=e.namedOnlyContent,r=e.countFlags,a=null!=e.name&&!n,l=null!=i||r>0||a;if(l&&t.WriteObjectStart(),null!=i)for(let[e,n]of i){let i=e,r=s(n,x);t.WritePropertyStart(i),this.WriteRuntimeContainer(t,r,!0),t.WritePropertyEnd()}r>0&&t.WriteIntProperty("#f",r),a&&t.WriteProperty("#n",e.name),l?t.WriteObjectEnd():t.WriteNull(),t.WriteArrayEnd()}static JArrayToContainer(t){let e=new x;e.content=this.JArrayToRuntimeObjList(t,!0);let n=t[t.length-1];if(null!=n){let t=new Map;for(let i in n)if("#f"==i)e.countFlags=parseInt(n[i]);else if("#n"==i)e.name=n[i].toString();else{let e=this.JTokenToRuntimeObject(n[i]),r=s(e,x);r&&(r.name=i),t.set(i,e)}e.namedOnlyContent=t}return e}static JObjectToChoice(t){let e=new G;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.isInvisibleDefault=!!t.isInvisibleDefault,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),t.WriteProperty("isInvisibleDefault",e.isInvisibleDefault),this.WriteChoiceTags(t,e),t.WriteObjectEnd()}static WriteChoiceTags(t,e){if(e.tags&&e.tags.length>0){t.WritePropertyStart("tags"),t.WriteArrayStart();for(const n of e.tags)t.Write(n);t.WriteArrayEnd(),t.WritePropertyEnd()}}static WriteInkList(t,e){let n=e.value;if(null===n)return p("rawList");t.WriteObjectStart(),t.WritePropertyStart("list"),t.WriteObjectStart();for(let[e,i]of n){let n=g.fromSerializedKey(e),r=i;if(null===n.itemName)return p("item.itemName");t.WritePropertyNameStart(),t.WritePropertyNameInner(n.originName?n.originName:"?"),t.WritePropertyNameInner("."),t.WritePropertyNameInner(n.itemName),t.WritePropertyNameEnd(),t.Write(r),t.WritePropertyEnd()}if(t.WriteObjectEnd(),t.WritePropertyEnd(),0==n.Count&&null!=n.originNames&&n.originNames.length>0){t.WritePropertyStart("origins"),t.WriteArrayStart();for(let e of n.originNames)t.Write(e);t.WriteArrayEnd(),t.WritePropertyEnd()}t.WriteObjectEnd()}static ListDefinitionsToJToken(t){let e={};for(let n of t.lists){let t={};for(let[e,i]of n.items){let n=g.fromSerializedKey(e);if(null===n.itemName)return p("item.itemName");t[n.itemName]=i}e[n.name]=t}return e}static JTokenToListDefinitions(t){let e=t,n=[];for(let t in e)if(e.hasOwnProperty(t)){let i=t.toString(),r=e[t],a=new Map;for(let n in r)if(e.hasOwnProperty(t)){let t=r[n];a.set(n,parseInt(t))}let s=new M(i,a);n.push(s)}return new J(n)}}q._controlCommandNames=(()=>{let t=[];t[k.CommandType.EvalStart]="ev",t[k.CommandType.EvalOutput]="out",t[k.CommandType.EvalEnd]="/ev",t[k.CommandType.Duplicate]="du",t[k.CommandType.PopEvaluatedValue]="pop",t[k.CommandType.PopFunction]="~ret",t[k.CommandType.PopTunnel]="->->",t[k.CommandType.BeginString]="str",t[k.CommandType.EndString]="/str",t[k.CommandType.NoOp]="nop",t[k.CommandType.ChoiceCount]="choiceCnt",t[k.CommandType.Turns]="turn",t[k.CommandType.TurnsSince]="turns",t[k.CommandType.ReadCount]="readc",t[k.CommandType.Random]="rnd",t[k.CommandType.SeedRandom]="srnd",t[k.CommandType.VisitIndex]="visit",t[k.CommandType.SequenceShuffleIndex]="seq",t[k.CommandType.StartThread]="thread",t[k.CommandType.Done]="done",t[k.CommandType.End]="end",t[k.CommandType.ListFromInt]="listInt",t[k.CommandType.ListRange]="range",t[k.CommandType.ListRandom]="lrnd",t[k.CommandType.BeginTag]="#",t[k.CommandType.EndTag]="/#";for(let e=0;e1}constructor(){if(this._threadCounter=0,this._startOfRoot=F.Null,arguments[0]instanceof Z){let t=arguments[0];this._startOfRoot=F.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 U.Thread),this._threads[0].callstack.push(new U.Element(r.Tunnel,this._startOfRoot))}SetJsonToken(t,e){this._threads.length=0;let n=t.threads;for(let t of n){let n=t,i=new U.Thread(n,e);this._threads.push(i)}this._threadCounter=parseInt(t.threadCounter),this._startOfRoot=F.StartOf(e.rootContentContainer)}WriteJson(t){t.WriteObject((t=>{t.WritePropertyStart("threads"),t.WriteArrayStart();for(let e of this._threads)e.WriteJson(t);t.WriteArrayEnd(),t.WritePropertyEnd(),t.WritePropertyStart("threadCounter"),t.WriteInt(this._threadCounter),t.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)throw new Error("Can't pop thread");this._threads.splice(this._threads.indexOf(this.currentThread),1)}get canPopThread(){return this._threads.length>1&&!this.elementIsEvaluateFromGame}get elementIsEvaluateFromGame(){return this.currentElement.type==r.FunctionEvaluationFromGame}Push(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,i=new U.Element(t,this.currentElement.currentPointer,!1);i.evaluationStackHeightWhenPushed=e,i.functionStartInOutputStream=n,this.callStack.push(i)}CanPop(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;return!!this.canPop&&(null==t||this.currentElement.type==t)}Pop(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;if(!this.CanPop(t))throw new Error("Mismatched push/pop in Callstack");this.callStack.pop()}GetTemporaryVariableWithName(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1;-1==e&&(e=this.currentElementIndex+1);let n=v(this.callStack[e-1].temporaryVariables,t,null);return n.exists?n.result:null}SetTemporaryVariable(t,e,n){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:-1;-1==i&&(i=this.currentElementIndex+1);let r=this.callStack[i-1];if(!n&&!r.temporaryVariables.get(t))throw new Error("Could not find temporary variable to set: "+t);let a=v(r.temporaryVariables,t,null);a.exists&&O.RetainListOriginsForAssignment(a.result,e),r.temporaryVariables.set(t,e)}ContextForVariableNamed(t){return this.currentElement.temporaryVariables.get(t)?this.currentElementIndex+1:0}ThreadWithIndex(t){let e=this._threads.filter((e=>{if(e.threadIndex==t)return e}));return e.length>0?e[0]:null}get callStack(){return this.currentThread.callstack}get callStackTrace(){let t=new f;for(let e=0;e")}}}return t.toString()}}!function(t){class n{constructor(t,e){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];this.evaluationStackHeightWhenPushed=0,this.functionStartInOutputStream=0,this.currentPointer=e.copy(),this.inExpressionEvaluation=n,this.temporaryVariables=new Map,this.type=t}Copy(){let t=new n(this.type,this.currentPointer,this.inExpressionEvaluation);return t.temporaryVariables=new Map(this.temporaryVariables),t.evaluationStackHeightWhenPushed=this.evaluationStackHeightWhenPushed,t.functionStartInOutputStream=this.functionStartInOutputStream,t}}t.Element=n;class i{constructor(){if(this.threadIndex=0,this.previousPointer=F.Null,this.callstack=[],arguments[0]&&arguments[1]){let t=arguments[0],i=arguments[1];this.threadIndex=parseInt(t.threadIndex);let r=t.callstack;for(let t of r){let r,a=t,s=parseInt(a.type),l=F.Null,o=a.cPath;if(void 0!==o){r=o.toString();let t=i.ContentAtPath(new e(r));if(l.container=t.container,l.index=parseInt(a.idx),null==t.obj)throw new Error("When loading state, internal story location couldn't be found: "+r+". Has the story changed since this save data was created?");t.approximate&&(null!==l.container?i.Warning("When loading state, exact internal story location couldn't be found: '"+r+"', so it was approximated to '"+l.container.path.toString()+"' to recover. Has the story changed since this save data was created?"):i.Warning("When loading state, exact internal story location couldn't be found: '"+r+"' and it may not be recoverable. Has the story changed since this save data was created?"))}let h=!!a.exp,u=new n(s,l,h),c=a.temp;void 0!==c?u.temporaryVariables=q.JObjectToDictionaryRuntimeObjs(c):u.temporaryVariables.clear(),this.callstack.push(u)}let a=t.previousContentObject;if(void 0!==a){let t=new e(a.toString());this.previousPointer=i.PointerAtPath(t)}}}Copy(){let t=new i;t.threadIndex=this.threadIndex;for(let e of this.callstack)t.callstack.push(e.Copy());return t.previousPointer=this.previousPointer.copy(),t}WriteJson(t){t.WriteObjectStart(),t.WritePropertyStart("callstack"),t.WriteArrayStart();for(let e of this.callstack){if(t.WriteObjectStart(),!e.currentPointer.isNull){if(null===e.currentPointer.container)return p("el.currentPointer.container");t.WriteProperty("cPath",e.currentPointer.container.path.componentsString),t.WriteIntProperty("idx",e.currentPointer.index)}t.WriteProperty("exp",e.inExpressionEvaluation),t.WriteIntProperty("type",e.type),e.temporaryVariables.size>0&&(t.WritePropertyStart("temp"),q.WriteDictionaryRuntimeObjs(t,e.temporaryVariables),t.WritePropertyEnd()),t.WriteObjectEnd()}if(t.WriteArrayEnd(),t.WritePropertyEnd(),t.WriteIntProperty("threadIndex",this.threadIndex),!this.previousPointer.isNull){let e=this.previousPointer.Resolve();if(null===e)return p("this.previousPointer.Resolve()");t.WriteProperty("previousContentObject",e.path.toString())}t.WriteObjectEnd()}}t.Thread=i}(U||(U={}));class K extends class{}{variableChangedEvent(t,e){for(let n of this.variableChangedEventCallbacks)n(t,e)}StartVariableObservation(){this._batchObservingVariableChanges=!0,this._changedVariablesForBatchObs=new Set}CompleteVariableObservation(){this._batchObservingVariableChanges=!1;let t=new Map;if(null!=this._changedVariablesForBatchObs)for(let t of this._changedVariablesForBatchObs){let e=this._globalVariables.get(t);this.variableChangedEvent(t,e)}if(null!=this.patch)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(const[e,n]of t)this.variableChangedEvent(e,n)}get callStack(){return this._callStack}set callStack(t){this._callStack=t}$(t,e){if(void 0===e){let e=null;return null!==this.patch&&(e=this.patch.TryGetGlobal(t,null),e.exists)?e.result.valueObject:(e=this._globalVariables.get(t),void 0===e&&(e=this._defaultGlobalVariables.get(t)),void 0!==e?e.valueObject:null)}{if(void 0===this._defaultGlobalVariables.get(t))throw new y("Cannot assign to a variable ("+t+") that hasn't been declared in the story");let n=b.Create(e);if(null==n)throw null==e?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=!1,this._globalVariables=new Map,this._callStack=t,this._listDefsOrigin=e;try{return new Proxy(this,{get:(t,e)=>e in t?t[e]:t.$(e),set:(t,e,n)=>(e in t?t[e]=n:t.$(e,n),!0),ownKeys:t=>[...new Set([...t._defaultGlobalVariables.keys(),...t._globalVariables.keys()])],getOwnPropertyDescriptor:(t,e)=>({enumerable:!0,configurable:!0,value:t.$(e)})})}catch(t){}}ApplyPatch(){if(null===this.patch)return p("this.patch");for(let[t,e]of this.patch.globals)this._globalVariables.set(t,e);if(null!==this._changedVariablesForBatchObs)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(void 0!==i){let t=q.JTokenToRuntimeObject(i);if(null===t)return p("tokenInkObject");this._globalVariables.set(e,t)}else this._globalVariables.set(e,n)}}WriteJson(t){t.WriteObjectStart();for(let[e,n]of this._globalVariables){let i=e,r=n;if(K.dontSaveDefaultValues&&this._defaultGlobalVariables.has(i)){let t=this._defaultGlobalVariables.get(i);if(this.RuntimeObjectsEqual(r,t))continue}t.WritePropertyStart(i),q.WriteRuntimeObject(t,r),t.WritePropertyEnd()}t.WriteObjectEnd()}RuntimeObjectsEqual(t,e){if(null===t)return p("obj1");if(null===e)return p("obj2");if(t.constructor!==e.constructor)return!1;let n=s(t,_);if(null!==n)return n.value===l(e,_).value;let i=s(t,w);if(null!==i)return i.value===l(e,w).value;let r=s(t,T);if(null!==r)return r.value===l(e,T).value;let a=s(t,b),o=s(e,b);if(null!==a&&null!==o)return u(a.valueObject)&&u(o.valueObject)?a.valueObject.Equals(o.valueObject):a.valueObject===o.valueObject;throw new Error("FastRoughDefinitelyEquals: Unsupported runtime object type: "+t.constructor.name)}GetVariableWithName(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1,n=this.GetRawVariableWithName(t,e),i=s(n,N);return null!==i&&(n=this.ValueAtVariablePointer(i)),n}TryGetDefaultVariableValue(t){let e=v(this._defaultGlobalVariables,t,null);return e.exists?e.result:null}GlobalVariableExistsWithName(t){return this._globalVariables.has(t)||null!==this._defaultGlobalVariables&&this._defaultGlobalVariables.has(t)}GetRawVariableWithName(t,e){let n=null;if(0==e||-1==e){let e=null;if(null!==this.patch&&(e=this.patch.TryGetGlobal(t,null),e.exists))return e.result;if(e=v(this._globalVariables,t,null),e.exists)return e.result;if(null!==this._defaultGlobalVariables&&(e=v(this._defaultGlobalVariables,t,null),e.exists))return e.result;if(null===this._listDefsOrigin)return p("VariablesState._listDefsOrigin");let n=this._listDefsOrigin.FindSingleItemListWithName(t);if(n)return n}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(null===n)return p("name");let i=-1,r=!1;if(r=t.isNewDeclaration?t.isGlobal:this.GlobalVariableExistsWithName(n),t.isNewDeclaration){let t=s(e,N);if(null!==t){e=this.ResolveVariablePointer(t)}}else{let t=null;do{t=s(this.GetRawVariableWithName(n,i),N),null!=t&&(n=t.variableName,i=t.contextIndex,r=0==i)}while(null!=t)}r?this.SetGlobal(n,e):this._callStack.SetTemporaryVariable(n,e,t.isNewDeclaration,i)}SnapshotDefaultGlobals(){this._defaultGlobalVariables=new Map(this._globalVariables)}RetainListOriginsForAssignment(t,e){let n=l(t,O),i=l(e,O);n.value&&i.value&&0==i.value.Count&&i.value.SetInitialOriginNames(n.value.originNames)}SetGlobal(t,e){let n=null;if(null===this.patch&&(n=v(this._globalVariables,t,null)),null!==this.patch&&(n=this.patch.TryGetGlobal(t,null),n.exists||(n=v(this._globalVariables,t,null))),O.RetainListOriginsForAssignment(n.result,e),null===t)return p("variableName");if(null!==this.patch?this.patch.SetGlobal(t,e):this._globalVariables.set(t,e),null!==this.variableChangedEvent&&null!==n&&e!==n.result)if(this._batchObservingVariableChanges){if(null===this._changedVariablesForBatchObs)return p("this._changedVariablesForBatchObs");null!==this.patch?this.patch.AddChangedVariable(t):null!==this._changedVariablesForBatchObs&&this._changedVariablesForBatchObs.add(t)}else this.variableChangedEvent(t,e)}ResolveVariablePointer(t){let e=t.contextIndex;-1==e&&(e=this.GetContextIndexOfVariableNamed(t.variableName));let n=s(this.GetRawVariableWithName(t.variableName,e),N);return null!=n?n:new N(t.variableName,e)}GetContextIndexOfVariableNamed(t){return this.GlobalVariableExistsWithName(t)?0:this._callStack.currentElementIndex}ObserveVariableChange(t){this.variableChangedEventCallbacks.push(t)}}K.dontSaveDefaultValues=!0;class z{constructor(t){this.seed=t%2147483647,this.seed<=0&&(this.seed+=2147483646)}next(){return this.seed=48271*this.seed%2147483647}nextFloat(){return(this.next()-1)/2147483646}}class H{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,1===arguments.length&&null!==arguments[0]){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 null!==t&&this._globals.has(t)?{result:this._globals.get(t),exists:!0}:{result:e,exists:!1}}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:!0}:{result:e,exists:!1}}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:!0}:{result:e,exists:!1}}}class ${static TextToDictionary(t){return new $.Reader(t).ToDictionary()}static TextToArray(t){return new $.Reader(t).ToArray()}}!function(t){t.Reader=class{constructor(t){if(JSON.parse("0",((t,e,n)=>null!=n))){const e=(t,e,n)=>Number.isInteger(e)&&n.source.endsWith(".0")?n.source+"f":e;this._rootObject=JSON.parse(t,e)}else{const e=t.replace(/(,\s*)([0-9]+\.[0]+)([,]*)/g,'$1"$2f"$3');this._rootObject=JSON.parse(e)}}ToDictionary(){return this._rootObject}ToArray(){return this._rootObject}};class e{constructor(){this._currentPropertyName=null,this._currentString=null,this._stateStack=[],this._collectionStack=[],this._propertyNameStack=[],this._jsonObject=null}WriteObject(t){this.WriteObjectStart(),t(this),this.WriteObjectEnd()}WriteObjectStart(){this.StartNewObject(!0);let e={};if(this.state===t.Writer.State.Property){this.Assert(null!==this.currentCollection),this.Assert(null!==this.currentPropertyName);let t=this._propertyNameStack.pop();this.currentCollection[t]=e,this._collectionStack.push(e)}else this.state===t.Writer.State.Array?(this.Assert(null!==this.currentCollection),this.currentCollection.push(e),this._collectionStack.push(e)):(this.Assert(this.state===t.Writer.State.None),this._jsonObject=e,this._collectionStack.push(e));this._stateStack.push(new t.Writer.StateElement(t.Writer.State.Object))}WriteObjectEnd(){this.Assert(this.state===t.Writer.State.Object),this._collectionStack.pop(),this._stateStack.pop()}WriteProperty(t,e){if(this.WritePropertyStart(t),arguments[1]instanceof Function){(0,arguments[1])(this)}else{let t=arguments[1];this.Write(t)}this.WritePropertyEnd()}WriteIntProperty(t,e){this.WritePropertyStart(t),this.WriteInt(e),this.WritePropertyEnd()}WriteFloatProperty(t,e){this.WritePropertyStart(t),this.WriteFloat(e),this.WritePropertyEnd()}WritePropertyStart(e){this.Assert(this.state===t.Writer.State.Object),this._propertyNameStack.push(e),this.IncrementChildCount(),this._stateStack.push(new t.Writer.StateElement(t.Writer.State.Property))}WritePropertyEnd(){this.Assert(this.state===t.Writer.State.Property),this.Assert(1===this.childCount),this._stateStack.pop()}WritePropertyNameStart(){this.Assert(this.state===t.Writer.State.Object),this.IncrementChildCount(),this._currentPropertyName="",this._stateStack.push(new t.Writer.StateElement(t.Writer.State.Property)),this._stateStack.push(new t.Writer.StateElement(t.Writer.State.PropertyName))}WritePropertyNameEnd(){this.Assert(this.state===t.Writer.State.PropertyName),this.Assert(null!==this._currentPropertyName),this._propertyNameStack.push(this._currentPropertyName),this._currentPropertyName=null,this._stateStack.pop()}WritePropertyNameInner(e){this.Assert(this.state===t.Writer.State.PropertyName),this.Assert(null!==this._currentPropertyName),this._currentPropertyName+=e}WriteArrayStart(){this.StartNewObject(!0);let e=[];if(this.state===t.Writer.State.Property){this.Assert(null!==this.currentCollection),this.Assert(null!==this.currentPropertyName);let t=this._propertyNameStack.pop();this.currentCollection[t]=e,this._collectionStack.push(e)}else this.state===t.Writer.State.Array?(this.Assert(null!==this.currentCollection),this.currentCollection.push(e),this._collectionStack.push(e)):(this.Assert(this.state===t.Writer.State.None),this._jsonObject=e,this._collectionStack.push(e));this._stateStack.push(new t.Writer.StateElement(t.Writer.State.Array))}WriteArrayEnd(){this.Assert(this.state===t.Writer.State.Array),this._collectionStack.pop(),this._stateStack.pop()}Write(t){null!==t?(this.StartNewObject(!1),this._addToCurrentObject(t)):console.error("Warning: trying to write a null value")}WriteBool(t){null!==t&&(this.StartNewObject(!1),this._addToCurrentObject(t))}WriteInt(t){null!==t&&(this.StartNewObject(!1),this._addToCurrentObject(Math.floor(t)))}WriteFloat(t){null!==t&&(this.StartNewObject(!1),t==Number.POSITIVE_INFINITY?this._addToCurrentObject(34e37):t==Number.NEGATIVE_INFINITY?this._addToCurrentObject(-34e37):isNaN(t)?this._addToCurrentObject(0):this._addToCurrentObject(t))}WriteNull(){this.StartNewObject(!1),this._addToCurrentObject(null)}WriteStringStart(){this.StartNewObject(!1),this._currentString="",this._stateStack.push(new t.Writer.StateElement(t.Writer.State.String))}WriteStringEnd(){this.Assert(this.state==t.Writer.State.String),this._stateStack.pop(),this._addToCurrentObject(this._currentString),this._currentString=null}WriteStringInner(e){this.Assert(this.state===t.Writer.State.String),null!==e?this._currentString+=e:console.error("Warning: trying to write a null string")}toString(){return null===this._jsonObject?"":JSON.stringify(this._jsonObject)}StartNewObject(e){e?this.Assert(this.state===t.Writer.State.None||this.state===t.Writer.State.Property||this.state===t.Writer.State.Array):this.Assert(this.state===t.Writer.State.Property||this.state===t.Writer.State.Array),this.state===t.Writer.State.Property&&this.Assert(0===this.childCount),this.state!==t.Writer.State.Array&&this.state!==t.Writer.State.Property||this.IncrementChildCount()}get state(){return this._stateStack.length>0?this._stateStack[this._stateStack.length-1].type:t.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 t=this._stateStack.pop();t.childCount++,this._stateStack.push(t)}Assert(t){if(!t)throw Error("Assert failed while writing JSON")}_addToCurrentObject(e){this.Assert(null!==this.currentCollection),this.state===t.Writer.State.Array?(this.Assert(Array.isArray(this.currentCollection)),this.currentCollection.push(e)):this.state===t.Writer.State.Property&&(this.Assert(!Array.isArray(this.currentCollection)),this.Assert(null!==this.currentPropertyName),this.currentCollection[this.currentPropertyName]=e,this._propertyNameStack.pop())}}t.Writer=e,function(e){var n;(n=e.State||(e.State={}))[n.None=0]="None",n[n.Object=1]="Object",n[n.Array=2]="Array",n[n.Property=3]="Property",n[n.PropertyName=4]="PropertyName",n[n.String=5]="String";e.StateElement=class{constructor(e){this.type=t.Writer.State.None,this.childCount=0,this.type=e}}}(e=t.Writer||(t.Writer={}))}($||($={}));class X{constructor(){let t=arguments[0],e=arguments[1];if(this.name=t,this.callStack=new U(e),arguments[2]){let t=arguments[2];this.callStack.SetJsonToken(t.callstack,e),this.outputStream=q.JArrayToRuntimeObjList(t.outputStream),this.currentChoices=q.JArrayToRuntimeObjList(t.currentChoices);let n=t.choiceThreads;void 0!==n&&this.LoadFlowChoiceThreads(n,e)}else this.outputStream=[],this.currentChoices=[]}WriteJson(t){t.WriteObjectStart(),t.WriteProperty("callstack",(t=>this.callStack.WriteJson(t))),t.WriteProperty("outputStream",(t=>q.WriteListRuntimeObjs(t,this.outputStream)));let e=!1;for(let n of this.currentChoices){if(null===n.threadAtGeneration)return p("c.threadAtGeneration");n.originalThreadIndex=n.threadAtGeneration.threadIndex,null===this.callStack.ThreadWithIndex(n.originalThreadIndex)&&(e||(e=!0,t.WritePropertyStart("choiceThreads"),t.WriteObjectStart()),t.WritePropertyStart(n.originalThreadIndex),n.threadAtGeneration.WriteJson(t),t.WritePropertyEnd())}e&&(t.WriteObjectEnd(),t.WritePropertyEnd()),t.WriteProperty("currentChoices",(t=>{t.WriteArrayStart();for(let e of this.currentChoices)q.WriteChoice(t,e);t.WriteArrayEnd()})),t.WriteObjectEnd()}LoadFlowChoiceThreads(t,e){for(let n of this.currentChoices){let i=this.callStack.ThreadWithIndex(n.originalThreadIndex);if(null!==i)n.threadAtGeneration=i.Copy();else{let i=t[`${n.originalThreadIndex}`];n.threadAtGeneration=new U.Thread(i,e)}}}}class Y{ToJson(){let t=new $.Writer;return this.WriteJson(t),t.toString()}toJson(){let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return this.ToJson(t)}LoadJson(t){let e=$.TextToDictionary(t);this.LoadJsonObj(e),null!==this.onDidLoadState&&this.onDidLoadState()}VisitCountAtPathString(t){let n;if(null!==this._patch){let i=this.story.ContentAtPath(new e(t)).container;if(null===i)throw new Error("Content at path not found: "+t);if(n=this._patch.TryGetVisitCount(i,0),n.exists)return n.result}return n=v(this._visitCounts,t,null),n.exists?n.result:0}VisitCountForContainer(t){if(null===t)return p("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(null!==this._patch){let e=this._patch.TryGetVisitCount(t,0);if(e.exists)return e.result}let e=t.path.toString(),n=v(this._visitCounts,e,null);return n.exists?n.result:0}IncrementVisitCountForContainer(t){if(null!==this._patch){let e=this.VisitCountForContainer(t);return e++,void this._patch.SetVisitCount(t,e)}let e=t.path.toString(),n=v(this._visitCounts,e,null);n.exists?this._visitCounts.set(e,n.result+1):this._visitCounts.set(e,1)}RecordTurnIndexVisitToContainer(t){if(null!==this._patch)return void this._patch.SetTurnIndex(t,this.currentTurnIndex);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)."),null!==this._patch){let e=this._patch.TryGetTurnIndex(t,0);if(e.exists)return this.currentTurnIndex-e.result}let e=t.path.toString(),n=v(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:null===t.path?p("pointer.path"):t.path.toString()}get previousPathString(){let t=this.previousPointer;return t.isNull?null:null===t.path?p("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 null!=this.currentErrors&&this.currentErrors.length>0}get hasWarning(){return null!=this.currentWarnings&&this.currentWarnings.length>0}get currentText(){if(this._outputStreamTextDirty){let t=new f,e=!1;for(let n of this.outputStream){let i=s(n,E);if(e||null===i){let t=s(n,k);null!==t&&(t.commandType==k.CommandType.BeginTag?e=!0:t.commandType==k.CommandType.EndTag&&(e=!1))}else t.Append(i.value)}this._currentText=this.CleanOutputWhitespace(t.toString()),this._outputStreamTextDirty=!1}return this._currentText}CleanOutputWhitespace(t){let e=new f,n=-1,i=0;for(let r=0;r0&&n!=i&&e.Append(" "),n=-1),"\n"==a&&(i=r+1),s||e.Append(a)}return e.toString()}get currentTags(){if(this._outputStreamTagsDirty){this._currentTags=[];let t=!1,e=new f;for(let n of this.outputStream){let i=s(n,k);if(null!=i){if(i.commandType==k.CommandType.BeginTag){if(t&&e.Length>0){let t=this.CleanOutputWhitespace(e.toString());this._currentTags.push(t),e.Clear()}t=!0}else if(i.commandType==k.CommandType.EndTag){if(e.Length>0){let t=this.CleanOutputWhitespace(e.toString());this._currentTags.push(t),e.Clear()}t=!1}}else if(t){let t=s(n,E);null!==t&&e.Append(t.value)}else{let t=s(n,B);null!=t&&null!=t.text&&t.text.length>0&&this._currentTags.push(t.text)}}if(e.Length>0){let t=this.CleanOutputWhitespace(e.toString());this._currentTags.push(t),e.Clear()}this._outputStreamTagsDirty=!1}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=[],null!=this._namedFlows)for(let t of this._namedFlows.keys())t!=this.kDefaultFlowName&&this._aliveFlowNames.push(t);this._aliveFlowNamesDirty=!1}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=F.Null,this._currentTurnIndex=0,this.storySeed=0,this.previousRandom=0,this.didSafeExit=!1,this._currentText=null,this._currentTags=null,this._outputStreamTextDirty=!0,this._outputStreamTagsDirty=!0,this._patch=null,this._aliveFlowNames=null,this._namedFlows=null,this.kDefaultFlowName="DEFAULT_FLOW",this._aliveFlowNamesDirty=!0,this.story=t,this._currentFlow=new X(this.kDefaultFlowName,t),this.OutputStreamDirty(),this._aliveFlowNamesDirty=!0,this._evaluationStack=[],this._variablesState=new K(this.callStack,t.listDefinitions),this._visitCounts=new Map,this._turnIndices=new Map,this.currentTurnIndex=-1;let e=(new Date).getTime();this.storySeed=new z(e).next()%100,this.previousRandom=0,this.GoToStart()}GoToStart(){this.callStack.currentElement.currentPointer=F.StartOf(this.story.mainContentContainer)}SwitchFlow_Internal(t){if(null===t)throw new Error("Must pass a non-null string to Story.SwitchFlow");if(null===this._namedFlows&&(this._namedFlows=new Map,this._namedFlows.set(this.kDefaultFlowName,this._currentFlow)),t===this._currentFlow.name)return;let e,n=v(this._namedFlows,t,null);n.exists?e=n.result:(e=new X(t,this.story),this._namedFlows.set(t,e),this._aliveFlowNamesDirty=!0),this._currentFlow=e,this.variablesState.callStack=this._currentFlow.callStack,this.OutputStreamDirty()}SwitchToDefaultFlow_Internal(){null!==this._namedFlows&&this.SwitchFlow_Internal(this.kDefaultFlowName)}RemoveFlow_Internal(t){if(null===t)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(),null===this._namedFlows)return p("this._namedFlows");this._namedFlows.delete(t),this._aliveFlowNamesDirty=!0}CopyAndStartPatching(t){let e=new Y(this.story);if(e._patch=new H(this._patch),e._currentFlow.name=this._currentFlow.name,e._currentFlow.callStack=new U(this._currentFlow.callStack),e._currentFlow.outputStream.push(...this._currentFlow.outputStream),e.OutputStreamDirty(),t)for(let t of this._currentFlow.currentChoices)e._currentFlow.currentChoices.push(t.Clone());else e._currentFlow.currentChoices.push(...this._currentFlow.currentChoices);if(null!==this._namedFlows){e._namedFlows=new Map;for(let[t,n]of this._namedFlows)e._namedFlows.set(t,n),e._aliveFlowNamesDirty=!0;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(null!==this._patch){this.variablesState.ApplyPatch();for(let[t,e]of this._patch.visitCounts)this.ApplyCountChanges(t,e,!0);for(let[t,e]of this._patch.turnIndices)this.ApplyCountChanges(t,e,!1);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(),null!==this._namedFlows)for(let[e,n]of this._namedFlows)t.WriteProperty(e,(t=>n.WriteJson(t)));else t.WriteProperty(this._currentFlow.name,(t=>this._currentFlow.WriteJson(t)));if(t.WriteObjectEnd(),t.WritePropertyEnd(),t.WriteProperty("currentFlowName",this._currentFlow.name),t.WriteProperty("variablesState",(t=>this.variablesState.WriteJson(t))),t.WriteProperty("evalStack",(t=>q.WriteListRuntimeObjs(t,this.evaluationStack))),!this.divertedPointer.isNull){if(null===this.divertedPointer.path)return p("divertedPointer");t.WriteProperty("currentDivertTarget",this.divertedPointer.path.componentsString)}t.WriteProperty("visitCounts",(t=>q.WriteIntDictionary(t,this._visitCounts))),t.WriteProperty("turnIndices",(t=>q.WriteIntDictionary(t,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",Z.inkVersionCurrent),t.WriteObjectEnd()}LoadJsonObj(t){let n=t,i=n.inkSaveVersion;if(null==i)throw new Error("ink save format incorrect, can't load.");if(parseInt(i)1){let t=n.currentFlowName;this._currentFlow=this._namedFlows.get(t)}}else{this._namedFlows=null,this._currentFlow.name=this.kDefaultFlowName,this._currentFlow.callStack.SetJsonToken(n.callstackThreads,this.story),this._currentFlow.outputStream=q.JArrayToRuntimeObjList(n.outputStream),this._currentFlow.currentChoices=q.JArrayToRuntimeObjList(n.currentChoices);let t=n.choiceThreads;this._currentFlow.LoadFlowChoiceThreads(t,this.story)}this.OutputStreamDirty(),this._aliveFlowNamesDirty=!0,this.variablesState.SetJsonToken(n.variablesState),this.variablesState.callStack=this._currentFlow.callStack,this._evaluationStack=q.JArrayToRuntimeObjList(n.evalStack);let a=n.currentDivertTarget;if(null!=a){let t=new e(a.toString());this.divertedPointer=this.story.PointerAtPath(t)}this._visitCounts=q.JObjectToIntDictionary(n.visitCounts),this._turnIndices=q.JObjectToIntDictionary(n.turnIndices),this.currentTurnIndex=parseInt(n.turnIdx),this.storySeed=parseInt(n.storySeed),this.previousRandom=parseInt(n.previousRandom)}ResetErrors(){this._currentErrors=null,this._currentWarnings=null}ResetOutput(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;this.outputStream.length=0,null!==t&&this.outputStream.push(...t),this.OutputStreamDirty()}PushToOutputStream(t){let e=s(t,E);if(null!==e){let t=this.TrySplittingHeadTailWhitespace(e);if(null!==t){for(let e of t)this.PushToOutputStreamIndividual(e);return void this.OutputStreamDirty()}}this.PushToOutputStreamIndividual(t),this.OutputStreamDirty()}PopFromOutputStream(t){this.outputStream.splice(this.outputStream.length-t,t),this.OutputStreamDirty()}TrySplittingHeadTailWhitespace(t){let e=t.value;if(null===e)return p("single.value");let n=-1,i=-1;for(let t=0;t=0;t--){let n=e[t];if("\n"!=n){if(" "==n||"\t"==n)continue;break}-1==r&&(r=t),a=t}if(-1==n&&-1==r)return null;let s=[],l=0,o=e.length;if(-1!=n){if(n>0){let t=new E(e.substring(0,n));s.push(t)}s.push(new E("\n")),l=i+1}if(-1!=r&&(o=a),o>l){let t=e.substring(l,o);s.push(new E(t))}if(-1!=r&&a>i&&(s.push(new E("\n")),r=0;e--){let n=this.outputStream[e],i=n instanceof k?n:null;if(null!=(n instanceof I?n:null)){a=e;break}if(null!=i&&i.commandType==k.CommandType.BeginString){e>=t&&(t=-1);break}}let s=-1;if(s=-1!=a&&-1!=t?Math.min(t,a):-1!=a?a:t,-1!=s){if(n.isNewline)i=!1;else if(n.isNonWhitespace&&(a>-1&&this.RemoveExistingGlue(),t>-1)){let t=this.callStack.elements;for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.type!=r.Function)break;n.functionStartInOutputStream=-1}}}else n.isNewline&&(!this.outputStreamEndsInNewline&&this.outputStreamContainsContent||(i=!1))}if(i){if(null===t)return p("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=s(n,k),r=s(n,E);if(null!=i||null!=r&&r.isNonWhitespace)break;null!=r&&r.isNewline&&(t=e),e--}if(t>=0)for(e=t;e=0;t--){let e=this.outputStream[t];if(e instanceof I)this.outputStream.splice(t,1);else if(e instanceof k)break}this.OutputStreamDirty()}get outputStreamEndsInNewline(){if(this.outputStream.length>0)for(let t=this.outputStream.length-1;t>=0;t--){if(this.outputStream[t]instanceof k)break;let e=this.outputStream[t];if(e instanceof E){if(e.isNewline)return!0;if(e.isNonWhitespace)break}}return!1}get outputStreamContainsContent(){for(let t of this.outputStream)if(t instanceof E)return!0;return!1}get inStringEvaluation(){for(let t=this.outputStream.length-1;t>=0;t--){let e=s(this.outputStream[t],k);if(e instanceof k&&e.commandType==k.CommandType.BeginString)return!0}return!1}PushEvaluationStack(t){let e=s(t,O);if(e){let t=e.value;if(null===t)return p("rawList");if(null!=t.originNames){t.origins||(t.origins=[]),t.origins.length=0;for(let e of t.originNames){if(null===this.story.listDefinitions)return p("StoryState.story.listDefinitions");let n=this.story.listDefinitions.TryListGetDefinition(e,null);if(null===n.result)return p("StoryState def.result");t.origins.indexOf(n.result)<0&&t.origins.push(n.result)}}}if(null===t)return p("obj");this.evaluationStack.push(t)}PopEvaluationStack(t){if(void 0===t){return h(this.evaluationStack.pop())}if(t>this.evaluationStack.length)throw new Error("trying to pop too many objects");return h(this.evaluationStack.splice(this.evaluationStack.length-t,t))}PeekEvaluationStack(){return this.evaluationStack[this.evaluationStack.length-1]}ForceEnd(){this.callStack.Reset(),this._currentFlow.currentChoices.length=0,this.currentPointer=F.Null,this.previousPointer=F.Null,this.didSafeExit=!0}TrimWhitespaceFromFunctionEnd(){n.Assert(this.callStack.currentElement.type==r.Function);let t=this.callStack.currentElement.functionStartInOutputStream;-1==t&&(t=0);for(let e=this.outputStream.length-1;e>=t;e--){let t=this.outputStream[e],n=s(t,E),i=s(t,k);if(null!=n){if(i)break;if(!n.isNewline&&!n.isInlineWhitespace)break;this.outputStream.splice(e,1),this.OutputStreamDirty()}}}PopCallStack(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;this.callStack.currentElement.type==r.Function&&this.TrimWhitespaceFromFunctionEnd(),this.callStack.Pop(t)}SetChosenPath(t,e){this._currentFlow.currentChoices.length=0;let n=this.story.PointerAtPath(t);n.isNull||-1!=n.index||(n.index=0),this.currentPointer=n,e&&this.currentTurnIndex++}StartFunctionEvaluationFromGame(t,e){this.callStack.Push(r.FunctionEvaluationFromGame,this.evaluationStack.length),this.callStack.currentElement.currentPointer=F.StartOf(t),this.PassArgumentsToEvaluationStack(e)}PassArgumentsToEvaluationStack(t){if(null!==t)for(let e=0;et;){let t=this.PopEvaluationStack();null===e&&(e=t)}if(this.PopCallStack(r.FunctionEvaluationFromGame),e){if(e instanceof R)return null;let t=l(e,b);return t.valueType==i.DivertTarget?"-> "+t.valueObject.toString():t.valueObject}return null}AddError(t,e){e?(null==this._currentWarnings&&(this._currentWarnings=[]),this._currentWarnings.push(t)):(null==this._currentErrors&&(this._currentErrors=[]),this._currentErrors.push(t))}OutputStreamDirty(){this._outputStreamTextDirty=!0,this._outputStreamTagsDirty=!0}}class Q{constructor(){this.startTime=void 0}get ElapsedMilliseconds(){return void 0===this.startTime?0:(new Date).getTime()-this.startTime}Start(){this.startTime=(new Date).getTime()}Stop(){this.startTime=void 0}}!function(t){t[t.Author=0]="Author",t[t.Warning=1]="Warning",t[t.Error=2]="Error"}(a||(a={})),Number.isInteger||(Number.isInteger=function(t){return"number"==typeof t&&isFinite(t)&&t>-9007199254740992&&t<9007199254740992&&Math.floor(t)===t});class Z extends m{get currentChoices(){let t=[];if(null===this._state)return p("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(){let t;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=!1,this._listDefinitions=null,this._variableObservers=null,this._hasValidatedExternals=!1,this._temporaryEvaluationContainer=null,this._asyncContinueActive=!1,this._stateSnapshotAtLastNewline=null,this._sawLookaheadUnsafeFunctionAfterNewline=!1,this._recursiveContinueCount=0,this._asyncSaving=!1,this._profiler=null;let e=null,n=null;if(arguments[0]instanceof x)t=arguments[0],void 0!==arguments[1]&&(e=arguments[1]),this._mainContentContainer=t;else if("string"==typeof arguments[0]){let t=arguments[0];n=$.TextToDictionary(t)}else n=arguments[0];if(null!=e&&(this._listDefinitions=new J(e)),this._externals=new Map,null!==n){let t=n,e=t.inkVersion;if(null==e)throw new Error("ink version number not found. Are you sure it's a valid .ink.json file?");let i=parseInt(e);if(i>Z.inkVersionCurrent)throw new Error("Version of ink used to build story was newer than the current version of the engine");if(iq.WriteRuntimeContainer(t,this._mainContentContainer))),null!=this._listDefinitions){t.WritePropertyStart("listDefs"),t.WriteObjectStart();for(let e of this._listDefinitions.lists){t.WritePropertyStart(e.name),t.WriteObjectStart();for(let[n,i]of e.items){let e=g.fromSerializedKey(n),r=i;t.WriteIntProperty(e.itemName,r)}t.WriteObjectEnd(),t.WritePropertyEnd()}t.WriteObjectEnd(),t.WritePropertyEnd()}if(t.WriteObjectEnd(),e)return t.toString()}ResetState(){this.IfAsyncWeCant("ResetState"),this._state=new Y(this),this._state.variablesState.ObserveVariableChange(this.VariableStateDidChangeEvent.bind(this)),this.ResetGlobals()}ResetErrors(){if(null===this._state)return p("this._state");this._state.ResetErrors()}ResetCallstack(){if(this.IfAsyncWeCant("ResetCallstack"),null===this._state)return p("this._state");this._state.ForceEnd()}ResetGlobals(){if(this._mainContentContainer.namedContent.get("global decl")){let t=this.state.currentPointer.copy();this.ChoosePath(new e("global decl"),!1),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(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;null!=this._profiler&&this._profiler.PreContinue();let e=t>0;if(this._recursiveContinueCount++,this._asyncContinueActive)this._asyncContinueActive&&!e&&(this._asyncContinueActive=!1);else{if(this._asyncContinueActive=e,!this.canContinue)throw new Error("Can't continue - should check canContinue before calling Continue");this._state.didSafeExit=!1,this._state.ResetOutput(),1==this._recursiveContinueCount&&this._state.variablesState.StartVariableObservation()}let n=new Q;n.Start();let i=!1;this._sawLookaheadUnsafeFunctionAfterNewline=!1;do{try{i=this.ContinueSingleStep()}catch(t){if(!(t instanceof y))throw t;this.AddError(t.message,void 0,t.useEndLineNumber);break}if(i)break;if(this._asyncContinueActive&&n.ElapsedMilliseconds>t)break}while(this.canContinue);n.Stop();let s=null;if(!i&&this.canContinue||(null!==this._stateSnapshotAtLastNewline&&this.RestoreStateSnapshot(),this.canContinue||(this.state.callStack.canPopThread&&this.AddError("Thread available to pop, threads should always be flat by the end of evaluation?"),0!=this.state.generatedChoices.length||this.state.didSafeExit||null!=this._temporaryEvaluationContainer||(this.state.callStack.CanPop(r.Tunnel)?this.AddError("unexpectedly reached end of content. Do you need a '->->' to return from a tunnel?"):this.state.callStack.CanPop(r.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=!1,this._sawLookaheadUnsafeFunctionAfterNewline=!1,1==this._recursiveContinueCount&&(s=this._state.variablesState.CompleteVariableObservation()),this._asyncContinueActive=!1,null!==this.onDidContinue&&this.onDidContinue()),this._recursiveContinueCount--,null!=this._profiler&&this._profiler.PostContinue(),this.state.hasError||this.state.hasWarning){if(null===this.onError){let t=new f;throw t.Append("Ink had "),this.state.hasError&&(t.Append(`${this.state.currentErrors.length}`),t.Append(1==this.state.currentErrors.length?" error":" errors"),this.state.hasWarning&&t.Append(" and ")),this.state.hasWarning&&(t.Append(`${this.state.currentWarnings.length}`),t.Append(1==this.state.currentWarnings.length?" warning":" warnings"),this.state.hasWarning&&t.Append(" and ")),t.Append(". It is strongly suggested that you assign an error handler to story.onError. The first issue was: "),t.Append(this.state.hasError?this.state.currentErrors[0]:this.state.currentWarnings[0]),new y(t.toString())}if(this.state.hasError)for(let t of this.state.currentErrors)this.onError(t,a.Error);if(this.state.hasWarning)for(let t of this.state.currentWarnings)this.onError(t,a.Warning);this.ResetErrors()}null!=s&&Object.keys(s).length>0&&this._state.variablesState.NotifyObservers(s)}ContinueSingleStep(){if(null!=this._profiler&&this._profiler.PreStep(),this.Step(),null!=this._profiler&&this._profiler.PostStep(),this.canContinue||this.state.callStack.elementIsEvaluateFromGame||this.TryFollowDefaultInvisibleChoice(),null!=this._profiler&&this._profiler.PreSnapshot(),!this.state.inStringEvaluation){if(null!==this._stateSnapshotAtLastNewline){if(null===this._stateSnapshotAtLastNewline.currentTags)return p("this._stateAtLastNewline.currentTags");if(null===this.state.currentTags)return p("this.state.currentTags");let t=this.CalculateNewlineOutputStateChange(this._stateSnapshotAtLastNewline.currentText,this.state.currentText,this._stateSnapshotAtLastNewline.currentTags.length,this.state.currentTags.length);if(t==Z.OutputStateChange.ExtendedBeyondNewline||this._sawLookaheadUnsafeFunctionAfterNewline)return this.RestoreStateSnapshot(),!0;t==Z.OutputStateChange.NewlineRemoved&&this.DiscardSnapshot()}this.state.outputStreamEndsInNewline&&(this.canContinue?null==this._stateSnapshotAtLastNewline&&this.StateSnapshot():this.DiscardSnapshot())}return null!=this._profiler&&this._profiler.PostSnapshot(),!1}CalculateNewlineOutputStateChange(t,e,n,i){if(null===t)return p("prevText");if(null===e)return p("currText");let r=e.length>=t.length&&t.length>0&&"\n"==e.charAt(t.length-1);if(n==i&&t.length==e.length&&r)return Z.OutputStateChange.NoChange;if(!r)return Z.OutputStateChange.NewlineRemoved;if(i>n)return Z.OutputStateChange.ExtendedBeyondNewline;for(let n=t.length;n0?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(!1)}RestoreStateSnapshot(){null===this._stateSnapshotAtLastNewline&&p("_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(!0),this._asyncSaving=!0,t}BackgroundSaveComplete(){null===this._stateSnapshotAtLastNewline&&this._state.ApplyAnyPatch(),this._asyncSaving=!1}Step(){let t=!0,e=this.state.currentPointer.copy();if(e.isNull)return;let n=s(e.Resolve(),x);for(;n&&(this.VisitContainer(n,!0),0!=n.content.length);)e=F.StartOf(n),n=s(e.Resolve(),x);this.state.currentPointer=e.copy(),null!=this._profiler&&this._profiler.Step(this.state.callStack);let i=e.Resolve(),r=this.PerformLogicAndFlowControl(i);if(this.state.currentPointer.isNull)return;r&&(t=!1);let a=s(i,V);if(a){let e=this.ProcessChoice(a);e&&this.state.generatedChoices.push(e),i=null,t=!1}if(i instanceof x&&(t=!1),t){let t=s(i,N);if(t&&-1==t.contextIndex){let e=this.state.callStack.ContextForVariableNamed(t.variableName);i=new N(t.variableName,e)}this.state.inExpressionEvaluation?this.state.PushEvaluationStack(i):this.state.PushToOutputStream(i)}this.NextContent();let l=s(i,k);l&&l.commandType==k.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||-1==e.index)return;if(this._prevContainers.length=0,!t.isNull){let e=s(t.Resolve(),x)||s(t.container,x);for(;e;)this._prevContainers.push(e),e=s(e.parent,x)}let n=e.Resolve();if(null==n)return;let i=s(n.parent,x),r=!0;for(;i&&(this._prevContainers.indexOf(i)<0||i.countingAtStartOnly);){let t=i.content.length>0&&n==i.content[0]&&r;t||(r=!1),this.VisitContainer(i,t),n=i,i=s(i.parent,x)}}PopChoiceStringAndTags(t){let e=l(this.state.PopEvaluationStack(),E);for(;this.state.evaluationStack.length>0&&null!=s(this.state.PeekEvaluationStack(),B);){let e=s(this.state.PopEvaluationStack(),B);e&&t.push(e.text)}return e.value}ProcessChoice(t){let e=!0;if(t.hasCondition){let t=this.state.PopEvaluationStack();this.IsTruthy(t)||(e=!1)}let n="",i="",r=[];if(t.hasChoiceOnlyContent&&(i=this.PopChoiceStringAndTags(r)||""),t.hasStartContent&&(n=this.PopChoiceStringAndTags(r)||""),t.onceOnly){this.state.VisitCountForContainer(t.choiceTarget)>0&&(e=!1)}if(!e)return null;let a=new G;return a.targetPath=t.pathOnChoice,a.sourcePath=t.path.toString(),a.isInvisibleDefault=t.isInvisibleDefault,a.threadAtGeneration=this.state.callStack.ForkThread(),a.tags=r.reverse(),a.text=(n+i).replace(/^[ \t]+|[ \t]+$/g,""),a}IsTruthy(t){if(t instanceof b){let e=t;if(e instanceof P){let t=e;return this.Error("Shouldn't use a divert target (to "+t.targetPath+") as a conditional value. Did you intend a function call 'likeThis()' or a read count check 'likeThis'? (no arrows)"),!1}return e.isTruthy}return!1}PerformLogicAndFlowControl(t){if(null==t)return!1;if(t instanceof W){let e=t;if(e.isConditional){let t=this.state.PopEvaluationStack();if(!this.IsTruthy(t))return!0}if(e.hasVariableTarget){let t=e.variableDivertName,n=this.state.variablesState.GetVariableWithName(t);if(null==n)this.Error("Tried to divert using a target from a variable that could not be found ("+t+")");else if(!(n instanceof P)){let e=s(n,w),i="Tried to divert to a target from a variable, but the variable ("+t+") didn't contain a divert target, it ";e instanceof w&&0==e.value?i+="was empty/null (the value 0).":i+="contained '"+n+"'.",this.Error(i)}let i=l(n,P);this.state.divertedPointer=this.PointerAtPath(i.targetPath)}else{if(e.isExternal)return this.CallExternalFunction(e.targetPathString,e.externalArgs),!0;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&&null!=e.debugMetadata.sourceName?this.Error("Divert target doesn't exist: "+e.debugMetadata.sourceName):this.Error("Divert resolution failed: "+e)),!0}if(t instanceof k){let e=t;switch(e.commandType){case k.CommandType.EvalStart:this.Assert(!1===this.state.inExpressionEvaluation,"Already in expression evaluation?"),this.state.inExpressionEvaluation=!0;break;case k.CommandType.EvalEnd:this.Assert(!0===this.state.inExpressionEvaluation,"Not in expression evaluation mode"),this.state.inExpressionEvaluation=!1;break;case k.CommandType.EvalOutput:if(this.state.evaluationStack.length>0){let t=this.state.PopEvaluationStack();if(!(t instanceof R)){let e=new E(t.toString());this.state.PushToOutputStream(e)}}break;case k.CommandType.NoOp:break;case k.CommandType.Duplicate:this.state.PushEvaluationStack(this.state.PeekEvaluationStack());break;case k.CommandType.PopEvaluatedValue:this.state.PopEvaluationStack();break;case k.CommandType.PopFunction:case k.CommandType.PopTunnel:let t=e.commandType==k.CommandType.PopFunction?r.Function:r.Tunnel,n=null;if(t==r.Tunnel){let t=this.state.PopEvaluationStack();n=s(t,P),null===n&&this.Assert(t instanceof R,"Expected void if ->-> doesn't override target")}if(this.state.TryExitFunctionEvaluationFromGame())break;if(this.state.callStack.currentElement.type==t&&this.state.callStack.canPop)this.state.PopCallStack(),n&&(this.state.divertedPointer=this.PointerAtPath(n.targetPath));else{let e=new Map;e.set(r.Function,"function return statement (~ return)"),e.set(r.Tunnel,"tunnel onwards statement (->->)");let n=e.get(this.state.callStack.currentElement.type);this.state.callStack.canPop||(n="end of flow (-> END or choice)");let i="Found "+e.get(t)+", when expected "+n;this.Error(i)}break;case k.CommandType.BeginString:this.state.PushToOutputStream(e),this.Assert(!0===this.state.inExpressionEvaluation,"Expected to be in an expression when evaluating a string"),this.state.inExpressionEvaluation=!1;break;case k.CommandType.BeginTag:this.state.PushToOutputStream(e);break;case k.CommandType.EndTag:if(this.state.inStringEvaluation){let t=[],e=0;for(let n=this.state.outputStream.length-1;n>=0;--n){let i=this.state.outputStream[n];e++;let r=s(i,k);if(null!=r){if(r.commandType==k.CommandType.BeginTag)break;this.Error("Unexpected ControlCommand while extracting tag from choice");break}i instanceof E&&t.push(i)}this.state.PopFromOutputStream(e);let n=new f;for(let e of t.reverse())n.Append(e.toString());let i=new B(this.state.CleanOutputWhitespace(n.toString()));this.state.PushEvaluationStack(i)}else this.state.PushToOutputStream(e);break;case k.CommandType.EndString:{let t=[],e=[],n=0;for(let i=this.state.outputStream.length-1;i>=0;--i){let r=this.state.outputStream[i];n++;let a=s(r,k);if(a&&a.commandType==k.CommandType.BeginString)break;r instanceof B&&e.push(r),r instanceof E&&t.push(r)}this.state.PopFromOutputStream(n);for(let t of e)this.state.PushToOutputStream(t);t=t.reverse();let i=new f;for(let e of t)i.Append(e.toString());this.state.inExpressionEvaluation=!0,this.state.PushEvaluationStack(new E(i.toString()));break}case k.CommandType.ChoiceCount:let i=this.state.generatedChoices.length;this.state.PushEvaluationStack(new w(i));break;case k.CommandType.Turns:this.state.PushEvaluationStack(new w(this.state.currentTurnIndex+1));break;case k.CommandType.TurnsSince:case k.CommandType.ReadCount:let a=this.state.PopEvaluationStack();if(!(a instanceof P)){let t="";a instanceof w&&(t=". 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 "+a+t);break}let o,h=l(a,P),u=s(this.ContentAtPath(h.targetPath).correctObj,x);null!=u?o=e.commandType==k.CommandType.TurnsSince?this.state.TurnsSinceForContainer(u):this.state.VisitCountForContainer(u):(o=e.commandType==k.CommandType.TurnsSince?-1:0,this.Warning("Failed to find container for "+e.toString()+" lookup at "+h.targetPath.toString())),this.state.PushEvaluationStack(new w(o));break;case k.CommandType.Random:{let t=s(this.state.PopEvaluationStack(),w),e=s(this.state.PopEvaluationStack(),w);if(null==e||e instanceof w==!1)return this.Error("Invalid value for minimum parameter of RANDOM(min, max)");if(null==t||t instanceof w==!1)return this.Error("Invalid value for maximum parameter of RANDOM(min, max)");if(null===t.value)return p("maxInt.value");if(null===e.value)return p("minInt.value");let n=t.value-e.value+1;(!isFinite(n)||n>Number.MAX_SAFE_INTEGER)&&(n=Number.MAX_SAFE_INTEGER,this.Error("RANDOM was called with a range that exceeds the size that ink numbers can use.")),n<=0&&this.Error("RANDOM was called with minimum as "+e.value+" and maximum as "+t.value+". The maximum must be larger");let i=this.state.storySeed+this.state.previousRandom,r=new z(i).next(),a=r%n+e.value;this.state.PushEvaluationStack(new w(a)),this.state.previousRandom=r;break}case k.CommandType.SeedRandom:let c=s(this.state.PopEvaluationStack(),w);if(null==c||c instanceof w==!1)return this.Error("Invalid value passed to SEED_RANDOM");if(null===c.value)return p("minInt.value");this.state.storySeed=c.value,this.state.previousRandom=0,this.state.PushEvaluationStack(new R);break;case k.CommandType.VisitIndex:let d=this.state.VisitCountForContainer(this.state.currentPointer.container)-1;this.state.PushEvaluationStack(new w(d));break;case k.CommandType.SequenceShuffleIndex:let m=this.NextSequenceShuffleIndex();this.state.PushEvaluationStack(new w(m));break;case k.CommandType.StartThread:break;case k.CommandType.Done:this.state.callStack.canPopThread?this.state.callStack.PopThread():(this.state.didSafeExit=!0,this.state.currentPointer=F.Null);break;case k.CommandType.End:this.state.ForceEnd();break;case k.CommandType.ListFromInt:let v=s(this.state.PopEvaluationStack(),w),C=l(this.state.PopEvaluationStack(),E);if(null===v)throw new y("Passed non-integer when creating a list element from a numerical value.");let _=null;if(null===this.listDefinitions)return p("this.listDefinitions");let T=this.listDefinitions.TryListGetDefinition(C.value,null);if(!T.exists)throw new y("Failed to find LIST called "+C.value);{if(null===v.value)return p("minInt.value");let t=T.result.TryGetItemWithValue(v.value,g.Null);t.exists&&(_=new O(t.result,v.value))}null==_&&(_=new O),this.state.PushEvaluationStack(_);break;case k.CommandType.ListRange:let N=s(this.state.PopEvaluationStack(),b),A=s(this.state.PopEvaluationStack(),b),I=s(this.state.PopEvaluationStack(),O);if(null===I||null===A||null===N)throw new y("Expected list, minimum and maximum for LIST_RANGE");if(null===I.value)return p("targetList.value");let W=I.value.ListWithSubRange(A.valueObject,N.valueObject);this.state.PushEvaluationStack(new O(W));break;case k.CommandType.ListRandom:{let t=this.state.PopEvaluationStack();if(null===t)throw new y("Expected list for LIST_RANDOM");let e=t.value,n=null;if(null===e)throw p("list");if(0==e.Count)n=new S;else{let t=this.state.storySeed+this.state.previousRandom,i=new z(t).next(),r=i%e.Count,a=e.entries();for(let t=0;t<=r-1;t++)a.next();let s=a.next().value,l={Key:g.fromSerializedKey(s[0]),Value:s[1]};if(null===l.Key.originName)return p("randomItem.Key.originName");n=new S(l.Key.originName,this),n.Add(l.Key,l.Value),this.state.previousRandom=i}this.state.PushEvaluationStack(new O(n));break}default:this.Error("unhandled ControlCommand: "+e)}return!0}if(t instanceof D){let e=t,n=this.state.PopEvaluationStack();return this.state.variablesState.Assign(e,n),!0}if(t instanceof L){let e=t,n=null;if(null!=e.pathForCount){let t=e.containerForCount,i=this.state.VisitCountForContainer(t);n=new w(i)}else n=this.state.variablesState.GetVariableWithName(e.name),null==n&&(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 w(0));return this.state.PushEvaluationStack(n),!0}if(t instanceof j){let e=t,n=this.state.PopEvaluationStack(e.numberOfParameters),i=e.Call(n);return this.state.PushEvaluationStack(i),!0}return!1}ChoosePathString(t){let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];if(this.IfAsyncWeCant("call ChoosePathString right now"),null!==this.onChoosePathString&&this.onChoosePathString(t,i),n)this.ResetCallstack();else if(this.state.callStack.currentElement.type==r.Function){let e="",n=this.state.callStack.currentElement.currentPointer.container;throw null!=n&&(e="("+n.path.toString()+") "),new Error("Story was running a function "+e+"when you called ChoosePathString("+t+") - this is almost certainly not not what you want! Full stack trace: \n"+this.state.callStack.callStackTrace)}this.state.PassArgumentsToEvaluationStack(i),this.ChoosePath(new e(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){let e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];this.state.SetChosenPath(t,e),this.VisitChangedContainersDueToDivert()}ChooseChoiceIndex(t){let e=this.currentChoices;this.Assert(t>=0&&t1&&void 0!==arguments[1]?arguments[1]:[],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(null!==this.onEvaluateFunction&&this.onEvaluateFunction(t,e),this.IfAsyncWeCant("evaluate a function"),null==t)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(null==i)throw new Error("Function doesn't exist: '"+t+"'");let r=[];r.push(...this.state.outputStream),this._state.ResetOutput(),this.state.StartFunctionEvaluationFromGame(i,e);let a=new f;for(;this.canContinue;)a.Append(this.Continue());let s=a.toString();this._state.ResetOutput(r);let l=this.state.CompleteFunctionEvaluationFromGame();return null!=this.onCompleteEvaluateFunction&&this.onCompleteEvaluateFunction(t,e,s,l),n?{returned:l,output:s}:l}EvaluateExpression(t){let e=this.state.callStack.elements.length;this.state.callStack.Push(r.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(null===t)return p("funcName");let n=this._externals.get(t),i=null,a=void 0!==n;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&&null!==this._stateSnapshotAtLastNewline)return void(this._sawLookaheadUnsafeFunctionAfterNewline=!0);if(!a){if(this.allowExternalFunctionFallbacks)return i=this.KnotContainerWithName(t),this.Assert(null!==i,"Trying to call EXTERNAL function '"+t+"' which has not been bound, and fallback ink function could not be found."),this.state.callStack.Push(r.Function,void 0,this.state.outputStream.length),void(this.state.divertedPointer=F.StartOf(i));this.Assert(!1,"Trying to call EXTERNAL function '"+t+"' which has not been bound (and ink fallbacks disabled).")}let s=[];for(let t=0;t2&&void 0!==arguments[2])||arguments[2];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){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];this.Assert(null!=e,"Can't bind a null function"),this.BindExternalFunctionGeneral(t,(t=>{this.Assert(t.length>=e.length,"External function expected "+e.length+" arguments");let n=[];for(let e=0,i=t.length;e1?"s":"",t+=": '",t+=Array.from(n).join("', '"),t+="' ",t+=this.allowExternalFunctionFallbacks?", and no fallback ink function found.":" (ink fallbacks disabled)",this.Error(t)}else if(null!=t){for(let e of t.content){null!=e&&e.hasValidName||this.ValidateExternalBindings(e,n)}for(let[,e]of t.namedContent)this.ValidateExternalBindings(s(e,m),n)}else if(null!=e){let t=s(e,W);if(t&&t.isExternal){let e=t.targetPathString;if(null===e)return p("name");if(!this._externals.has(e))if(this.allowExternalFunctionFallbacks){this.mainContentContainer.namedContent.has(e)||n.add(e)}else n.add(e)}}}ObserveVariable(t,e){if(this.IfAsyncWeCant("observe a new variable"),null===this._variableObservers&&(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=e.container.content.length;){t=!1;let n=s(e.container.parent,x);if(n instanceof x==!1)break;let i=n.content.indexOf(e.container);if(-1==i)break;if(e=new F(n,i),e.index++,t=!0,null===e.container)return p("pointer.container")}return t||(e=F.Null),this.state.callStack.currentElement.currentPointer=e.copy(),t}TryFollowDefaultInvisibleChoice(){let t=this._state.currentChoices,e=t.filter((t=>t.isInvisibleDefault));if(0==e.length||t.length>e.length)return!1;let n=e[0];return null===n.targetPath?p("choice.targetPath"):null===n.threadAtGeneration?p("choice.threadAtGeneration"):(this.state.callStack.currentThread=n.threadAtGeneration,null!==this._stateSnapshotAtLastNewline&&(this.state.callStack.currentThread=this.state.callStack.ForkThread()),this.ChoosePath(n.targetPath,!1),!0)}NextSequenceShuffleIndex(){let t=s(this.state.PopEvaluationStack(),w);if(!(t instanceof w))return this.Error("expected number of elements in sequence for shuffle index"),0;let e=this.state.currentPointer.container;if(null===e)return p("seqContainer");if(null===t.value)return p("numElementsIntVal.value");let n=t.value,i=l(this.state.PopEvaluationStack(),w).value;if(null===i)return p("seqCount");let r=i/n,a=i%n,o=e.path.toString(),h=0;for(let t=0,e=o.length;t1&&void 0!==arguments[1]&&arguments[1],n=new y(t);throw n.useEndLineNumber=e,n}Warning(t){this.AddError(t,!0)}AddError(t){let e=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=this.currentDebugMetadata,r=e?"WARNING":"ERROR";if(null!=i){let e=n?i.endLineNumber:i.startLineNumber;t="RUNTIME "+r+": '"+i.fileName+"' line "+e+": "+t}else t=this.state.currentPointer.isNull?"RUNTIME "+r+": "+t:"RUNTIME "+r+": ("+this.state.currentPointer+"): "+t;this.state.AddError(t,e),e||this.state.ForceEnd()}Assert(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;if(0==t)throw null==e&&(e="Story assert"),new Error(e+" "+this.currentDebugMetadata)}get currentDebugMetadata(){let t,e=this.state.currentPointer;if(!e.isNull&&null!==e.Resolve()&&(t=e.Resolve().debugMetadata,null!==t))return t;for(let n=this.state.callStack.elements.length-1;n>=0;--n)if(e=this.state.callStack.elements[n].currentPointer,!e.isNull&&null!==e.Resolve()&&(t=e.Resolve().debugMetadata,null!==t))return t;for(let e=this.state.outputStream.length-1;e>=0;--e){if(t=this.state.outputStream[e].debugMetadata,null!==t)return t}return null}get mainContentContainer(){return this._temporaryEvaluationContainer?this._temporaryEvaluationContainer:this._mainContentContainer}}Z.inkVersionCurrent=21,function(t){var e;(e=t.OutputStateChange||(t.OutputStateChange={}))[e.NoChange=0]="NoChange",e[e.ExtendedBeyondNewline=1]="ExtendedBeyondNewline",e[e.NewlineRemoved=2]="NewlineRemoved"}(Z||(Z={})),t.InkList=S,t.Story=Z}));
+//# sourceMappingURL=ink.js.map
diff --git a/Aetheria/static/interactive/ink.js.map b/Aetheria/static/interactive/ink.js.map
new file mode 100644
index 0000000..2dbf8e1
--- /dev/null
+++ b/Aetheria/static/interactive/ink.js.map
@@ -0,0 +1 @@
+{"version":3,"file":"ink.js","sources":["../src/engine/Path.ts","../src/engine/Debug.ts","../src/engine/Value.ts","../src/engine/PushPop.ts","../src/engine/Error.ts","../src/engine/TypeAssertion.ts","../src/engine/NullException.ts","../src/engine/Object.ts","../src/engine/StringBuilder.ts","../src/engine/InkList.ts","../src/engine/StoryException.ts","../src/engine/TryGetResult.ts","../src/engine/SearchResult.ts","../src/engine/Container.ts","../src/engine/Glue.ts","../src/engine/ControlCommand.ts","../src/engine/Pointer.ts","../src/engine/Divert.ts","../src/engine/ChoicePoint.ts","../src/engine/VariableReference.ts","../src/engine/VariableAssignment.ts","../src/engine/Void.ts","../src/engine/NativeFunctionCall.ts","../src/engine/Tag.ts","../src/engine/Choice.ts","../src/engine/ListDefinition.ts","../src/engine/ListDefinitionsOrigin.ts","../src/engine/JsonSerialisation.ts","../src/engine/CallStack.ts","../src/engine/VariablesState.ts","../src/engine/PRNG.ts","../src/engine/StatePatch.ts","../src/engine/SimpleJson.ts","../src/engine/Flow.ts","../src/engine/StoryState.ts","../src/engine/StopWatch.ts","../src/engine/Story.ts"],"sourcesContent":["export class Path {\n public static parentId = \"^\";\n\n public _isRelative: boolean;\n public _components: Path.Component[];\n public _componentsString: string | null;\n\n constructor();\n constructor(componentsString: string);\n constructor(head: Path.Component, tail: Path);\n constructor(head: Path.Component[], relative?: boolean);\n constructor() {\n this._components = [];\n this._componentsString = null;\n this._isRelative = false;\n\n if (typeof arguments[0] == \"string\") {\n let componentsString = arguments[0] as string;\n this.componentsString = componentsString;\n } else if (\n arguments[0] instanceof Path.Component &&\n arguments[1] instanceof Path\n ) {\n let head = arguments[0] as Path.Component;\n let tail = arguments[1] as Path;\n this._components.push(head);\n this._components = this._components.concat(tail._components);\n } else if (arguments[0] instanceof Array) {\n let head = arguments[0] as Path.Component[];\n let relative = !!arguments[1] as boolean;\n this._components = this._components.concat(head);\n this._isRelative = relative;\n }\n }\n get isRelative() {\n return this._isRelative;\n }\n get componentCount(): number {\n return this._components.length;\n }\n get head(): Path.Component | null {\n if (this._components.length > 0) {\n return this._components[0];\n } else {\n return null;\n }\n }\n get tail(): Path {\n if (this._components.length >= 2) {\n // careful, the original code uses length-1 here. This is because the second argument of\n // List.GetRange is a number of elements to extract, wherease Array.slice uses an index\n let tailComps = this._components.slice(1, this._components.length);\n return new Path(tailComps);\n } else {\n return Path.self;\n }\n }\n get length(): number {\n return this._components.length;\n }\n get lastComponent(): Path.Component | null {\n let lastComponentIdx = this._components.length - 1;\n if (lastComponentIdx >= 0) {\n return this._components[lastComponentIdx];\n } else {\n return null;\n }\n }\n get containsNamedComponent(): boolean {\n for (let i = 0, l = this._components.length; i < l; i++) {\n if (!this._components[i].isIndex) {\n return true;\n }\n }\n return false;\n }\n static get self(): Path {\n let path = new Path();\n path._isRelative = true;\n return path;\n }\n\n public GetComponent(index: number): Path.Component {\n return this._components[index];\n }\n public PathByAppendingPath(pathToAppend: Path): Path {\n let p = new Path();\n\n let upwardMoves = 0;\n for (let i = 0; i < pathToAppend._components.length; ++i) {\n if (pathToAppend._components[i].isParent) {\n upwardMoves++;\n } else {\n break;\n }\n }\n\n for (let i = 0; i < this._components.length - upwardMoves; ++i) {\n p._components.push(this._components[i]);\n }\n\n for (let i = upwardMoves; i < pathToAppend._components.length; ++i) {\n p._components.push(pathToAppend._components[i]);\n }\n\n return p;\n }\n get componentsString(): string {\n if (this._componentsString == null) {\n this._componentsString = this._components.join(\".\");\n if (this.isRelative)\n this._componentsString = \".\" + this._componentsString;\n }\n\n return this._componentsString;\n }\n set componentsString(value: string) {\n this._components.length = 0;\n\n this._componentsString = value;\n\n if (this._componentsString == null || this._componentsString == \"\") return;\n\n if (this._componentsString[0] == \".\") {\n this._isRelative = true;\n this._componentsString = this._componentsString.substring(1);\n }\n\n let componentStrings = this._componentsString.split(\".\");\n for (let str of componentStrings) {\n // we need to distinguish between named components that start with a number, eg \"42somewhere\", and indexed components\n // the normal parseInt won't do for the detection because it's too relaxed.\n // see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt\n if (/^(\\-|\\+)?([0-9]+|Infinity)$/.test(str)) {\n this._components.push(new Path.Component(parseInt(str)));\n } else {\n this._components.push(new Path.Component(str));\n }\n }\n }\n public toString(): string {\n return this.componentsString;\n }\n public Equals(otherPath: Path | null): boolean {\n if (otherPath == null) return false;\n\n if (otherPath._components.length != this._components.length) return false;\n\n if (otherPath.isRelative != this.isRelative) return false;\n\n // the original code uses SequenceEqual here, so we need to iterate over the components manually.\n for (let i = 0, l = otherPath._components.length; i < l; i++) {\n // it's not quite clear whether this test should use Equals or a simple == operator,\n // see https://github.com/y-lohse/inkjs/issues/22\n if (!otherPath._components[i].Equals(this._components[i])) return false;\n }\n\n return true;\n }\n public PathByAppendingComponent(c: Path.Component): Path {\n let p = new Path();\n p._components.push(...this._components);\n p._components.push(c);\n return p;\n }\n}\n\nexport namespace Path {\n export class Component {\n public readonly index: number;\n public readonly name: string | null;\n\n constructor(indexOrName: string | number) {\n this.index = -1;\n this.name = null;\n if (typeof indexOrName == \"string\") {\n this.name = indexOrName;\n } else {\n this.index = indexOrName;\n }\n }\n get isIndex(): boolean {\n return this.index >= 0;\n }\n get isParent(): boolean {\n return this.name == Path.parentId;\n }\n\n public static ToParent(): Component {\n return new Component(Path.parentId);\n }\n public toString(): string | null {\n if (this.isIndex) {\n return this.index.toString();\n } else {\n return this.name;\n }\n }\n public Equals(otherComp: Component): boolean {\n if (otherComp != null && otherComp.isIndex == this.isIndex) {\n if (this.isIndex) {\n return this.index == otherComp.index;\n } else {\n return this.name == otherComp.name;\n }\n }\n\n return false;\n }\n }\n}\n","export namespace Debug {\n export function AssertType(\n variable: any,\n type: new () => T,\n message: string\n ): void | never {\n Assert(variable instanceof type, message);\n }\n\n export function Assert(condition: boolean, message?: string): void | never {\n if (!condition) {\n if (typeof message !== \"undefined\") {\n console.warn(message);\n }\n\n if (console.trace) {\n console.trace();\n }\n\n throw new Error(\"\");\n }\n }\n}\n","import { InkObject } from \"./Object\";\nimport { Path } from \"./Path\";\nimport { InkList, InkListItem } from \"./InkList\";\nimport { StoryException } from \"./StoryException\";\nimport { asOrNull, asOrThrows } from \"./TypeAssertion\";\nimport { tryParseInt, tryParseFloat } from \"./TryGetResult\";\nimport { throwNullException } from \"./NullException\";\n\nexport abstract class AbstractValue extends InkObject {\n public abstract get valueType(): ValueType;\n public abstract get isTruthy(): boolean;\n public abstract get valueObject(): any;\n\n public abstract Cast(newType: ValueType): Value;\n\n public static Create(\n val: any,\n preferredNumberType?: ValueType\n ): Value | null {\n // This code doesn't exist in upstream and is simply here to enforce\n // the creation of the proper number value.\n // If `preferredNumberType` is not provided or if value doesn't match\n // `preferredNumberType`, this conditional does nothing.\n if (preferredNumberType) {\n if (\n preferredNumberType === (ValueType.Int as ValueType) &&\n Number.isInteger(Number(val))\n ) {\n return new IntValue(Number(val));\n } else if (\n preferredNumberType === (ValueType.Float as ValueType) &&\n !isNaN(val)\n ) {\n return new FloatValue(Number(val));\n }\n }\n\n if (typeof val === \"boolean\") {\n return new BoolValue(Boolean(val));\n }\n\n // https://github.com/y-lohse/inkjs/issues/425\n // Changed condition sequence, because Number('') is\n // parsed to 0, which made setting string to empty\n // impossible\n if (typeof val === \"string\") {\n return new StringValue(String(val));\n } else if (Number.isInteger(Number(val))) {\n return new IntValue(Number(val));\n } else if (!isNaN(val)) {\n return new FloatValue(Number(val));\n } else if (val instanceof Path) {\n return new DivertTargetValue(asOrThrows(val, Path));\n } else if (val instanceof InkList) {\n return new ListValue(asOrThrows(val, InkList));\n }\n\n return null;\n }\n public Copy() {\n return asOrThrows(AbstractValue.Create(this.valueObject), InkObject);\n }\n public BadCastException(targetType: ValueType) {\n return new StoryException(\n \"Can't cast \" +\n this.valueObject +\n \" from \" +\n this.valueType +\n \" to \" +\n targetType\n );\n }\n}\n\nexport abstract class Value<\n T extends { toString: () => string },\n> extends AbstractValue {\n public value: T | null;\n\n constructor(val: T | null) {\n super();\n this.value = val;\n }\n public get valueObject() {\n return this.value;\n }\n public toString() {\n if (this.value === null) return throwNullException(\"Value.value\");\n return this.value.toString();\n }\n}\n\nexport class BoolValue extends Value {\n constructor(val: boolean) {\n super(val || false);\n }\n public get isTruthy() {\n return Boolean(this.value);\n }\n public get valueType() {\n return ValueType.Bool;\n }\n\n public Cast(newType: ValueType): Value {\n if (this.value === null) return throwNullException(\"Value.value\");\n\n if (newType == this.valueType) {\n return this;\n }\n\n if (newType == ValueType.Int) {\n return new IntValue(this.value ? 1 : 0);\n }\n\n if (newType == ValueType.Float) {\n return new FloatValue(this.value ? 1.0 : 0.0);\n }\n\n if (newType == ValueType.String) {\n return new StringValue(this.value ? \"true\" : \"false\");\n }\n\n throw this.BadCastException(newType);\n }\n\n public toString() {\n return this.value ? \"true\" : \"false\";\n }\n}\n\nexport class IntValue extends Value {\n constructor(val: number) {\n super(val || 0);\n }\n public get isTruthy() {\n return this.value != 0;\n }\n public get valueType() {\n return ValueType.Int;\n }\n\n public Cast(newType: ValueType): Value {\n if (this.value === null) return throwNullException(\"Value.value\");\n\n if (newType == this.valueType) {\n return this;\n }\n\n if (newType == ValueType.Bool) {\n return new BoolValue(this.value === 0 ? false : true);\n }\n\n if (newType == ValueType.Float) {\n return new FloatValue(this.value);\n }\n\n if (newType == ValueType.String) {\n return new StringValue(\"\" + this.value);\n }\n\n throw this.BadCastException(newType);\n }\n}\n\nexport class FloatValue extends Value {\n constructor(val: number) {\n super(val || 0.0);\n }\n public get isTruthy() {\n return this.value != 0.0;\n }\n public get valueType() {\n return ValueType.Float;\n }\n\n public Cast(newType: ValueType): Value {\n if (this.value === null) return throwNullException(\"Value.value\");\n\n if (newType == this.valueType) {\n return this;\n }\n\n if (newType == ValueType.Bool) {\n return new BoolValue(this.value === 0.0 ? false : true);\n }\n\n if (newType == ValueType.Int) {\n return new IntValue(this.value);\n }\n\n if (newType == ValueType.String) {\n return new StringValue(\"\" + this.value);\n }\n\n throw this.BadCastException(newType);\n }\n}\n\nexport class StringValue extends Value {\n public _isNewline: boolean;\n public _isInlineWhitespace: boolean;\n\n constructor(val: string) {\n super(val || \"\");\n\n this._isNewline = this.value == \"\\n\";\n this._isInlineWhitespace = true;\n\n if (this.value === null) return throwNullException(\"Value.value\");\n\n if (this.value.length > 0) {\n this.value.split(\"\").every((c) => {\n if (c != \" \" && c != \"\\t\") {\n this._isInlineWhitespace = false;\n return false;\n }\n\n return true;\n });\n }\n }\n public get valueType() {\n return ValueType.String;\n }\n public get isTruthy() {\n if (this.value === null) return throwNullException(\"Value.value\");\n return this.value.length > 0;\n }\n public get isNewline() {\n return this._isNewline;\n }\n public get isInlineWhitespace() {\n return this._isInlineWhitespace;\n }\n public get isNonWhitespace() {\n return !this.isNewline && !this.isInlineWhitespace;\n }\n\n public Cast(newType: ValueType): Value {\n if (newType == this.valueType) {\n return this;\n }\n\n if (newType == ValueType.Int) {\n let parsedInt = tryParseInt(this.value);\n if (parsedInt.exists) {\n return new IntValue(parsedInt.result);\n } else {\n throw this.BadCastException(newType);\n }\n }\n\n if (newType == ValueType.Float) {\n let parsedFloat = tryParseFloat(this.value);\n if (parsedFloat.exists) {\n return new FloatValue(parsedFloat.result);\n } else {\n throw this.BadCastException(newType);\n }\n }\n\n throw this.BadCastException(newType);\n }\n}\n\nexport class DivertTargetValue extends Value {\n constructor(targetPath: Path | null = null) {\n super(targetPath);\n }\n public get valueType() {\n return ValueType.DivertTarget;\n }\n public get targetPath() {\n if (this.value === null) return throwNullException(\"Value.value\");\n return this.value;\n }\n public set targetPath(value: Path) {\n this.value = value;\n }\n public get isTruthy(): never {\n throw new Error(\"Shouldn't be checking the truthiness of a divert target\");\n }\n\n public Cast(newType: ValueType): Value {\n if (newType == this.valueType) return this;\n\n throw this.BadCastException(newType);\n }\n public toString() {\n return \"DivertTargetValue(\" + this.targetPath + \")\";\n }\n}\n\nexport class VariablePointerValue extends Value {\n public _contextIndex: number;\n\n constructor(variableName: string, contextIndex: number = -1) {\n super(variableName);\n\n this._contextIndex = contextIndex;\n }\n\n public get contextIndex() {\n return this._contextIndex;\n }\n public set contextIndex(value: number) {\n this._contextIndex = value;\n }\n public get variableName() {\n if (this.value === null) return throwNullException(\"Value.value\");\n return this.value;\n }\n public set variableName(value: string) {\n this.value = value;\n }\n public get valueType() {\n return ValueType.VariablePointer;\n }\n\n public get isTruthy(): never {\n throw new Error(\n \"Shouldn't be checking the truthiness of a variable pointer\"\n );\n }\n\n public Cast(newType: ValueType): Value {\n if (newType == this.valueType) return this;\n\n throw this.BadCastException(newType);\n }\n public toString() {\n return \"VariablePointerValue(\" + this.variableName + \")\";\n }\n public Copy() {\n return new VariablePointerValue(this.variableName, this.contextIndex);\n }\n}\n\nexport class ListValue extends Value {\n public get isTruthy() {\n if (this.value === null) {\n return throwNullException(\"this.value\");\n }\n return this.value.Count > 0;\n }\n public get valueType() {\n return ValueType.List;\n }\n public Cast(newType: ValueType): Value {\n if (this.value === null) return throwNullException(\"Value.value\");\n\n if (newType == ValueType.Int) {\n let max = this.value.maxItem;\n if (max.Key.isNull) return new IntValue(0);\n else return new IntValue(max.Value);\n } else if (newType == ValueType.Float) {\n let max = this.value.maxItem;\n if (max.Key.isNull) return new FloatValue(0.0);\n else return new FloatValue(max.Value);\n } else if (newType == ValueType.String) {\n let max = this.value.maxItem;\n if (max.Key.isNull) return new StringValue(\"\");\n else {\n return new StringValue(max.Key.toString());\n }\n }\n\n if (newType == this.valueType) return this;\n\n throw this.BadCastException(newType);\n }\n constructor();\n constructor(list: InkList);\n constructor(listOrSingleItem: InkListItem, singleValue: number);\n constructor(listOrSingleItem?: InkListItem | InkList, singleValue?: number) {\n super(null);\n\n if (!listOrSingleItem && !singleValue) {\n this.value = new InkList();\n } else if (listOrSingleItem instanceof InkList) {\n this.value = new InkList(listOrSingleItem);\n } else if (\n listOrSingleItem instanceof InkListItem &&\n typeof singleValue === \"number\"\n ) {\n this.value = new InkList({\n Key: listOrSingleItem,\n Value: singleValue,\n });\n }\n }\n public static RetainListOriginsForAssignment(\n oldValue: InkObject | null,\n newValue: InkObject\n ) {\n let oldList = asOrNull(oldValue, ListValue);\n let newList = asOrNull(newValue, ListValue);\n\n if (newList && newList.value === null)\n return throwNullException(\"newList.value\");\n if (oldList && oldList.value === null)\n return throwNullException(\"oldList.value\");\n\n // When assigning the empty list, try to retain any initial origin names\n if (oldList && newList && newList.value!.Count == 0)\n newList.value!.SetInitialOriginNames(oldList.value!.originNames);\n }\n}\n\nexport enum ValueType {\n Bool = -1,\n Int = 0,\n Float = 1,\n List = 2,\n String = 3,\n DivertTarget = 4,\n VariablePointer = 5,\n}\n","export enum PushPopType {\n Tunnel = 0,\n Function = 1,\n FunctionEvaluationFromGame = 2,\n}\n","// TODO: Unify with Compiler.\n\nexport type ErrorHandler = (message: string, type: ErrorType) => void;\n\nexport enum ErrorType {\n Author,\n Warning,\n Error,\n}\n","import { INamedContent } from \"./INamedContent\";\n\nexport function asOrNull(\n obj: any,\n type: (new (...arg: any[]) => T) | (Function & { prototype: T })\n): T | null {\n if (obj instanceof type) {\n return unsafeTypeAssertion(obj, type);\n } else {\n return null;\n }\n}\n\nexport function asOrThrows(\n obj: any,\n type: (new (...arg: any[]) => T) | (Function & { prototype: T })\n): T | never {\n if (obj instanceof type) {\n return unsafeTypeAssertion(obj, type);\n } else {\n throw new Error(`${obj} is not of type ${type}`);\n }\n}\n\nexport function asNumberOrThrows(obj: any) {\n if (typeof obj === \"number\") {\n return obj as number;\n } else {\n throw new Error(`${obj} is not a number`);\n }\n}\n\nexport function asBooleanOrThrows(obj: any) {\n if (typeof obj === \"boolean\") {\n return obj as boolean;\n } else {\n throw new Error(`${obj} is not a boolean`);\n }\n}\n\n// So here, in the reference implementation, contentObj is casted to an INamedContent\n// but here we use js-style duck typing: if it implements the same props as the interface,\n// we treat it as valid.\nexport function asINamedContentOrNull(obj: any): INamedContent | null {\n if (obj.hasValidName && obj.name) {\n return obj as INamedContent;\n }\n\n return null;\n}\n\nexport function nullIfUndefined(obj: T | undefined): T | null {\n if (typeof obj === \"undefined\") {\n return null;\n }\n\n return obj;\n}\n\nexport function isEquatable(type: any) {\n return typeof type === \"object\" && typeof type.Equals === \"function\";\n}\n\nfunction unsafeTypeAssertion(\n obj: any,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n type: (new () => T) | (Function & { prototype: T })\n) {\n return obj as T;\n}\n\nexport function filterUndef(element: T | undefined): element is T {\n return element != undefined;\n}\n","/**\n * In the original C# code, a SystemException would be thrown when passing\n * null to methods expected a valid instance. Javascript has no such\n * concept, but TypeScript will not allow `null` to be passed to methods\n * explicitely requiring a valid type.\n *\n * Whenever TypeScript complain about the possibility of a `null` value,\n * check the offending value and it it's null, throw this exception using\n * `throwNullException(name: string)`.\n */\nexport class NullException extends Error {}\n\n/**\n * Throw a NullException.\n *\n * @param name a short description of the offending value (often its name within the code).\n */\nexport function throwNullException(name: string): never {\n throw new NullException(`${name} is null or undefined`);\n}\n","import { Path } from \"./Path\";\nimport { Container } from \"./Container\";\nimport { Debug } from \"./Debug\";\nimport { asOrNull, asINamedContentOrNull } from \"./TypeAssertion\";\nimport { throwNullException } from \"./NullException\";\nimport { SearchResult } from \"./SearchResult\";\nimport { DebugMetadata } from \"./DebugMetadata\";\n\nexport class InkObject {\n public parent: InkObject | null = null;\n\n get debugMetadata(): DebugMetadata | null {\n if (this._debugMetadata === null) {\n if (this.parent) {\n return this.parent.debugMetadata;\n }\n }\n\n return this._debugMetadata;\n }\n\n set debugMetadata(value) {\n this._debugMetadata = value;\n }\n\n get ownDebugMetadata() {\n return this._debugMetadata;\n }\n\n private _debugMetadata: DebugMetadata | null = null;\n\n public DebugLineNumberOfPath(path: Path) {\n if (path === null) return null;\n\n // Try to get a line number from debug metadata\n let root = this.rootContentContainer;\n if (root) {\n let targetContent = root.ContentAtPath(path).obj;\n if (targetContent) {\n let dm = targetContent.debugMetadata;\n if (dm !== null) {\n return dm.startLineNumber;\n }\n }\n }\n\n return null;\n }\n\n get path() {\n if (this._path == null) {\n if (this.parent == null) {\n this._path = new Path();\n } else {\n let comps: Path.Component[] = [];\n\n let child: InkObject = this;\n let container = asOrNull(child.parent, Container);\n\n while (container !== null) {\n let namedChild = asINamedContentOrNull(child);\n if (namedChild != null && namedChild.hasValidName) {\n if (namedChild.name === null)\n return throwNullException(\"namedChild.name\");\n comps.unshift(new Path.Component(namedChild.name!));\n } else {\n comps.unshift(new Path.Component(container.content.indexOf(child)));\n }\n\n child = container;\n container = asOrNull(container.parent, Container);\n }\n\n this._path = new Path(comps);\n }\n }\n\n return this._path;\n }\n private _path: Path | null = null;\n\n public ResolvePath(path: Path | null): SearchResult {\n if (path === null) return throwNullException(\"path\");\n if (path.isRelative) {\n let nearestContainer = asOrNull(this, Container);\n\n if (nearestContainer === null) {\n Debug.Assert(\n this.parent !== null,\n \"Can't resolve relative path because we don't have a parent\"\n );\n nearestContainer = asOrNull(this.parent, Container);\n Debug.Assert(\n nearestContainer !== null,\n \"Expected parent to be a container\"\n );\n Debug.Assert(path.GetComponent(0).isParent);\n path = path.tail;\n }\n\n if (nearestContainer === null) {\n return throwNullException(\"nearestContainer\");\n }\n return nearestContainer.ContentAtPath(path);\n } else {\n let contentContainer = this.rootContentContainer;\n if (contentContainer === null) {\n return throwNullException(\"contentContainer\");\n }\n return contentContainer.ContentAtPath(path);\n }\n }\n\n public ConvertPathToRelative(globalPath: Path) {\n let ownPath = this.path;\n\n let minPathLength = Math.min(globalPath.length, ownPath.length);\n let lastSharedPathCompIndex = -1;\n\n for (let i = 0; i < minPathLength; ++i) {\n let ownComp = ownPath.GetComponent(i);\n let otherComp = globalPath.GetComponent(i);\n\n if (ownComp.Equals(otherComp)) {\n lastSharedPathCompIndex = i;\n } else {\n break;\n }\n }\n\n // No shared path components, so just use global path\n if (lastSharedPathCompIndex == -1) return globalPath;\n\n let numUpwardsMoves = ownPath.componentCount - 1 - lastSharedPathCompIndex;\n\n let newPathComps: Path.Component[] = [];\n\n for (let up = 0; up < numUpwardsMoves; ++up)\n newPathComps.push(Path.Component.ToParent());\n\n for (\n let down = lastSharedPathCompIndex + 1;\n down < globalPath.componentCount;\n ++down\n )\n newPathComps.push(globalPath.GetComponent(down));\n\n let relativePath = new Path(newPathComps, true);\n return relativePath;\n }\n\n public CompactPathString(otherPath: Path) {\n let globalPathStr = null;\n let relativePathStr = null;\n\n if (otherPath.isRelative) {\n relativePathStr = otherPath.componentsString;\n globalPathStr = this.path.PathByAppendingPath(otherPath).componentsString;\n } else {\n let relativePath = this.ConvertPathToRelative(otherPath);\n relativePathStr = relativePath.componentsString;\n globalPathStr = otherPath.componentsString;\n }\n\n if (relativePathStr.length < globalPathStr.length) return relativePathStr;\n else return globalPathStr;\n }\n\n get rootContentContainer() {\n let ancestor: InkObject = this;\n while (ancestor.parent) {\n ancestor = ancestor.parent;\n }\n return asOrNull(ancestor, Container);\n }\n\n public Copy(): InkObject {\n throw Error(\"Not Implemented: Doesn't support copying\");\n }\n // SetChild works slightly diferently in the js implementation.\n // Since we can't pass an objets property by reference, we instead pass\n // the object and the property string.\n // TODO: This method can probably be rewritten with type-safety in mind.\n public SetChild(obj: any, prop: any, value: any) {\n if (obj[prop]) obj[prop] = null;\n\n obj[prop] = value;\n\n if (obj[prop]) obj[prop].parent = this;\n }\n\n public Equals(obj: any) {\n return obj === this;\n }\n}\n","export class StringBuilder {\n private string: string;\n\n constructor(str?: string) {\n str = typeof str !== \"undefined\" ? str.toString() : \"\";\n this.string = str;\n }\n get Length(): number {\n return this.string.length;\n }\n public Append(str: string | null) {\n if (str !== null) {\n this.string += str;\n }\n }\n public AppendLine(str?: string) {\n if (typeof str !== \"undefined\") this.Append(str);\n this.string += \"\\n\";\n }\n public AppendFormat(format: string, ...args: any[]) {\n // taken from http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format\n this.string += format.replace(/{(\\d+)}/g, (match: string, num: number) =>\n typeof args[num] != \"undefined\" ? args[num] : match\n );\n }\n public toString(): string {\n return this.string;\n }\n\n public Clear() {\n this.string = \"\";\n }\n}\n","import { throwNullException } from \"./NullException\";\nimport { StringBuilder } from \"./StringBuilder\";\nimport { ListDefinition } from \"./ListDefinition\";\nimport { Story } from \"./Story\";\n\nexport class InkListItem implements IInkListItem {\n // InkListItem is a struct\n\n public readonly originName: string | null = null;\n public readonly itemName: string | null = null;\n\n constructor(originName: string | null, itemName: string | null);\n constructor(fullName: string | null);\n constructor() {\n if (typeof arguments[1] !== \"undefined\") {\n let originName = arguments[0] as string | null;\n let itemName = arguments[1] as string | null;\n\n this.originName = originName;\n this.itemName = itemName;\n } else if (arguments[0]) {\n let fullName = arguments[0] as string;\n\n let nameParts = fullName.toString().split(\".\");\n this.originName = nameParts[0];\n this.itemName = nameParts[1];\n }\n }\n public static get Null() {\n return new InkListItem(null, null);\n }\n public get isNull() {\n return this.originName == null && this.itemName == null;\n }\n get fullName() {\n return (\n (this.originName !== null ? this.originName : \"?\") + \".\" + this.itemName\n );\n }\n public toString(): string {\n return this.fullName;\n }\n public Equals(obj: InkListItem) {\n if (obj instanceof InkListItem) {\n let otherItem = obj;\n return (\n otherItem.itemName == this.itemName &&\n otherItem.originName == this.originName\n );\n }\n\n return false;\n }\n\n // These methods did not exist in the original C# code. Their purpose is to\n // make `InkListItem` mimics the value-type semantics of the original\n // struct. Please refer to the end of this file, for a more in-depth\n // explanation.\n\n /**\n * Returns a shallow clone of the current instance.\n */\n public copy() {\n return new InkListItem(this.originName, this.itemName);\n }\n /**\n * Returns a `SerializedInkListItem` representing the current\n * instance. The result is intended to be used as a key inside a Map.\n */\n public serialized(): SerializedInkListItem {\n // We are simply using a JSON representation as a value-typed key.\n return JSON.stringify({\n originName: this.originName,\n itemName: this.itemName,\n });\n }\n\n /**\n * Reconstructs a `InkListItem` from the given SerializedInkListItem.\n */\n public static fromSerializedKey(key: SerializedInkListItem): InkListItem {\n let obj = JSON.parse(key);\n if (!InkListItem.isLikeInkListItem(obj)) return InkListItem.Null;\n\n let inkListItem = obj as IInkListItem;\n\n return new InkListItem(inkListItem.originName, inkListItem.itemName);\n }\n\n /**\n * Determines whether the given item is sufficiently `InkListItem`-like\n * to be used as a template when reconstructing the InkListItem.\n */\n private static isLikeInkListItem(item: any) {\n if (typeof item !== \"object\") return false;\n if (!item.hasOwnProperty(\"originName\") || !item.hasOwnProperty(\"itemName\"))\n return false;\n if (typeof item.originName !== \"string\" && typeof item.originName !== null)\n return false;\n if (typeof item.itemName !== \"string\" && typeof item.itemName !== null)\n return false;\n\n return true;\n }\n}\n\nexport class InkList extends Map {\n public origins: ListDefinition[] | null = null;\n public _originNames: string[] | null = [];\n\n constructor();\n constructor(otherList: InkList);\n constructor(singleOriginListName: string, originStory: Story);\n constructor(singleElement: KeyValuePair);\n constructor() {\n // Trying to be smart here, this emulates the constructor inheritance found\n // in the original code, but only if otherList is an InkList. IIFE FTW.\n super(\n (() => {\n if (arguments[0] instanceof InkList) {\n return arguments[0];\n } else {\n return [];\n }\n })()\n );\n\n if (arguments[0] instanceof InkList) {\n let otherList = arguments[0] as InkList;\n\n let otherOriginNames = otherList.originNames as string[];\n if (otherOriginNames !== null)\n this._originNames = otherOriginNames.slice();\n if (otherList.origins !== null) {\n this.origins = otherList.origins.slice();\n }\n } else if (typeof arguments[0] === \"string\") {\n let singleOriginListName = arguments[0] as string;\n let originStory = arguments[1] as Story;\n this.SetInitialOriginName(singleOriginListName);\n\n if (originStory.listDefinitions === null) {\n return throwNullException(\"originStory.listDefinitions\");\n }\n let def = originStory.listDefinitions.TryListGetDefinition(\n singleOriginListName,\n null\n );\n if (def.exists) {\n // Throwing now, because if the value is `null` it will\n // eventually throw down the line.\n if (def.result === null) {\n return throwNullException(\"def.result\");\n }\n this.origins = [def.result];\n } else {\n throw new Error(\n \"InkList origin could not be found in story when constructing new list: \" +\n singleOriginListName\n );\n }\n } else if (\n typeof arguments[0] === \"object\" &&\n arguments[0].hasOwnProperty(\"Key\") &&\n arguments[0].hasOwnProperty(\"Value\")\n ) {\n let singleElement = arguments[0] as KeyValuePair;\n this.Add(singleElement.Key, singleElement.Value);\n }\n }\n\n public static FromString(myListItem: string, originStory: Story) {\n if (myListItem == null || myListItem == \"\") return new InkList();\n let listValue =\n originStory.listDefinitions?.FindSingleItemListWithName(myListItem);\n if (listValue) {\n if (listValue.value === null) {\n return throwNullException(\"listValue.value\");\n }\n return new InkList(listValue.value);\n } else {\n throw new Error(\n \"Could not find the InkListItem from the string '\" +\n myListItem +\n \"' to create an InkList because it doesn't exist in the original list definition in ink.\"\n );\n }\n }\n\n public AddItem(\n itemOrItemName: InkListItem | string | null,\n storyObject: Story | null = null\n ) {\n if (itemOrItemName instanceof InkListItem) {\n let item = itemOrItemName;\n\n if (item.originName == null) {\n this.AddItem(item.itemName);\n return;\n }\n\n if (this.origins === null) return throwNullException(\"this.origins\");\n\n for (let origin of this.origins) {\n if (origin.name == item.originName) {\n let intVal = origin.TryGetValueForItem(item, 0);\n if (intVal.exists) {\n this.Add(item, intVal.result);\n return;\n } else {\n throw new Error(\n \"Could not add the item \" +\n item +\n \" to this list because it doesn't exist in the original list definition in ink.\"\n );\n }\n }\n }\n\n throw new Error(\n \"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.\"\n );\n } else if (itemOrItemName !== null) {\n //itemOrItemName is a string\n let itemName = itemOrItemName as string;\n\n let foundListDef: ListDefinition | null = null;\n\n if (this.origins === null) return throwNullException(\"this.origins\");\n\n for (let origin of this.origins) {\n if (itemName === null) return throwNullException(\"itemName\");\n\n if (origin.ContainsItemWithName(itemName)) {\n if (foundListDef != null) {\n throw new Error(\n \"Could not add the item \" +\n itemName +\n \" to this list because it could come from either \" +\n origin.name +\n \" or \" +\n foundListDef.name\n );\n } else {\n foundListDef = origin;\n }\n }\n }\n\n if (foundListDef == null) {\n if (storyObject == null) {\n throw new Error(\n \"Could not add the item \" +\n itemName +\n \" to this list because it isn't known to any list definitions previously associated with this list.\"\n );\n } else {\n let newItem = InkList.FromString(itemName, storyObject)\n .orderedItems[0];\n this.Add(newItem.Key, newItem.Value);\n }\n } else {\n let item = new InkListItem(foundListDef.name, itemName);\n let itemVal = foundListDef.ValueForItem(item);\n this.Add(item, itemVal);\n }\n }\n }\n public ContainsItemNamed(itemName: string | null) {\n for (let [key] of this) {\n let item = InkListItem.fromSerializedKey(key);\n if (item.itemName == itemName) return true;\n }\n\n return false;\n }\n public ContainsKey(key: InkListItem) {\n return this.has(key.serialized());\n }\n public Add(key: InkListItem, value: number) {\n let serializedKey = key.serialized();\n if (this.has(serializedKey)) {\n // Throw an exception to match the C# behavior.\n throw new Error(`The Map already contains an entry for ${key}`);\n }\n this.set(serializedKey, value);\n }\n public Remove(key: InkListItem) {\n return this.delete(key.serialized());\n }\n get Count() {\n return this.size;\n }\n get originOfMaxItem(): ListDefinition | null {\n if (this.origins == null) return null;\n\n let maxOriginName = this.maxItem.Key.originName;\n let result = null;\n this.origins.every((origin) => {\n if (origin.name == maxOriginName) {\n result = origin;\n return false;\n } else return true;\n });\n\n return result;\n }\n get originNames(): string[] {\n if (this.Count > 0) {\n if (this._originNames == null && this.Count > 0) this._originNames = [];\n else {\n if (!this._originNames) this._originNames = [];\n this._originNames.length = 0;\n }\n\n for (let [key] of this) {\n let item = InkListItem.fromSerializedKey(key);\n if (item.originName === null)\n return throwNullException(\"item.originName\");\n this._originNames.push(item.originName);\n }\n }\n\n return this._originNames as string[];\n }\n public SetInitialOriginName(initialOriginName: string) {\n this._originNames = [initialOriginName];\n }\n public SetInitialOriginNames(initialOriginNames: string[]) {\n if (initialOriginNames == null) this._originNames = null;\n else this._originNames = initialOriginNames.slice(); // store a copy\n }\n get maxItem() {\n let max: KeyValuePair = {\n Key: InkListItem.Null,\n Value: 0,\n };\n for (let [key, value] of this) {\n let item = InkListItem.fromSerializedKey(key);\n if (max.Key.isNull || value > max.Value)\n max = { Key: item, Value: value };\n }\n\n return max;\n }\n get minItem() {\n let min: KeyValuePair = {\n Key: InkListItem.Null,\n Value: 0,\n };\n for (let [key, value] of this) {\n let item = InkListItem.fromSerializedKey(key);\n if (min.Key.isNull || value < min.Value) {\n min = { Key: item, Value: value };\n }\n }\n return min;\n }\n get inverse() {\n let list = new InkList();\n if (this.origins != null) {\n for (let origin of this.origins) {\n for (let [key, value] of origin.items) {\n let item = InkListItem.fromSerializedKey(key);\n if (!this.ContainsKey(item)) list.Add(item, value);\n }\n }\n }\n return list;\n }\n get all() {\n let list = new InkList();\n if (this.origins != null) {\n for (let origin of this.origins) {\n for (let [key, value] of origin.items) {\n let item = InkListItem.fromSerializedKey(key);\n list.set(item.serialized(), value);\n }\n }\n }\n return list;\n }\n public Union(otherList: InkList) {\n let union = new InkList(this);\n for (let [key, value] of otherList) {\n union.set(key, value);\n }\n return union;\n }\n public Intersect(otherList: InkList) {\n let intersection = new InkList();\n for (let [key, value] of this) {\n if (otherList.has(key)) intersection.set(key, value);\n }\n\n return intersection;\n }\n public HasIntersection(otherList: InkList): boolean {\n for (let [key] of this) {\n if (otherList.has(key)) return true;\n }\n return false;\n }\n public Without(listToRemove: InkList) {\n let result = new InkList(this);\n for (let [key] of listToRemove) {\n result.delete(key);\n }\n\n return result;\n }\n\n public Contains(key: string): boolean;\n public Contains(otherList: InkList): boolean;\n public Contains(what: string | InkList): boolean {\n if (typeof what == \"string\") return this.ContainsItemNamed(what);\n const otherList = what;\n if (otherList.size == 0 || this.size == 0) return false;\n for (let [key] of otherList) {\n if (!this.has(key)) return false;\n }\n\n return true;\n }\n public GreaterThan(otherList: InkList) {\n if (this.Count == 0) return false;\n if (otherList.Count == 0) return true;\n\n return this.minItem.Value > otherList.maxItem.Value;\n }\n public GreaterThanOrEquals(otherList: InkList) {\n if (this.Count == 0) return false;\n if (otherList.Count == 0) return true;\n\n return (\n this.minItem.Value >= otherList.minItem.Value &&\n this.maxItem.Value >= otherList.maxItem.Value\n );\n }\n public LessThan(otherList: InkList) {\n if (otherList.Count == 0) return false;\n if (this.Count == 0) return true;\n\n return this.maxItem.Value < otherList.minItem.Value;\n }\n public LessThanOrEquals(otherList: InkList) {\n if (otherList.Count == 0) return false;\n if (this.Count == 0) return true;\n\n return (\n this.maxItem.Value <= otherList.maxItem.Value &&\n this.minItem.Value <= otherList.minItem.Value\n );\n }\n public MaxAsList() {\n if (this.Count > 0) return new InkList(this.maxItem);\n else return new InkList();\n }\n public MinAsList() {\n if (this.Count > 0) return new InkList(this.minItem);\n else return new InkList();\n }\n public ListWithSubRange(minBound: any, maxBound: any) {\n if (this.Count == 0) return new InkList();\n\n let ordered = this.orderedItems;\n\n let minValue = 0;\n let maxValue = Number.MAX_SAFE_INTEGER;\n\n if (Number.isInteger(minBound)) {\n minValue = minBound;\n } else {\n if (minBound instanceof InkList && minBound.Count > 0)\n minValue = minBound.minItem.Value;\n }\n\n if (Number.isInteger(maxBound)) {\n maxValue = maxBound;\n } else {\n if (maxBound instanceof InkList && maxBound.Count > 0)\n maxValue = maxBound.maxItem.Value;\n }\n\n let subList = new InkList();\n subList.SetInitialOriginNames(this.originNames);\n for (let item of ordered) {\n if (item.Value >= minValue && item.Value <= maxValue) {\n subList.Add(item.Key, item.Value);\n }\n }\n\n return subList;\n }\n public Equals(otherInkList: InkList) {\n if (otherInkList instanceof InkList === false) return false;\n if (otherInkList.Count != this.Count) return false;\n\n for (let [key] of this) {\n if (!otherInkList.has(key)) return false;\n }\n\n return true;\n }\n // GetHashCode not implemented\n get orderedItems() {\n // List>\n let ordered = new Array>();\n\n for (let [key, value] of this) {\n let item = InkListItem.fromSerializedKey(key);\n ordered.push({ Key: item, Value: value });\n }\n\n ordered.sort((x, y) => {\n if (x.Key.originName === null) {\n return throwNullException(\"x.Key.originName\");\n }\n if (y.Key.originName === null) {\n return throwNullException(\"y.Key.originName\");\n }\n\n if (x.Value == y.Value) {\n return x.Key.originName.localeCompare(y.Key.originName);\n } else {\n // TODO: refactor this bit into a numberCompareTo method?\n if (x.Value < y.Value) return -1;\n return x.Value > y.Value ? 1 : 0;\n }\n });\n\n return ordered;\n }\n\n get singleItem(): InkListItem | null {\n for (let item of this.orderedItems) {\n return item.Key;\n }\n return null;\n }\n\n public toString() {\n let ordered = this.orderedItems;\n\n let sb = new StringBuilder();\n for (let i = 0; i < ordered.length; i++) {\n if (i > 0) sb.Append(\", \");\n\n let item = ordered[i].Key;\n if (item.itemName === null) return throwNullException(\"item.itemName\");\n sb.Append(item.itemName);\n }\n\n return sb.toString();\n }\n // casting a InkList to a Number, for somereason, actually gives a number.\n // This messes up the type detection when creating a Value from a InkList.\n // Returning NaN here prevents that.\n public valueOf() {\n return NaN;\n }\n}\n\n/**\n * In the original C# code, `InkListItem` was defined as value type, meaning\n * that two `InkListItem` would be considered equal as long as they held the\n * same values. This doesn't hold true in Javascript, as `InkListItem` is a\n * reference type (Javascript doesn't allow the creation of custom value types).\n *\n * The key equality of Map objects is based on the \"SameValueZero\" algorithm;\n * since `InkListItem` is a value type, two keys will only be considered\n * equal if they are, in fact, the same object. As we are trying to emulate\n * the original behavior as close as possible, this will lead to unforeseen\n * side effects.\n *\n * In order to have a key equality based on value semantics, we'll convert\n * `InkListItem` to a valid string representation and use this representation\n * as a key (strings are value types in Javascript). Rather than using the\n * type `string` directly, we'll alias it to `SerializedInkListItem` and use\n * this type as the key for our Map-based `InkList`.\n *\n * Reducing `InkListItem` to a JSON representation would not be bulletproof\n * in the general case, but for our needs it works well. The major downside of\n * this method is that we will have to to reconstruct the original `InkListItem`\n * every time we'll need to access its properties.\n */\nexport type SerializedInkListItem = string;\n\n/**\n * An interface inherited by `InkListItem`, defining exposed\n * properties. It's mainly used when deserializing a `InkListItem` from its\n * key (`SerializedInkListItem`)\n */\ninterface IInkListItem {\n readonly originName: string | null;\n readonly itemName: string | null;\n}\nexport interface KeyValuePair {\n Key: K;\n Value: V;\n}\n","export class StoryException extends Error {\n public useEndLineNumber: boolean;\n public message: string;\n public name: string;\n\n constructor(message: string) {\n super(message);\n this.useEndLineNumber = false;\n this.message = message;\n this.name = \"StoryException\";\n }\n}\n","/**\n * This interface normalize the `TryGet` behavior found in the original\n * C# project. Any `TryGet` method will return a object conforming to this\n * interface.\n *\n * The original function returns a boolean and has a second parameter called\n * item that is an `out`. Both are needed and we can't just return the item\n * because it'll always be truthy. Instead, we return an object containing\n * whether the result exists (`exists`) and the result itself (`result`).\n *\n * For instance a `TryGet` prototype would look like this:\n```\nTryGetItemWithValue(val: number, item: InkListItem): TryGetResult{\n```\n *\n * On the other hand, dealing with the result can be done in the following way:\n```\nvar item = item.TryGetItemWithValue(intVal, InkListItem.Null);\nif (item.exists) {\n\tconsole.log(item.result)\n}\n```\n *\n */\nexport interface TryGetResult {\n result: T;\n exists: boolean;\n}\n\nexport function tryGetValueFromMap(\n map: Map | null,\n key: K,\n /* out */ value: V\n): TryGetResult {\n if (map === null) {\n return { result: value, exists: false };\n }\n\n let val = map.get(key);\n\n if (typeof val === \"undefined\") {\n return { result: value, exists: false };\n } else {\n return { result: val, exists: true };\n }\n}\n\nexport function tryParseInt(\n value: any,\n /* out */ defaultValue: number = 0\n): TryGetResult {\n let val = parseInt(value);\n\n if (!Number.isNaN(val)) {\n return { result: val, exists: true };\n } else {\n return { result: defaultValue, exists: false };\n }\n}\n\nexport function tryParseFloat(\n value: any,\n /* out */ defaultValue: number = 0\n): TryGetResult {\n let val = parseFloat(value);\n\n if (!Number.isNaN(val)) {\n return { result: val, exists: true };\n } else {\n return { result: defaultValue, exists: false };\n }\n}\n","import { InkObject } from \"./Object\";\nimport { Container } from \"./Container\";\n\nexport class SearchResult {\n public obj: InkObject | null = null;\n public approximate: boolean = false;\n\n get correctObj() {\n return this.approximate ? null : this.obj;\n }\n\n get container() {\n return this.obj instanceof Container ? this.obj : null;\n }\n\n public copy() {\n let searchResult = new SearchResult();\n searchResult.obj = this.obj;\n searchResult.approximate = this.approximate;\n\n return searchResult;\n }\n}\n","import { StringValue } from \"./Value\";\nimport { throwNullException } from \"./NullException\";\nimport { StringBuilder } from \"./StringBuilder\";\nimport { INamedContent } from \"./INamedContent\";\nimport { InkObject } from \"./Object\";\nimport { SearchResult } from \"./SearchResult\";\nimport { Path } from \"./Path\";\nimport { Debug } from \"./Debug\";\nimport { tryGetValueFromMap } from \"./TryGetResult\";\nimport { asINamedContentOrNull, asOrNull, asOrThrows } from \"./TypeAssertion\";\n\nexport class Container extends InkObject implements INamedContent {\n public name: string | null = null;\n\n public _content: InkObject[] = [];\n public namedContent: Map = new Map();\n\n public visitsShouldBeCounted: boolean = false;\n public turnIndexShouldBeCounted: boolean = false;\n public countingAtStartOnly: boolean = false;\n\n public _pathToFirstLeafContent: Path | null = null;\n\n get hasValidName() {\n return this.name != null && this.name.length > 0;\n }\n get content() {\n return this._content;\n }\n set content(value: InkObject[]) {\n this.AddContent(value);\n }\n get namedOnlyContent() {\n let namedOnlyContentDict: Map | null = new Map();\n\n for (let [key, value] of this.namedContent) {\n let inkObject = asOrThrows(value, InkObject);\n namedOnlyContentDict.set(key, inkObject);\n }\n\n for (let c of this.content) {\n let named = asINamedContentOrNull(c);\n if (named != null && named.hasValidName) {\n namedOnlyContentDict.delete(named.name!);\n }\n }\n\n if (namedOnlyContentDict.size == 0) namedOnlyContentDict = null;\n\n return namedOnlyContentDict;\n }\n set namedOnlyContent(value: Map | null) {\n let existingNamedOnly = this.namedOnlyContent;\n if (existingNamedOnly != null) {\n for (let [key] of existingNamedOnly) {\n this.namedContent.delete(key);\n }\n }\n\n if (value == null) return;\n\n for (let [, val] of value) {\n let named = asINamedContentOrNull(val);\n if (named != null) this.AddToNamedContentOnly(named);\n }\n }\n get countFlags(): number {\n let flags: Container.CountFlags = 0;\n if (this.visitsShouldBeCounted) flags |= Container.CountFlags.Visits;\n if (this.turnIndexShouldBeCounted) flags |= Container.CountFlags.Turns;\n if (this.countingAtStartOnly) flags |= Container.CountFlags.CountStartOnly;\n\n if (flags == Container.CountFlags.CountStartOnly) {\n flags = 0;\n }\n\n return flags;\n }\n set countFlags(value: number) {\n let flag: Container.CountFlags = value;\n if ((flag & Container.CountFlags.Visits) > 0)\n this.visitsShouldBeCounted = true;\n if ((flag & Container.CountFlags.Turns) > 0)\n this.turnIndexShouldBeCounted = true;\n if ((flag & Container.CountFlags.CountStartOnly) > 0)\n this.countingAtStartOnly = true;\n }\n get pathToFirstLeafContent() {\n if (this._pathToFirstLeafContent == null)\n this._pathToFirstLeafContent = this.path.PathByAppendingPath(\n this.internalPathToFirstLeafContent\n );\n\n return this._pathToFirstLeafContent;\n }\n get internalPathToFirstLeafContent() {\n let components: Path.Component[] = [];\n let container: Container = this;\n while (container instanceof Container) {\n if (container.content.length > 0) {\n components.push(new Path.Component(0));\n container = container.content[0] as Container;\n }\n }\n return new Path(components);\n }\n\n public AddContent(contentObjOrList: InkObject | InkObject[]) {\n if (contentObjOrList instanceof Array) {\n let contentList = contentObjOrList as InkObject[];\n\n for (let c of contentList) {\n this.AddContent(c);\n }\n } else {\n let contentObj = contentObjOrList as InkObject;\n\n this._content.push(contentObj);\n\n if (contentObj.parent) {\n throw new Error(\"content is already in \" + contentObj.parent);\n }\n\n contentObj.parent = this;\n\n this.TryAddNamedContent(contentObj);\n }\n }\n public TryAddNamedContent(contentObj: InkObject) {\n let namedContentObj = asINamedContentOrNull(contentObj);\n if (namedContentObj != null && namedContentObj.hasValidName) {\n this.AddToNamedContentOnly(namedContentObj);\n }\n }\n public AddToNamedContentOnly(namedContentObj: INamedContent) {\n Debug.AssertType(\n namedContentObj,\n InkObject,\n \"Can only add Runtime.Objects to a Runtime.Container\"\n );\n let runtimeObj = asOrThrows(namedContentObj, InkObject);\n runtimeObj.parent = this;\n\n if (namedContentObj.name === null)\n return throwNullException(\"namedContentObj.name\");\n this.namedContent.set(namedContentObj.name!, namedContentObj);\n }\n public ContentAtPath(\n path: Path,\n partialPathStart: number = 0,\n partialPathLength: number = -1\n ) {\n if (partialPathLength == -1) partialPathLength = path.length;\n\n let result = new SearchResult();\n result.approximate = false;\n\n let currentContainer: Container | null = this;\n let currentObj: InkObject = this;\n\n for (let i = partialPathStart; i < partialPathLength; ++i) {\n let comp = path.GetComponent(i);\n if (currentContainer == null) {\n result.approximate = true;\n break;\n }\n\n let foundObj: InkObject | null =\n currentContainer.ContentWithPathComponent(comp);\n\n // Couldn't resolve entire path?\n if (foundObj == null) {\n result.approximate = true;\n break;\n }\n\n // Are we about to loop into another container?\n // Is the object a container as expected? It might\n // no longer be if the content has shuffled around, so what\n // was originally a container no longer is.\n const nextContainer: Container | null = asOrNull(foundObj, Container);\n if (i < partialPathLength - 1 && nextContainer == null) {\n result.approximate = true;\n break;\n }\n\n currentObj = foundObj;\n currentContainer = nextContainer;\n }\n\n result.obj = currentObj;\n\n return result;\n }\n public InsertContent(contentObj: InkObject, index: number) {\n this.content.splice(index, 0, contentObj);\n\n if (contentObj.parent) {\n throw new Error(\"content is already in \" + contentObj.parent);\n }\n\n contentObj.parent = this;\n\n this.TryAddNamedContent(contentObj);\n }\n public AddContentsOfContainer(otherContainer: Container) {\n this.content.push(...otherContainer.content);\n\n for (let obj of otherContainer.content) {\n obj.parent = this;\n this.TryAddNamedContent(obj);\n }\n }\n public ContentWithPathComponent(component: Path.Component): InkObject | null {\n if (component.isIndex) {\n if (component.index >= 0 && component.index < this.content.length) {\n return this.content[component.index];\n } else {\n return null;\n }\n } else if (component.isParent) {\n return this.parent;\n } else {\n if (component.name === null) {\n return throwNullException(\"component.name\");\n }\n let foundContent = tryGetValueFromMap(\n this.namedContent,\n component.name,\n null\n );\n if (foundContent.exists) {\n return asOrThrows(foundContent.result, InkObject);\n } else {\n return null;\n }\n }\n }\n public BuildStringOfHierarchy(): string;\n public BuildStringOfHierarchy(\n sb: StringBuilder,\n indentation: number,\n pointedObj: InkObject | null\n ): string;\n public BuildStringOfHierarchy() {\n let sb: StringBuilder;\n if (arguments.length == 0) {\n sb = new StringBuilder();\n this.BuildStringOfHierarchy(sb, 0, null);\n return sb.toString();\n }\n\n sb = arguments[0] as StringBuilder;\n let indentation = arguments[1] as number;\n let pointedObj = arguments[2] as InkObject | null;\n\n function appendIndentation() {\n const spacesPerIndent = 4; // Truly const in the original code\n for (let i = 0; i < spacesPerIndent * indentation; ++i) {\n sb.Append(\" \");\n }\n }\n\n appendIndentation();\n sb.Append(\"[\");\n\n if (this.hasValidName) {\n sb.AppendFormat(\" ({0})\", this.name);\n }\n\n if (this == pointedObj) {\n sb.Append(\" <---\");\n }\n\n sb.AppendLine();\n\n indentation++;\n\n for (let i = 0; i < this.content.length; ++i) {\n let obj = this.content[i];\n\n if (obj instanceof Container) {\n let container = obj as Container;\n\n container.BuildStringOfHierarchy(sb, indentation, pointedObj);\n } else {\n appendIndentation();\n if (obj instanceof StringValue) {\n sb.Append('\"');\n sb.Append(obj.toString().replace(\"\\n\", \"\\\\n\"));\n sb.Append('\"');\n } else {\n sb.Append(obj.toString());\n }\n }\n\n if (i != this.content.length - 1) {\n sb.Append(\",\");\n }\n\n if (!(obj instanceof Container) && obj == pointedObj) {\n sb.Append(\" <---\");\n }\n\n sb.AppendLine();\n }\n\n let onlyNamed: Map = new Map();\n\n for (let [key, value] of this.namedContent) {\n if (this.content.indexOf(asOrThrows(value, InkObject)) >= 0) {\n continue;\n } else {\n onlyNamed.set(key, value);\n }\n }\n\n if (onlyNamed.size > 0) {\n appendIndentation();\n sb.AppendLine(\"-- named: --\");\n\n for (let [, value] of onlyNamed) {\n Debug.AssertType(\n value,\n Container,\n \"Can only print out named Containers\"\n );\n let container = value as Container;\n container.BuildStringOfHierarchy(sb, indentation, pointedObj);\n sb.AppendLine();\n }\n }\n\n indentation--;\n\n appendIndentation();\n sb.Append(\"]\");\n }\n}\n\nexport namespace Container {\n export enum CountFlags {\n Start = 0,\n Visits = 1,\n Turns = 2,\n CountStartOnly = 4,\n }\n}\n","import { InkObject } from \"./Object\";\n\nexport class Glue extends InkObject {\n public toString() {\n return \"Glue\";\n }\n}\n","import { InkObject } from \"./Object\";\n\nexport class ControlCommand extends InkObject {\n private _commandType: ControlCommand.CommandType;\n\n get commandType(): ControlCommand.CommandType {\n return this._commandType;\n }\n\n constructor(\n commandType: ControlCommand.CommandType = ControlCommand.CommandType.NotSet\n ) {\n super();\n this._commandType = commandType;\n }\n\n public Copy() {\n return new ControlCommand(this.commandType);\n }\n public static EvalStart() {\n return new ControlCommand(ControlCommand.CommandType.EvalStart);\n }\n public static EvalOutput() {\n return new ControlCommand(ControlCommand.CommandType.EvalOutput);\n }\n public static EvalEnd() {\n return new ControlCommand(ControlCommand.CommandType.EvalEnd);\n }\n public static Duplicate() {\n return new ControlCommand(ControlCommand.CommandType.Duplicate);\n }\n public static PopEvaluatedValue() {\n return new ControlCommand(ControlCommand.CommandType.PopEvaluatedValue);\n }\n public static PopFunction() {\n return new ControlCommand(ControlCommand.CommandType.PopFunction);\n }\n public static PopTunnel() {\n return new ControlCommand(ControlCommand.CommandType.PopTunnel);\n }\n public static BeginString() {\n return new ControlCommand(ControlCommand.CommandType.BeginString);\n }\n public static EndString() {\n return new ControlCommand(ControlCommand.CommandType.EndString);\n }\n public static NoOp() {\n return new ControlCommand(ControlCommand.CommandType.NoOp);\n }\n public static ChoiceCount() {\n return new ControlCommand(ControlCommand.CommandType.ChoiceCount);\n }\n public static Turns() {\n return new ControlCommand(ControlCommand.CommandType.Turns);\n }\n public static TurnsSince() {\n return new ControlCommand(ControlCommand.CommandType.TurnsSince);\n }\n public static ReadCount() {\n return new ControlCommand(ControlCommand.CommandType.ReadCount);\n }\n public static Random() {\n return new ControlCommand(ControlCommand.CommandType.Random);\n }\n public static SeedRandom() {\n return new ControlCommand(ControlCommand.CommandType.SeedRandom);\n }\n public static VisitIndex() {\n return new ControlCommand(ControlCommand.CommandType.VisitIndex);\n }\n public static SequenceShuffleIndex() {\n return new ControlCommand(ControlCommand.CommandType.SequenceShuffleIndex);\n }\n public static StartThread() {\n return new ControlCommand(ControlCommand.CommandType.StartThread);\n }\n public static Done() {\n return new ControlCommand(ControlCommand.CommandType.Done);\n }\n public static End() {\n return new ControlCommand(ControlCommand.CommandType.End);\n }\n public static ListFromInt() {\n return new ControlCommand(ControlCommand.CommandType.ListFromInt);\n }\n public static ListRange() {\n return new ControlCommand(ControlCommand.CommandType.ListRange);\n }\n public static ListRandom() {\n return new ControlCommand(ControlCommand.CommandType.ListRandom);\n }\n public static BeginTag() {\n return new ControlCommand(ControlCommand.CommandType.BeginTag);\n }\n public static EndTag() {\n return new ControlCommand(ControlCommand.CommandType.EndTag);\n }\n public toString() {\n return \"ControlCommand \" + this.commandType.toString();\n }\n}\n\nexport namespace ControlCommand {\n export enum CommandType {\n NotSet = -1,\n EvalStart, // 0\n EvalOutput, // 1\n EvalEnd, // 2\n Duplicate, // 3\n PopEvaluatedValue, // 4\n PopFunction, // 5\n PopTunnel, // 6\n BeginString, // 7\n EndString, // 8\n NoOp, // 9\n ChoiceCount, // 10\n Turns, // 11\n TurnsSince, // 12\n ReadCount, // 13\n Random, // 14\n SeedRandom, // 15\n VisitIndex, // 16\n SequenceShuffleIndex, // 17\n StartThread, // 18\n Done, // 19\n End, // 20\n ListFromInt, // 21\n ListRange, // 22\n ListRandom, // 23\n BeginTag, // 24\n EndTag, // 25\n\n TOTAL_VALUES,\n }\n}\n","import { Path } from \"./Path\";\nimport { Container } from \"./Container\";\nimport { InkObject } from \"./Object\";\n\nexport class Pointer {\n public container: Container | null = null;\n public index: number = -1;\n\n constructor();\n constructor(container: Container | null, index: number);\n constructor() {\n if (arguments.length === 2) {\n this.container = arguments[0];\n this.index = arguments[1];\n }\n }\n\n public Resolve(): InkObject | null {\n if (this.index < 0) return this.container;\n if (this.container == null) return null;\n if (this.container.content.length == 0) return this.container;\n if (this.index >= this.container.content.length) return null;\n\n return this.container.content[this.index];\n }\n\n get isNull(): boolean {\n return this.container == null;\n }\n\n get path(): Path | null {\n if (this.isNull) return null;\n\n if (this.index >= 0)\n return this.container!.path.PathByAppendingComponent(\n new Path.Component(this.index)\n );\n else return this.container!.path;\n }\n\n public toString(): string {\n if (!this.container) return \"Ink Pointer (null)\";\n\n return (\n \"Ink Pointer -> \" +\n this.container.path.toString() +\n \" -- index \" +\n this.index\n );\n }\n\n // This method does not exist in the original C# code, but is here to maintain the\n // value semantics of Pointer.\n public copy(): Pointer {\n return new Pointer(this.container, this.index);\n }\n\n public static StartOf(container: Container | null): Pointer {\n return new Pointer(container, 0);\n }\n\n public static get Null(): Pointer {\n return new Pointer(null, -1);\n }\n}\n","import { Path } from \"./Path\";\nimport { PushPopType } from \"./PushPop\";\nimport { StringBuilder } from \"./StringBuilder\";\nimport { InkObject } from \"./Object\";\nimport { Pointer } from \"./Pointer\";\nimport { Container } from \"./Container\";\nimport { throwNullException } from \"./NullException\";\n\nexport class Divert extends InkObject {\n get targetPath() {\n if (this._targetPath != null && this._targetPath.isRelative) {\n let targetObj = this.targetPointer.Resolve();\n if (targetObj) {\n this._targetPath = targetObj.path;\n }\n }\n\n return this._targetPath;\n }\n set targetPath(value: Path | null) {\n this._targetPath = value;\n this._targetPointer = Pointer.Null;\n }\n\n public _targetPath: Path | null = null;\n\n get targetPointer() {\n if (this._targetPointer.isNull) {\n let targetObj = this.ResolvePath(this._targetPath).obj;\n\n if (this._targetPath === null)\n return throwNullException(\"this._targetPath\");\n if (this._targetPath.lastComponent === null)\n return throwNullException(\"this._targetPath.lastComponent\");\n\n if (this._targetPath.lastComponent.isIndex) {\n if (targetObj === null) return throwNullException(\"targetObj\");\n this._targetPointer.container =\n targetObj.parent instanceof Container ? targetObj.parent : null;\n this._targetPointer.index = this._targetPath.lastComponent.index;\n } else {\n this._targetPointer = Pointer.StartOf(\n targetObj instanceof Container ? targetObj : null\n );\n }\n }\n\n return this._targetPointer.copy();\n }\n\n public _targetPointer: Pointer = Pointer.Null;\n\n get targetPathString() {\n if (this.targetPath == null) return null;\n\n return this.CompactPathString(this.targetPath);\n }\n set targetPathString(value: string | null) {\n if (value == null) {\n this.targetPath = null;\n } else {\n this.targetPath = new Path(value);\n }\n }\n\n public variableDivertName: string | null = null;\n get hasVariableTarget() {\n return this.variableDivertName != null;\n }\n\n public pushesToStack: boolean = false;\n public stackPushType: PushPopType = 0;\n\n public isExternal: boolean = false;\n public externalArgs: number = 0;\n\n public isConditional: boolean = false;\n\n constructor(stackPushType?: PushPopType) {\n super();\n this.pushesToStack = false;\n\n if (typeof stackPushType !== \"undefined\") {\n this.pushesToStack = true;\n this.stackPushType = stackPushType;\n }\n }\n\n public Equals(obj: Divert | null) {\n let otherDivert = obj;\n if (otherDivert instanceof Divert) {\n if (this.hasVariableTarget == otherDivert.hasVariableTarget) {\n if (this.hasVariableTarget) {\n return this.variableDivertName == otherDivert.variableDivertName;\n } else {\n if (this.targetPath === null)\n return throwNullException(\"this.targetPath\");\n return this.targetPath.Equals(otherDivert.targetPath);\n }\n }\n }\n return false;\n }\n\n public toString() {\n if (this.hasVariableTarget) {\n return \"Divert(variable: \" + this.variableDivertName + \")\";\n } else if (this.targetPath == null) {\n return \"Divert(null)\";\n } else {\n let sb = new StringBuilder();\n\n let targetStr = this.targetPath.toString();\n // int? targetLineNum = DebugLineNumberOfPath (targetPath);\n let targetLineNum = null;\n if (targetLineNum != null) {\n targetStr = \"line \" + targetLineNum;\n }\n\n sb.Append(\"Divert\");\n\n if (this.isConditional) sb.Append(\"?\");\n\n if (this.pushesToStack) {\n if (this.stackPushType == PushPopType.Function) {\n sb.Append(\" function\");\n } else {\n sb.Append(\" tunnel\");\n }\n }\n\n sb.Append(\" -> \");\n sb.Append(this.targetPathString);\n\n sb.Append(\" (\");\n sb.Append(targetStr);\n sb.Append(\")\");\n\n return sb.toString();\n }\n }\n}\n","import { InkObject } from \"./Object\";\nimport { Path } from \"./Path\";\nimport { Container } from \"./Container\";\nimport { throwNullException } from \"./NullException\";\n\nexport class ChoicePoint extends InkObject {\n public _pathOnChoice: Path | null = null;\n public hasCondition: boolean = false;\n public hasStartContent: boolean = false;\n public hasChoiceOnlyContent: boolean = false;\n public isInvisibleDefault: boolean = false;\n public onceOnly: boolean = true;\n\n constructor(onceOnly: boolean = true) {\n super();\n this.onceOnly = onceOnly;\n }\n get pathOnChoice(): Path | null {\n if (this._pathOnChoice != null && this._pathOnChoice.isRelative) {\n let choiceTargetObj = this.choiceTarget;\n if (choiceTargetObj) {\n this._pathOnChoice = choiceTargetObj.path;\n }\n }\n return this._pathOnChoice;\n }\n set pathOnChoice(value: Path | null) {\n this._pathOnChoice = value;\n }\n get choiceTarget(): Container | null {\n if (this._pathOnChoice === null)\n return throwNullException(\"ChoicePoint._pathOnChoice\");\n return this.ResolvePath(this._pathOnChoice).container;\n }\n get pathStringOnChoice(): string {\n if (this.pathOnChoice === null)\n return throwNullException(\"ChoicePoint.pathOnChoice\");\n return this.CompactPathString(this.pathOnChoice);\n }\n set pathStringOnChoice(value: string) {\n this.pathOnChoice = new Path(value);\n }\n get flags(): number {\n let flags = 0;\n if (this.hasCondition) flags |= 1;\n if (this.hasStartContent) flags |= 2;\n if (this.hasChoiceOnlyContent) flags |= 4;\n if (this.isInvisibleDefault) flags |= 8;\n if (this.onceOnly) flags |= 16;\n return flags;\n }\n set flags(value: number) {\n this.hasCondition = (value & 1) > 0;\n this.hasStartContent = (value & 2) > 0;\n this.hasChoiceOnlyContent = (value & 4) > 0;\n this.isInvisibleDefault = (value & 8) > 0;\n this.onceOnly = (value & 16) > 0;\n }\n public toString(): string {\n if (this.pathOnChoice === null)\n return throwNullException(\"ChoicePoint.pathOnChoice\");\n // int? targetLineNum = DebugLineNumberOfPath (pathOnChoice);\n let targetLineNum = null;\n let targetString = this.pathOnChoice.toString();\n\n if (targetLineNum != null) {\n targetString = \" line \" + targetLineNum + \"(\" + targetString + \")\";\n }\n\n return \"Choice: -> \" + targetString;\n }\n}\n","import { InkObject } from \"./Object\";\nimport { Path } from \"./Path\";\n\nexport class VariableReference extends InkObject {\n public name: string | null;\n public pathForCount: Path | null = null;\n\n get containerForCount() {\n if (this.pathForCount === null) return null;\n return this.ResolvePath(this.pathForCount).container;\n }\n get pathStringForCount() {\n if (this.pathForCount === null) return null;\n\n return this.CompactPathString(this.pathForCount);\n }\n set pathStringForCount(value: string | null) {\n if (value === null) this.pathForCount = null;\n else this.pathForCount = new Path(value);\n }\n\n constructor(name: string | null = null) {\n super();\n this.name = name;\n }\n\n public toString() {\n if (this.name != null) {\n return \"var(\" + this.name + \")\";\n } else {\n let pathStr = this.pathStringForCount;\n return \"read_count(\" + pathStr + \")\";\n }\n }\n}\n","import { InkObject } from \"./Object\";\n\nexport class VariableAssignment extends InkObject {\n public readonly variableName: string | null;\n public readonly isNewDeclaration: boolean;\n public isGlobal: boolean;\n\n constructor(variableName: string | null, isNewDeclaration: boolean) {\n super();\n this.variableName = variableName || null;\n this.isNewDeclaration = !!isNewDeclaration;\n this.isGlobal = false;\n }\n\n public toString(): string {\n return \"VarAssign to \" + this.variableName;\n }\n}\n","import { InkObject } from \"./Object\";\n\nexport class Void extends InkObject {\n public toString() {\n return \"Void\";\n }\n}\n","import { Value, ValueType, IntValue, ListValue, BoolValue } from \"./Value\";\nimport { StoryException } from \"./StoryException\";\nimport { Void } from \"./Void\";\nimport { Path } from \"./Path\";\nimport { InkList, InkListItem } from \"./InkList\";\nimport { InkObject } from \"./Object\";\nimport { asOrNull, asOrThrows, asBooleanOrThrows } from \"./TypeAssertion\";\nimport { throwNullException } from \"./NullException\";\n\ntype BinaryOp = (left: T, right: T) => any;\ntype UnaryOp = (val: T) => any;\n\nexport class NativeFunctionCall extends InkObject {\n public static readonly Add: string = \"+\";\n public static readonly Subtract: string = \"-\";\n public static readonly Divide: string = \"/\";\n public static readonly Multiply: string = \"*\";\n public static readonly Mod: string = \"%\";\n public static readonly Negate: string = \"_\";\n public static readonly Equal: string = \"==\";\n public static readonly Greater: string = \">\";\n public static readonly Less: string = \"<\";\n public static readonly GreaterThanOrEquals: string = \">=\";\n public static readonly LessThanOrEquals: string = \"<=\";\n public static readonly NotEquals: string = \"!=\";\n public static readonly Not: string = \"!\";\n public static readonly And: string = \"&&\";\n public static readonly Or: string = \"||\";\n public static readonly Min: string = \"MIN\";\n public static readonly Max: string = \"MAX\";\n public static readonly Pow: string = \"POW\";\n public static readonly Floor: string = \"FLOOR\";\n public static readonly Ceiling: string = \"CEILING\";\n public static readonly Int: string = \"INT\";\n public static readonly Float: string = \"FLOAT\";\n public static readonly Has: string = \"?\";\n public static readonly Hasnt: string = \"!?\";\n public static readonly Intersect: string = \"^\";\n public static readonly ListMin: string = \"LIST_MIN\";\n public static readonly ListMax: string = \"LIST_MAX\";\n public static readonly All: string = \"LIST_ALL\";\n public static readonly Count: string = \"LIST_COUNT\";\n public static readonly ValueOfList: string = \"LIST_VALUE\";\n public static readonly Invert: string = \"LIST_INVERT\";\n\n public static CallWithName(functionName: string) {\n return new NativeFunctionCall(functionName);\n }\n\n public static CallExistsWithName(functionName: string) {\n this.GenerateNativeFunctionsIfNecessary();\n return this._nativeFunctions!.get(functionName);\n }\n\n get name() {\n if (this._name === null)\n return throwNullException(\"NativeFunctionCall._name\");\n return this._name;\n }\n set name(value: string) {\n this._name = value;\n if (!this._isPrototype) {\n if (NativeFunctionCall._nativeFunctions === null)\n throwNullException(\"NativeFunctionCall._nativeFunctions\");\n else\n this._prototype =\n NativeFunctionCall._nativeFunctions.get(this._name) || null;\n }\n }\n public _name: string | null = null;\n\n get numberOfParameters() {\n if (this._prototype) {\n return this._prototype.numberOfParameters;\n } else {\n return this._numberOfParameters;\n }\n }\n set numberOfParameters(value: number) {\n this._numberOfParameters = value;\n }\n public _numberOfParameters: number = 0;\n\n public Call(parameters: InkObject[]): InkObject | null {\n if (this._prototype) {\n return this._prototype.Call(parameters);\n }\n\n if (this.numberOfParameters != parameters.length) {\n throw new Error(\"Unexpected number of parameters\");\n }\n\n let hasList = false;\n for (let p of parameters) {\n if (p instanceof Void)\n throw new StoryException(\n \"Attempting to perform \" +\n this.name +\n ' on a void value. Did you forget to \"return\" a value from a function you called here?'\n );\n if (p instanceof ListValue) hasList = true;\n }\n\n if (parameters.length == 2 && hasList) {\n return this.CallBinaryListOperation(parameters);\n }\n\n let coercedParams = this.CoerceValuesToSingleType(parameters);\n let coercedType = coercedParams[0].valueType;\n\n if (coercedType == ValueType.Int) {\n return this.CallType(coercedParams);\n } else if (coercedType == ValueType.Float) {\n return this.CallType(coercedParams);\n } else if (coercedType == ValueType.String) {\n return this.CallType(coercedParams);\n } else if (coercedType == ValueType.DivertTarget) {\n return this.CallType(coercedParams);\n } else if (coercedType == ValueType.List) {\n return this.CallType(coercedParams);\n }\n\n return null;\n }\n\n public CallType string }>(\n parametersOfSingleType: Array>\n ) {\n let param1 = asOrThrows(parametersOfSingleType[0], Value);\n let valType = param1.valueType;\n\n let val1 = param1 as Value;\n\n let paramCount = parametersOfSingleType.length;\n\n if (paramCount == 2 || paramCount == 1) {\n if (this._operationFuncs === null)\n return throwNullException(\"NativeFunctionCall._operationFuncs\");\n let opForTypeObj = this._operationFuncs.get(valType);\n if (!opForTypeObj) {\n const key = ValueType[valType];\n throw new StoryException(\n \"Cannot perform operation \" + this.name + \" on \" + key\n );\n }\n\n if (paramCount == 2) {\n let param2 = asOrThrows(parametersOfSingleType[1], Value);\n\n let val2 = param2 as Value;\n\n let opForType = opForTypeObj as BinaryOp;\n\n if (val1.value === null || val2.value === null)\n return throwNullException(\"NativeFunctionCall.Call BinaryOp values\");\n let resultVal = opForType(val1.value, val2.value);\n\n return Value.Create(resultVal);\n } else {\n let opForType = opForTypeObj as UnaryOp;\n\n if (val1.value === null)\n return throwNullException(\"NativeFunctionCall.Call UnaryOp value\");\n let resultVal = opForType(val1.value);\n\n // This code is different from upstream. Since JavaScript treats\n // integers and floats as the same numbers, it's impossible\n // to force an number to be either an integer or a float.\n //\n // It can be useful to force a specific number type\n // (especially for divisions), so the result of INT() & FLOAT()\n // is coerced to the the proper value type.\n //\n // Note that we also force all other unary operation to\n // return the same value type, although this is only\n // meaningful for numbers. See `Value.Create`.\n if (this.name === NativeFunctionCall.Int) {\n return Value.Create(resultVal, ValueType.Int);\n } else if (this.name === NativeFunctionCall.Float) {\n return Value.Create(resultVal, ValueType.Float);\n } else {\n return Value.Create(resultVal, param1.valueType);\n }\n }\n } else {\n throw new Error(\n \"Unexpected number of parameters to NativeFunctionCall: \" +\n parametersOfSingleType.length\n );\n }\n }\n\n public CallBinaryListOperation(parameters: InkObject[]) {\n if (\n (this.name == \"+\" || this.name == \"-\") &&\n parameters[0] instanceof ListValue &&\n parameters[1] instanceof IntValue\n )\n return this.CallListIncrementOperation(parameters);\n\n let v1 = asOrThrows(parameters[0], Value);\n let v2 = asOrThrows(parameters[1], Value);\n\n if (\n (this.name == \"&&\" || this.name == \"||\") &&\n (v1.valueType != ValueType.List || v2.valueType != ValueType.List)\n ) {\n if (this._operationFuncs === null)\n return throwNullException(\"NativeFunctionCall._operationFuncs\");\n let op = this._operationFuncs.get(ValueType.Int) as BinaryOp;\n if (op === null)\n return throwNullException(\n \"NativeFunctionCall.CallBinaryListOperation op\"\n );\n let result = asBooleanOrThrows(\n op(v1.isTruthy ? 1 : 0, v2.isTruthy ? 1 : 0)\n );\n return new BoolValue(result);\n }\n\n if (v1.valueType == ValueType.List && v2.valueType == ValueType.List)\n return this.CallType([v1, v2]);\n\n throw new StoryException(\n \"Can not call use \" +\n this.name +\n \" operation on \" +\n ValueType[v1.valueType] +\n \" and \" +\n ValueType[v2.valueType]\n );\n }\n\n public CallListIncrementOperation(listIntParams: InkObject[]) {\n let listVal = asOrThrows(listIntParams[0], ListValue);\n let intVal = asOrThrows(listIntParams[1], IntValue);\n\n let resultInkList = new InkList();\n\n if (listVal.value === null)\n return throwNullException(\n \"NativeFunctionCall.CallListIncrementOperation listVal.value\"\n );\n for (let [listItemKey, listItemValue] of listVal.value) {\n let listItem = InkListItem.fromSerializedKey(listItemKey);\n\n if (this._operationFuncs === null)\n return throwNullException(\"NativeFunctionCall._operationFuncs\");\n let intOp = this._operationFuncs.get(ValueType.Int) as BinaryOp;\n\n if (intVal.value === null)\n return throwNullException(\n \"NativeFunctionCall.CallListIncrementOperation intVal.value\"\n );\n let targetInt = intOp(listItemValue, intVal.value);\n\n let itemOrigin = null;\n if (listVal.value.origins === null)\n return throwNullException(\n \"NativeFunctionCall.CallListIncrementOperation listVal.value.origins\"\n );\n for (let origin of listVal.value.origins) {\n if (origin.name == listItem.originName) {\n itemOrigin = origin;\n break;\n }\n }\n if (itemOrigin != null) {\n let incrementedItem = itemOrigin.TryGetItemWithValue(\n targetInt,\n InkListItem.Null\n );\n if (incrementedItem.exists)\n resultInkList.Add(incrementedItem.result, targetInt);\n }\n }\n\n return new ListValue(resultInkList);\n }\n\n public CoerceValuesToSingleType(parametersIn: InkObject[]) {\n let valType = ValueType.Int;\n\n let specialCaseList: null | ListValue = null;\n\n for (let obj of parametersIn) {\n let val = asOrThrows(obj, Value);\n if (val.valueType > valType) {\n valType = val.valueType;\n }\n\n if (val.valueType == ValueType.List) {\n specialCaseList = asOrNull(val, ListValue);\n }\n }\n\n let parametersOut = [];\n\n if (ValueType[valType] == ValueType[ValueType.List]) {\n for (let inkObjectVal of parametersIn) {\n let val = asOrThrows(inkObjectVal, Value);\n if (val.valueType == ValueType.List) {\n parametersOut.push(val);\n } else if (val.valueType == ValueType.Int) {\n let intVal = parseInt(val.valueObject);\n\n specialCaseList = asOrThrows(specialCaseList, ListValue);\n if (specialCaseList.value === null)\n return throwNullException(\n \"NativeFunctionCall.CoerceValuesToSingleType specialCaseList.value\"\n );\n let list = specialCaseList.value.originOfMaxItem;\n\n if (list === null)\n return throwNullException(\n \"NativeFunctionCall.CoerceValuesToSingleType list\"\n );\n let item = list.TryGetItemWithValue(intVal, InkListItem.Null);\n if (item.exists) {\n let castedValue = new ListValue(item.result, intVal);\n parametersOut.push(castedValue);\n } else\n throw new StoryException(\n \"Could not find List item with the value \" +\n intVal +\n \" in \" +\n list.name\n );\n } else {\n const key = ValueType[val.valueType];\n throw new StoryException(\n \"Cannot mix Lists and \" + key + \" values in this operation\"\n );\n }\n }\n } else {\n for (let inkObjectVal of parametersIn) {\n let val = asOrThrows(inkObjectVal, Value);\n let castedValue = val.Cast(valType);\n parametersOut.push(castedValue);\n }\n }\n\n return parametersOut;\n }\n\n constructor(name: string);\n constructor(name: string, numberOfParameters: number);\n constructor();\n constructor() {\n super();\n\n if (arguments.length === 0) {\n NativeFunctionCall.GenerateNativeFunctionsIfNecessary();\n } else if (arguments.length === 1) {\n let name = arguments[0];\n NativeFunctionCall.GenerateNativeFunctionsIfNecessary();\n this.name = name;\n } else if (arguments.length === 2) {\n let name = arguments[0];\n let numberOfParameters = arguments[1];\n\n this._isPrototype = true;\n this.name = name;\n this.numberOfParameters = numberOfParameters;\n }\n }\n\n public static Identity(t: T): any {\n return t;\n }\n\n public static GenerateNativeFunctionsIfNecessary() {\n if (this._nativeFunctions == null) {\n this._nativeFunctions = new Map();\n\n // Int operations\n this.AddIntBinaryOp(this.Add, (x, y) => x + y);\n this.AddIntBinaryOp(this.Subtract, (x, y) => x - y);\n this.AddIntBinaryOp(this.Multiply, (x, y) => x * y);\n this.AddIntBinaryOp(this.Divide, (x, y) => Math.floor(x / y));\n this.AddIntBinaryOp(this.Mod, (x, y) => x % y);\n this.AddIntUnaryOp(this.Negate, (x) => -x);\n\n this.AddIntBinaryOp(this.Equal, (x, y) => x == y);\n this.AddIntBinaryOp(this.Greater, (x, y) => x > y);\n this.AddIntBinaryOp(this.Less, (x, y) => x < y);\n this.AddIntBinaryOp(this.GreaterThanOrEquals, (x, y) => x >= y);\n this.AddIntBinaryOp(this.LessThanOrEquals, (x, y) => x <= y);\n this.AddIntBinaryOp(this.NotEquals, (x, y) => x != y);\n this.AddIntUnaryOp(this.Not, (x) => x == 0);\n\n this.AddIntBinaryOp(this.And, (x, y) => x != 0 && y != 0);\n this.AddIntBinaryOp(this.Or, (x, y) => x != 0 || y != 0);\n\n this.AddIntBinaryOp(this.Max, (x, y) => Math.max(x, y));\n this.AddIntBinaryOp(this.Min, (x, y) => Math.min(x, y));\n\n this.AddIntBinaryOp(this.Pow, (x, y) => Math.pow(x, y));\n this.AddIntUnaryOp(this.Floor, NativeFunctionCall.Identity);\n this.AddIntUnaryOp(this.Ceiling, NativeFunctionCall.Identity);\n this.AddIntUnaryOp(this.Int, NativeFunctionCall.Identity);\n this.AddIntUnaryOp(this.Float, (x) => x);\n\n // Float operations\n this.AddFloatBinaryOp(this.Add, (x, y) => x + y);\n this.AddFloatBinaryOp(this.Subtract, (x, y) => x - y);\n this.AddFloatBinaryOp(this.Multiply, (x, y) => x * y);\n this.AddFloatBinaryOp(this.Divide, (x, y) => x / y);\n this.AddFloatBinaryOp(this.Mod, (x, y) => x % y);\n this.AddFloatUnaryOp(this.Negate, (x) => -x);\n\n this.AddFloatBinaryOp(this.Equal, (x, y) => x == y);\n this.AddFloatBinaryOp(this.Greater, (x, y) => x > y);\n this.AddFloatBinaryOp(this.Less, (x, y) => x < y);\n this.AddFloatBinaryOp(this.GreaterThanOrEquals, (x, y) => x >= y);\n this.AddFloatBinaryOp(this.LessThanOrEquals, (x, y) => x <= y);\n this.AddFloatBinaryOp(this.NotEquals, (x, y) => x != y);\n this.AddFloatUnaryOp(this.Not, (x) => x == 0.0);\n\n this.AddFloatBinaryOp(this.And, (x, y) => x != 0.0 && y != 0.0);\n this.AddFloatBinaryOp(this.Or, (x, y) => x != 0.0 || y != 0.0);\n\n this.AddFloatBinaryOp(this.Max, (x, y) => Math.max(x, y));\n this.AddFloatBinaryOp(this.Min, (x, y) => Math.min(x, y));\n\n this.AddFloatBinaryOp(this.Pow, (x, y) => Math.pow(x, y));\n this.AddFloatUnaryOp(this.Floor, (x) => Math.floor(x));\n this.AddFloatUnaryOp(this.Ceiling, (x) => Math.ceil(x));\n this.AddFloatUnaryOp(this.Int, (x) => Math.floor(x));\n this.AddFloatUnaryOp(this.Float, NativeFunctionCall.Identity);\n\n // String operations\n this.AddStringBinaryOp(this.Add, (x, y) => x + y); // concat\n this.AddStringBinaryOp(this.Equal, (x, y) => x === y);\n this.AddStringBinaryOp(this.NotEquals, (x, y) => !(x === y));\n this.AddStringBinaryOp(this.Has, (x, y) => x.includes(y));\n this.AddStringBinaryOp(this.Hasnt, (x, y) => !x.includes(y));\n\n this.AddListBinaryOp(this.Add, (x, y) => x.Union(y));\n this.AddListBinaryOp(this.Subtract, (x, y) => x.Without(y));\n this.AddListBinaryOp(this.Has, (x, y) => x.Contains(y));\n this.AddListBinaryOp(this.Hasnt, (x, y) => !x.Contains(y));\n this.AddListBinaryOp(this.Intersect, (x, y) => x.Intersect(y));\n\n this.AddListBinaryOp(this.Equal, (x, y) => x.Equals(y));\n this.AddListBinaryOp(this.Greater, (x, y) => x.GreaterThan(y));\n this.AddListBinaryOp(this.Less, (x, y) => x.LessThan(y));\n this.AddListBinaryOp(this.GreaterThanOrEquals, (x, y) =>\n x.GreaterThanOrEquals(y)\n );\n this.AddListBinaryOp(this.LessThanOrEquals, (x, y) =>\n x.LessThanOrEquals(y)\n );\n this.AddListBinaryOp(this.NotEquals, (x, y) => !x.Equals(y));\n\n this.AddListBinaryOp(this.And, (x, y) => x.Count > 0 && y.Count > 0);\n this.AddListBinaryOp(this.Or, (x, y) => x.Count > 0 || y.Count > 0);\n\n this.AddListUnaryOp(this.Not, (x) => (x.Count == 0 ? 1 : 0));\n\n this.AddListUnaryOp(this.Invert, (x) => x.inverse);\n this.AddListUnaryOp(this.All, (x) => x.all);\n this.AddListUnaryOp(this.ListMin, (x) => x.MinAsList());\n this.AddListUnaryOp(this.ListMax, (x) => x.MaxAsList());\n this.AddListUnaryOp(this.Count, (x) => x.Count);\n this.AddListUnaryOp(this.ValueOfList, (x) => x.maxItem.Value);\n\n let divertTargetsEqual = (d1: Path, d2: Path) => d1.Equals(d2);\n let divertTargetsNotEqual = (d1: Path, d2: Path) => !d1.Equals(d2);\n this.AddOpToNativeFunc(\n this.Equal,\n 2,\n ValueType.DivertTarget,\n divertTargetsEqual\n );\n this.AddOpToNativeFunc(\n this.NotEquals,\n 2,\n ValueType.DivertTarget,\n divertTargetsNotEqual\n );\n }\n }\n\n public AddOpFuncForType(\n valType: ValueType,\n op: UnaryOp | BinaryOp\n ): void {\n if (this._operationFuncs == null) {\n this._operationFuncs = new Map();\n }\n\n this._operationFuncs.set(valType, op);\n }\n\n public static AddOpToNativeFunc(\n name: string,\n args: number,\n valType: ValueType,\n op: UnaryOp | BinaryOp\n ): void {\n if (this._nativeFunctions === null)\n return throwNullException(\"NativeFunctionCall._nativeFunctions\");\n let nativeFunc = this._nativeFunctions.get(name);\n if (!nativeFunc) {\n nativeFunc = new NativeFunctionCall(name, args);\n this._nativeFunctions.set(name, nativeFunc);\n }\n\n nativeFunc.AddOpFuncForType(valType, op);\n }\n\n public static AddIntBinaryOp(name: string, op: BinaryOp) {\n this.AddOpToNativeFunc(name, 2, ValueType.Int, op);\n }\n public static AddIntUnaryOp(name: string, op: UnaryOp) {\n this.AddOpToNativeFunc(name, 1, ValueType.Int, op);\n }\n\n public static AddFloatBinaryOp(name: string, op: BinaryOp) {\n this.AddOpToNativeFunc(name, 2, ValueType.Float, op);\n }\n public static AddFloatUnaryOp(name: string, op: UnaryOp) {\n this.AddOpToNativeFunc(name, 1, ValueType.Float, op);\n }\n\n public static AddStringBinaryOp(name: string, op: BinaryOp) {\n this.AddOpToNativeFunc(name, 2, ValueType.String, op);\n }\n\n public static AddListBinaryOp(name: string, op: BinaryOp) {\n this.AddOpToNativeFunc(name, 2, ValueType.List, op);\n }\n public static AddListUnaryOp(name: string, op: UnaryOp) {\n this.AddOpToNativeFunc(name, 1, ValueType.List, op);\n }\n\n public toString() {\n return 'Native \"' + this.name + '\"';\n }\n\n public _prototype: NativeFunctionCall | null = null;\n public _isPrototype: boolean = false;\n public _operationFuncs: Map | UnaryOp> | null =\n null;\n public static _nativeFunctions: Map | null = null;\n}\n","import { InkObject } from \"./Object\";\n\n// New version of tags is dynamic - it constructs the tags\n// at runtime based on BeginTag and EndTag control commands.\n// Plain text that's in the output stream is turned into tags\n// when you do story.currentTags.\n// The only place this is used is when flattening tags down\n// to string in advance, during dynamic string generation if\n// there's a tag embedded in it. See how ControlCommand.EndString\n// is implemented in Story.cs for more details + comment\nexport class Tag extends InkObject {\n public readonly text: string;\n\n constructor(tagText: string) {\n super();\n this.text = tagText.toString() || \"\";\n }\n\n public toString(): string {\n return \"# \" + this.text;\n }\n}\n","import { Path } from \"./Path\";\nimport { CallStack } from \"./CallStack\";\nimport { throwNullException } from \"./NullException\";\nimport { InkObject } from \"./Object\";\n\nexport class Choice extends InkObject {\n public text: string = \"\";\n public index: number = 0;\n public threadAtGeneration: CallStack.Thread | null = null;\n public sourcePath: string = \"\";\n public targetPath: Path | null = null;\n public isInvisibleDefault: boolean = false;\n public tags: string[] | null = null;\n public originalThreadIndex: number = 0;\n\n get pathStringOnChoice(): string {\n if (this.targetPath === null)\n return throwNullException(\"Choice.targetPath\");\n return this.targetPath.toString();\n }\n set pathStringOnChoice(value: string) {\n this.targetPath = new Path(value);\n }\n\n public Clone() {\n let copy = new Choice();\n copy.text = this.text;\n copy.sourcePath = this.sourcePath;\n copy.index = this.index;\n copy.targetPath = this.targetPath;\n copy.originalThreadIndex = this.originalThreadIndex;\n copy.isInvisibleDefault = this.isInvisibleDefault;\n if (this.threadAtGeneration !== null)\n copy.threadAtGeneration = this.threadAtGeneration.Copy();\n\n return copy;\n }\n}\n","import { InkListItem, SerializedInkListItem } from \"./InkList\";\nimport { TryGetResult } from \"./TryGetResult\";\n\nexport class ListDefinition {\n public _name: string;\n public _items: Map | null;\n public _itemNameToValues: Map;\n\n constructor(name: string, items: Map | null) {\n this._name = name || \"\";\n this._items = null;\n this._itemNameToValues = items || new Map();\n }\n get name() {\n return this._name;\n }\n get items() {\n if (this._items == null) {\n this._items = new Map();\n for (let [key, value] of this._itemNameToValues) {\n let item = new InkListItem(this.name, key);\n this._items.set(item.serialized(), value);\n }\n }\n\n return this._items;\n }\n\n public ValueForItem(item: InkListItem) {\n if (!item.itemName) return 0;\n\n let intVal = this._itemNameToValues.get(item.itemName);\n if (typeof intVal !== \"undefined\") return intVal;\n else return 0;\n }\n public ContainsItem(item: InkListItem) {\n if (!item.itemName) return false;\n if (item.originName != this.name) return false;\n\n return this._itemNameToValues.has(item.itemName);\n }\n public ContainsItemWithName(itemName: string) {\n return this._itemNameToValues.has(itemName);\n }\n public TryGetItemWithValue(\n val: number,\n /* out */ item: InkListItem\n ): TryGetResult {\n for (let [key, value] of this._itemNameToValues) {\n if (value == val) {\n item = new InkListItem(this.name, key);\n return { result: item, exists: true };\n }\n }\n\n item = InkListItem.Null;\n return { result: item, exists: false };\n }\n\n public TryGetValueForItem(\n item: InkListItem,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n /* out */ intVal: number\n ): TryGetResult {\n if (!item.itemName) return { result: 0, exists: false };\n let value = this._itemNameToValues.get(item.itemName);\n\n if (!value) return { result: 0, exists: false };\n return { result: value, exists: true };\n }\n}\n","import { InkListItem } from \"./InkList\";\nimport { ListValue } from \"./Value\";\nimport { ListDefinition } from \"./ListDefinition\";\nimport { TryGetResult } from \"./TryGetResult\";\nimport { throwNullException } from \"./NullException\";\n\nexport class ListDefinitionsOrigin {\n protected _lists: Map;\n protected _allUnambiguousListValueCache: Map;\n\n constructor(lists: ListDefinition[]) {\n this._lists = new Map();\n this._allUnambiguousListValueCache = new Map();\n\n for (let list of lists) {\n this._lists.set(list.name, list);\n\n for (let [key, val] of list.items) {\n let item = InkListItem.fromSerializedKey(key);\n let listValue = new ListValue(item, val);\n\n if (!item.itemName) {\n throw new Error(\"item.itemName is null or undefined.\");\n }\n\n this._allUnambiguousListValueCache.set(item.itemName, listValue);\n this._allUnambiguousListValueCache.set(item.fullName, listValue);\n }\n }\n }\n get lists(): ListDefinition[] {\n let listOfLists: ListDefinition[] = [];\n\n for (let [, value] of this._lists) {\n listOfLists.push(value);\n }\n\n return listOfLists;\n }\n public TryListGetDefinition(\n name: string | null,\n /* out */ def: ListDefinition | null\n ): TryGetResult {\n if (name === null) {\n return { result: def, exists: false };\n }\n // initially, this function returns a boolean and the second parameter is an out.\n let definition = this._lists.get(name);\n if (!definition) return { result: def, exists: false };\n\n return { result: definition, exists: true };\n }\n public FindSingleItemListWithName(name: string | null) {\n if (name === null) {\n return throwNullException(\"name\");\n }\n let val = this._allUnambiguousListValueCache.get(name);\n\n if (typeof val !== \"undefined\") {\n return val;\n }\n\n return null;\n }\n}\n","import { Container } from \"./Container\";\nimport {\n Value,\n IntValue,\n FloatValue,\n StringValue,\n DivertTargetValue,\n VariablePointerValue,\n ListValue,\n BoolValue,\n} from \"./Value\";\nimport { Glue } from \"./Glue\";\nimport { ControlCommand } from \"./ControlCommand\";\nimport { PushPopType } from \"./PushPop\";\nimport { Divert } from \"./Divert\";\nimport { ChoicePoint } from \"./ChoicePoint\";\nimport { VariableReference } from \"./VariableReference\";\nimport { VariableAssignment } from \"./VariableAssignment\";\nimport { NativeFunctionCall } from \"./NativeFunctionCall\";\nimport { Void } from \"./Void\";\nimport { Tag } from \"./Tag\";\nimport { Path } from \"./Path\";\nimport { Choice } from \"./Choice\";\nimport { ListDefinition } from \"./ListDefinition\";\nimport { ListDefinitionsOrigin } from \"./ListDefinitionsOrigin\";\nimport { InkListItem, InkList } from \"./InkList\";\nimport { InkObject } from \"./Object\";\nimport { asOrNull } from \"./TypeAssertion\";\nimport { throwNullException } from \"./NullException\";\nimport { SimpleJson } from \"./SimpleJson\";\n\nexport class JsonSerialisation {\n public static JArrayToRuntimeObjList(\n jArray: any[],\n skipLast: boolean = false\n ) {\n let count = jArray.length;\n if (skipLast) count--;\n\n let list: InkObject[] = [];\n\n for (let i = 0; i < count; i++) {\n let jTok = jArray[i];\n let runtimeObj = this.JTokenToRuntimeObject(jTok);\n if (runtimeObj === null) {\n return throwNullException(\"runtimeObj\");\n }\n list.push(runtimeObj);\n }\n\n return list;\n }\n\n public static WriteDictionaryRuntimeObjs(\n writer: SimpleJson.Writer,\n dictionary: Map\n ) {\n writer.WriteObjectStart();\n for (let [key, value] of dictionary) {\n writer.WritePropertyStart(key);\n this.WriteRuntimeObject(writer, value);\n writer.WritePropertyEnd();\n }\n writer.WriteObjectEnd();\n }\n\n public static WriteListRuntimeObjs(\n writer: SimpleJson.Writer,\n list: InkObject[]\n ) {\n writer.WriteArrayStart();\n for (let value of list) {\n this.WriteRuntimeObject(writer, value);\n }\n writer.WriteArrayEnd();\n }\n\n public static WriteIntDictionary(\n writer: SimpleJson.Writer,\n dict: Map\n ) {\n writer.WriteObjectStart();\n for (let [key, value] of dict) {\n writer.WriteIntProperty(key, value);\n }\n writer.WriteObjectEnd();\n }\n\n public static WriteRuntimeObject(\n writer: SimpleJson.Writer,\n obj: InkObject\n ): void {\n let container = asOrNull(obj, Container);\n if (container) {\n this.WriteRuntimeContainer(writer, container);\n return;\n }\n\n let divert = asOrNull(obj, Divert);\n if (divert) {\n let divTypeKey = \"->\";\n if (divert.isExternal) {\n divTypeKey = \"x()\";\n } else if (divert.pushesToStack) {\n if (divert.stackPushType == PushPopType.Function) {\n divTypeKey = \"f()\";\n } else if (divert.stackPushType == PushPopType.Tunnel) {\n divTypeKey = \"->t->\";\n }\n }\n\n let targetStr;\n if (divert.hasVariableTarget) {\n targetStr = divert.variableDivertName;\n } else {\n targetStr = divert.targetPathString;\n }\n\n writer.WriteObjectStart();\n writer.WriteProperty(divTypeKey, targetStr);\n\n if (divert.hasVariableTarget) {\n writer.WriteProperty(\"var\", true);\n }\n\n if (divert.isConditional) {\n writer.WriteProperty(\"c\", true);\n }\n\n if (divert.externalArgs > 0) {\n writer.WriteIntProperty(\"exArgs\", divert.externalArgs);\n }\n\n writer.WriteObjectEnd();\n return;\n }\n\n let choicePoint = asOrNull(obj, ChoicePoint);\n if (choicePoint) {\n writer.WriteObjectStart();\n writer.WriteProperty(\"*\", choicePoint.pathStringOnChoice);\n writer.WriteIntProperty(\"flg\", choicePoint.flags);\n writer.WriteObjectEnd();\n return;\n }\n\n let boolVal = asOrNull(obj, BoolValue);\n if (boolVal) {\n writer.WriteBool(boolVal.value);\n return;\n }\n\n let intVal = asOrNull(obj, IntValue);\n if (intVal) {\n writer.WriteInt(intVal.value);\n return;\n }\n\n let floatVal = asOrNull(obj, FloatValue);\n if (floatVal) {\n writer.WriteFloat(floatVal.value);\n return;\n }\n\n let strVal = asOrNull(obj, StringValue);\n if (strVal) {\n if (strVal.isNewline) {\n writer.Write(\"\\n\", false);\n } else {\n writer.WriteStringStart();\n writer.WriteStringInner(\"^\");\n writer.WriteStringInner(strVal.value);\n writer.WriteStringEnd();\n }\n return;\n }\n\n let listVal = asOrNull(obj, ListValue);\n if (listVal) {\n this.WriteInkList(writer, listVal);\n return;\n }\n\n let divTargetVal = asOrNull(obj, DivertTargetValue);\n if (divTargetVal) {\n writer.WriteObjectStart();\n if (divTargetVal.value === null) {\n return throwNullException(\"divTargetVal.value\");\n }\n writer.WriteProperty(\"^->\", divTargetVal.value.componentsString);\n writer.WriteObjectEnd();\n\n return;\n }\n\n let varPtrVal = asOrNull(obj, VariablePointerValue);\n if (varPtrVal) {\n writer.WriteObjectStart();\n writer.WriteProperty(\"^var\", varPtrVal.value);\n writer.WriteIntProperty(\"ci\", varPtrVal.contextIndex);\n writer.WriteObjectEnd();\n return;\n }\n\n let glue = asOrNull(obj, Glue);\n if (glue) {\n writer.Write(\"<>\");\n return;\n }\n\n let controlCmd = asOrNull(obj, ControlCommand);\n if (controlCmd) {\n writer.Write(\n JsonSerialisation._controlCommandNames[controlCmd.commandType]\n );\n return;\n }\n\n let nativeFunc = asOrNull(obj, NativeFunctionCall);\n if (nativeFunc) {\n let name = nativeFunc.name;\n\n if (name == \"^\") name = \"L^\";\n\n writer.Write(name);\n return;\n }\n\n let varRef = asOrNull(obj, VariableReference);\n if (varRef) {\n writer.WriteObjectStart();\n let readCountPath = varRef.pathStringForCount;\n if (readCountPath != null) {\n writer.WriteProperty(\"CNT?\", readCountPath);\n } else {\n writer.WriteProperty(\"VAR?\", varRef.name);\n }\n\n writer.WriteObjectEnd();\n return;\n }\n\n let varAss = asOrNull(obj, VariableAssignment);\n if (varAss) {\n writer.WriteObjectStart();\n\n let key = varAss.isGlobal ? \"VAR=\" : \"temp=\";\n writer.WriteProperty(key, varAss.variableName);\n\n // Reassignment?\n if (!varAss.isNewDeclaration) writer.WriteProperty(\"re\", true);\n\n writer.WriteObjectEnd();\n\n return;\n }\n\n let voidObj = asOrNull(obj, Void);\n if (voidObj) {\n writer.Write(\"void\");\n return;\n }\n\n let tag = asOrNull(obj, Tag);\n if (tag) {\n writer.WriteObjectStart();\n writer.WriteProperty(\"#\", tag.text);\n writer.WriteObjectEnd();\n return;\n }\n\n let choice = asOrNull(obj, Choice);\n if (choice) {\n this.WriteChoice(writer, choice);\n return;\n }\n\n throw new Error(\"Failed to convert runtime object to Json token: \" + obj);\n }\n\n public static JObjectToDictionaryRuntimeObjs(jObject: Record) {\n let dict: Map = new Map();\n\n for (let key in jObject) {\n if (jObject.hasOwnProperty(key)) {\n let inkObject = this.JTokenToRuntimeObject(jObject[key]);\n if (inkObject === null) {\n return throwNullException(\"inkObject\");\n }\n dict.set(key, inkObject);\n }\n }\n\n return dict;\n }\n\n public static JObjectToIntDictionary(jObject: Record) {\n let dict: Map = new Map();\n for (let key in jObject) {\n if (jObject.hasOwnProperty(key)) {\n dict.set(key, parseInt(jObject[key]));\n }\n }\n return dict;\n }\n\n public static JTokenToRuntimeObject(token: any): InkObject | null {\n if (\n (typeof token === \"number\" && !isNaN(token)) ||\n typeof token === \"boolean\"\n ) {\n return Value.Create(token);\n }\n\n if (typeof token === \"string\") {\n let str = token.toString();\n\n //Explicit float value of the form \"123.00f\"\n const floatRepresentation = /^([0-9]+.[0-9]+f)$/.exec(str);\n if (floatRepresentation) {\n return new FloatValue(parseFloat(floatRepresentation[0]));\n }\n\n // String value\n let firstChar = str[0];\n if (firstChar == \"^\") return new StringValue(str.substring(1));\n else if (firstChar == \"\\n\" && str.length == 1)\n return new StringValue(\"\\n\");\n\n // Glue\n if (str == \"<>\") return new Glue();\n\n // Control commands (would looking up in a hash set be faster?)\n for (let i = 0; i < JsonSerialisation._controlCommandNames.length; ++i) {\n let cmdName = JsonSerialisation._controlCommandNames[i];\n if (str == cmdName) {\n return new ControlCommand(i);\n }\n }\n\n // Native functions\n if (str == \"L^\") str = \"^\";\n if (NativeFunctionCall.CallExistsWithName(str))\n return NativeFunctionCall.CallWithName(str);\n\n // Pop\n if (str == \"->->\") return ControlCommand.PopTunnel();\n else if (str == \"~ret\") return ControlCommand.PopFunction();\n\n // Void\n if (str == \"void\") return new Void();\n }\n\n if (typeof token === \"object\" && !Array.isArray(token)) {\n let obj = token as Record;\n let propValue;\n\n // Divert target value to path\n if (obj[\"^->\"]) {\n propValue = obj[\"^->\"];\n return new DivertTargetValue(new Path(propValue.toString()));\n }\n\n // VariablePointerValue\n if (obj[\"^var\"]) {\n propValue = obj[\"^var\"];\n let varPtr = new VariablePointerValue(propValue.toString());\n if (\"ci\" in obj) {\n propValue = obj[\"ci\"];\n varPtr.contextIndex = parseInt(propValue);\n }\n return varPtr;\n }\n\n // Divert\n let isDivert = false;\n let pushesToStack = false;\n let divPushType = PushPopType.Function;\n let external = false;\n if ((propValue = obj[\"->\"])) {\n isDivert = true;\n } else if ((propValue = obj[\"f()\"])) {\n isDivert = true;\n pushesToStack = true;\n divPushType = PushPopType.Function;\n } else if ((propValue = obj[\"->t->\"])) {\n isDivert = true;\n pushesToStack = true;\n divPushType = PushPopType.Tunnel;\n } else if ((propValue = obj[\"x()\"])) {\n isDivert = true;\n external = true;\n pushesToStack = false;\n divPushType = PushPopType.Function;\n }\n\n if (isDivert) {\n let divert = new Divert();\n divert.pushesToStack = pushesToStack;\n divert.stackPushType = divPushType;\n divert.isExternal = external;\n\n let target = propValue.toString();\n\n if ((propValue = obj[\"var\"])) divert.variableDivertName = target;\n else divert.targetPathString = target;\n\n divert.isConditional = !!obj[\"c\"];\n\n if (external) {\n if ((propValue = obj[\"exArgs\"]))\n divert.externalArgs = parseInt(propValue);\n }\n\n return divert;\n }\n\n // Choice\n if ((propValue = obj[\"*\"])) {\n let choice = new ChoicePoint();\n choice.pathStringOnChoice = propValue.toString();\n\n if ((propValue = obj[\"flg\"])) choice.flags = parseInt(propValue);\n\n return choice;\n }\n\n // Variable reference\n if ((propValue = obj[\"VAR?\"])) {\n return new VariableReference(propValue.toString());\n } else if ((propValue = obj[\"CNT?\"])) {\n let readCountVarRef = new VariableReference();\n readCountVarRef.pathStringForCount = propValue.toString();\n return readCountVarRef;\n }\n\n // Variable assignment\n let isVarAss = false;\n let isGlobalVar = false;\n if ((propValue = obj[\"VAR=\"])) {\n isVarAss = true;\n isGlobalVar = true;\n } else if ((propValue = obj[\"temp=\"])) {\n isVarAss = true;\n isGlobalVar = false;\n }\n if (isVarAss) {\n let varName = propValue.toString();\n let isNewDecl = !obj[\"re\"];\n let varAss = new VariableAssignment(varName, isNewDecl);\n varAss.isGlobal = isGlobalVar;\n return varAss;\n }\n if (obj[\"#\"] !== undefined) {\n propValue = obj[\"#\"];\n return new Tag(propValue.toString());\n }\n\n // List value\n if ((propValue = obj[\"list\"])) {\n // var listContent = (Dictionary)propValue;\n let listContent = propValue as Record;\n let rawList = new InkList();\n if ((propValue = obj[\"origins\"])) {\n // var namesAsObjs = (List