@inkweave/core 1.1.0 → 1.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +19 -19
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +380 -382
- package/dist/index.js.map +1 -1
- package/dist/state/contents.d.ts +0 -4
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,36 +1,36 @@
|
|
|
1
|
-
"use strict";var ma=Object.defineProperty;var ga=(o,n,a)=>n in o?ma(o,n,{enumerable:!0,configurable:!0,writable:!0,value:a}):o[n]=a;var z=(o,n,a)=>ga(o,typeof n!="symbol"?n+"":n,a);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const wi=require("zustand"),Li=require("inkjs/engine/Story"),ii=o=>{let n=o;return n.use=new Proxy({},{get:(a,e)=>()=>n(f=>f[e])}),n},Ca=wi.create(o=>({contents:[],refreshKey:0,setContents:n=>o({contents:n}),add:n=>{o(a=>({contents:[...a.contents,...n]}))},clear:()=>o({contents:[]}),refresh:()=>o(n=>({refreshKey:n.refreshKey+1}))})),Yt=ii(Ca),ks="\0ink-divider\0",va={debug:!1,linedelay:.05};class Ds{constructor(n){z(this,"basePath");this.basePath=(n==null?void 0:n.basePath)||""}resolveFilename(n){return this.basePath?this.basePath+"/"+n:n}loadFile(n){throw new Error("loadFile must be implemented by subclass")}}let Vs=class{constructor(n,a,e="default"){z(this,"text");z(this,"index");z(this,"type");z(this,"val");this.text=n||"",this.index=a,this.type=e}};const It=class It{static get functions(){return It._functions}static clear(){for(const[n,a]of this._functions.entries())this.excludeKeys.has(n)||this._functions.delete(n)}static add(n,a){It.functions.set(n,a)}};z(It,"_functions",new Map),z(It,"excludeKeys",new Set(["clear","restart"])),z(It,"process",(n,a)=>{var f;const e=Pi(a,":");if(e)if(It.functions.has(e.before))(f=It.functions.get(e.before))==null||f(e.after,n);else{const t=n.options;if(t[e.before]!=null){let p=e.after;switch(typeof t[e.before]){case"string":break;case"number":typeof p=="string"?p=parseFloat(p):p=void 0;break;case"boolean":p=!!p;break;default:p=void 0}p!==void 0&&!Number.isNaN(p)&&(t[e.before]=p)}}});let Zt=It;const Pi=(o,n)=>{if(!o)return;let a=o.indexOf(n);return a==-1?{before:o.trim().toLowerCase()}:{before:o.slice(0,a).trim().toLowerCase(),after:o.slice(a+1).trim()}};Zt.add("clear",(o,n)=>{n.clear()});Zt.add("restart",(o,n)=>{n.restart()});const dt=class dt{static get tags(){return dt._tags}};z(dt,"_tags",new Map),z(dt,"excludeKeys",new Set(["unclickable"])),z(dt,"clear",()=>{for(const[n,a]of dt._tags.entries())dt.excludeKeys.has(n)||dt._tags.delete(n)}),z(dt,"add",(n,a)=>{dt.tags.set(n,a)}),z(dt,"process",(n,a)=>{if(!n.text)return a;n.tags&&n.tags.length&&dt.tags.size&&n.tags.forEach(function(e){var t;let f=Pi(e,":");f&&dt.tags.has(f.before)&&((t=dt.tags.get(f.before))==null||t(a,f.after))})});let qn=dt;qn.add("unclickable",o=>{o.type="unclickable"});const Sa=wi.create(o=>({choices:[],setChoices:n=>{const a=n.map(e=>{const f=new Vs(e.text,e.index);return e.tags&&e.tags.length&&qn.process(e,f),f});o({choices:a})},clear:()=>o({choices:[]})})),Ci=ii(Sa),ya=wi.create(o=>({variables:new Map,setGlobalVars:n=>{const a=new Map,f=n._globalVariables;if(f)for(const t of f.keys()){const p=f.get(t);p&&a.set(t,p.value)}o({variables:a})}})),Ws=ii(ya),Pt=class Pt{static get patches(){return Pt._patches}static set patches(n){Pt._patches=n}static add(n,a={}){Object.assign(this._options,a),n&&Pt._patches.push(n)}static apply(n,a){const e=n;Object.assign(e.options,Pt._options);for(const f of Pt._patches)f&&f.bind(e,a)()}static clear(){Pt._patches=[],Pt._options={}}};z(Pt,"_patches",[]),z(Pt,"_options",{});let ti=Pt;const ct=class ct{static get tags(){return ct._tags}static get patterns(){return ct._patterns}static tag(n,a){ct.tags[n]=a}static pattern(n,a){ct.patterns.push({matcher:n,callback:a})}};z(ct,"_tags",{}),z(ct,"_patterns",[]),z(ct,"clear",()=>{ct._tags={},ct._patterns=[]}),z(ct,"process",(n,a=[])=>{if(!n)return"";let e={text:n,tags:a,classes:[]};return e.tags.length&&Object.keys(ct.tags).length&&e.tags.forEach(function(f){let t=Pi(f,":");t&&t.before in ct.tags&&ct.tags[t.before](e,t.before,t.after)}),e.text&&ct.patterns.length&&ct.patterns.forEach(function(f){(typeof f.matcher=="string"&&e.text.includes(f.matcher)||f.matcher instanceof RegExp&&e.text.match(f.matcher))&&f.callback(e)}),e.text});let ei=ct;const At=class At{static get functions(){return At._functions}static set functions(n){At._functions=n}static add(n,a){At.functions.set(n,a)}static get(n){return At.functions.get(n)}static bind(n,a){const e=At.get(a)||(typeof window<"u"?window[a]:void 0);e&&n.story.BindExternalFunction(a,e.bind(n))}static clear(){At.functions.clear()}};z(At,"_functions",new Map);let ni=At;class Ls{constructor(n,a,e){z(this,"title");z(this,"story");z(this,"options");z(this,"_side_effects",[]);z(this,"_cleanups",[]);z(this,"_clears",[]);z(this,"_save_label",["contents"]);z(this,"bindExternalFunctions",n=>{new Set(Array.from(n.matchAll(/\"x\(\)\":\"(\w+)/gi),a=>a[1])).forEach(a=>{ni.bind(this,a)})});this.options={...va,...e},this.story=n,this.title=a;const f=this.story.ToJson()||"";ba(this),ti.apply(this,f),this.bindExternalFunctions(f),this.clears.push(()=>{this.contents.length=0})}get contents(){return Yt.getState().contents}set contents(n){Yt.getState().setContents(n)}get choices(){return Ci.getState().choices}get clears(){return this._clears}get cleanups(){return this._cleanups}get effects(){return this._side_effects}get save_label(){return this._save_label}continue(){const n=[];for(;this.story.canContinue;){let f=this.story.Continue()||"";this.story.currentTags&&(this.story.currentTags.forEach(t=>{Zt.process(this,t),(t==="clear"||t==="restart")&&(n.length=0)}),f&&this.story.currentTags.length&&(f=ei.process(f,this.story.currentTags))),f.trim()&&n.push(f)}Yt.getState().add(n);const{currentChoices:a,variablesState:e}=this.story;Ci.getState().setChoices(a),Ws.getState().setGlobalVars(e)}choose(n){this.story.ChooseChoiceIndex(n),Yt.getState().add([ks]),this.continue()}clear(){this.clears.map(n=>{n()})}restart(){this.story.ResetState(),this.clear(),Yt.getState().refresh(),this.continue()}useEffect(){this.effects.map(n=>{n&&n()})}dispose(){this.cleanups.map(n=>{n&&n()})}}function ba(o){const n=Object.getPrototypeOf(o);Object.getOwnPropertyNames(n).forEach(function(a){var e;if(a!=="constructor"&&typeof((e=Object.getOwnPropertyDescriptor(n,a))==null?void 0:e.value)=="function"){const f=o;f[a]=f[a].bind(o)}})}var pi={},ae={},ji;function vi(){if(ji)return ae;ji=1,Object.defineProperty(ae,"__esModule",{value:!0}),ae.CompilerOptions=void 0;let o=class{constructor(a=null,e=[],f=!1,t=null,p=null){this.sourceFilename=a,this.pluginNames=e,this.countAllVisits=f,this.errorHandler=t,this.fileHandler=p}};return ae.CompilerOptions=o,ae}var oe={},Mi;function _a(){if(Mi)return oe;Mi=1,Object.defineProperty(oe,"__esModule",{value:!0}),oe.DebugSourceRange=void 0;let o=class{constructor(a,e,f){this.length=a,this.debugMetadata=e,this.text=f}};return oe.DebugSourceRange=o,oe}var le={},Bi;function Oi(){if(Bi)return le;Bi=1,Object.defineProperty(le,"__esModule",{value:!0}),le.ErrorType=void 0;var o;return(function(n){n[n.Author=0]="Author",n[n.Warning=1]="Warning",n[n.Error=2]="Error"})(o||(le.ErrorType=o={})),le}var ue={},he={},qi;function Ea(){if(qi)return he;qi=1,Object.defineProperty(he,"__esModule",{value:!0}),he.Argument=void 0;let o=class{constructor(a=null,e=null,f=null){this.identifier=a,this.isByReference=e,this.isDivertTarget=f}get typeName(){return"Argument"}};return he.Argument=o,he}var ce={},de={},at={},Gi;function Z(){if(Gi)return at;Gi=1,Object.defineProperty(at,"__esModule",{value:!0}),at.filterUndef=at.isEquatable=at.nullIfUndefined=at.asINamedContentOrNull=at.asBooleanOrThrows=at.asNumberOrThrows=at.asOrThrows=at.asOrNull=void 0;function o(s,c){return s instanceof c?r(s):null}at.asOrNull=o;function n(s,c){if(s instanceof c)return r(s);throw new Error(`${s} is not of type ${c}`)}at.asOrThrows=n;function a(s){if(typeof s=="number")return s;throw new Error(`${s} is not a number`)}at.asNumberOrThrows=a;function e(s){if(typeof s=="boolean")return s;throw new Error(`${s} is not a boolean`)}at.asBooleanOrThrows=e;function f(s){return s.hasValidName&&s.name?s:null}at.asINamedContentOrNull=f;function t(s){return typeof s>"u"?null:s}at.nullIfUndefined=t;function p(s){return typeof s=="object"&&typeof s.Equals=="function"}at.isEquatable=p;function r(s,c){return s}function y(s){return s!=null}return at.filterUndef=y,at}var $i;function et(){if($i)return de;$i=1,Object.defineProperty(de,"__esModule",{value:!0}),de.ParsedObject=void 0;const o=Z();class n{constructor(){this._alreadyHadError=!1,this._alreadyHadWarning=!1,this._debugMetadata=null,this._runtimeObject=null,this.content=[],this.parent=null,this.GetType=()=>this.typeName,this.AddContent=e=>{this.content===null&&(this.content=[]);const f=Array.isArray(e)?e:[e];for(const t of f)t.hasOwnProperty("parent")&&(t.parent=this),this.content.push(t);if(!Array.isArray(e))return e},this.InsertContent=(e,f)=>(this.content===null&&(this.content=[]),f.parent=this,this.content.splice(e,0,f),f),this.Find=e=>(f=null)=>{let t=(0,o.asOrNull)(this,e);if(t!==null&&(f===null||f(t)===!0))return t;if(this.content===null)return null;for(const p of this.content){let r=p.Find&&p.Find(e)(f);if(r)return r}return null},this.FindAll=e=>(f,t)=>{const p=Array.isArray(t)?t:[],r=(0,o.asOrNull)(this,e);if(r!==null&&(!f||f(r)===!0)&&p.push(r),this.content===null)return[];for(const y of this.content)y.FindAll&&y.FindAll(e)(f,p);return p},this.Warning=(e,f=null)=>{this.Error(e,f,!0)}}get debugMetadata(){return this._debugMetadata===null&&this.parent?this.parent.debugMetadata:this._debugMetadata}set debugMetadata(e){this._debugMetadata=e}get hasOwnDebugMetadata(){return!!this.debugMetadata}get typeName(){return"ParsedObject"}get story(){let e=this;for(;e.parent;)e=e.parent;return e}get runtimeObject(){return this._runtimeObject||(this._runtimeObject=this.GenerateRuntimeObject(),this._runtimeObject&&(this._runtimeObject.debugMetadata=this.debugMetadata)),this._runtimeObject}set runtimeObject(e){this._runtimeObject=e}get runtimePath(){if(!this.runtimeObject.path)throw new Error;return this.runtimeObject.path}get containerForCounting(){return this.runtimeObject}get ancestry(){let e=[],f=this.parent;for(;f;)e.push(f),f=f.parent;return e=e.reverse(),e}ResolveReferences(e){if(this.content!==null)for(const f of this.content)f.ResolveReferences(e)}Error(e,f=null,t=!1){if(f===null&&(f=this),!(f._alreadyHadError&&!t||f._alreadyHadWarning&&t)){if(this.parent)this.parent.Error(e,f,t);else throw new Error(`No parent object to send error to: ${e}`);t?f._alreadyHadWarning=!0:f._alreadyHadError=!0}}}return de.ParsedObject=n,de}var Ui;function xi(){if(Ui)return ce;Ui=1,Object.defineProperty(ce,"__esModule",{value:!0}),ce.AuthorWarning=void 0;const o=et();let n=class extends o.ParsedObject{constructor(e){super(),this.warningMessage=e,this.GenerateRuntimeObject=()=>(this.Warning(this.warningMessage),null)}get typeName(){return"AuthorWarning"}};return ce.AuthorWarning=n,ce}var fe={},pe={},Kt={},tt={},me={},Ht={},Ki;function St(){if(Ki)return Ht;Ki=1,Object.defineProperty(Ht,"__esModule",{value:!0}),Ht.Path=void 0;class o{constructor(){if(this._components=[],this._componentsString=null,this._isRelative=!1,typeof arguments[0]=="string"){let a=arguments[0];this.componentsString=a}else if(arguments[0]instanceof o.Component&&arguments[1]instanceof o){let a=arguments[0],e=arguments[1];this._components.push(a),this._components=this._components.concat(e._components)}else if(arguments[0]instanceof Array){let a=arguments[0],e=!!arguments[1];this._components=this._components.concat(a),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 a=this._components.slice(1,this._components.length);return new o(a)}else return o.self}get length(){return this._components.length}get lastComponent(){let a=this._components.length-1;return a>=0?this._components[a]:null}get containsNamedComponent(){for(let a=0,e=this._components.length;a<e;a++)if(!this._components[a].isIndex)return!0;return!1}static get self(){let a=new o;return a._isRelative=!0,a}GetComponent(a){return this._components[a]}PathByAppendingPath(a){let e=new o,f=0;for(let t=0;t<a._components.length&&a._components[t].isParent;++t)f++;for(let t=0;t<this._components.length-f;++t)e._components.push(this._components[t]);for(let t=f;t<a._components.length;++t)e._components.push(a._components[t]);return e}get componentsString(){return this._componentsString==null&&(this._componentsString=this._components.join("."),this.isRelative&&(this._componentsString="."+this._componentsString)),this._componentsString}set componentsString(a){if(this._components.length=0,this._componentsString=a,this._componentsString==null||this._componentsString=="")return;this._componentsString[0]=="."&&(this._isRelative=!0,this._componentsString=this._componentsString.substring(1));let e=this._componentsString.split(".");for(let f of e)/^(\-|\+)?([0-9]+|Infinity)$/.test(f)?this._components.push(new o.Component(parseInt(f))):this._components.push(new o.Component(f))}toString(){return this.componentsString}Equals(a){if(a==null||a._components.length!=this._components.length||a.isRelative!=this.isRelative)return!1;for(let e=0,f=a._components.length;e<f;e++)if(!a._components[e].Equals(this._components[e]))return!1;return!0}PathByAppendingComponent(a){let e=new o;return e._components.push(...this._components),e._components.push(a),e}}return Ht.Path=o,o.parentId="^",(function(n){class a{constructor(f){this.index=-1,this.name=null,typeof f=="string"?this.name=f:this.index=f}get isIndex(){return this.index>=0}get isParent(){return this.name==n.parentId}static ToParent(){return new a(n.parentId)}toString(){return this.isIndex?this.index.toString():this.name}Equals(f){return f!=null&&f.isIndex==this.isIndex?this.isIndex?this.index==f.index:this.name==f.name:!1}}n.Component=a})(o||(Ht.Path=o={})),Ht}var ge={},Hi;function ri(){if(Hi)return ge;Hi=1,Object.defineProperty(ge,"__esModule",{value:!0}),ge.Debug=void 0;var o;return(function(n){function a(f,t,p){e(f instanceof t,p)}n.AssertType=a;function e(f,t){if(!f)throw typeof t<"u"&&console.warn(t),console.trace&&console.trace(),new Error("")}n.Assert=e})(o||(ge.Debug=o={})),ge}var jt={},Ji;function ft(){if(Ji)return jt;Ji=1,Object.defineProperty(jt,"__esModule",{value:!0}),jt.throwNullException=jt.NullException=void 0;let o=class extends Error{};jt.NullException=o;function n(a){throw new o(`${a} is null or undefined`)}return jt.throwNullException=n,jt}var zi;function yt(){if(zi)return me;zi=1,Object.defineProperty(me,"__esModule",{value:!0}),me.InkObject=void 0;const o=St(),n=ot(),a=ri(),e=Z(),f=ft();class t{constructor(){this.parent=null,this._debugMetadata=null,this._path=null}get debugMetadata(){return this._debugMetadata===null&&this.parent?this.parent.debugMetadata:this._debugMetadata}set debugMetadata(r){this._debugMetadata=r}get ownDebugMetadata(){return this._debugMetadata}DebugLineNumberOfPath(r){if(r===null)return null;let y=this.rootContentContainer;if(y){let s=y.ContentAtPath(r).obj;if(s){let c=s.debugMetadata;if(c!==null)return c.startLineNumber}}return null}get path(){if(this._path==null)if(this.parent==null)this._path=new o.Path;else{let r=[],y=this,s=(0,e.asOrNull)(y.parent,n.Container);for(;s!==null;){let c=(0,e.asINamedContentOrNull)(y);if(c!=null&&c.hasValidName){if(c.name===null)return(0,f.throwNullException)("namedChild.name");r.unshift(new o.Path.Component(c.name))}else r.unshift(new o.Path.Component(s.content.indexOf(y)));y=s,s=(0,e.asOrNull)(s.parent,n.Container)}this._path=new o.Path(r)}return this._path}ResolvePath(r){if(r===null)return(0,f.throwNullException)("path");if(r.isRelative){let y=(0,e.asOrNull)(this,n.Container);return y===null&&(a.Debug.Assert(this.parent!==null,"Can't resolve relative path because we don't have a parent"),y=(0,e.asOrNull)(this.parent,n.Container),a.Debug.Assert(y!==null,"Expected parent to be a container"),a.Debug.Assert(r.GetComponent(0).isParent),r=r.tail),y===null?(0,f.throwNullException)("nearestContainer"):y.ContentAtPath(r)}else{let y=this.rootContentContainer;return y===null?(0,f.throwNullException)("contentContainer"):y.ContentAtPath(r)}}ConvertPathToRelative(r){let y=this.path,s=Math.min(r.length,y.length),c=-1;for(let P=0;P<s;++P){let N=y.GetComponent(P),O=r.GetComponent(P);if(N.Equals(O))c=P;else break}if(c==-1)return r;let i=y.componentCount-1-c,l=[];for(let P=0;P<i;++P)l.push(o.Path.Component.ToParent());for(let P=c+1;P<r.componentCount;++P)l.push(r.GetComponent(P));return new o.Path(l,!0)}CompactPathString(r){let y=null,s=null;return r.isRelative?(s=r.componentsString,y=this.path.PathByAppendingPath(r).componentsString):(s=this.ConvertPathToRelative(r).componentsString,y=r.componentsString),s.length<y.length?s:y}get rootContentContainer(){let r=this;for(;r.parent;)r=r.parent;return(0,e.asOrNull)(r,n.Container)}Copy(){throw Error("Not Implemented: Doesn't support copying")}SetChild(r,y,s){r[y]&&(r[y]=null),r[y]=s,r[y]&&(r[y].parent=this)}Equals(r){return r===this}}return me.InkObject=t,me}var Mt={},Ce={},Xi;function Qt(){if(Xi)return Ce;Xi=1,Object.defineProperty(Ce,"__esModule",{value:!0}),Ce.StringBuilder=void 0;let o=class{constructor(a){a=typeof a<"u"?a.toString():"",this.string=a}get Length(){return this.string.length}Append(a){a!==null&&(this.string+=a)}AppendLine(a){typeof a<"u"&&this.Append(a),this.string+=`
|
|
2
|
-
`}AppendFormat(a,...e){this.string+=a.replace(/{(\d+)}/g,(f,t)=>typeof e[t]<"u"?e[t]:f)}toString(){return this.string}Clear(){this.string=""}};return Ce.StringBuilder=o,Ce}var Yi;function vt(){if(Yi)return Mt;Yi=1,Object.defineProperty(Mt,"__esModule",{value:!0}),Mt.InkList=Mt.InkListItem=void 0;const o=ft(),n=Qt();class a{constructor(){if(this.originName=null,this.itemName=null,typeof arguments[1]<"u"){let t=arguments[0],p=arguments[1];this.originName=t,this.itemName=p}else if(arguments[0]){let p=arguments[0].toString().split(".");this.originName=p[0],this.itemName=p[1]}}static get Null(){return new a(null,null)}get isNull(){return this.originName==null&&this.itemName==null}get fullName(){return(this.originName!==null?this.originName:"?")+"."+this.itemName}toString(){return this.fullName}Equals(t){if(t instanceof a){let p=t;return p.itemName==this.itemName&&p.originName==this.originName}return!1}copy(){return new a(this.originName,this.itemName)}serialized(){return JSON.stringify({originName:this.originName,itemName:this.itemName})}static fromSerializedKey(t){let p=JSON.parse(t);if(!a.isLikeInkListItem(p))return a.Null;let r=p;return new a(r.originName,r.itemName)}static isLikeInkListItem(t){return!(typeof t!="object"||!t.hasOwnProperty("originName")||!t.hasOwnProperty("itemName")||typeof t.originName!="string"&&typeof t.originName!==null||typeof t.itemName!="string"&&typeof t.itemName!==null)}}Mt.InkListItem=a;let e=class st extends Map{constructor(){if(super(arguments[0]instanceof st?arguments[0]:[]),this.origins=null,this._originNames=[],arguments[0]instanceof st){let t=arguments[0],p=t.originNames;p!==null&&(this._originNames=p.slice()),t.origins!==null&&(this.origins=t.origins.slice())}else if(typeof arguments[0]=="string"){let t=arguments[0],p=arguments[1];if(this.SetInitialOriginName(t),p.listDefinitions===null)return(0,o.throwNullException)("originStory.listDefinitions");let r=p.listDefinitions.TryListGetDefinition(t,null);if(r.exists){if(r.result===null)return(0,o.throwNullException)("def.result");this.origins=[r.result]}else throw new Error("InkList origin could not be found in story when constructing new list: "+t)}else if(typeof arguments[0]=="object"&&arguments[0].hasOwnProperty("Key")&&arguments[0].hasOwnProperty("Value")){let t=arguments[0];this.Add(t.Key,t.Value)}}static FromString(t,p){var r;if(t==null||t=="")return new st;let y=(r=p.listDefinitions)===null||r===void 0?void 0:r.FindSingleItemListWithName(t);if(y)return y.value===null?(0,o.throwNullException)("listValue.value"):new st(y.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,p=null){if(t instanceof a){let r=t;if(r.originName==null){this.AddItem(r.itemName);return}if(this.origins===null)return(0,o.throwNullException)("this.origins");for(let y of this.origins)if(y.name==r.originName){let s=y.TryGetValueForItem(r,0);if(s.exists){this.Add(r,s.result);return}else throw new Error("Could not add the item "+r+" to this list because it doesn't exist in the original list definition in ink.")}throw new Error("Failed to add item to list because the item was from a new list definition that wasn't previously known to this list. Only items from previously known lists can be used, so that the int value can be found.")}else if(t!==null){let r=t,y=null;if(this.origins===null)return(0,o.throwNullException)("this.origins");for(let s of this.origins){if(r===null)return(0,o.throwNullException)("itemName");if(s.ContainsItemWithName(r)){if(y!=null)throw new Error("Could not add the item "+r+" to this list because it could come from either "+s.name+" or "+y.name);y=s}}if(y==null){if(p==null)throw new Error("Could not add the item "+r+" to this list because it isn't known to any list definitions previously associated with this list.");{let s=st.FromString(r,p).orderedItems[0];this.Add(s.Key,s.Value)}}else{let s=new a(y.name,r),c=y.ValueForItem(s);this.Add(s,c)}}}ContainsItemNamed(t){for(let[p]of this)if(a.fromSerializedKey(p).itemName==t)return!0;return!1}ContainsKey(t){return this.has(t.serialized())}Add(t,p){let r=t.serialized();if(this.has(r))throw new Error(`The Map already contains an entry for ${t}`);this.set(r,p)}Remove(t){return this.delete(t.serialized())}get Count(){return this.size}get originOfMaxItem(){if(this.origins==null)return null;let t=this.maxItem.Key.originName,p=null;return this.origins.every(r=>r.name==t?(p=r,!1):!0),p}get originNames(){if(this.Count>0){this._originNames==null&&this.Count>0?this._originNames=[]:(this._originNames||(this._originNames=[]),this._originNames.length=0);for(let[t]of this){let p=a.fromSerializedKey(t);if(p.originName===null)return(0,o.throwNullException)("item.originName");this._originNames.push(p.originName)}}return this._originNames}SetInitialOriginName(t){this._originNames=[t]}SetInitialOriginNames(t){t==null?this._originNames=null:this._originNames=t.slice()}get maxItem(){let t={Key:a.Null,Value:0};for(let[p,r]of this){let y=a.fromSerializedKey(p);(t.Key.isNull||r>t.Value)&&(t={Key:y,Value:r})}return t}get minItem(){let t={Key:a.Null,Value:0};for(let[p,r]of this){let y=a.fromSerializedKey(p);(t.Key.isNull||r<t.Value)&&(t={Key:y,Value:r})}return t}get inverse(){let t=new st;if(this.origins!=null)for(let p of this.origins)for(let[r,y]of p.items){let s=a.fromSerializedKey(r);this.ContainsKey(s)||t.Add(s,y)}return t}get all(){let t=new st;if(this.origins!=null)for(let p of this.origins)for(let[r,y]of p.items){let s=a.fromSerializedKey(r);t.set(s.serialized(),y)}return t}Union(t){let p=new st(this);for(let[r,y]of t)p.set(r,y);return p}Intersect(t){let p=new st;for(let[r,y]of this)t.has(r)&&p.set(r,y);return p}HasIntersection(t){for(let[p]of this)if(t.has(p))return!0;return!1}Without(t){let p=new st(this);for(let[r]of t)p.delete(r);return p}Contains(t){if(typeof t=="string")return this.ContainsItemNamed(t);const p=t;if(p.size==0||this.size==0)return!1;for(let[r]of p)if(!this.has(r))return!1;return!0}GreaterThan(t){return this.Count==0?!1:t.Count==0?!0:this.minItem.Value>t.maxItem.Value}GreaterThanOrEquals(t){return this.Count==0?!1:t.Count==0?!0:this.minItem.Value>=t.minItem.Value&&this.maxItem.Value>=t.maxItem.Value}LessThan(t){return t.Count==0?!1:this.Count==0?!0:this.maxItem.Value<t.minItem.Value}LessThanOrEquals(t){return t.Count==0?!1:this.Count==0?!0:this.maxItem.Value<=t.maxItem.Value&&this.minItem.Value<=t.minItem.Value}MaxAsList(){return this.Count>0?new st(this.maxItem):new st}MinAsList(){return this.Count>0?new st(this.minItem):new st}ListWithSubRange(t,p){if(this.Count==0)return new st;let r=this.orderedItems,y=0,s=Number.MAX_SAFE_INTEGER;Number.isInteger(t)?y=t:t instanceof st&&t.Count>0&&(y=t.minItem.Value),Number.isInteger(p)?s=p:p instanceof st&&p.Count>0&&(s=p.maxItem.Value);let c=new st;c.SetInitialOriginNames(this.originNames);for(let i of r)i.Value>=y&&i.Value<=s&&c.Add(i.Key,i.Value);return c}Equals(t){if(!(t instanceof st)||t.Count!=this.Count)return!1;for(let[p]of this)if(!t.has(p))return!1;return!0}get orderedItems(){let t=new Array;for(let[p,r]of this){let y=a.fromSerializedKey(p);t.push({Key:y,Value:r})}return t.sort((p,r)=>p.Key.originName===null?(0,o.throwNullException)("x.Key.originName"):r.Key.originName===null?(0,o.throwNullException)("y.Key.originName"):p.Value==r.Value?p.Key.originName.localeCompare(r.Key.originName):p.Value<r.Value?-1:p.Value>r.Value?1:0),t}get singleItem(){for(let t of this.orderedItems)return t.Key;return null}toString(){let t=this.orderedItems,p=new n.StringBuilder;for(let r=0;r<t.length;r++){r>0&&p.Append(", ");let y=t[r].Key;if(y.itemName===null)return(0,o.throwNullException)("item.itemName");p.Append(y.itemName)}return p.toString()}valueOf(){return NaN}};return Mt.InkList=e,Mt}var ve={},Zi;function si(){if(Zi)return ve;Zi=1,Object.defineProperty(ve,"__esModule",{value:!0}),ve.StoryException=void 0;let o=class extends Error{constructor(a){super(a),this.useEndLineNumber=!1,this.message=a,this.name="StoryException"}};return ve.StoryException=o,ve}var Nt={},Qi;function Gn(){if(Qi)return Nt;Qi=1,Object.defineProperty(Nt,"__esModule",{value:!0}),Nt.tryParseFloat=Nt.tryParseInt=Nt.tryGetValueFromMap=void 0;function o(e,f,t){if(e===null)return{result:t,exists:!1};let p=e.get(f);return typeof p>"u"?{result:t,exists:!1}:{result:p,exists:!0}}Nt.tryGetValueFromMap=o;function n(e,f=0){let t=parseInt(e);return Number.isNaN(t)?{result:f,exists:!1}:{result:t,exists:!0}}Nt.tryParseInt=n;function a(e,f=0){let t=parseFloat(e);return Number.isNaN(t)?{result:f,exists:!1}:{result:t,exists:!0}}return Nt.tryParseFloat=a,Nt}var tr;function it(){if(tr)return tt;tr=1,Object.defineProperty(tt,"__esModule",{value:!0}),tt.ValueType=tt.ListValue=tt.VariablePointerValue=tt.DivertTargetValue=tt.StringValue=tt.FloatValue=tt.IntValue=tt.BoolValue=tt.Value=tt.AbstractValue=void 0;const o=yt(),n=St(),a=vt(),e=si(),f=Z(),t=Gn(),p=ft();class r extends o.InkObject{static Create(w,F){if(F){if(F===O.Int&&Number.isInteger(Number(w)))return new c(Number(w));if(F===O.Float&&!isNaN(w))return new i(Number(w))}if(typeof w=="boolean")return new s(!!w);if(typeof w=="string")return new l(String(w));if(Number.isInteger(Number(w)))return new c(Number(w));if(isNaN(w)){if(w instanceof n.Path)return new S((0,f.asOrThrows)(w,n.Path));if(w instanceof a.InkList)return new N((0,f.asOrThrows)(w,a.InkList))}else return new i(Number(w));return null}Copy(){return(0,f.asOrThrows)(r.Create(this.valueObject),o.InkObject)}BadCastException(w){return new e.StoryException("Can't cast "+this.valueObject+" from "+this.valueType+" to "+w)}}tt.AbstractValue=r;let y=class extends r{constructor(w){super(),this.value=w}get valueObject(){return this.value}toString(){return this.value===null?(0,p.throwNullException)("Value.value"):this.value.toString()}};tt.Value=y;class s extends y{constructor(w){super(w||!1)}get isTruthy(){return!!this.value}get valueType(){return O.Bool}Cast(w){if(this.value===null)return(0,p.throwNullException)("Value.value");if(w==this.valueType)return this;if(w==O.Int)return new c(this.value?1:0);if(w==O.Float)return new i(this.value?1:0);if(w==O.String)return new l(this.value?"true":"false");throw this.BadCastException(w)}toString(){return this.value?"true":"false"}}tt.BoolValue=s;class c extends y{constructor(w){super(w||0)}get isTruthy(){return this.value!=0}get valueType(){return O.Int}Cast(w){if(this.value===null)return(0,p.throwNullException)("Value.value");if(w==this.valueType)return this;if(w==O.Bool)return new s(this.value!==0);if(w==O.Float)return new i(this.value);if(w==O.String)return new l(""+this.value);throw this.BadCastException(w)}}tt.IntValue=c;class i extends y{constructor(w){super(w||0)}get isTruthy(){return this.value!=0}get valueType(){return O.Float}Cast(w){if(this.value===null)return(0,p.throwNullException)("Value.value");if(w==this.valueType)return this;if(w==O.Bool)return new s(this.value!==0);if(w==O.Int)return new c(this.value);if(w==O.String)return new l(""+this.value);throw this.BadCastException(w)}}tt.FloatValue=i;class l extends y{constructor(w){if(super(w||""),this._isNewline=this.value==`
|
|
3
|
-
`,this._isInlineWhitespace=!0,this.value===null)return(0,p.throwNullException)("Value.value");this.value.length>0&&this.value.split("").every(F=>F!=" "&&F!=" "?(this._isInlineWhitespace=!1,!1):!0)}get valueType(){return O.String}get isTruthy(){return this.value===null?(0,p.throwNullException)("Value.value"):this.value.length>0}get isNewline(){return this._isNewline}get isInlineWhitespace(){return this._isInlineWhitespace}get isNonWhitespace(){return!this.isNewline&&!this.isInlineWhitespace}Cast(w){if(w==this.valueType)return this;if(w==O.Int){let F=(0,t.tryParseInt)(this.value);if(F.exists)return new c(F.result);throw this.BadCastException(w)}if(w==O.Float){let F=(0,t.tryParseFloat)(this.value);if(F.exists)return new i(F.result);throw this.BadCastException(w)}throw this.BadCastException(w)}}tt.StringValue=l;class S extends y{constructor(w=null){super(w)}get valueType(){return O.DivertTarget}get targetPath(){return this.value===null?(0,p.throwNullException)("Value.value"):this.value}set targetPath(w){this.value=w}get isTruthy(){throw new Error("Shouldn't be checking the truthiness of a divert target")}Cast(w){if(w==this.valueType)return this;throw this.BadCastException(w)}toString(){return"DivertTargetValue("+this.targetPath+")"}}tt.DivertTargetValue=S;class P extends y{constructor(w,F=-1){super(w),this._contextIndex=F}get contextIndex(){return this._contextIndex}set contextIndex(w){this._contextIndex=w}get variableName(){return this.value===null?(0,p.throwNullException)("Value.value"):this.value}set variableName(w){this.value=w}get valueType(){return O.VariablePointer}get isTruthy(){throw new Error("Shouldn't be checking the truthiness of a variable pointer")}Cast(w){if(w==this.valueType)return this;throw this.BadCastException(w)}toString(){return"VariablePointerValue("+this.variableName+")"}Copy(){return new P(this.variableName,this.contextIndex)}}tt.VariablePointerValue=P;class N extends y{get isTruthy(){return this.value===null?(0,p.throwNullException)("this.value"):this.value.Count>0}get valueType(){return O.List}Cast(w){if(this.value===null)return(0,p.throwNullException)("Value.value");if(w==O.Int){let F=this.value.maxItem;return F.Key.isNull?new c(0):new c(F.Value)}else if(w==O.Float){let F=this.value.maxItem;return F.Key.isNull?new i(0):new i(F.Value)}else if(w==O.String){let F=this.value.maxItem;return F.Key.isNull?new l(""):new l(F.Key.toString())}if(w==this.valueType)return this;throw this.BadCastException(w)}constructor(w,F){super(null),!w&&!F?this.value=new a.InkList:w instanceof a.InkList?this.value=new a.InkList(w):w instanceof a.InkListItem&&typeof F=="number"&&(this.value=new a.InkList({Key:w,Value:F}))}static RetainListOriginsForAssignment(w,F){let k=(0,f.asOrNull)(w,N),m=(0,f.asOrNull)(F,N);if(m&&m.value===null)return(0,p.throwNullException)("newList.value");if(k&&k.value===null)return(0,p.throwNullException)("oldList.value");k&&m&&m.value.Count==0&&m.value.SetInitialOriginNames(k.value.originNames)}}tt.ListValue=N;var O;return(function(I){I[I.Bool=-1]="Bool",I[I.Int=0]="Int",I[I.Float=1]="Float",I[I.List=2]="List",I[I.String=3]="String",I[I.DivertTarget=4]="DivertTarget",I[I.VariablePointer=5]="VariablePointer"})(O||(tt.ValueType=O={})),tt}var
|
|
4
|
-
`,"\\n")),i.Append('"')):i.Append(I.toString())),O!=this.content.length-1&&i.Append(","),!(I instanceof gt)&&I==S&&i.Append(" <---"),i.AppendLine()}let N=new Map;for(let[O,I]of this.namedContent)this.content.indexOf((0,y.asOrThrows)(I,e.InkObject))>=0||N.set(O,I);if(N.size>0){P(),i.AppendLine("-- named: --");for(let[,O]of N)p.Debug.AssertType(O,gt,"Can only print out named Containers"),O.BuildStringOfHierarchy(i,l,S),i.AppendLine()}l--,P(),i.Append("]")}};return Kt.Container=s,(function(c){(function(i){i[i.Start=0]="Start",i[i.Visits=1]="Visits",i[i.Turns=2]="Turns",i[i.CountStartOnly=4]="CountStartOnly"})(c.CountFlags||(c.CountFlags={}))})(s||(Kt.Container=s={})),Kt}var Jt={},ir;function pt(){if(ir)return Jt;ir=1,Object.defineProperty(Jt,"__esModule",{value:!0}),Jt.ControlCommand=void 0;const o=yt();let n=class q extends o.InkObject{get commandType(){return this._commandType}constructor(e=q.CommandType.NotSet){super(),this._commandType=e}Copy(){return new q(this.commandType)}static EvalStart(){return new q(q.CommandType.EvalStart)}static EvalOutput(){return new q(q.CommandType.EvalOutput)}static EvalEnd(){return new q(q.CommandType.EvalEnd)}static Duplicate(){return new q(q.CommandType.Duplicate)}static PopEvaluatedValue(){return new q(q.CommandType.PopEvaluatedValue)}static PopFunction(){return new q(q.CommandType.PopFunction)}static PopTunnel(){return new q(q.CommandType.PopTunnel)}static BeginString(){return new q(q.CommandType.BeginString)}static EndString(){return new q(q.CommandType.EndString)}static NoOp(){return new q(q.CommandType.NoOp)}static ChoiceCount(){return new q(q.CommandType.ChoiceCount)}static Turns(){return new q(q.CommandType.Turns)}static TurnsSince(){return new q(q.CommandType.TurnsSince)}static ReadCount(){return new q(q.CommandType.ReadCount)}static Random(){return new q(q.CommandType.Random)}static SeedRandom(){return new q(q.CommandType.SeedRandom)}static VisitIndex(){return new q(q.CommandType.VisitIndex)}static SequenceShuffleIndex(){return new q(q.CommandType.SequenceShuffleIndex)}static StartThread(){return new q(q.CommandType.StartThread)}static Done(){return new q(q.CommandType.Done)}static End(){return new q(q.CommandType.End)}static ListFromInt(){return new q(q.CommandType.ListFromInt)}static ListRange(){return new q(q.CommandType.ListRange)}static ListRandom(){return new q(q.CommandType.ListRandom)}static BeginTag(){return new q(q.CommandType.BeginTag)}static EndTag(){return new q(q.CommandType.EndTag)}toString(){return"ControlCommand "+this.commandType.toString()}};return Jt.ControlCommand=n,(function(a){(function(e){e[e.NotSet=-1]="NotSet",e[e.EvalStart=0]="EvalStart",e[e.EvalOutput=1]="EvalOutput",e[e.EvalEnd=2]="EvalEnd",e[e.Duplicate=3]="Duplicate",e[e.PopEvaluatedValue=4]="PopEvaluatedValue",e[e.PopFunction=5]="PopFunction",e[e.PopTunnel=6]="PopTunnel",e[e.BeginString=7]="BeginString",e[e.EndString=8]="EndString",e[e.NoOp=9]="NoOp",e[e.ChoiceCount=10]="ChoiceCount",e[e.Turns=11]="Turns",e[e.TurnsSince=12]="TurnsSince",e[e.ReadCount=13]="ReadCount",e[e.Random=14]="Random",e[e.SeedRandom=15]="SeedRandom",e[e.VisitIndex=16]="VisitIndex",e[e.SequenceShuffleIndex=17]="SequenceShuffleIndex",e[e.StartThread=18]="StartThread",e[e.Done=19]="Done",e[e.End=20]="End",e[e.ListFromInt=21]="ListFromInt",e[e.ListRange=22]="ListRange",e[e.ListRandom=23]="ListRandom",e[e.BeginTag=24]="BeginTag",e[e.EndTag=25]="EndTag",e[e.TOTAL_VALUES=26]="TOTAL_VALUES"})(a.CommandType||(a.CommandType={}))})(n||(Jt.ControlCommand=n={})),Jt}var rr;function Ot(){if(rr)return pe;rr=1,Object.defineProperty(pe,"__esModule",{value:!0}),pe.Expression=void 0;const o=ot(),n=pt(),a=et();let e=class extends a.ParsedObject{constructor(){super(...arguments),this._prototypeRuntimeConstantExpression=null,this.outputWhenComplete=!1,this.GenerateRuntimeObject=()=>{const t=new o.Container;return t.AddContent(n.ControlCommand.EvalStart()),this.GenerateIntoContainer(t),this.outputWhenComplete&&t.AddContent(n.ControlCommand.EvalOutput()),t.AddContent(n.ControlCommand.EvalEnd()),t},this.GenerateConstantIntoContainer=t=>{this._prototypeRuntimeConstantExpression===null&&(this._prototypeRuntimeConstantExpression=new o.Container,this.GenerateIntoContainer(this._prototypeRuntimeConstantExpression));for(const p of this._prototypeRuntimeConstantExpression.content){const r=p.Copy();r&&t.AddContent(r)}},this.toString=()=>"No string value in JavaScript."}get typeName(){return"Expression"}Equals(t){return!1}};return pe.Expression=e,pe}var ye={},be={},sr;function te(){if(sr)return be;sr=1,Object.defineProperty(be,"__esModule",{value:!0}),be.Void=void 0;const o=yt();let n=class extends o.InkObject{toString(){return"Void"}};return be.Void=n,be}var ar;function Ft(){if(ar)return ye;ar=1,Object.defineProperty(ye,"__esModule",{value:!0}),ye.NativeFunctionCall=void 0;const o=it(),n=si(),a=te(),e=vt(),f=yt(),t=Z(),p=ft();let r=class Ct extends f.InkObject{static CallWithName(s){return new Ct(s)}static CallExistsWithName(s){return this.GenerateNativeFunctionsIfNecessary(),this._nativeFunctions.get(s)}get name(){return this._name===null?(0,p.throwNullException)("NativeFunctionCall._name"):this._name}set name(s){this._name=s,this._isPrototype||(Ct._nativeFunctions===null?(0,p.throwNullException)("NativeFunctionCall._nativeFunctions"):this._prototype=Ct._nativeFunctions.get(this._name)||null)}get numberOfParameters(){return this._prototype?this._prototype.numberOfParameters:this._numberOfParameters}set numberOfParameters(s){this._numberOfParameters=s}Call(s){if(this._prototype)return this._prototype.Call(s);if(this.numberOfParameters!=s.length)throw new Error("Unexpected number of parameters");let c=!1;for(let S of s){if(S instanceof a.Void)throw new n.StoryException("Attempting to perform "+this.name+' on a void value. Did you forget to "return" a value from a function you called here?');S instanceof o.ListValue&&(c=!0)}if(s.length==2&&c)return this.CallBinaryListOperation(s);let i=this.CoerceValuesToSingleType(s),l=i[0].valueType;return l==o.ValueType.Int?this.CallType(i):l==o.ValueType.Float?this.CallType(i):l==o.ValueType.String?this.CallType(i):l==o.ValueType.DivertTarget?this.CallType(i):l==o.ValueType.List?this.CallType(i):null}CallType(s){let c=(0,t.asOrThrows)(s[0],o.Value),i=c.valueType,l=c,S=s.length;if(S==2||S==1){if(this._operationFuncs===null)return(0,p.throwNullException)("NativeFunctionCall._operationFuncs");let P=this._operationFuncs.get(i);if(!P){const N=o.ValueType[i];throw new n.StoryException("Cannot perform operation "+this.name+" on "+N)}if(S==2){let O=(0,t.asOrThrows)(s[1],o.Value),I=P;if(l.value===null||O.value===null)return(0,p.throwNullException)("NativeFunctionCall.Call BinaryOp values");let w=I(l.value,O.value);return o.Value.Create(w)}else{let N=P;if(l.value===null)return(0,p.throwNullException)("NativeFunctionCall.Call UnaryOp value");let O=N(l.value);return this.name===Ct.Int?o.Value.Create(O,o.ValueType.Int):this.name===Ct.Float?o.Value.Create(O,o.ValueType.Float):o.Value.Create(O,c.valueType)}}else throw new Error("Unexpected number of parameters to NativeFunctionCall: "+s.length)}CallBinaryListOperation(s){if((this.name=="+"||this.name=="-")&&s[0]instanceof o.ListValue&&s[1]instanceof o.IntValue)return this.CallListIncrementOperation(s);let c=(0,t.asOrThrows)(s[0],o.Value),i=(0,t.asOrThrows)(s[1],o.Value);if((this.name=="&&"||this.name=="||")&&(c.valueType!=o.ValueType.List||i.valueType!=o.ValueType.List)){if(this._operationFuncs===null)return(0,p.throwNullException)("NativeFunctionCall._operationFuncs");let l=this._operationFuncs.get(o.ValueType.Int);if(l===null)return(0,p.throwNullException)("NativeFunctionCall.CallBinaryListOperation op");let S=(0,t.asBooleanOrThrows)(l(c.isTruthy?1:0,i.isTruthy?1:0));return new o.BoolValue(S)}if(c.valueType==o.ValueType.List&&i.valueType==o.ValueType.List)return this.CallType([c,i]);throw new n.StoryException("Can not call use "+this.name+" operation on "+o.ValueType[c.valueType]+" and "+o.ValueType[i.valueType])}CallListIncrementOperation(s){let c=(0,t.asOrThrows)(s[0],o.ListValue),i=(0,t.asOrThrows)(s[1],o.IntValue),l=new e.InkList;if(c.value===null)return(0,p.throwNullException)("NativeFunctionCall.CallListIncrementOperation listVal.value");for(let[S,P]of c.value){let N=e.InkListItem.fromSerializedKey(S);if(this._operationFuncs===null)return(0,p.throwNullException)("NativeFunctionCall._operationFuncs");let O=this._operationFuncs.get(o.ValueType.Int);if(i.value===null)return(0,p.throwNullException)("NativeFunctionCall.CallListIncrementOperation intVal.value");let I=O(P,i.value),w=null;if(c.value.origins===null)return(0,p.throwNullException)("NativeFunctionCall.CallListIncrementOperation listVal.value.origins");for(let F of c.value.origins)if(F.name==N.originName){w=F;break}if(w!=null){let F=w.TryGetItemWithValue(I,e.InkListItem.Null);F.exists&&l.Add(F.result,I)}}return new o.ListValue(l)}CoerceValuesToSingleType(s){let c=o.ValueType.Int,i=null;for(let S of s){let P=(0,t.asOrThrows)(S,o.Value);P.valueType>c&&(c=P.valueType),P.valueType==o.ValueType.List&&(i=(0,t.asOrNull)(P,o.ListValue))}let l=[];if(o.ValueType[c]==o.ValueType[o.ValueType.List])for(let S of s){let P=(0,t.asOrThrows)(S,o.Value);if(P.valueType==o.ValueType.List)l.push(P);else if(P.valueType==o.ValueType.Int){let N=parseInt(P.valueObject);if(i=(0,t.asOrThrows)(i,o.ListValue),i.value===null)return(0,p.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType specialCaseList.value");let O=i.value.originOfMaxItem;if(O===null)return(0,p.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType list");let I=O.TryGetItemWithValue(N,e.InkListItem.Null);if(I.exists){let w=new o.ListValue(I.result,N);l.push(w)}else throw new n.StoryException("Could not find List item with the value "+N+" in "+O.name)}else{const N=o.ValueType[P.valueType];throw new n.StoryException("Cannot mix Lists and "+N+" values in this operation")}}else for(let S of s){let N=(0,t.asOrThrows)(S,o.Value).Cast(c);l.push(N)}return l}constructor(){if(super(),this._name=null,this._numberOfParameters=0,this._prototype=null,this._isPrototype=!1,this._operationFuncs=null,arguments.length===0)Ct.GenerateNativeFunctionsIfNecessary();else if(arguments.length===1){let s=arguments[0];Ct.GenerateNativeFunctionsIfNecessary(),this.name=s}else if(arguments.length===2){let s=arguments[0],c=arguments[1];this._isPrototype=!0,this.name=s,this.numberOfParameters=c}}static Identity(s){return s}static GenerateNativeFunctionsIfNecessary(){if(this._nativeFunctions==null){this._nativeFunctions=new Map,this.AddIntBinaryOp(this.Add,(i,l)=>i+l),this.AddIntBinaryOp(this.Subtract,(i,l)=>i-l),this.AddIntBinaryOp(this.Multiply,(i,l)=>i*l),this.AddIntBinaryOp(this.Divide,(i,l)=>Math.floor(i/l)),this.AddIntBinaryOp(this.Mod,(i,l)=>i%l),this.AddIntUnaryOp(this.Negate,i=>-i),this.AddIntBinaryOp(this.Equal,(i,l)=>i==l),this.AddIntBinaryOp(this.Greater,(i,l)=>i>l),this.AddIntBinaryOp(this.Less,(i,l)=>i<l),this.AddIntBinaryOp(this.GreaterThanOrEquals,(i,l)=>i>=l),this.AddIntBinaryOp(this.LessThanOrEquals,(i,l)=>i<=l),this.AddIntBinaryOp(this.NotEquals,(i,l)=>i!=l),this.AddIntUnaryOp(this.Not,i=>i==0),this.AddIntBinaryOp(this.And,(i,l)=>i!=0&&l!=0),this.AddIntBinaryOp(this.Or,(i,l)=>i!=0||l!=0),this.AddIntBinaryOp(this.Max,(i,l)=>Math.max(i,l)),this.AddIntBinaryOp(this.Min,(i,l)=>Math.min(i,l)),this.AddIntBinaryOp(this.Pow,(i,l)=>Math.pow(i,l)),this.AddIntUnaryOp(this.Floor,Ct.Identity),this.AddIntUnaryOp(this.Ceiling,Ct.Identity),this.AddIntUnaryOp(this.Int,Ct.Identity),this.AddIntUnaryOp(this.Float,i=>i),this.AddFloatBinaryOp(this.Add,(i,l)=>i+l),this.AddFloatBinaryOp(this.Subtract,(i,l)=>i-l),this.AddFloatBinaryOp(this.Multiply,(i,l)=>i*l),this.AddFloatBinaryOp(this.Divide,(i,l)=>i/l),this.AddFloatBinaryOp(this.Mod,(i,l)=>i%l),this.AddFloatUnaryOp(this.Negate,i=>-i),this.AddFloatBinaryOp(this.Equal,(i,l)=>i==l),this.AddFloatBinaryOp(this.Greater,(i,l)=>i>l),this.AddFloatBinaryOp(this.Less,(i,l)=>i<l),this.AddFloatBinaryOp(this.GreaterThanOrEquals,(i,l)=>i>=l),this.AddFloatBinaryOp(this.LessThanOrEquals,(i,l)=>i<=l),this.AddFloatBinaryOp(this.NotEquals,(i,l)=>i!=l),this.AddFloatUnaryOp(this.Not,i=>i==0),this.AddFloatBinaryOp(this.And,(i,l)=>i!=0&&l!=0),this.AddFloatBinaryOp(this.Or,(i,l)=>i!=0||l!=0),this.AddFloatBinaryOp(this.Max,(i,l)=>Math.max(i,l)),this.AddFloatBinaryOp(this.Min,(i,l)=>Math.min(i,l)),this.AddFloatBinaryOp(this.Pow,(i,l)=>Math.pow(i,l)),this.AddFloatUnaryOp(this.Floor,i=>Math.floor(i)),this.AddFloatUnaryOp(this.Ceiling,i=>Math.ceil(i)),this.AddFloatUnaryOp(this.Int,i=>Math.floor(i)),this.AddFloatUnaryOp(this.Float,Ct.Identity),this.AddStringBinaryOp(this.Add,(i,l)=>i+l),this.AddStringBinaryOp(this.Equal,(i,l)=>i===l),this.AddStringBinaryOp(this.NotEquals,(i,l)=>i!==l),this.AddStringBinaryOp(this.Has,(i,l)=>i.includes(l)),this.AddStringBinaryOp(this.Hasnt,(i,l)=>!i.includes(l)),this.AddListBinaryOp(this.Add,(i,l)=>i.Union(l)),this.AddListBinaryOp(this.Subtract,(i,l)=>i.Without(l)),this.AddListBinaryOp(this.Has,(i,l)=>i.Contains(l)),this.AddListBinaryOp(this.Hasnt,(i,l)=>!i.Contains(l)),this.AddListBinaryOp(this.Intersect,(i,l)=>i.Intersect(l)),this.AddListBinaryOp(this.Equal,(i,l)=>i.Equals(l)),this.AddListBinaryOp(this.Greater,(i,l)=>i.GreaterThan(l)),this.AddListBinaryOp(this.Less,(i,l)=>i.LessThan(l)),this.AddListBinaryOp(this.GreaterThanOrEquals,(i,l)=>i.GreaterThanOrEquals(l)),this.AddListBinaryOp(this.LessThanOrEquals,(i,l)=>i.LessThanOrEquals(l)),this.AddListBinaryOp(this.NotEquals,(i,l)=>!i.Equals(l)),this.AddListBinaryOp(this.And,(i,l)=>i.Count>0&&l.Count>0),this.AddListBinaryOp(this.Or,(i,l)=>i.Count>0||l.Count>0),this.AddListUnaryOp(this.Not,i=>i.Count==0?1:0),this.AddListUnaryOp(this.Invert,i=>i.inverse),this.AddListUnaryOp(this.All,i=>i.all),this.AddListUnaryOp(this.ListMin,i=>i.MinAsList()),this.AddListUnaryOp(this.ListMax,i=>i.MaxAsList()),this.AddListUnaryOp(this.Count,i=>i.Count),this.AddListUnaryOp(this.ValueOfList,i=>i.maxItem.Value);let s=(i,l)=>i.Equals(l),c=(i,l)=>!i.Equals(l);this.AddOpToNativeFunc(this.Equal,2,o.ValueType.DivertTarget,s),this.AddOpToNativeFunc(this.NotEquals,2,o.ValueType.DivertTarget,c)}}AddOpFuncForType(s,c){this._operationFuncs==null&&(this._operationFuncs=new Map),this._operationFuncs.set(s,c)}static AddOpToNativeFunc(s,c,i,l){if(this._nativeFunctions===null)return(0,p.throwNullException)("NativeFunctionCall._nativeFunctions");let S=this._nativeFunctions.get(s);S||(S=new Ct(s,c),this._nativeFunctions.set(s,S)),S.AddOpFuncForType(i,l)}static AddIntBinaryOp(s,c){this.AddOpToNativeFunc(s,2,o.ValueType.Int,c)}static AddIntUnaryOp(s,c){this.AddOpToNativeFunc(s,1,o.ValueType.Int,c)}static AddFloatBinaryOp(s,c){this.AddOpToNativeFunc(s,2,o.ValueType.Float,c)}static AddFloatUnaryOp(s,c){this.AddOpToNativeFunc(s,1,o.ValueType.Float,c)}static AddStringBinaryOp(s,c){this.AddOpToNativeFunc(s,2,o.ValueType.String,c)}static AddListBinaryOp(s,c){this.AddOpToNativeFunc(s,2,o.ValueType.List,c)}static AddListUnaryOp(s,c){this.AddOpToNativeFunc(s,1,o.ValueType.List,c)}toString(){return'Native "'+this.name+'"'}};return ye.NativeFunctionCall=r,r.Add="+",r.Subtract="-",r.Divide="/",r.Multiply="*",r.Mod="%",r.Negate="_",r.Equal="==",r.Greater=">",r.Less="<",r.GreaterThanOrEquals=">=",r.LessThanOrEquals="<=",r.NotEquals="!=",r.Not="!",r.And="&&",r.Or="||",r.Min="MIN",r.Max="MAX",r.Pow="POW",r.Floor="FLOOR",r.Ceiling="CEILING",r.Int="INT",r.Float="FLOAT",r.Has="?",r.Hasnt="!?",r.Intersect="^",r.ListMin="LIST_MIN",r.ListMax="LIST_MAX",r.All="LIST_ALL",r.Count="LIST_COUNT",r.ValueOfList="LIST_VALUE",r.Invert="LIST_INVERT",r._nativeFunctions=null,ye}var _e={},Ee={},or;function Ti(){if(or)return Ee;or=1,Object.defineProperty(Ee,"__esModule",{value:!0}),Ee.NumberExpression=void 0;const o=Ot(),n=it(),a=Z();let e=class Ms extends o.Expression{constructor(t,p){if(super(),this.isInt=()=>this.subtype=="int",this.isFloat=()=>this.subtype=="float",this.isBool=()=>this.subtype=="bool",this.GenerateIntoContainer=r=>{this.isInt()?r.AddContent(new n.IntValue(this.value)):this.isFloat()?r.AddContent(new n.FloatValue(this.value)):this.isBool()&&r.AddContent(new n.BoolValue(this.value))},this.toString=()=>String(this.value),typeof t=="number"&&!Number.isNaN(t)||typeof t=="boolean")this.value=t,this.subtype=p;else throw new Error("Unexpected object type in NumberExpression.")}get typeName(){return"Number"}Equals(t){const p=(0,a.asOrNull)(t,Ms);return p?p.subtype==this.subtype&&p.value==this.value:!1}};return Ee.NumberExpression=e,Ee}var lr;function Bs(){if(lr)return _e;lr=1,Object.defineProperty(_e,"__esModule",{value:!0}),_e.UnaryExpression=void 0;const o=Ot(),n=Ft(),a=Ti(),e=Z();let f=class extends o.Expression{get nativeNameForOp(){return this.op==="-"?"_":this.op==="not"?"!":this.op}constructor(p,r){super(),this.op=r,this.GenerateIntoContainer=y=>{this.innerExpression.GenerateIntoContainer(y),y.AddContent(n.NativeFunctionCall.CallWithName(this.nativeNameForOp))},this.toString=()=>this.nativeNameForOp+this.innerExpression,this.innerExpression=this.AddContent(p)}get typeName(){return"UnaryExpression"}};return _e.UnaryExpression=f,f.WithInner=(t,p)=>{const r=(0,e.asOrNull)(t,a.NumberExpression);if(r){if(p==="-"){if(r.isInt())return new a.NumberExpression(-r.value,"int");if(r.isFloat())return new a.NumberExpression(-r.value,"float")}else if(p=="!"||p=="not"){if(r.isInt())return new a.NumberExpression(r.value==0,"bool");if(r.isFloat())return new a.NumberExpression(r.value==0,"bool");if(r.isBool())return new a.NumberExpression(!r.value,"bool")}throw new Error("Unexpected operation or number type")}return new f(t,p)},_e}var ur;function qs(){if(ur)return fe;ur=1,Object.defineProperty(fe,"__esModule",{value:!0}),fe.BinaryExpression=void 0;const o=Ot(),n=Ft(),a=Bs(),e=Z();let f=class extends o.Expression{constructor(p,r,y){super(),this.opName=y,this.GenerateIntoContainer=s=>{this.leftExpression.GenerateIntoContainer(s),this.rightExpression.GenerateIntoContainer(s),this.opName=this.NativeNameForOp(this.opName),s.AddContent(n.NativeFunctionCall.CallWithName(this.opName))},this.NativeNameForOp=s=>s==="and"?"&&":s==="or"?"||":s==="mod"?"%":s==="has"?"?":s==="hasnt"?"!?":s,this.toString=()=>`(${this.leftExpression} ${this.opName} ${this.rightExpression})`,this.leftExpression=this.AddContent(p),this.rightExpression=this.AddContent(r),this.opName=y}get typeName(){return"BinaryExpression"}ResolveReferences(p){if(super.ResolveReferences(p),this.NativeNameForOp(this.opName)==="?"){const r=(0,e.asOrNull)(this.leftExpression,a.UnaryExpression);r!==null&&(r.op==="not"||r.op==="!")&&this.Error(`Using 'not' or '!' here negates '${r.innerExpression}' rather than the result of the '?' or 'has' operator. You need to add parentheses around the (A ? B) expression.`)}}};return fe.BinaryExpression=f,fe}var we={},Pe={},hr;function ai(){if(hr)return Pe;hr=1,Object.defineProperty(Pe,"__esModule",{value:!0}),Pe.CharacterSet=void 0;let o=class{constructor(a){this.set=new Set,this.Add=e=>this.set.add(e),this.AddRange=(e,f)=>{for(let t=e.charCodeAt(0);t<=f.charCodeAt(0);++t)this.Add(String.fromCharCode(t));return this},this.AddCharacters=e=>{if(typeof e=="string"||Array.isArray(e))for(const f of e)this.Add(f);else for(const f of e.set)this.Add(f);return this},a&&this.AddCharacters(a)}};return Pe.CharacterSet=o,o.FromRange=(n,a)=>new o().AddRange(n,a),Pe}var cr;function Pa(){if(cr)return we;cr=1,Object.defineProperty(we,"__esModule",{value:!0}),we.CharacterRange=void 0;const o=ai();let n=class{constructor(e,f,t=[]){if(this._start=e,this._end=f,this._correspondingCharSet=new o.CharacterSet,this._excludes=new Set,this.ToCharacterSet=()=>{if(this._correspondingCharSet.set.size===0)for(let p=this.start.charCodeAt(0),r;p<=this.end.charCodeAt(0);p+=1)r=String.fromCharCode(p),this._excludes.has(r)||this._correspondingCharSet.AddCharacters(r);return this._correspondingCharSet},t instanceof o.CharacterSet)this._excludes=t.set;else for(const p of t)this._excludes.add(p)}get start(){return this._start}get end(){return this._end}};return we.CharacterRange=n,n.Define=(a,e,f=[])=>new n(a,e,f),we}var Oe={},xe={},dr;function Ni(){if(dr)return xe;dr=1,Object.defineProperty(xe,"__esModule",{value:!0}),xe.ChoicePoint=void 0;const o=yt(),n=St(),a=ft();let e=class extends o.InkObject{constructor(t=!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(this._pathOnChoice!=null&&this._pathOnChoice.isRelative){let t=this.choiceTarget;t&&(this._pathOnChoice=t.path)}return this._pathOnChoice}set pathOnChoice(t){this._pathOnChoice=t}get choiceTarget(){return this._pathOnChoice===null?(0,a.throwNullException)("ChoicePoint._pathOnChoice"):this.ResolvePath(this._pathOnChoice).container}get pathStringOnChoice(){return this.pathOnChoice===null?(0,a.throwNullException)("ChoicePoint.pathOnChoice"):this.CompactPathString(this.pathOnChoice)}set pathStringOnChoice(t){this.pathOnChoice=new n.Path(t)}get flags(){let t=0;return this.hasCondition&&(t|=1),this.hasStartContent&&(t|=2),this.hasChoiceOnlyContent&&(t|=4),this.isInvisibleDefault&&(t|=8),this.onceOnly&&(t|=16),t}set flags(t){this.hasCondition=(t&1)>0,this.hasStartContent=(t&2)>0,this.hasChoiceOnlyContent=(t&4)>0,this.isInvisibleDefault=(t&8)>0,this.onceOnly=(t&16)>0}toString(){return this.pathOnChoice===null?(0,a.throwNullException)("ChoicePoint.pathOnChoice"):"Choice: -> "+this.pathOnChoice.toString()}};return xe.ChoicePoint=e,xe}var Te={},Ne={},fr;function ee(){if(fr)return Ne;fr=1,Object.defineProperty(Ne,"__esModule",{value:!0}),Ne.PushPopType=void 0;var o;return(function(n){n[n.Tunnel=0]="Tunnel",n[n.Function=1]="Function",n[n.FunctionEvaluationFromGame=2]="FunctionEvaluationFromGame"})(o||(Ne.PushPopType=o={})),Ne}var Ie={},pr;function oi(){if(pr)return Ie;pr=1,Object.defineProperty(Ie,"__esModule",{value:!0}),Ie.Pointer=void 0;const o=St();let n=class Yn{constructor(){this.container=null,this.index=-1,arguments.length===2&&(this.container=arguments[0],this.index=arguments[1])}Resolve(){return this.index<0?this.container:this.container==null?null:this.container.content.length==0?this.container:this.index>=this.container.content.length?null:this.container.content[this.index]}get isNull(){return this.container==null}get path(){return this.isNull?null:this.index>=0?this.container.path.PathByAppendingComponent(new o.Path.Component(this.index)):this.container.path}toString(){return this.container?"Ink Pointer -> "+this.container.path.toString()+" -- index "+this.index:"Ink Pointer (null)"}copy(){return new Yn(this.container,this.index)}static StartOf(e){return new Yn(e,0)}static get Null(){return new Yn(null,-1)}};return Ie.Pointer=n,Ie}var mr;function Rt(){if(mr)return Te;mr=1,Object.defineProperty(Te,"__esModule",{value:!0}),Te.Divert=void 0;const o=St(),n=ee(),a=Qt(),e=yt(),f=oi(),t=ot(),p=ft();class r extends e.InkObject{get targetPath(){if(this._targetPath!=null&&this._targetPath.isRelative){let s=this.targetPointer.Resolve();s&&(this._targetPath=s.path)}return this._targetPath}set targetPath(s){this._targetPath=s,this._targetPointer=f.Pointer.Null}get targetPointer(){if(this._targetPointer.isNull){let s=this.ResolvePath(this._targetPath).obj;if(this._targetPath===null)return(0,p.throwNullException)("this._targetPath");if(this._targetPath.lastComponent===null)return(0,p.throwNullException)("this._targetPath.lastComponent");if(this._targetPath.lastComponent.isIndex){if(s===null)return(0,p.throwNullException)("targetObj");this._targetPointer.container=s.parent instanceof t.Container?s.parent:null,this._targetPointer.index=this._targetPath.lastComponent.index}else this._targetPointer=f.Pointer.StartOf(s instanceof t.Container?s:null)}return this._targetPointer.copy()}get targetPathString(){return this.targetPath==null?null:this.CompactPathString(this.targetPath)}set targetPathString(s){s==null?this.targetPath=null:this.targetPath=new o.Path(s)}get hasVariableTarget(){return this.variableDivertName!=null}constructor(s){super(),this._targetPath=null,this._targetPointer=f.Pointer.Null,this.variableDivertName=null,this.pushesToStack=!1,this.stackPushType=0,this.isExternal=!1,this.externalArgs=0,this.isConditional=!1,this.pushesToStack=!1,typeof s<"u"&&(this.pushesToStack=!0,this.stackPushType=s)}Equals(s){let c=s;return c instanceof r&&this.hasVariableTarget==c.hasVariableTarget?this.hasVariableTarget?this.variableDivertName==c.variableDivertName:this.targetPath===null?(0,p.throwNullException)("this.targetPath"):this.targetPath.Equals(c.targetPath):!1}toString(){if(this.hasVariableTarget)return"Divert(variable: "+this.variableDivertName+")";if(this.targetPath==null)return"Divert(null)";{let s=new a.StringBuilder,c=this.targetPath.toString();return s.Append("Divert"),this.isConditional&&s.Append("?"),this.pushesToStack&&(this.stackPushType==n.PushPopType.Function?s.Append(" function"):s.Append(" tunnel")),s.Append(" -> "),s.Append(this.targetPathString),s.Append(" ("),s.Append(c),s.Append(")"),s.toString()}}}return Te.Divert=r,Te}var Ae={},gr;function Wt(){if(gr)return Ae;gr=1,Object.defineProperty(Ae,"__esModule",{value:!0}),Ae.SymbolType=void 0;var o;return(function(n){n[n.Knot=0]="Knot",n[n.List=1]="List",n[n.ListItem=2]="ListItem",n[n.Var=3]="Var",n[n.SubFlowAndWeave=4]="SubFlowAndWeave",n[n.Arg=5]="Arg",n[n.Temp=6]="Temp"})(o||(Ae.SymbolType=o={})),Ae}var Fe={},Cr;function Gt(){if(Cr)return Fe;Cr=1,Object.defineProperty(Fe,"__esModule",{value:!0}),Fe.VariableAssignment=void 0;const o=yt();class n extends o.InkObject{constructor(e,f){super(),this.variableName=e||null,this.isNewDeclaration=!!f,this.isGlobal=!1}toString(){return"VarAssign to "+this.variableName}}return Fe.VariableAssignment=n,Fe}var vr;function $n(){if(vr)return Oe;vr=1,Object.defineProperty(Oe,"__esModule",{value:!0}),Oe.Choice=void 0;const o=Ni(),n=ot(),a=pt(),e=Rt(),f=it(),t=et(),p=Wt(),r=Gt();class y extends t.ParsedObject{get runtimeChoice(){if(!this._runtimeChoice)throw new Error;return this._runtimeChoice}get name(){var c;return((c=this.identifier)===null||c===void 0?void 0:c.name)||null}get condition(){return this._condition}set condition(c){this._condition=c,c&&this.AddContent(c)}get runtimeContainer(){return this._innerContentContainer}get innerContentContainer(){return this._innerContentContainer}get containerForCounting(){return this._innerContentContainer}get runtimePath(){if(!this.innerContentContainer||!this.innerContentContainer.path)throw new Error;return this.innerContentContainer.path}constructor(c,i,l){super(),this._condition=null,this._innerContentContainer=null,this._outerContainer=null,this._runtimeChoice=null,this._returnToR1=null,this._returnToR2=null,this._r1Label=null,this._r2Label=null,this._divertToStartContentOuter=null,this._divertToStartContentInner=null,this._startContentRuntimeContainer=null,this.isInvisibleDefault=!1,this.hasWeaveStyleInlineBrackets=!1,this.GenerateRuntimeObject=()=>{if(this._outerContainer=new n.Container,this._runtimeChoice=new o.ChoicePoint(this.onceOnly),this._runtimeChoice.isInvisibleDefault=this.isInvisibleDefault,(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(a.ControlCommand.EvalStart()),this.startContent){this._returnToR1=new f.DivertTargetValue,this._outerContainer.AddContent(this._returnToR1);const S=new r.VariableAssignment("$r",!0);this._outerContainer.AddContent(S),this._outerContainer.AddContent(a.ControlCommand.BeginString()),this._divertToStartContentOuter=new e.Divert,this._outerContainer.AddContent(this._divertToStartContentOuter),this._startContentRuntimeContainer=this.startContent.GenerateRuntimeObject(),this._startContentRuntimeContainer.name="s";const P=new e.Divert;P.variableDivertName="$r",this._startContentRuntimeContainer.AddContent(P),this._outerContainer.AddToNamedContentOnly(this._startContentRuntimeContainer),this._r1Label=new n.Container,this._r1Label.name="$r1",this._outerContainer.AddContent(this._r1Label),this._outerContainer.AddContent(a.ControlCommand.EndString()),this._runtimeChoice.hasStartContent=!0}if(this.choiceOnlyContent){this._outerContainer.AddContent(a.ControlCommand.BeginString());const S=this.choiceOnlyContent.GenerateRuntimeObject();this._outerContainer.AddContentsOfContainer(S),this._outerContainer.AddContent(a.ControlCommand.EndString()),this._runtimeChoice.hasChoiceOnlyContent=!0}if(this.condition&&(this.condition.GenerateIntoContainer(this._outerContainer),this._runtimeChoice.hasCondition=!0),(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(a.ControlCommand.EvalEnd()),this._outerContainer.AddContent(this._runtimeChoice),this._innerContentContainer=new n.Container,this.startContent){this._returnToR2=new f.DivertTargetValue,this._innerContentContainer.AddContent(a.ControlCommand.EvalStart()),this._innerContentContainer.AddContent(this._returnToR2),this._innerContentContainer.AddContent(a.ControlCommand.EvalEnd());const S=new r.VariableAssignment("$r",!0);this._innerContentContainer.AddContent(S),this._divertToStartContentInner=new e.Divert,this._innerContentContainer.AddContent(this._divertToStartContentInner),this._r2Label=new n.Container,this._r2Label.name="$r2",this._innerContentContainer.AddContent(this._r2Label)}if(this.innerContent){const S=this.innerContent.GenerateRuntimeObject();this._innerContentContainer.AddContentsOfContainer(S)}return this.story.countAllVisits&&(this._innerContentContainer.visitsShouldBeCounted=!0),this._innerContentContainer.countingAtStartOnly=!0,this._outerContainer},this.toString=()=>this.choiceOnlyContent!==null?`* ${this.startContent}[${this.choiceOnlyContent}]...`:`* ${this.startContent}...`,this.startContent=c,this.choiceOnlyContent=i,this.innerContent=l,this.indentationDepth=1,c&&this.AddContent(this.startContent),i&&this.AddContent(this.choiceOnlyContent),l&&this.AddContent(this.innerContent),this.onceOnly=!0}get typeName(){return"Choice"}ResolveReferences(c){var i;if(this._innerContentContainer&&(this.runtimeChoice.pathOnChoice=this._innerContentContainer.path,this.onceOnly&&(this._innerContentContainer.visitsShouldBeCounted=!0)),this._returnToR1){if(!this._r1Label)throw new Error;this._returnToR1.targetPath=this._r1Label.path}if(this._returnToR2){if(!this._r2Label)throw new Error;this._returnToR2.targetPath=this._r2Label.path}if(this._divertToStartContentOuter){if(!this._startContentRuntimeContainer)throw new Error;this._divertToStartContentOuter.targetPath=this._startContentRuntimeContainer.path}if(this._divertToStartContentInner){if(!this._startContentRuntimeContainer)throw new Error;this._divertToStartContentInner.targetPath=this._startContentRuntimeContainer.path}super.ResolveReferences(c),this.identifier&&(((i=this.identifier)===null||i===void 0?void 0:i.name)||"").length>0&&c.CheckForNamingCollisions(this,this.identifier,p.SymbolType.SubFlowAndWeave)}}return Oe.Choice=y,Oe}var Re={},mi={},ke={},De={},Sr;function Oa(){if(Sr)return De;Sr=1,Object.defineProperty(De,"__esModule",{value:!0}),De.StringParserElement=void 0;let o=class Si{constructor(){this.characterIndex=0,this.characterInLineIndex=0,this.lineIndex=0,this.reportedErrorInScope=!1,this.uniqueId=0,this.customFlags=0,this.CopyFrom=a=>{Si._uniqueIdCounter++,this.uniqueId=Si._uniqueIdCounter,this.characterIndex=a.characterIndex,this.characterInLineIndex=a.characterInLineIndex,this.lineIndex=a.lineIndex,this.customFlags=a.customFlags,this.reportedErrorInScope=!1},this.SquashFrom=a=>{this.characterIndex=a.characterIndex,this.characterInLineIndex=a.characterInLineIndex,this.lineIndex=a.lineIndex,this.reportedErrorInScope=a.reportedErrorInScope,this.customFlags=a.customFlags}}};return De.StringParserElement=o,o._uniqueIdCounter=1e3,De}var yr;function xa(){if(yr)return ke;yr=1,Object.defineProperty(ke,"__esModule",{value:!0}),ke.StringParserState=void 0;const o=Oa();let n=class{get currentElement(){return this._stack[this._numElements-1]}get lineIndex(){return this.currentElement.lineIndex}set lineIndex(e){this.currentElement.lineIndex=e}get characterIndex(){return this.currentElement.characterIndex}set characterIndex(e){this.currentElement.characterIndex=e}get characterInLineIndex(){return this.currentElement.characterInLineIndex}set characterInLineIndex(e){this.currentElement.characterInLineIndex=e}get customFlags(){return this.currentElement.customFlags}set customFlags(e){this.currentElement.customFlags=e}get errorReportedAlreadyInScope(){return this.currentElement.reportedErrorInScope}get stackHeight(){return this._numElements}constructor(){this._stack=[],this._numElements=0,this.StringParserState=()=>{this._stack=new Array(200);for(let t=0;t<200;++t)this._stack[t]=new o.StringParserElement;this._numElements=1},this.Push=()=>{if(this._numElements>=this._stack.length&&this._numElements>0)throw new Error("Stack overflow in parser state.");const f=this._stack[this._numElements-1],t=this._stack[this._numElements];return this._numElements++,t.CopyFrom(f),t.uniqueId},this.Pop=f=>{if(this._numElements==1)throw new Error("Attempting to remove final stack element is illegal! Mismatched Begin/Succceed/Fail?");if(this.currentElement.uniqueId!=f)throw new Error("Mismatched rule IDs while Poping - do you have mismatched Begin/Succeed/Fail?");this._numElements-=1},this.Peek=f=>{if(this.currentElement.uniqueId!=f)throw new Error("Mismatched rule IDs while Peeking - do you have mismatched Begin/Succeed/Fail?");return this._stack[this._numElements-1]},this.PeekPenultimate=()=>this._numElements>=2?this._stack[this._numElements-2]:null,this.Squash=()=>{if(this._numElements<2)throw new Error("Attempting to remove final stack element is illegal! Mismatched Begin/Succceed/Fail?");const f=this._stack[this._numElements-2],t=this._stack[this._numElements-1];f.SquashFrom(t),this._numElements-=1},this.NoteErrorReported=()=>{for(const f of this._stack)f.reportedErrorInScope=!0};const e=200;for(let f=0;f<e;f++)this._stack[f]=new o.StringParserElement;this._numElements=1}};return ke.StringParserState=n,ke}var br;function Gs(){return br||(br=1,(function(o){Object.defineProperty(o,"__esModule",{value:!0}),o.StringParser=o.ParseSuccess=void 0;const n=ai(),a=xa();o.ParseSuccess=Symbol("ParseSuccessStruct");class e{constructor(t){this.ParseRule=null,this.errorHandler=null,this.hadError=!1,this.BeginRule=()=>this.state.Push(),this.FailRule=r=>(this.state.Pop(r),null),this.CancelRule=r=>{this.state.Pop(r)},this.SucceedRule=(r,y=null)=>{const s=this.state.Peek(r),c=this.state.PeekPenultimate();this.RuleDidSucceed&&this.RuleDidSucceed(y,c,s),this.state.Squash();let i=y;return i===null&&(i=e.ParseSuccess),i},this.Expect=(r,y=null,s=null)=>{let c=this.ParseObject(r);if(c===null){y===null&&(y=r.name);let i;const l=this.LineRemainder();l===null||l.length===0?i="end of line":i=`'${l}'`,this.Error(`Expected ${y} but saw ${i}`),s!==null&&(c=s())}return c},this.Error=(r,y=!1)=>{this.ErrorOnLine(r,this.lineIndex+1,y)},this.ErrorWithParsedObject=(r,y,s=!1)=>{this.ErrorOnLine(r,y.debugMetadata?y.debugMetadata.startLineNumber:-1,s)},this.ErrorOnLine=(r,y,s)=>{if(!this.state.errorReportedAlreadyInScope){const c=s?"Warning":"Error";if(this.errorHandler)this.errorHandler(r,this.index,y-1,s);else throw new Error(`${c} on line ${y}: ${r}`);this.state.NoteErrorReported()}s||(this.hadError=!0)},this.Warning=r=>this.Error(r,!0),this.LineRemainder=()=>this.Peek(()=>this.ParseUntilCharactersFromString(`
|
|
1
|
+
"use strict";var ma=Object.defineProperty;var ga=(o,n,a)=>n in o?ma(o,n,{enumerable:!0,configurable:!0,writable:!0,value:a}):o[n]=a;var z=(o,n,a)=>ga(o,typeof n!="symbol"?n+"":n,a);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const wi=require("zustand"),Li=require("inkjs/engine/Story"),ii=o=>{let n=o;return n.use=new Proxy({},{get:(a,e)=>()=>n(f=>f[e])}),n},Ca=wi.create(o=>({contents:[],setContents:n=>o({contents:n}),add:n=>{o(a=>({contents:[...a.contents,...n]}))},clear:()=>o({contents:[]})})),Mn=ii(Ca),ks="\0ink-divider\0",va={debug:!1,linedelay:.05};class Ds{constructor(n){z(this,"basePath");this.basePath=(n==null?void 0:n.basePath)||""}resolveFilename(n){return this.basePath?this.basePath+"/"+n:n}loadFile(n){throw new Error("loadFile must be implemented by subclass")}}let Vs=class{constructor(n,a,e="default"){z(this,"text");z(this,"index");z(this,"type");z(this,"val");this.text=n||"",this.index=a,this.type=e}};const It=class It{static get functions(){return It._functions}static clear(){for(const[n,a]of this._functions.entries())this.excludeKeys.has(n)||this._functions.delete(n)}static add(n,a){It.functions.set(n,a)}};z(It,"_functions",new Map),z(It,"excludeKeys",new Set(["clear","restart"])),z(It,"process",(n,a)=>{var f;const e=Pi(a,":");if(e)if(It.functions.has(e.before))(f=It.functions.get(e.before))==null||f(e.after,n);else{const t=n.options;if(t[e.before]!=null){let p=e.after;switch(typeof t[e.before]){case"string":break;case"number":typeof p=="string"?p=parseFloat(p):p=void 0;break;case"boolean":p=!!p;break;default:p=void 0}p!==void 0&&!Number.isNaN(p)&&(t[e.before]=p)}}});let Yt=It;const Pi=(o,n)=>{if(!o)return;let a=o.indexOf(n);return a==-1?{before:o.trim().toLowerCase()}:{before:o.slice(0,a).trim().toLowerCase(),after:o.slice(a+1).trim()}};Yt.add("clear",(o,n)=>{n.clear()});Yt.add("restart",(o,n)=>{n.restart()});const dt=class dt{static get tags(){return dt._tags}};z(dt,"_tags",new Map),z(dt,"excludeKeys",new Set(["unclickable"])),z(dt,"clear",()=>{for(const[n,a]of dt._tags.entries())dt.excludeKeys.has(n)||dt._tags.delete(n)}),z(dt,"add",(n,a)=>{dt.tags.set(n,a)}),z(dt,"process",(n,a)=>{if(!n.text)return a;n.tags&&n.tags.length&&dt.tags.size&&n.tags.forEach(function(e){var t;let f=Pi(e,":");f&&dt.tags.has(f.before)&&((t=dt.tags.get(f.before))==null||t(a,f.after))})});let qn=dt;qn.add("unclickable",o=>{o.type="unclickable"});const Sa=wi.create(o=>({choices:[],setChoices:n=>{const a=n.map(e=>{const f=new Vs(e.text,e.index);return e.tags&&e.tags.length&&qn.process(e,f),f});o({choices:a})},clear:()=>o({choices:[]})})),Ci=ii(Sa),ya=wi.create(o=>({variables:new Map,setGlobalVars:n=>{const a=new Map,f=n._globalVariables;if(f)for(const t of f.keys()){const p=f.get(t);p&&a.set(t,p.value)}o({variables:a})}})),Ws=ii(ya),Pt=class Pt{static get patches(){return Pt._patches}static set patches(n){Pt._patches=n}static add(n,a={}){Object.assign(this._options,a),n&&Pt._patches.push(n)}static apply(n,a){const e=n;Object.assign(e.options,Pt._options);for(const f of Pt._patches)f&&f.bind(e,a)()}static clear(){Pt._patches=[],Pt._options={}}};z(Pt,"_patches",[]),z(Pt,"_options",{});let ti=Pt;const ct=class ct{static get tags(){return ct._tags}static get patterns(){return ct._patterns}static tag(n,a){ct.tags[n]=a}static pattern(n,a){ct.patterns.push({matcher:n,callback:a})}};z(ct,"_tags",{}),z(ct,"_patterns",[]),z(ct,"clear",()=>{ct._tags={},ct._patterns=[]}),z(ct,"process",(n,a=[])=>{if(!n)return"";let e={text:n,tags:a,classes:[]};return e.tags.length&&Object.keys(ct.tags).length&&e.tags.forEach(function(f){let t=Pi(f,":");t&&t.before in ct.tags&&ct.tags[t.before](e,t.before,t.after)}),e.text&&ct.patterns.length&&ct.patterns.forEach(function(f){(typeof f.matcher=="string"&&e.text.includes(f.matcher)||f.matcher instanceof RegExp&&e.text.match(f.matcher))&&f.callback(e)}),e.text});let ei=ct;const At=class At{static get functions(){return At._functions}static set functions(n){At._functions=n}static add(n,a){At.functions.set(n,a)}static get(n){return At.functions.get(n)}static bind(n,a){const e=At.get(a)||(typeof window<"u"?window[a]:void 0);e&&n.story.BindExternalFunction(a,e.bind(n))}static clear(){At.functions.clear()}};z(At,"_functions",new Map);let ni=At;class Ls{constructor(n,a,e){z(this,"title");z(this,"story");z(this,"options");z(this,"_side_effects",[]);z(this,"_cleanups",[]);z(this,"_clears",[]);z(this,"_save_label",["contents"]);z(this,"bindExternalFunctions",n=>{new Set(Array.from(n.matchAll(/\"x\(\)\":\"(\w+)/gi),a=>a[1])).forEach(a=>{ni.bind(this,a)})});this.options={...va,...e},this.story=n,this.title=a;const f=this.story.ToJson()||"";ba(this),ti.apply(this,f),this.bindExternalFunctions(f),this.clears.push(()=>{this.contents.length=0})}get contents(){return Mn.getState().contents}set contents(n){Mn.getState().setContents(n)}get choices(){return Ci.getState().choices}get clears(){return this._clears}get cleanups(){return this._cleanups}get effects(){return this._side_effects}get save_label(){return this._save_label}continue(){const n=[];for(;this.story.canContinue;){let f=this.story.Continue()||"";this.story.currentTags&&(this.story.currentTags.forEach(t=>{Yt.process(this,t),(t==="clear"||t==="restart")&&(n.length=0)}),f&&this.story.currentTags.length&&(f=ei.process(f,this.story.currentTags))),f.trim()&&n.push(f)}Mn.getState().add(n);const{currentChoices:a,variablesState:e}=this.story;Ci.getState().setChoices(a),Ws.getState().setGlobalVars(e)}choose(n){this.story.ChooseChoiceIndex(n),Mn.getState().add([ks]),this.continue()}clear(){this.clears.map(n=>{n()})}restart(){this.story.ResetState(),this.clear(),this.continue()}useEffect(){this.effects.map(n=>{n&&n()})}dispose(){this.cleanups.map(n=>{n&&n()})}}function ba(o){const n=Object.getPrototypeOf(o);Object.getOwnPropertyNames(n).forEach(function(a){var e;if(a!=="constructor"&&typeof((e=Object.getOwnPropertyDescriptor(n,a))==null?void 0:e.value)=="function"){const f=o;f[a]=f[a].bind(o)}})}var pi={},se={},ji;function vi(){if(ji)return se;ji=1,Object.defineProperty(se,"__esModule",{value:!0}),se.CompilerOptions=void 0;let o=class{constructor(a=null,e=[],f=!1,t=null,p=null){this.sourceFilename=a,this.pluginNames=e,this.countAllVisits=f,this.errorHandler=t,this.fileHandler=p}};return se.CompilerOptions=o,se}var ae={},Mi;function _a(){if(Mi)return ae;Mi=1,Object.defineProperty(ae,"__esModule",{value:!0}),ae.DebugSourceRange=void 0;let o=class{constructor(a,e,f){this.length=a,this.debugMetadata=e,this.text=f}};return ae.DebugSourceRange=o,ae}var oe={},Bi;function Oi(){if(Bi)return oe;Bi=1,Object.defineProperty(oe,"__esModule",{value:!0}),oe.ErrorType=void 0;var o;return(function(n){n[n.Author=0]="Author",n[n.Warning=1]="Warning",n[n.Error=2]="Error"})(o||(oe.ErrorType=o={})),oe}var le={},ue={},qi;function Ea(){if(qi)return ue;qi=1,Object.defineProperty(ue,"__esModule",{value:!0}),ue.Argument=void 0;let o=class{constructor(a=null,e=null,f=null){this.identifier=a,this.isByReference=e,this.isDivertTarget=f}get typeName(){return"Argument"}};return ue.Argument=o,ue}var he={},ce={},at={},Gi;function Z(){if(Gi)return at;Gi=1,Object.defineProperty(at,"__esModule",{value:!0}),at.filterUndef=at.isEquatable=at.nullIfUndefined=at.asINamedContentOrNull=at.asBooleanOrThrows=at.asNumberOrThrows=at.asOrThrows=at.asOrNull=void 0;function o(s,c){return s instanceof c?r(s):null}at.asOrNull=o;function n(s,c){if(s instanceof c)return r(s);throw new Error(`${s} is not of type ${c}`)}at.asOrThrows=n;function a(s){if(typeof s=="number")return s;throw new Error(`${s} is not a number`)}at.asNumberOrThrows=a;function e(s){if(typeof s=="boolean")return s;throw new Error(`${s} is not a boolean`)}at.asBooleanOrThrows=e;function f(s){return s.hasValidName&&s.name?s:null}at.asINamedContentOrNull=f;function t(s){return typeof s>"u"?null:s}at.nullIfUndefined=t;function p(s){return typeof s=="object"&&typeof s.Equals=="function"}at.isEquatable=p;function r(s,c){return s}function y(s){return s!=null}return at.filterUndef=y,at}var $i;function et(){if($i)return ce;$i=1,Object.defineProperty(ce,"__esModule",{value:!0}),ce.ParsedObject=void 0;const o=Z();class n{constructor(){this._alreadyHadError=!1,this._alreadyHadWarning=!1,this._debugMetadata=null,this._runtimeObject=null,this.content=[],this.parent=null,this.GetType=()=>this.typeName,this.AddContent=e=>{this.content===null&&(this.content=[]);const f=Array.isArray(e)?e:[e];for(const t of f)t.hasOwnProperty("parent")&&(t.parent=this),this.content.push(t);if(!Array.isArray(e))return e},this.InsertContent=(e,f)=>(this.content===null&&(this.content=[]),f.parent=this,this.content.splice(e,0,f),f),this.Find=e=>(f=null)=>{let t=(0,o.asOrNull)(this,e);if(t!==null&&(f===null||f(t)===!0))return t;if(this.content===null)return null;for(const p of this.content){let r=p.Find&&p.Find(e)(f);if(r)return r}return null},this.FindAll=e=>(f,t)=>{const p=Array.isArray(t)?t:[],r=(0,o.asOrNull)(this,e);if(r!==null&&(!f||f(r)===!0)&&p.push(r),this.content===null)return[];for(const y of this.content)y.FindAll&&y.FindAll(e)(f,p);return p},this.Warning=(e,f=null)=>{this.Error(e,f,!0)}}get debugMetadata(){return this._debugMetadata===null&&this.parent?this.parent.debugMetadata:this._debugMetadata}set debugMetadata(e){this._debugMetadata=e}get hasOwnDebugMetadata(){return!!this.debugMetadata}get typeName(){return"ParsedObject"}get story(){let e=this;for(;e.parent;)e=e.parent;return e}get runtimeObject(){return this._runtimeObject||(this._runtimeObject=this.GenerateRuntimeObject(),this._runtimeObject&&(this._runtimeObject.debugMetadata=this.debugMetadata)),this._runtimeObject}set runtimeObject(e){this._runtimeObject=e}get runtimePath(){if(!this.runtimeObject.path)throw new Error;return this.runtimeObject.path}get containerForCounting(){return this.runtimeObject}get ancestry(){let e=[],f=this.parent;for(;f;)e.push(f),f=f.parent;return e=e.reverse(),e}ResolveReferences(e){if(this.content!==null)for(const f of this.content)f.ResolveReferences(e)}Error(e,f=null,t=!1){if(f===null&&(f=this),!(f._alreadyHadError&&!t||f._alreadyHadWarning&&t)){if(this.parent)this.parent.Error(e,f,t);else throw new Error(`No parent object to send error to: ${e}`);t?f._alreadyHadWarning=!0:f._alreadyHadError=!0}}}return ce.ParsedObject=n,ce}var Ui;function xi(){if(Ui)return he;Ui=1,Object.defineProperty(he,"__esModule",{value:!0}),he.AuthorWarning=void 0;const o=et();let n=class extends o.ParsedObject{constructor(e){super(),this.warningMessage=e,this.GenerateRuntimeObject=()=>(this.Warning(this.warningMessage),null)}get typeName(){return"AuthorWarning"}};return he.AuthorWarning=n,he}var de={},fe={},Ht={},tt={},pe={},Kt={},Hi;function St(){if(Hi)return Kt;Hi=1,Object.defineProperty(Kt,"__esModule",{value:!0}),Kt.Path=void 0;class o{constructor(){if(this._components=[],this._componentsString=null,this._isRelative=!1,typeof arguments[0]=="string"){let a=arguments[0];this.componentsString=a}else if(arguments[0]instanceof o.Component&&arguments[1]instanceof o){let a=arguments[0],e=arguments[1];this._components.push(a),this._components=this._components.concat(e._components)}else if(arguments[0]instanceof Array){let a=arguments[0],e=!!arguments[1];this._components=this._components.concat(a),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 a=this._components.slice(1,this._components.length);return new o(a)}else return o.self}get length(){return this._components.length}get lastComponent(){let a=this._components.length-1;return a>=0?this._components[a]:null}get containsNamedComponent(){for(let a=0,e=this._components.length;a<e;a++)if(!this._components[a].isIndex)return!0;return!1}static get self(){let a=new o;return a._isRelative=!0,a}GetComponent(a){return this._components[a]}PathByAppendingPath(a){let e=new o,f=0;for(let t=0;t<a._components.length&&a._components[t].isParent;++t)f++;for(let t=0;t<this._components.length-f;++t)e._components.push(this._components[t]);for(let t=f;t<a._components.length;++t)e._components.push(a._components[t]);return e}get componentsString(){return this._componentsString==null&&(this._componentsString=this._components.join("."),this.isRelative&&(this._componentsString="."+this._componentsString)),this._componentsString}set componentsString(a){if(this._components.length=0,this._componentsString=a,this._componentsString==null||this._componentsString=="")return;this._componentsString[0]=="."&&(this._isRelative=!0,this._componentsString=this._componentsString.substring(1));let e=this._componentsString.split(".");for(let f of e)/^(\-|\+)?([0-9]+|Infinity)$/.test(f)?this._components.push(new o.Component(parseInt(f))):this._components.push(new o.Component(f))}toString(){return this.componentsString}Equals(a){if(a==null||a._components.length!=this._components.length||a.isRelative!=this.isRelative)return!1;for(let e=0,f=a._components.length;e<f;e++)if(!a._components[e].Equals(this._components[e]))return!1;return!0}PathByAppendingComponent(a){let e=new o;return e._components.push(...this._components),e._components.push(a),e}}return Kt.Path=o,o.parentId="^",(function(n){class a{constructor(f){this.index=-1,this.name=null,typeof f=="string"?this.name=f:this.index=f}get isIndex(){return this.index>=0}get isParent(){return this.name==n.parentId}static ToParent(){return new a(n.parentId)}toString(){return this.isIndex?this.index.toString():this.name}Equals(f){return f!=null&&f.isIndex==this.isIndex?this.isIndex?this.index==f.index:this.name==f.name:!1}}n.Component=a})(o||(Kt.Path=o={})),Kt}var me={},Ki;function ri(){if(Ki)return me;Ki=1,Object.defineProperty(me,"__esModule",{value:!0}),me.Debug=void 0;var o;return(function(n){function a(f,t,p){e(f instanceof t,p)}n.AssertType=a;function e(f,t){if(!f)throw typeof t<"u"&&console.warn(t),console.trace&&console.trace(),new Error("")}n.Assert=e})(o||(me.Debug=o={})),me}var jt={},Ji;function ft(){if(Ji)return jt;Ji=1,Object.defineProperty(jt,"__esModule",{value:!0}),jt.throwNullException=jt.NullException=void 0;let o=class extends Error{};jt.NullException=o;function n(a){throw new o(`${a} is null or undefined`)}return jt.throwNullException=n,jt}var zi;function yt(){if(zi)return pe;zi=1,Object.defineProperty(pe,"__esModule",{value:!0}),pe.InkObject=void 0;const o=St(),n=ot(),a=ri(),e=Z(),f=ft();class t{constructor(){this.parent=null,this._debugMetadata=null,this._path=null}get debugMetadata(){return this._debugMetadata===null&&this.parent?this.parent.debugMetadata:this._debugMetadata}set debugMetadata(r){this._debugMetadata=r}get ownDebugMetadata(){return this._debugMetadata}DebugLineNumberOfPath(r){if(r===null)return null;let y=this.rootContentContainer;if(y){let s=y.ContentAtPath(r).obj;if(s){let c=s.debugMetadata;if(c!==null)return c.startLineNumber}}return null}get path(){if(this._path==null)if(this.parent==null)this._path=new o.Path;else{let r=[],y=this,s=(0,e.asOrNull)(y.parent,n.Container);for(;s!==null;){let c=(0,e.asINamedContentOrNull)(y);if(c!=null&&c.hasValidName){if(c.name===null)return(0,f.throwNullException)("namedChild.name");r.unshift(new o.Path.Component(c.name))}else r.unshift(new o.Path.Component(s.content.indexOf(y)));y=s,s=(0,e.asOrNull)(s.parent,n.Container)}this._path=new o.Path(r)}return this._path}ResolvePath(r){if(r===null)return(0,f.throwNullException)("path");if(r.isRelative){let y=(0,e.asOrNull)(this,n.Container);return y===null&&(a.Debug.Assert(this.parent!==null,"Can't resolve relative path because we don't have a parent"),y=(0,e.asOrNull)(this.parent,n.Container),a.Debug.Assert(y!==null,"Expected parent to be a container"),a.Debug.Assert(r.GetComponent(0).isParent),r=r.tail),y===null?(0,f.throwNullException)("nearestContainer"):y.ContentAtPath(r)}else{let y=this.rootContentContainer;return y===null?(0,f.throwNullException)("contentContainer"):y.ContentAtPath(r)}}ConvertPathToRelative(r){let y=this.path,s=Math.min(r.length,y.length),c=-1;for(let P=0;P<s;++P){let N=y.GetComponent(P),O=r.GetComponent(P);if(N.Equals(O))c=P;else break}if(c==-1)return r;let i=y.componentCount-1-c,l=[];for(let P=0;P<i;++P)l.push(o.Path.Component.ToParent());for(let P=c+1;P<r.componentCount;++P)l.push(r.GetComponent(P));return new o.Path(l,!0)}CompactPathString(r){let y=null,s=null;return r.isRelative?(s=r.componentsString,y=this.path.PathByAppendingPath(r).componentsString):(s=this.ConvertPathToRelative(r).componentsString,y=r.componentsString),s.length<y.length?s:y}get rootContentContainer(){let r=this;for(;r.parent;)r=r.parent;return(0,e.asOrNull)(r,n.Container)}Copy(){throw Error("Not Implemented: Doesn't support copying")}SetChild(r,y,s){r[y]&&(r[y]=null),r[y]=s,r[y]&&(r[y].parent=this)}Equals(r){return r===this}}return pe.InkObject=t,pe}var Mt={},ge={},Xi;function Zt(){if(Xi)return ge;Xi=1,Object.defineProperty(ge,"__esModule",{value:!0}),ge.StringBuilder=void 0;let o=class{constructor(a){a=typeof a<"u"?a.toString():"",this.string=a}get Length(){return this.string.length}Append(a){a!==null&&(this.string+=a)}AppendLine(a){typeof a<"u"&&this.Append(a),this.string+=`
|
|
2
|
+
`}AppendFormat(a,...e){this.string+=a.replace(/{(\d+)}/g,(f,t)=>typeof e[t]<"u"?e[t]:f)}toString(){return this.string}Clear(){this.string=""}};return ge.StringBuilder=o,ge}var Yi;function vt(){if(Yi)return Mt;Yi=1,Object.defineProperty(Mt,"__esModule",{value:!0}),Mt.InkList=Mt.InkListItem=void 0;const o=ft(),n=Zt();class a{constructor(){if(this.originName=null,this.itemName=null,typeof arguments[1]<"u"){let t=arguments[0],p=arguments[1];this.originName=t,this.itemName=p}else if(arguments[0]){let p=arguments[0].toString().split(".");this.originName=p[0],this.itemName=p[1]}}static get Null(){return new a(null,null)}get isNull(){return this.originName==null&&this.itemName==null}get fullName(){return(this.originName!==null?this.originName:"?")+"."+this.itemName}toString(){return this.fullName}Equals(t){if(t instanceof a){let p=t;return p.itemName==this.itemName&&p.originName==this.originName}return!1}copy(){return new a(this.originName,this.itemName)}serialized(){return JSON.stringify({originName:this.originName,itemName:this.itemName})}static fromSerializedKey(t){let p=JSON.parse(t);if(!a.isLikeInkListItem(p))return a.Null;let r=p;return new a(r.originName,r.itemName)}static isLikeInkListItem(t){return!(typeof t!="object"||!t.hasOwnProperty("originName")||!t.hasOwnProperty("itemName")||typeof t.originName!="string"&&typeof t.originName!==null||typeof t.itemName!="string"&&typeof t.itemName!==null)}}Mt.InkListItem=a;let e=class st extends Map{constructor(){if(super(arguments[0]instanceof st?arguments[0]:[]),this.origins=null,this._originNames=[],arguments[0]instanceof st){let t=arguments[0],p=t.originNames;p!==null&&(this._originNames=p.slice()),t.origins!==null&&(this.origins=t.origins.slice())}else if(typeof arguments[0]=="string"){let t=arguments[0],p=arguments[1];if(this.SetInitialOriginName(t),p.listDefinitions===null)return(0,o.throwNullException)("originStory.listDefinitions");let r=p.listDefinitions.TryListGetDefinition(t,null);if(r.exists){if(r.result===null)return(0,o.throwNullException)("def.result");this.origins=[r.result]}else throw new Error("InkList origin could not be found in story when constructing new list: "+t)}else if(typeof arguments[0]=="object"&&arguments[0].hasOwnProperty("Key")&&arguments[0].hasOwnProperty("Value")){let t=arguments[0];this.Add(t.Key,t.Value)}}static FromString(t,p){var r;if(t==null||t=="")return new st;let y=(r=p.listDefinitions)===null||r===void 0?void 0:r.FindSingleItemListWithName(t);if(y)return y.value===null?(0,o.throwNullException)("listValue.value"):new st(y.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,p=null){if(t instanceof a){let r=t;if(r.originName==null){this.AddItem(r.itemName);return}if(this.origins===null)return(0,o.throwNullException)("this.origins");for(let y of this.origins)if(y.name==r.originName){let s=y.TryGetValueForItem(r,0);if(s.exists){this.Add(r,s.result);return}else throw new Error("Could not add the item "+r+" to this list because it doesn't exist in the original list definition in ink.")}throw new Error("Failed to add item to list because the item was from a new list definition that wasn't previously known to this list. Only items from previously known lists can be used, so that the int value can be found.")}else if(t!==null){let r=t,y=null;if(this.origins===null)return(0,o.throwNullException)("this.origins");for(let s of this.origins){if(r===null)return(0,o.throwNullException)("itemName");if(s.ContainsItemWithName(r)){if(y!=null)throw new Error("Could not add the item "+r+" to this list because it could come from either "+s.name+" or "+y.name);y=s}}if(y==null){if(p==null)throw new Error("Could not add the item "+r+" to this list because it isn't known to any list definitions previously associated with this list.");{let s=st.FromString(r,p).orderedItems[0];this.Add(s.Key,s.Value)}}else{let s=new a(y.name,r),c=y.ValueForItem(s);this.Add(s,c)}}}ContainsItemNamed(t){for(let[p]of this)if(a.fromSerializedKey(p).itemName==t)return!0;return!1}ContainsKey(t){return this.has(t.serialized())}Add(t,p){let r=t.serialized();if(this.has(r))throw new Error(`The Map already contains an entry for ${t}`);this.set(r,p)}Remove(t){return this.delete(t.serialized())}get Count(){return this.size}get originOfMaxItem(){if(this.origins==null)return null;let t=this.maxItem.Key.originName,p=null;return this.origins.every(r=>r.name==t?(p=r,!1):!0),p}get originNames(){if(this.Count>0){this._originNames==null&&this.Count>0?this._originNames=[]:(this._originNames||(this._originNames=[]),this._originNames.length=0);for(let[t]of this){let p=a.fromSerializedKey(t);if(p.originName===null)return(0,o.throwNullException)("item.originName");this._originNames.push(p.originName)}}return this._originNames}SetInitialOriginName(t){this._originNames=[t]}SetInitialOriginNames(t){t==null?this._originNames=null:this._originNames=t.slice()}get maxItem(){let t={Key:a.Null,Value:0};for(let[p,r]of this){let y=a.fromSerializedKey(p);(t.Key.isNull||r>t.Value)&&(t={Key:y,Value:r})}return t}get minItem(){let t={Key:a.Null,Value:0};for(let[p,r]of this){let y=a.fromSerializedKey(p);(t.Key.isNull||r<t.Value)&&(t={Key:y,Value:r})}return t}get inverse(){let t=new st;if(this.origins!=null)for(let p of this.origins)for(let[r,y]of p.items){let s=a.fromSerializedKey(r);this.ContainsKey(s)||t.Add(s,y)}return t}get all(){let t=new st;if(this.origins!=null)for(let p of this.origins)for(let[r,y]of p.items){let s=a.fromSerializedKey(r);t.set(s.serialized(),y)}return t}Union(t){let p=new st(this);for(let[r,y]of t)p.set(r,y);return p}Intersect(t){let p=new st;for(let[r,y]of this)t.has(r)&&p.set(r,y);return p}HasIntersection(t){for(let[p]of this)if(t.has(p))return!0;return!1}Without(t){let p=new st(this);for(let[r]of t)p.delete(r);return p}Contains(t){if(typeof t=="string")return this.ContainsItemNamed(t);const p=t;if(p.size==0||this.size==0)return!1;for(let[r]of p)if(!this.has(r))return!1;return!0}GreaterThan(t){return this.Count==0?!1:t.Count==0?!0:this.minItem.Value>t.maxItem.Value}GreaterThanOrEquals(t){return this.Count==0?!1:t.Count==0?!0:this.minItem.Value>=t.minItem.Value&&this.maxItem.Value>=t.maxItem.Value}LessThan(t){return t.Count==0?!1:this.Count==0?!0:this.maxItem.Value<t.minItem.Value}LessThanOrEquals(t){return t.Count==0?!1:this.Count==0?!0:this.maxItem.Value<=t.maxItem.Value&&this.minItem.Value<=t.minItem.Value}MaxAsList(){return this.Count>0?new st(this.maxItem):new st}MinAsList(){return this.Count>0?new st(this.minItem):new st}ListWithSubRange(t,p){if(this.Count==0)return new st;let r=this.orderedItems,y=0,s=Number.MAX_SAFE_INTEGER;Number.isInteger(t)?y=t:t instanceof st&&t.Count>0&&(y=t.minItem.Value),Number.isInteger(p)?s=p:p instanceof st&&p.Count>0&&(s=p.maxItem.Value);let c=new st;c.SetInitialOriginNames(this.originNames);for(let i of r)i.Value>=y&&i.Value<=s&&c.Add(i.Key,i.Value);return c}Equals(t){if(!(t instanceof st)||t.Count!=this.Count)return!1;for(let[p]of this)if(!t.has(p))return!1;return!0}get orderedItems(){let t=new Array;for(let[p,r]of this){let y=a.fromSerializedKey(p);t.push({Key:y,Value:r})}return t.sort((p,r)=>p.Key.originName===null?(0,o.throwNullException)("x.Key.originName"):r.Key.originName===null?(0,o.throwNullException)("y.Key.originName"):p.Value==r.Value?p.Key.originName.localeCompare(r.Key.originName):p.Value<r.Value?-1:p.Value>r.Value?1:0),t}get singleItem(){for(let t of this.orderedItems)return t.Key;return null}toString(){let t=this.orderedItems,p=new n.StringBuilder;for(let r=0;r<t.length;r++){r>0&&p.Append(", ");let y=t[r].Key;if(y.itemName===null)return(0,o.throwNullException)("item.itemName");p.Append(y.itemName)}return p.toString()}valueOf(){return NaN}};return Mt.InkList=e,Mt}var Ce={},Zi;function si(){if(Zi)return Ce;Zi=1,Object.defineProperty(Ce,"__esModule",{value:!0}),Ce.StoryException=void 0;let o=class extends Error{constructor(a){super(a),this.useEndLineNumber=!1,this.message=a,this.name="StoryException"}};return Ce.StoryException=o,Ce}var Nt={},Qi;function Gn(){if(Qi)return Nt;Qi=1,Object.defineProperty(Nt,"__esModule",{value:!0}),Nt.tryParseFloat=Nt.tryParseInt=Nt.tryGetValueFromMap=void 0;function o(e,f,t){if(e===null)return{result:t,exists:!1};let p=e.get(f);return typeof p>"u"?{result:t,exists:!1}:{result:p,exists:!0}}Nt.tryGetValueFromMap=o;function n(e,f=0){let t=parseInt(e);return Number.isNaN(t)?{result:f,exists:!1}:{result:t,exists:!0}}Nt.tryParseInt=n;function a(e,f=0){let t=parseFloat(e);return Number.isNaN(t)?{result:f,exists:!1}:{result:t,exists:!0}}return Nt.tryParseFloat=a,Nt}var tr;function it(){if(tr)return tt;tr=1,Object.defineProperty(tt,"__esModule",{value:!0}),tt.ValueType=tt.ListValue=tt.VariablePointerValue=tt.DivertTargetValue=tt.StringValue=tt.FloatValue=tt.IntValue=tt.BoolValue=tt.Value=tt.AbstractValue=void 0;const o=yt(),n=St(),a=vt(),e=si(),f=Z(),t=Gn(),p=ft();class r extends o.InkObject{static Create(w,F){if(F){if(F===O.Int&&Number.isInteger(Number(w)))return new c(Number(w));if(F===O.Float&&!isNaN(w))return new i(Number(w))}if(typeof w=="boolean")return new s(!!w);if(typeof w=="string")return new l(String(w));if(Number.isInteger(Number(w)))return new c(Number(w));if(isNaN(w)){if(w instanceof n.Path)return new S((0,f.asOrThrows)(w,n.Path));if(w instanceof a.InkList)return new N((0,f.asOrThrows)(w,a.InkList))}else return new i(Number(w));return null}Copy(){return(0,f.asOrThrows)(r.Create(this.valueObject),o.InkObject)}BadCastException(w){return new e.StoryException("Can't cast "+this.valueObject+" from "+this.valueType+" to "+w)}}tt.AbstractValue=r;let y=class extends r{constructor(w){super(),this.value=w}get valueObject(){return this.value}toString(){return this.value===null?(0,p.throwNullException)("Value.value"):this.value.toString()}};tt.Value=y;class s extends y{constructor(w){super(w||!1)}get isTruthy(){return!!this.value}get valueType(){return O.Bool}Cast(w){if(this.value===null)return(0,p.throwNullException)("Value.value");if(w==this.valueType)return this;if(w==O.Int)return new c(this.value?1:0);if(w==O.Float)return new i(this.value?1:0);if(w==O.String)return new l(this.value?"true":"false");throw this.BadCastException(w)}toString(){return this.value?"true":"false"}}tt.BoolValue=s;class c extends y{constructor(w){super(w||0)}get isTruthy(){return this.value!=0}get valueType(){return O.Int}Cast(w){if(this.value===null)return(0,p.throwNullException)("Value.value");if(w==this.valueType)return this;if(w==O.Bool)return new s(this.value!==0);if(w==O.Float)return new i(this.value);if(w==O.String)return new l(""+this.value);throw this.BadCastException(w)}}tt.IntValue=c;class i extends y{constructor(w){super(w||0)}get isTruthy(){return this.value!=0}get valueType(){return O.Float}Cast(w){if(this.value===null)return(0,p.throwNullException)("Value.value");if(w==this.valueType)return this;if(w==O.Bool)return new s(this.value!==0);if(w==O.Int)return new c(this.value);if(w==O.String)return new l(""+this.value);throw this.BadCastException(w)}}tt.FloatValue=i;class l extends y{constructor(w){if(super(w||""),this._isNewline=this.value==`
|
|
3
|
+
`,this._isInlineWhitespace=!0,this.value===null)return(0,p.throwNullException)("Value.value");this.value.length>0&&this.value.split("").every(F=>F!=" "&&F!=" "?(this._isInlineWhitespace=!1,!1):!0)}get valueType(){return O.String}get isTruthy(){return this.value===null?(0,p.throwNullException)("Value.value"):this.value.length>0}get isNewline(){return this._isNewline}get isInlineWhitespace(){return this._isInlineWhitespace}get isNonWhitespace(){return!this.isNewline&&!this.isInlineWhitespace}Cast(w){if(w==this.valueType)return this;if(w==O.Int){let F=(0,t.tryParseInt)(this.value);if(F.exists)return new c(F.result);throw this.BadCastException(w)}if(w==O.Float){let F=(0,t.tryParseFloat)(this.value);if(F.exists)return new i(F.result);throw this.BadCastException(w)}throw this.BadCastException(w)}}tt.StringValue=l;class S extends y{constructor(w=null){super(w)}get valueType(){return O.DivertTarget}get targetPath(){return this.value===null?(0,p.throwNullException)("Value.value"):this.value}set targetPath(w){this.value=w}get isTruthy(){throw new Error("Shouldn't be checking the truthiness of a divert target")}Cast(w){if(w==this.valueType)return this;throw this.BadCastException(w)}toString(){return"DivertTargetValue("+this.targetPath+")"}}tt.DivertTargetValue=S;class P extends y{constructor(w,F=-1){super(w),this._contextIndex=F}get contextIndex(){return this._contextIndex}set contextIndex(w){this._contextIndex=w}get variableName(){return this.value===null?(0,p.throwNullException)("Value.value"):this.value}set variableName(w){this.value=w}get valueType(){return O.VariablePointer}get isTruthy(){throw new Error("Shouldn't be checking the truthiness of a variable pointer")}Cast(w){if(w==this.valueType)return this;throw this.BadCastException(w)}toString(){return"VariablePointerValue("+this.variableName+")"}Copy(){return new P(this.variableName,this.contextIndex)}}tt.VariablePointerValue=P;class N extends y{get isTruthy(){return this.value===null?(0,p.throwNullException)("this.value"):this.value.Count>0}get valueType(){return O.List}Cast(w){if(this.value===null)return(0,p.throwNullException)("Value.value");if(w==O.Int){let F=this.value.maxItem;return F.Key.isNull?new c(0):new c(F.Value)}else if(w==O.Float){let F=this.value.maxItem;return F.Key.isNull?new i(0):new i(F.Value)}else if(w==O.String){let F=this.value.maxItem;return F.Key.isNull?new l(""):new l(F.Key.toString())}if(w==this.valueType)return this;throw this.BadCastException(w)}constructor(w,F){super(null),!w&&!F?this.value=new a.InkList:w instanceof a.InkList?this.value=new a.InkList(w):w instanceof a.InkListItem&&typeof F=="number"&&(this.value=new a.InkList({Key:w,Value:F}))}static RetainListOriginsForAssignment(w,F){let k=(0,f.asOrNull)(w,N),m=(0,f.asOrNull)(F,N);if(m&&m.value===null)return(0,p.throwNullException)("newList.value");if(k&&k.value===null)return(0,p.throwNullException)("oldList.value");k&&m&&m.value.Count==0&&m.value.SetInitialOriginNames(k.value.originNames)}}tt.ListValue=N;var O;return(function(I){I[I.Bool=-1]="Bool",I[I.Int=0]="Int",I[I.Float=1]="Float",I[I.List=2]="List",I[I.String=3]="String",I[I.DivertTarget=4]="DivertTarget",I[I.VariablePointer=5]="VariablePointer"})(O||(tt.ValueType=O={})),tt}var ve={},er;function wa(){if(er)return ve;er=1,Object.defineProperty(ve,"__esModule",{value:!0}),ve.SearchResult=void 0;const o=ot();let n=class js{constructor(){this.obj=null,this.approximate=!1}get correctObj(){return this.approximate?null:this.obj}get container(){return this.obj instanceof o.Container?this.obj:null}copy(){let e=new js;return e.obj=this.obj,e.approximate=this.approximate,e}};return ve.SearchResult=n,ve}var nr;function ot(){if(nr)return Ht;nr=1,Object.defineProperty(Ht,"__esModule",{value:!0}),Ht.Container=void 0;const o=it(),n=ft(),a=Zt(),e=yt(),f=wa(),t=St(),p=ri(),r=Gn(),y=Z();let s=class gt extends e.InkObject{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 this.name!=null&&this.name.length>0}get content(){return this._content}set content(i){this.AddContent(i)}get namedOnlyContent(){let i=new Map;for(let[l,S]of this.namedContent){let P=(0,y.asOrThrows)(S,e.InkObject);i.set(l,P)}for(let l of this.content){let S=(0,y.asINamedContentOrNull)(l);S!=null&&S.hasValidName&&i.delete(S.name)}return i.size==0&&(i=null),i}set namedOnlyContent(i){let l=this.namedOnlyContent;if(l!=null)for(let[S]of l)this.namedContent.delete(S);if(i!=null)for(let[,S]of i){let P=(0,y.asINamedContentOrNull)(S);P!=null&&this.AddToNamedContentOnly(P)}}get countFlags(){let i=0;return this.visitsShouldBeCounted&&(i|=gt.CountFlags.Visits),this.turnIndexShouldBeCounted&&(i|=gt.CountFlags.Turns),this.countingAtStartOnly&&(i|=gt.CountFlags.CountStartOnly),i==gt.CountFlags.CountStartOnly&&(i=0),i}set countFlags(i){let l=i;(l>.CountFlags.Visits)>0&&(this.visitsShouldBeCounted=!0),(l>.CountFlags.Turns)>0&&(this.turnIndexShouldBeCounted=!0),(l>.CountFlags.CountStartOnly)>0&&(this.countingAtStartOnly=!0)}get pathToFirstLeafContent(){return this._pathToFirstLeafContent==null&&(this._pathToFirstLeafContent=this.path.PathByAppendingPath(this.internalPathToFirstLeafContent)),this._pathToFirstLeafContent}get internalPathToFirstLeafContent(){let i=[],l=this;for(;l instanceof gt;)l.content.length>0&&(i.push(new t.Path.Component(0)),l=l.content[0]);return new t.Path(i)}AddContent(i){if(i instanceof Array){let l=i;for(let S of l)this.AddContent(S)}else{let l=i;if(this._content.push(l),l.parent)throw new Error("content is already in "+l.parent);l.parent=this,this.TryAddNamedContent(l)}}TryAddNamedContent(i){let l=(0,y.asINamedContentOrNull)(i);l!=null&&l.hasValidName&&this.AddToNamedContentOnly(l)}AddToNamedContentOnly(i){p.Debug.AssertType(i,e.InkObject,"Can only add Runtime.Objects to a Runtime.Container");let l=(0,y.asOrThrows)(i,e.InkObject);if(l.parent=this,i.name===null)return(0,n.throwNullException)("namedContentObj.name");this.namedContent.set(i.name,i)}ContentAtPath(i,l=0,S=-1){S==-1&&(S=i.length);let P=new f.SearchResult;P.approximate=!1;let N=this,O=this;for(let I=l;I<S;++I){let w=i.GetComponent(I);if(N==null){P.approximate=!0;break}let F=N.ContentWithPathComponent(w);if(F==null){P.approximate=!0;break}const k=(0,y.asOrNull)(F,gt);if(I<S-1&&k==null){P.approximate=!0;break}O=F,N=k}return P.obj=O,P}InsertContent(i,l){if(this.content.splice(l,0,i),i.parent)throw new Error("content is already in "+i.parent);i.parent=this,this.TryAddNamedContent(i)}AddContentsOfContainer(i){this.content.push(...i.content);for(let l of i.content)l.parent=this,this.TryAddNamedContent(l)}ContentWithPathComponent(i){if(i.isIndex)return i.index>=0&&i.index<this.content.length?this.content[i.index]:null;if(i.isParent)return this.parent;{if(i.name===null)return(0,n.throwNullException)("component.name");let l=(0,r.tryGetValueFromMap)(this.namedContent,i.name,null);return l.exists?(0,y.asOrThrows)(l.result,e.InkObject):null}}BuildStringOfHierarchy(){let i;if(arguments.length==0)return i=new a.StringBuilder,this.BuildStringOfHierarchy(i,0,null),i.toString();i=arguments[0];let l=arguments[1],S=arguments[2];function P(){for(let I=0;I<4*l;++I)i.Append(" ")}P(),i.Append("["),this.hasValidName&&i.AppendFormat(" ({0})",this.name),this==S&&i.Append(" <---"),i.AppendLine(),l++;for(let O=0;O<this.content.length;++O){let I=this.content[O];I instanceof gt?I.BuildStringOfHierarchy(i,l,S):(P(),I instanceof o.StringValue?(i.Append('"'),i.Append(I.toString().replace(`
|
|
4
|
+
`,"\\n")),i.Append('"')):i.Append(I.toString())),O!=this.content.length-1&&i.Append(","),!(I instanceof gt)&&I==S&&i.Append(" <---"),i.AppendLine()}let N=new Map;for(let[O,I]of this.namedContent)this.content.indexOf((0,y.asOrThrows)(I,e.InkObject))>=0||N.set(O,I);if(N.size>0){P(),i.AppendLine("-- named: --");for(let[,O]of N)p.Debug.AssertType(O,gt,"Can only print out named Containers"),O.BuildStringOfHierarchy(i,l,S),i.AppendLine()}l--,P(),i.Append("]")}};return Ht.Container=s,(function(c){(function(i){i[i.Start=0]="Start",i[i.Visits=1]="Visits",i[i.Turns=2]="Turns",i[i.CountStartOnly=4]="CountStartOnly"})(c.CountFlags||(c.CountFlags={}))})(s||(Ht.Container=s={})),Ht}var Jt={},ir;function pt(){if(ir)return Jt;ir=1,Object.defineProperty(Jt,"__esModule",{value:!0}),Jt.ControlCommand=void 0;const o=yt();let n=class q extends o.InkObject{get commandType(){return this._commandType}constructor(e=q.CommandType.NotSet){super(),this._commandType=e}Copy(){return new q(this.commandType)}static EvalStart(){return new q(q.CommandType.EvalStart)}static EvalOutput(){return new q(q.CommandType.EvalOutput)}static EvalEnd(){return new q(q.CommandType.EvalEnd)}static Duplicate(){return new q(q.CommandType.Duplicate)}static PopEvaluatedValue(){return new q(q.CommandType.PopEvaluatedValue)}static PopFunction(){return new q(q.CommandType.PopFunction)}static PopTunnel(){return new q(q.CommandType.PopTunnel)}static BeginString(){return new q(q.CommandType.BeginString)}static EndString(){return new q(q.CommandType.EndString)}static NoOp(){return new q(q.CommandType.NoOp)}static ChoiceCount(){return new q(q.CommandType.ChoiceCount)}static Turns(){return new q(q.CommandType.Turns)}static TurnsSince(){return new q(q.CommandType.TurnsSince)}static ReadCount(){return new q(q.CommandType.ReadCount)}static Random(){return new q(q.CommandType.Random)}static SeedRandom(){return new q(q.CommandType.SeedRandom)}static VisitIndex(){return new q(q.CommandType.VisitIndex)}static SequenceShuffleIndex(){return new q(q.CommandType.SequenceShuffleIndex)}static StartThread(){return new q(q.CommandType.StartThread)}static Done(){return new q(q.CommandType.Done)}static End(){return new q(q.CommandType.End)}static ListFromInt(){return new q(q.CommandType.ListFromInt)}static ListRange(){return new q(q.CommandType.ListRange)}static ListRandom(){return new q(q.CommandType.ListRandom)}static BeginTag(){return new q(q.CommandType.BeginTag)}static EndTag(){return new q(q.CommandType.EndTag)}toString(){return"ControlCommand "+this.commandType.toString()}};return Jt.ControlCommand=n,(function(a){(function(e){e[e.NotSet=-1]="NotSet",e[e.EvalStart=0]="EvalStart",e[e.EvalOutput=1]="EvalOutput",e[e.EvalEnd=2]="EvalEnd",e[e.Duplicate=3]="Duplicate",e[e.PopEvaluatedValue=4]="PopEvaluatedValue",e[e.PopFunction=5]="PopFunction",e[e.PopTunnel=6]="PopTunnel",e[e.BeginString=7]="BeginString",e[e.EndString=8]="EndString",e[e.NoOp=9]="NoOp",e[e.ChoiceCount=10]="ChoiceCount",e[e.Turns=11]="Turns",e[e.TurnsSince=12]="TurnsSince",e[e.ReadCount=13]="ReadCount",e[e.Random=14]="Random",e[e.SeedRandom=15]="SeedRandom",e[e.VisitIndex=16]="VisitIndex",e[e.SequenceShuffleIndex=17]="SequenceShuffleIndex",e[e.StartThread=18]="StartThread",e[e.Done=19]="Done",e[e.End=20]="End",e[e.ListFromInt=21]="ListFromInt",e[e.ListRange=22]="ListRange",e[e.ListRandom=23]="ListRandom",e[e.BeginTag=24]="BeginTag",e[e.EndTag=25]="EndTag",e[e.TOTAL_VALUES=26]="TOTAL_VALUES"})(a.CommandType||(a.CommandType={}))})(n||(Jt.ControlCommand=n={})),Jt}var rr;function Ot(){if(rr)return fe;rr=1,Object.defineProperty(fe,"__esModule",{value:!0}),fe.Expression=void 0;const o=ot(),n=pt(),a=et();let e=class extends a.ParsedObject{constructor(){super(...arguments),this._prototypeRuntimeConstantExpression=null,this.outputWhenComplete=!1,this.GenerateRuntimeObject=()=>{const t=new o.Container;return t.AddContent(n.ControlCommand.EvalStart()),this.GenerateIntoContainer(t),this.outputWhenComplete&&t.AddContent(n.ControlCommand.EvalOutput()),t.AddContent(n.ControlCommand.EvalEnd()),t},this.GenerateConstantIntoContainer=t=>{this._prototypeRuntimeConstantExpression===null&&(this._prototypeRuntimeConstantExpression=new o.Container,this.GenerateIntoContainer(this._prototypeRuntimeConstantExpression));for(const p of this._prototypeRuntimeConstantExpression.content){const r=p.Copy();r&&t.AddContent(r)}},this.toString=()=>"No string value in JavaScript."}get typeName(){return"Expression"}Equals(t){return!1}};return fe.Expression=e,fe}var Se={},ye={},sr;function Qt(){if(sr)return ye;sr=1,Object.defineProperty(ye,"__esModule",{value:!0}),ye.Void=void 0;const o=yt();let n=class extends o.InkObject{toString(){return"Void"}};return ye.Void=n,ye}var ar;function Ft(){if(ar)return Se;ar=1,Object.defineProperty(Se,"__esModule",{value:!0}),Se.NativeFunctionCall=void 0;const o=it(),n=si(),a=Qt(),e=vt(),f=yt(),t=Z(),p=ft();let r=class Ct extends f.InkObject{static CallWithName(s){return new Ct(s)}static CallExistsWithName(s){return this.GenerateNativeFunctionsIfNecessary(),this._nativeFunctions.get(s)}get name(){return this._name===null?(0,p.throwNullException)("NativeFunctionCall._name"):this._name}set name(s){this._name=s,this._isPrototype||(Ct._nativeFunctions===null?(0,p.throwNullException)("NativeFunctionCall._nativeFunctions"):this._prototype=Ct._nativeFunctions.get(this._name)||null)}get numberOfParameters(){return this._prototype?this._prototype.numberOfParameters:this._numberOfParameters}set numberOfParameters(s){this._numberOfParameters=s}Call(s){if(this._prototype)return this._prototype.Call(s);if(this.numberOfParameters!=s.length)throw new Error("Unexpected number of parameters");let c=!1;for(let S of s){if(S instanceof a.Void)throw new n.StoryException("Attempting to perform "+this.name+' on a void value. Did you forget to "return" a value from a function you called here?');S instanceof o.ListValue&&(c=!0)}if(s.length==2&&c)return this.CallBinaryListOperation(s);let i=this.CoerceValuesToSingleType(s),l=i[0].valueType;return l==o.ValueType.Int?this.CallType(i):l==o.ValueType.Float?this.CallType(i):l==o.ValueType.String?this.CallType(i):l==o.ValueType.DivertTarget?this.CallType(i):l==o.ValueType.List?this.CallType(i):null}CallType(s){let c=(0,t.asOrThrows)(s[0],o.Value),i=c.valueType,l=c,S=s.length;if(S==2||S==1){if(this._operationFuncs===null)return(0,p.throwNullException)("NativeFunctionCall._operationFuncs");let P=this._operationFuncs.get(i);if(!P){const N=o.ValueType[i];throw new n.StoryException("Cannot perform operation "+this.name+" on "+N)}if(S==2){let O=(0,t.asOrThrows)(s[1],o.Value),I=P;if(l.value===null||O.value===null)return(0,p.throwNullException)("NativeFunctionCall.Call BinaryOp values");let w=I(l.value,O.value);return o.Value.Create(w)}else{let N=P;if(l.value===null)return(0,p.throwNullException)("NativeFunctionCall.Call UnaryOp value");let O=N(l.value);return this.name===Ct.Int?o.Value.Create(O,o.ValueType.Int):this.name===Ct.Float?o.Value.Create(O,o.ValueType.Float):o.Value.Create(O,c.valueType)}}else throw new Error("Unexpected number of parameters to NativeFunctionCall: "+s.length)}CallBinaryListOperation(s){if((this.name=="+"||this.name=="-")&&s[0]instanceof o.ListValue&&s[1]instanceof o.IntValue)return this.CallListIncrementOperation(s);let c=(0,t.asOrThrows)(s[0],o.Value),i=(0,t.asOrThrows)(s[1],o.Value);if((this.name=="&&"||this.name=="||")&&(c.valueType!=o.ValueType.List||i.valueType!=o.ValueType.List)){if(this._operationFuncs===null)return(0,p.throwNullException)("NativeFunctionCall._operationFuncs");let l=this._operationFuncs.get(o.ValueType.Int);if(l===null)return(0,p.throwNullException)("NativeFunctionCall.CallBinaryListOperation op");let S=(0,t.asBooleanOrThrows)(l(c.isTruthy?1:0,i.isTruthy?1:0));return new o.BoolValue(S)}if(c.valueType==o.ValueType.List&&i.valueType==o.ValueType.List)return this.CallType([c,i]);throw new n.StoryException("Can not call use "+this.name+" operation on "+o.ValueType[c.valueType]+" and "+o.ValueType[i.valueType])}CallListIncrementOperation(s){let c=(0,t.asOrThrows)(s[0],o.ListValue),i=(0,t.asOrThrows)(s[1],o.IntValue),l=new e.InkList;if(c.value===null)return(0,p.throwNullException)("NativeFunctionCall.CallListIncrementOperation listVal.value");for(let[S,P]of c.value){let N=e.InkListItem.fromSerializedKey(S);if(this._operationFuncs===null)return(0,p.throwNullException)("NativeFunctionCall._operationFuncs");let O=this._operationFuncs.get(o.ValueType.Int);if(i.value===null)return(0,p.throwNullException)("NativeFunctionCall.CallListIncrementOperation intVal.value");let I=O(P,i.value),w=null;if(c.value.origins===null)return(0,p.throwNullException)("NativeFunctionCall.CallListIncrementOperation listVal.value.origins");for(let F of c.value.origins)if(F.name==N.originName){w=F;break}if(w!=null){let F=w.TryGetItemWithValue(I,e.InkListItem.Null);F.exists&&l.Add(F.result,I)}}return new o.ListValue(l)}CoerceValuesToSingleType(s){let c=o.ValueType.Int,i=null;for(let S of s){let P=(0,t.asOrThrows)(S,o.Value);P.valueType>c&&(c=P.valueType),P.valueType==o.ValueType.List&&(i=(0,t.asOrNull)(P,o.ListValue))}let l=[];if(o.ValueType[c]==o.ValueType[o.ValueType.List])for(let S of s){let P=(0,t.asOrThrows)(S,o.Value);if(P.valueType==o.ValueType.List)l.push(P);else if(P.valueType==o.ValueType.Int){let N=parseInt(P.valueObject);if(i=(0,t.asOrThrows)(i,o.ListValue),i.value===null)return(0,p.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType specialCaseList.value");let O=i.value.originOfMaxItem;if(O===null)return(0,p.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType list");let I=O.TryGetItemWithValue(N,e.InkListItem.Null);if(I.exists){let w=new o.ListValue(I.result,N);l.push(w)}else throw new n.StoryException("Could not find List item with the value "+N+" in "+O.name)}else{const N=o.ValueType[P.valueType];throw new n.StoryException("Cannot mix Lists and "+N+" values in this operation")}}else for(let S of s){let N=(0,t.asOrThrows)(S,o.Value).Cast(c);l.push(N)}return l}constructor(){if(super(),this._name=null,this._numberOfParameters=0,this._prototype=null,this._isPrototype=!1,this._operationFuncs=null,arguments.length===0)Ct.GenerateNativeFunctionsIfNecessary();else if(arguments.length===1){let s=arguments[0];Ct.GenerateNativeFunctionsIfNecessary(),this.name=s}else if(arguments.length===2){let s=arguments[0],c=arguments[1];this._isPrototype=!0,this.name=s,this.numberOfParameters=c}}static Identity(s){return s}static GenerateNativeFunctionsIfNecessary(){if(this._nativeFunctions==null){this._nativeFunctions=new Map,this.AddIntBinaryOp(this.Add,(i,l)=>i+l),this.AddIntBinaryOp(this.Subtract,(i,l)=>i-l),this.AddIntBinaryOp(this.Multiply,(i,l)=>i*l),this.AddIntBinaryOp(this.Divide,(i,l)=>Math.floor(i/l)),this.AddIntBinaryOp(this.Mod,(i,l)=>i%l),this.AddIntUnaryOp(this.Negate,i=>-i),this.AddIntBinaryOp(this.Equal,(i,l)=>i==l),this.AddIntBinaryOp(this.Greater,(i,l)=>i>l),this.AddIntBinaryOp(this.Less,(i,l)=>i<l),this.AddIntBinaryOp(this.GreaterThanOrEquals,(i,l)=>i>=l),this.AddIntBinaryOp(this.LessThanOrEquals,(i,l)=>i<=l),this.AddIntBinaryOp(this.NotEquals,(i,l)=>i!=l),this.AddIntUnaryOp(this.Not,i=>i==0),this.AddIntBinaryOp(this.And,(i,l)=>i!=0&&l!=0),this.AddIntBinaryOp(this.Or,(i,l)=>i!=0||l!=0),this.AddIntBinaryOp(this.Max,(i,l)=>Math.max(i,l)),this.AddIntBinaryOp(this.Min,(i,l)=>Math.min(i,l)),this.AddIntBinaryOp(this.Pow,(i,l)=>Math.pow(i,l)),this.AddIntUnaryOp(this.Floor,Ct.Identity),this.AddIntUnaryOp(this.Ceiling,Ct.Identity),this.AddIntUnaryOp(this.Int,Ct.Identity),this.AddIntUnaryOp(this.Float,i=>i),this.AddFloatBinaryOp(this.Add,(i,l)=>i+l),this.AddFloatBinaryOp(this.Subtract,(i,l)=>i-l),this.AddFloatBinaryOp(this.Multiply,(i,l)=>i*l),this.AddFloatBinaryOp(this.Divide,(i,l)=>i/l),this.AddFloatBinaryOp(this.Mod,(i,l)=>i%l),this.AddFloatUnaryOp(this.Negate,i=>-i),this.AddFloatBinaryOp(this.Equal,(i,l)=>i==l),this.AddFloatBinaryOp(this.Greater,(i,l)=>i>l),this.AddFloatBinaryOp(this.Less,(i,l)=>i<l),this.AddFloatBinaryOp(this.GreaterThanOrEquals,(i,l)=>i>=l),this.AddFloatBinaryOp(this.LessThanOrEquals,(i,l)=>i<=l),this.AddFloatBinaryOp(this.NotEquals,(i,l)=>i!=l),this.AddFloatUnaryOp(this.Not,i=>i==0),this.AddFloatBinaryOp(this.And,(i,l)=>i!=0&&l!=0),this.AddFloatBinaryOp(this.Or,(i,l)=>i!=0||l!=0),this.AddFloatBinaryOp(this.Max,(i,l)=>Math.max(i,l)),this.AddFloatBinaryOp(this.Min,(i,l)=>Math.min(i,l)),this.AddFloatBinaryOp(this.Pow,(i,l)=>Math.pow(i,l)),this.AddFloatUnaryOp(this.Floor,i=>Math.floor(i)),this.AddFloatUnaryOp(this.Ceiling,i=>Math.ceil(i)),this.AddFloatUnaryOp(this.Int,i=>Math.floor(i)),this.AddFloatUnaryOp(this.Float,Ct.Identity),this.AddStringBinaryOp(this.Add,(i,l)=>i+l),this.AddStringBinaryOp(this.Equal,(i,l)=>i===l),this.AddStringBinaryOp(this.NotEquals,(i,l)=>i!==l),this.AddStringBinaryOp(this.Has,(i,l)=>i.includes(l)),this.AddStringBinaryOp(this.Hasnt,(i,l)=>!i.includes(l)),this.AddListBinaryOp(this.Add,(i,l)=>i.Union(l)),this.AddListBinaryOp(this.Subtract,(i,l)=>i.Without(l)),this.AddListBinaryOp(this.Has,(i,l)=>i.Contains(l)),this.AddListBinaryOp(this.Hasnt,(i,l)=>!i.Contains(l)),this.AddListBinaryOp(this.Intersect,(i,l)=>i.Intersect(l)),this.AddListBinaryOp(this.Equal,(i,l)=>i.Equals(l)),this.AddListBinaryOp(this.Greater,(i,l)=>i.GreaterThan(l)),this.AddListBinaryOp(this.Less,(i,l)=>i.LessThan(l)),this.AddListBinaryOp(this.GreaterThanOrEquals,(i,l)=>i.GreaterThanOrEquals(l)),this.AddListBinaryOp(this.LessThanOrEquals,(i,l)=>i.LessThanOrEquals(l)),this.AddListBinaryOp(this.NotEquals,(i,l)=>!i.Equals(l)),this.AddListBinaryOp(this.And,(i,l)=>i.Count>0&&l.Count>0),this.AddListBinaryOp(this.Or,(i,l)=>i.Count>0||l.Count>0),this.AddListUnaryOp(this.Not,i=>i.Count==0?1:0),this.AddListUnaryOp(this.Invert,i=>i.inverse),this.AddListUnaryOp(this.All,i=>i.all),this.AddListUnaryOp(this.ListMin,i=>i.MinAsList()),this.AddListUnaryOp(this.ListMax,i=>i.MaxAsList()),this.AddListUnaryOp(this.Count,i=>i.Count),this.AddListUnaryOp(this.ValueOfList,i=>i.maxItem.Value);let s=(i,l)=>i.Equals(l),c=(i,l)=>!i.Equals(l);this.AddOpToNativeFunc(this.Equal,2,o.ValueType.DivertTarget,s),this.AddOpToNativeFunc(this.NotEquals,2,o.ValueType.DivertTarget,c)}}AddOpFuncForType(s,c){this._operationFuncs==null&&(this._operationFuncs=new Map),this._operationFuncs.set(s,c)}static AddOpToNativeFunc(s,c,i,l){if(this._nativeFunctions===null)return(0,p.throwNullException)("NativeFunctionCall._nativeFunctions");let S=this._nativeFunctions.get(s);S||(S=new Ct(s,c),this._nativeFunctions.set(s,S)),S.AddOpFuncForType(i,l)}static AddIntBinaryOp(s,c){this.AddOpToNativeFunc(s,2,o.ValueType.Int,c)}static AddIntUnaryOp(s,c){this.AddOpToNativeFunc(s,1,o.ValueType.Int,c)}static AddFloatBinaryOp(s,c){this.AddOpToNativeFunc(s,2,o.ValueType.Float,c)}static AddFloatUnaryOp(s,c){this.AddOpToNativeFunc(s,1,o.ValueType.Float,c)}static AddStringBinaryOp(s,c){this.AddOpToNativeFunc(s,2,o.ValueType.String,c)}static AddListBinaryOp(s,c){this.AddOpToNativeFunc(s,2,o.ValueType.List,c)}static AddListUnaryOp(s,c){this.AddOpToNativeFunc(s,1,o.ValueType.List,c)}toString(){return'Native "'+this.name+'"'}};return Se.NativeFunctionCall=r,r.Add="+",r.Subtract="-",r.Divide="/",r.Multiply="*",r.Mod="%",r.Negate="_",r.Equal="==",r.Greater=">",r.Less="<",r.GreaterThanOrEquals=">=",r.LessThanOrEquals="<=",r.NotEquals="!=",r.Not="!",r.And="&&",r.Or="||",r.Min="MIN",r.Max="MAX",r.Pow="POW",r.Floor="FLOOR",r.Ceiling="CEILING",r.Int="INT",r.Float="FLOAT",r.Has="?",r.Hasnt="!?",r.Intersect="^",r.ListMin="LIST_MIN",r.ListMax="LIST_MAX",r.All="LIST_ALL",r.Count="LIST_COUNT",r.ValueOfList="LIST_VALUE",r.Invert="LIST_INVERT",r._nativeFunctions=null,Se}var be={},_e={},or;function Ti(){if(or)return _e;or=1,Object.defineProperty(_e,"__esModule",{value:!0}),_e.NumberExpression=void 0;const o=Ot(),n=it(),a=Z();let e=class Ms extends o.Expression{constructor(t,p){if(super(),this.isInt=()=>this.subtype=="int",this.isFloat=()=>this.subtype=="float",this.isBool=()=>this.subtype=="bool",this.GenerateIntoContainer=r=>{this.isInt()?r.AddContent(new n.IntValue(this.value)):this.isFloat()?r.AddContent(new n.FloatValue(this.value)):this.isBool()&&r.AddContent(new n.BoolValue(this.value))},this.toString=()=>String(this.value),typeof t=="number"&&!Number.isNaN(t)||typeof t=="boolean")this.value=t,this.subtype=p;else throw new Error("Unexpected object type in NumberExpression.")}get typeName(){return"Number"}Equals(t){const p=(0,a.asOrNull)(t,Ms);return p?p.subtype==this.subtype&&p.value==this.value:!1}};return _e.NumberExpression=e,_e}var lr;function Bs(){if(lr)return be;lr=1,Object.defineProperty(be,"__esModule",{value:!0}),be.UnaryExpression=void 0;const o=Ot(),n=Ft(),a=Ti(),e=Z();let f=class extends o.Expression{get nativeNameForOp(){return this.op==="-"?"_":this.op==="not"?"!":this.op}constructor(p,r){super(),this.op=r,this.GenerateIntoContainer=y=>{this.innerExpression.GenerateIntoContainer(y),y.AddContent(n.NativeFunctionCall.CallWithName(this.nativeNameForOp))},this.toString=()=>this.nativeNameForOp+this.innerExpression,this.innerExpression=this.AddContent(p)}get typeName(){return"UnaryExpression"}};return be.UnaryExpression=f,f.WithInner=(t,p)=>{const r=(0,e.asOrNull)(t,a.NumberExpression);if(r){if(p==="-"){if(r.isInt())return new a.NumberExpression(-r.value,"int");if(r.isFloat())return new a.NumberExpression(-r.value,"float")}else if(p=="!"||p=="not"){if(r.isInt())return new a.NumberExpression(r.value==0,"bool");if(r.isFloat())return new a.NumberExpression(r.value==0,"bool");if(r.isBool())return new a.NumberExpression(!r.value,"bool")}throw new Error("Unexpected operation or number type")}return new f(t,p)},be}var ur;function qs(){if(ur)return de;ur=1,Object.defineProperty(de,"__esModule",{value:!0}),de.BinaryExpression=void 0;const o=Ot(),n=Ft(),a=Bs(),e=Z();let f=class extends o.Expression{constructor(p,r,y){super(),this.opName=y,this.GenerateIntoContainer=s=>{this.leftExpression.GenerateIntoContainer(s),this.rightExpression.GenerateIntoContainer(s),this.opName=this.NativeNameForOp(this.opName),s.AddContent(n.NativeFunctionCall.CallWithName(this.opName))},this.NativeNameForOp=s=>s==="and"?"&&":s==="or"?"||":s==="mod"?"%":s==="has"?"?":s==="hasnt"?"!?":s,this.toString=()=>`(${this.leftExpression} ${this.opName} ${this.rightExpression})`,this.leftExpression=this.AddContent(p),this.rightExpression=this.AddContent(r),this.opName=y}get typeName(){return"BinaryExpression"}ResolveReferences(p){if(super.ResolveReferences(p),this.NativeNameForOp(this.opName)==="?"){const r=(0,e.asOrNull)(this.leftExpression,a.UnaryExpression);r!==null&&(r.op==="not"||r.op==="!")&&this.Error(`Using 'not' or '!' here negates '${r.innerExpression}' rather than the result of the '?' or 'has' operator. You need to add parentheses around the (A ? B) expression.`)}}};return de.BinaryExpression=f,de}var Ee={},we={},hr;function ai(){if(hr)return we;hr=1,Object.defineProperty(we,"__esModule",{value:!0}),we.CharacterSet=void 0;let o=class{constructor(a){this.set=new Set,this.Add=e=>this.set.add(e),this.AddRange=(e,f)=>{for(let t=e.charCodeAt(0);t<=f.charCodeAt(0);++t)this.Add(String.fromCharCode(t));return this},this.AddCharacters=e=>{if(typeof e=="string"||Array.isArray(e))for(const f of e)this.Add(f);else for(const f of e.set)this.Add(f);return this},a&&this.AddCharacters(a)}};return we.CharacterSet=o,o.FromRange=(n,a)=>new o().AddRange(n,a),we}var cr;function Pa(){if(cr)return Ee;cr=1,Object.defineProperty(Ee,"__esModule",{value:!0}),Ee.CharacterRange=void 0;const o=ai();let n=class{constructor(e,f,t=[]){if(this._start=e,this._end=f,this._correspondingCharSet=new o.CharacterSet,this._excludes=new Set,this.ToCharacterSet=()=>{if(this._correspondingCharSet.set.size===0)for(let p=this.start.charCodeAt(0),r;p<=this.end.charCodeAt(0);p+=1)r=String.fromCharCode(p),this._excludes.has(r)||this._correspondingCharSet.AddCharacters(r);return this._correspondingCharSet},t instanceof o.CharacterSet)this._excludes=t.set;else for(const p of t)this._excludes.add(p)}get start(){return this._start}get end(){return this._end}};return Ee.CharacterRange=n,n.Define=(a,e,f=[])=>new n(a,e,f),Ee}var Pe={},Oe={},dr;function Ni(){if(dr)return Oe;dr=1,Object.defineProperty(Oe,"__esModule",{value:!0}),Oe.ChoicePoint=void 0;const o=yt(),n=St(),a=ft();let e=class extends o.InkObject{constructor(t=!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(this._pathOnChoice!=null&&this._pathOnChoice.isRelative){let t=this.choiceTarget;t&&(this._pathOnChoice=t.path)}return this._pathOnChoice}set pathOnChoice(t){this._pathOnChoice=t}get choiceTarget(){return this._pathOnChoice===null?(0,a.throwNullException)("ChoicePoint._pathOnChoice"):this.ResolvePath(this._pathOnChoice).container}get pathStringOnChoice(){return this.pathOnChoice===null?(0,a.throwNullException)("ChoicePoint.pathOnChoice"):this.CompactPathString(this.pathOnChoice)}set pathStringOnChoice(t){this.pathOnChoice=new n.Path(t)}get flags(){let t=0;return this.hasCondition&&(t|=1),this.hasStartContent&&(t|=2),this.hasChoiceOnlyContent&&(t|=4),this.isInvisibleDefault&&(t|=8),this.onceOnly&&(t|=16),t}set flags(t){this.hasCondition=(t&1)>0,this.hasStartContent=(t&2)>0,this.hasChoiceOnlyContent=(t&4)>0,this.isInvisibleDefault=(t&8)>0,this.onceOnly=(t&16)>0}toString(){return this.pathOnChoice===null?(0,a.throwNullException)("ChoicePoint.pathOnChoice"):"Choice: -> "+this.pathOnChoice.toString()}};return Oe.ChoicePoint=e,Oe}var xe={},Te={},fr;function te(){if(fr)return Te;fr=1,Object.defineProperty(Te,"__esModule",{value:!0}),Te.PushPopType=void 0;var o;return(function(n){n[n.Tunnel=0]="Tunnel",n[n.Function=1]="Function",n[n.FunctionEvaluationFromGame=2]="FunctionEvaluationFromGame"})(o||(Te.PushPopType=o={})),Te}var Ne={},pr;function oi(){if(pr)return Ne;pr=1,Object.defineProperty(Ne,"__esModule",{value:!0}),Ne.Pointer=void 0;const o=St();let n=class Yn{constructor(){this.container=null,this.index=-1,arguments.length===2&&(this.container=arguments[0],this.index=arguments[1])}Resolve(){return this.index<0?this.container:this.container==null?null:this.container.content.length==0?this.container:this.index>=this.container.content.length?null:this.container.content[this.index]}get isNull(){return this.container==null}get path(){return this.isNull?null:this.index>=0?this.container.path.PathByAppendingComponent(new o.Path.Component(this.index)):this.container.path}toString(){return this.container?"Ink Pointer -> "+this.container.path.toString()+" -- index "+this.index:"Ink Pointer (null)"}copy(){return new Yn(this.container,this.index)}static StartOf(e){return new Yn(e,0)}static get Null(){return new Yn(null,-1)}};return Ne.Pointer=n,Ne}var mr;function Rt(){if(mr)return xe;mr=1,Object.defineProperty(xe,"__esModule",{value:!0}),xe.Divert=void 0;const o=St(),n=te(),a=Zt(),e=yt(),f=oi(),t=ot(),p=ft();class r extends e.InkObject{get targetPath(){if(this._targetPath!=null&&this._targetPath.isRelative){let s=this.targetPointer.Resolve();s&&(this._targetPath=s.path)}return this._targetPath}set targetPath(s){this._targetPath=s,this._targetPointer=f.Pointer.Null}get targetPointer(){if(this._targetPointer.isNull){let s=this.ResolvePath(this._targetPath).obj;if(this._targetPath===null)return(0,p.throwNullException)("this._targetPath");if(this._targetPath.lastComponent===null)return(0,p.throwNullException)("this._targetPath.lastComponent");if(this._targetPath.lastComponent.isIndex){if(s===null)return(0,p.throwNullException)("targetObj");this._targetPointer.container=s.parent instanceof t.Container?s.parent:null,this._targetPointer.index=this._targetPath.lastComponent.index}else this._targetPointer=f.Pointer.StartOf(s instanceof t.Container?s:null)}return this._targetPointer.copy()}get targetPathString(){return this.targetPath==null?null:this.CompactPathString(this.targetPath)}set targetPathString(s){s==null?this.targetPath=null:this.targetPath=new o.Path(s)}get hasVariableTarget(){return this.variableDivertName!=null}constructor(s){super(),this._targetPath=null,this._targetPointer=f.Pointer.Null,this.variableDivertName=null,this.pushesToStack=!1,this.stackPushType=0,this.isExternal=!1,this.externalArgs=0,this.isConditional=!1,this.pushesToStack=!1,typeof s<"u"&&(this.pushesToStack=!0,this.stackPushType=s)}Equals(s){let c=s;return c instanceof r&&this.hasVariableTarget==c.hasVariableTarget?this.hasVariableTarget?this.variableDivertName==c.variableDivertName:this.targetPath===null?(0,p.throwNullException)("this.targetPath"):this.targetPath.Equals(c.targetPath):!1}toString(){if(this.hasVariableTarget)return"Divert(variable: "+this.variableDivertName+")";if(this.targetPath==null)return"Divert(null)";{let s=new a.StringBuilder,c=this.targetPath.toString();return s.Append("Divert"),this.isConditional&&s.Append("?"),this.pushesToStack&&(this.stackPushType==n.PushPopType.Function?s.Append(" function"):s.Append(" tunnel")),s.Append(" -> "),s.Append(this.targetPathString),s.Append(" ("),s.Append(c),s.Append(")"),s.toString()}}}return xe.Divert=r,xe}var Ie={},gr;function Wt(){if(gr)return Ie;gr=1,Object.defineProperty(Ie,"__esModule",{value:!0}),Ie.SymbolType=void 0;var o;return(function(n){n[n.Knot=0]="Knot",n[n.List=1]="List",n[n.ListItem=2]="ListItem",n[n.Var=3]="Var",n[n.SubFlowAndWeave=4]="SubFlowAndWeave",n[n.Arg=5]="Arg",n[n.Temp=6]="Temp"})(o||(Ie.SymbolType=o={})),Ie}var Ae={},Cr;function Gt(){if(Cr)return Ae;Cr=1,Object.defineProperty(Ae,"__esModule",{value:!0}),Ae.VariableAssignment=void 0;const o=yt();class n extends o.InkObject{constructor(e,f){super(),this.variableName=e||null,this.isNewDeclaration=!!f,this.isGlobal=!1}toString(){return"VarAssign to "+this.variableName}}return Ae.VariableAssignment=n,Ae}var vr;function $n(){if(vr)return Pe;vr=1,Object.defineProperty(Pe,"__esModule",{value:!0}),Pe.Choice=void 0;const o=Ni(),n=ot(),a=pt(),e=Rt(),f=it(),t=et(),p=Wt(),r=Gt();class y extends t.ParsedObject{get runtimeChoice(){if(!this._runtimeChoice)throw new Error;return this._runtimeChoice}get name(){var c;return((c=this.identifier)===null||c===void 0?void 0:c.name)||null}get condition(){return this._condition}set condition(c){this._condition=c,c&&this.AddContent(c)}get runtimeContainer(){return this._innerContentContainer}get innerContentContainer(){return this._innerContentContainer}get containerForCounting(){return this._innerContentContainer}get runtimePath(){if(!this.innerContentContainer||!this.innerContentContainer.path)throw new Error;return this.innerContentContainer.path}constructor(c,i,l){super(),this._condition=null,this._innerContentContainer=null,this._outerContainer=null,this._runtimeChoice=null,this._returnToR1=null,this._returnToR2=null,this._r1Label=null,this._r2Label=null,this._divertToStartContentOuter=null,this._divertToStartContentInner=null,this._startContentRuntimeContainer=null,this.isInvisibleDefault=!1,this.hasWeaveStyleInlineBrackets=!1,this.GenerateRuntimeObject=()=>{if(this._outerContainer=new n.Container,this._runtimeChoice=new o.ChoicePoint(this.onceOnly),this._runtimeChoice.isInvisibleDefault=this.isInvisibleDefault,(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(a.ControlCommand.EvalStart()),this.startContent){this._returnToR1=new f.DivertTargetValue,this._outerContainer.AddContent(this._returnToR1);const S=new r.VariableAssignment("$r",!0);this._outerContainer.AddContent(S),this._outerContainer.AddContent(a.ControlCommand.BeginString()),this._divertToStartContentOuter=new e.Divert,this._outerContainer.AddContent(this._divertToStartContentOuter),this._startContentRuntimeContainer=this.startContent.GenerateRuntimeObject(),this._startContentRuntimeContainer.name="s";const P=new e.Divert;P.variableDivertName="$r",this._startContentRuntimeContainer.AddContent(P),this._outerContainer.AddToNamedContentOnly(this._startContentRuntimeContainer),this._r1Label=new n.Container,this._r1Label.name="$r1",this._outerContainer.AddContent(this._r1Label),this._outerContainer.AddContent(a.ControlCommand.EndString()),this._runtimeChoice.hasStartContent=!0}if(this.choiceOnlyContent){this._outerContainer.AddContent(a.ControlCommand.BeginString());const S=this.choiceOnlyContent.GenerateRuntimeObject();this._outerContainer.AddContentsOfContainer(S),this._outerContainer.AddContent(a.ControlCommand.EndString()),this._runtimeChoice.hasChoiceOnlyContent=!0}if(this.condition&&(this.condition.GenerateIntoContainer(this._outerContainer),this._runtimeChoice.hasCondition=!0),(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(a.ControlCommand.EvalEnd()),this._outerContainer.AddContent(this._runtimeChoice),this._innerContentContainer=new n.Container,this.startContent){this._returnToR2=new f.DivertTargetValue,this._innerContentContainer.AddContent(a.ControlCommand.EvalStart()),this._innerContentContainer.AddContent(this._returnToR2),this._innerContentContainer.AddContent(a.ControlCommand.EvalEnd());const S=new r.VariableAssignment("$r",!0);this._innerContentContainer.AddContent(S),this._divertToStartContentInner=new e.Divert,this._innerContentContainer.AddContent(this._divertToStartContentInner),this._r2Label=new n.Container,this._r2Label.name="$r2",this._innerContentContainer.AddContent(this._r2Label)}if(this.innerContent){const S=this.innerContent.GenerateRuntimeObject();this._innerContentContainer.AddContentsOfContainer(S)}return this.story.countAllVisits&&(this._innerContentContainer.visitsShouldBeCounted=!0),this._innerContentContainer.countingAtStartOnly=!0,this._outerContainer},this.toString=()=>this.choiceOnlyContent!==null?`* ${this.startContent}[${this.choiceOnlyContent}]...`:`* ${this.startContent}...`,this.startContent=c,this.choiceOnlyContent=i,this.innerContent=l,this.indentationDepth=1,c&&this.AddContent(this.startContent),i&&this.AddContent(this.choiceOnlyContent),l&&this.AddContent(this.innerContent),this.onceOnly=!0}get typeName(){return"Choice"}ResolveReferences(c){var i;if(this._innerContentContainer&&(this.runtimeChoice.pathOnChoice=this._innerContentContainer.path,this.onceOnly&&(this._innerContentContainer.visitsShouldBeCounted=!0)),this._returnToR1){if(!this._r1Label)throw new Error;this._returnToR1.targetPath=this._r1Label.path}if(this._returnToR2){if(!this._r2Label)throw new Error;this._returnToR2.targetPath=this._r2Label.path}if(this._divertToStartContentOuter){if(!this._startContentRuntimeContainer)throw new Error;this._divertToStartContentOuter.targetPath=this._startContentRuntimeContainer.path}if(this._divertToStartContentInner){if(!this._startContentRuntimeContainer)throw new Error;this._divertToStartContentInner.targetPath=this._startContentRuntimeContainer.path}super.ResolveReferences(c),this.identifier&&(((i=this.identifier)===null||i===void 0?void 0:i.name)||"").length>0&&c.CheckForNamingCollisions(this,this.identifier,p.SymbolType.SubFlowAndWeave)}}return Pe.Choice=y,Pe}var Fe={},mi={},Re={},ke={},Sr;function Oa(){if(Sr)return ke;Sr=1,Object.defineProperty(ke,"__esModule",{value:!0}),ke.StringParserElement=void 0;let o=class Si{constructor(){this.characterIndex=0,this.characterInLineIndex=0,this.lineIndex=0,this.reportedErrorInScope=!1,this.uniqueId=0,this.customFlags=0,this.CopyFrom=a=>{Si._uniqueIdCounter++,this.uniqueId=Si._uniqueIdCounter,this.characterIndex=a.characterIndex,this.characterInLineIndex=a.characterInLineIndex,this.lineIndex=a.lineIndex,this.customFlags=a.customFlags,this.reportedErrorInScope=!1},this.SquashFrom=a=>{this.characterIndex=a.characterIndex,this.characterInLineIndex=a.characterInLineIndex,this.lineIndex=a.lineIndex,this.reportedErrorInScope=a.reportedErrorInScope,this.customFlags=a.customFlags}}};return ke.StringParserElement=o,o._uniqueIdCounter=1e3,ke}var yr;function xa(){if(yr)return Re;yr=1,Object.defineProperty(Re,"__esModule",{value:!0}),Re.StringParserState=void 0;const o=Oa();let n=class{get currentElement(){return this._stack[this._numElements-1]}get lineIndex(){return this.currentElement.lineIndex}set lineIndex(e){this.currentElement.lineIndex=e}get characterIndex(){return this.currentElement.characterIndex}set characterIndex(e){this.currentElement.characterIndex=e}get characterInLineIndex(){return this.currentElement.characterInLineIndex}set characterInLineIndex(e){this.currentElement.characterInLineIndex=e}get customFlags(){return this.currentElement.customFlags}set customFlags(e){this.currentElement.customFlags=e}get errorReportedAlreadyInScope(){return this.currentElement.reportedErrorInScope}get stackHeight(){return this._numElements}constructor(){this._stack=[],this._numElements=0,this.StringParserState=()=>{this._stack=new Array(200);for(let t=0;t<200;++t)this._stack[t]=new o.StringParserElement;this._numElements=1},this.Push=()=>{if(this._numElements>=this._stack.length&&this._numElements>0)throw new Error("Stack overflow in parser state.");const f=this._stack[this._numElements-1],t=this._stack[this._numElements];return this._numElements++,t.CopyFrom(f),t.uniqueId},this.Pop=f=>{if(this._numElements==1)throw new Error("Attempting to remove final stack element is illegal! Mismatched Begin/Succceed/Fail?");if(this.currentElement.uniqueId!=f)throw new Error("Mismatched rule IDs while Poping - do you have mismatched Begin/Succeed/Fail?");this._numElements-=1},this.Peek=f=>{if(this.currentElement.uniqueId!=f)throw new Error("Mismatched rule IDs while Peeking - do you have mismatched Begin/Succeed/Fail?");return this._stack[this._numElements-1]},this.PeekPenultimate=()=>this._numElements>=2?this._stack[this._numElements-2]:null,this.Squash=()=>{if(this._numElements<2)throw new Error("Attempting to remove final stack element is illegal! Mismatched Begin/Succceed/Fail?");const f=this._stack[this._numElements-2],t=this._stack[this._numElements-1];f.SquashFrom(t),this._numElements-=1},this.NoteErrorReported=()=>{for(const f of this._stack)f.reportedErrorInScope=!0};const e=200;for(let f=0;f<e;f++)this._stack[f]=new o.StringParserElement;this._numElements=1}};return Re.StringParserState=n,Re}var br;function Gs(){return br||(br=1,(function(o){Object.defineProperty(o,"__esModule",{value:!0}),o.StringParser=o.ParseSuccess=void 0;const n=ai(),a=xa();o.ParseSuccess=Symbol("ParseSuccessStruct");class e{constructor(t){this.ParseRule=null,this.errorHandler=null,this.hadError=!1,this.BeginRule=()=>this.state.Push(),this.FailRule=r=>(this.state.Pop(r),null),this.CancelRule=r=>{this.state.Pop(r)},this.SucceedRule=(r,y=null)=>{const s=this.state.Peek(r),c=this.state.PeekPenultimate();this.RuleDidSucceed&&this.RuleDidSucceed(y,c,s),this.state.Squash();let i=y;return i===null&&(i=e.ParseSuccess),i},this.Expect=(r,y=null,s=null)=>{let c=this.ParseObject(r);if(c===null){y===null&&(y=r.name);let i;const l=this.LineRemainder();l===null||l.length===0?i="end of line":i=`'${l}'`,this.Error(`Expected ${y} but saw ${i}`),s!==null&&(c=s())}return c},this.Error=(r,y=!1)=>{this.ErrorOnLine(r,this.lineIndex+1,y)},this.ErrorWithParsedObject=(r,y,s=!1)=>{this.ErrorOnLine(r,y.debugMetadata?y.debugMetadata.startLineNumber:-1,s)},this.ErrorOnLine=(r,y,s)=>{if(!this.state.errorReportedAlreadyInScope){const c=s?"Warning":"Error";if(this.errorHandler)this.errorHandler(r,this.index,y-1,s);else throw new Error(`${c} on line ${y}: ${r}`);this.state.NoteErrorReported()}s||(this.hadError=!0)},this.Warning=r=>this.Error(r,!0),this.LineRemainder=()=>this.Peek(()=>this.ParseUntilCharactersFromString(`
|
|
5
5
|
\r`)),this.SetFlag=(r,y)=>{y?this.state.customFlags|=r:this.state.customFlags&=~r},this.GetFlag=r=>!!(this.state.customFlags&r),this.ParseObject=r=>{const y=this.BeginRule(),s=this.state.stackHeight,c=r();if(s!==this.state.stackHeight)throw new Error("Mismatched Begin/Fail/Succeed rules");return c===null?this.FailRule(y):(this.SucceedRule(y,c),c)},this.Parse=r=>{const y=this.BeginRule(),s=r();return s===null?(this.FailRule(y),null):(this.SucceedRule(y,s),s)},this.OneOf=r=>{for(const y of r){const s=this.ParseObject(y);if(s!==null)return s}return null},this.OneOrMore=r=>{const y=[];let s=null;do s=this.ParseObject(r),s!==null&&y.push(s);while(s!==null);return y.length>0?y:null},this.Optional=r=>()=>{const y=this.ParseObject(r);return y===null?e.ParseSuccess:y},this.Exclude=r=>()=>this.ParseObject(r)&&e.ParseSuccess,this.OptionalExclude=r=>()=>(this.ParseObject(r),e.ParseSuccess),this.String=r=>()=>this.ParseString(r),this.TryAddResultToList=(r,y,s=!0)=>{if(r!==e.ParseSuccess){if(s&&Array.isArray(r)){const c=r;if(c!==null){for(const i of c)y.push(i);return}}y.push(r)}},this.Interleave=(r,y,s=null,c=!0)=>{const i=this.BeginRule(),l=[],S=this.ParseObject(r);if(S===null)return this.FailRule(i);this.TryAddResultToList(S,l,c);let P=null,N=null;do{if(s!==null&&this.Peek(s)!==null||(P=this.ParseObject(y),P===null))break;if(this.TryAddResultToList(P,l,c),N=null,P!==null){if(N=this.ParseObject(r),N===null)break;this.TryAddResultToList(N,l,c)}}while((P!==null||N!==null)&&!(P===e.ParseSuccess&&N==e.ParseSuccess)&&this.remainingLength>0);return l.length===0?this.FailRule(i):this.SucceedRule(i,l)},this.ParseString=r=>{if(r.length>this.remainingLength)return null;const y=this.BeginRule();let s=this.index,c=this.characterInLineIndex,i=this.lineIndex,l=!0;for(let S=0;S<r.length;S+=1){const P=r[S];if(this._chars[s]!==P){l=!1;break}P===`
|
|
6
6
|
`&&(i++,c=-1),s++,c++}return this.index=s,this.characterInLineIndex=c,this.lineIndex=i,l?this.SucceedRule(y,r):this.FailRule(y)},this.ParseSingleCharacter=()=>{if(this.remainingLength>0){const r=this._chars[this.index];return r===`
|
|
7
7
|
`&&(this.lineIndex+=1,this.characterInLineIndex=-1),this.index+=1,this.characterInLineIndex+=1,r}return"0"},this.ParseUntilCharactersFromString=(r,y=-1)=>this.ParseCharactersFromString(r,!1,y),this.ParseUntilCharactersFromCharSet=(r,y=-1)=>this.ParseCharactersFromCharSet(r,!1,y),this.ParseCharactersFromString=(r,y=-1,s=-1)=>{const c=new n.CharacterSet(r);return typeof y=="number"?this.ParseCharactersFromCharSet(c,!0,y):this.ParseCharactersFromCharSet(c,y,s)},this.ParseCharactersFromCharSet=(r,y=!0,s=-1)=>{s===-1&&(s=Number.MAX_SAFE_INTEGER);const c=this.index;let i=this.index,l=this.characterInLineIndex,S=this.lineIndex,P=0;for(;i<this._chars.length&&r.set.has(this._chars[i])===y&&P<s;)this._chars[i]===`
|
|
8
8
|
`&&(S+=1,l=-1),i+=1,l+=1,P+=1;return this.index=i,this.characterInLineIndex=l,this.lineIndex=S,this.index>c?this._chars.slice(c,this.index).join(""):null},this.Peek=r=>{const y=this.BeginRule(),s=r();return this.CancelRule(y),s},this.ParseInt=()=>{const r=this.index,y=this.characterInLineIndex,s=this.ParseString("-")!==null;this.ParseCharactersFromString(" ");const c=this.ParseCharactersFromCharSet(e.numbersCharacterSet);if(c===null)return this.index=r,this.characterInLineIndex=y,null;let i;return Number.isNaN(Number(c))?(this.Error("Failed to read integer value: "+c+". Perhaps it's out of the range of acceptable numbers ink supports? ("+Number.MIN_SAFE_INTEGER+" to "+Number.MAX_SAFE_INTEGER+")"),null):(i=Number(c),s?-i:i)},this.ParseFloat=()=>{const r=this.index,y=this.characterInLineIndex,s=this.ParseInt();if(s!==null&&this.ParseString(".")!==null){const c=this.ParseCharactersFromCharSet(e.numbersCharacterSet);return+`${s}.${c}`}return this.index=r,this.characterInLineIndex=y,null},this.ParseNewline=()=>{const r=this.BeginRule();return this.ParseString("\r"),this.ParseString(`
|
|
9
9
|
`)===null?this.FailRule(r):this.SucceedRule(r,`
|
|
10
10
|
`)};const p=this.PreProcessInputString(t);this.state=new a.StringParserState,t?this._chars=p.split(""):this._chars=[],this.inputString=p}get currentCharacter(){return this.index>=0&&this.remainingLength>0?this._chars[this.index]:"0"}PreProcessInputString(t){return t}get endOfInput(){return this.index>=this._chars.length}get remainingString(){return this._chars.slice(this.index,this.index+this.remainingLength).join("")}get remainingLength(){return this._chars.length-this.index}get lineIndex(){return this.state.lineIndex}set lineIndex(t){this.state.lineIndex=t}set characterInLineIndex(t){this.state.characterInLineIndex=t}get characterInLineIndex(){return this.state.characterInLineIndex}get index(){return this.state.characterIndex}set index(t){this.state.characterIndex=t}ParseUntil(t,p=null,r=null){const y=this.BeginRule(),s=new n.CharacterSet;p!==null&&(s.set=new Set([...s.set.values(),...p.set.values()])),r!==null&&(s.set=new Set([...s.set.values(),...r.set.values()]));let c="",i=null;do{const l=this.ParseUntilCharactersFromCharSet(s);if(l&&(c+=l),i=this.Peek(t),i!==null)break;{if(this.endOfInput)break;const S=this.currentCharacter;if(p!==null&&p.set.has(S)){c+=S,S===`
|
|
11
|
-
`&&(this.lineIndex+=1,this.characterInLineIndex=-1),this.index+=1,this.characterInLineIndex+=1;continue}else break}}while(!0);return c.length>0?this.SucceedRule(y,String(c)):this.FailRule(y)}}o.StringParser=e,e.ParseSuccess=o.ParseSuccess,e.numbersCharacterSet=new n.CharacterSet("0123456789")})(mi)),mi}var _r;function Ta(){if(_r)return
|
|
11
|
+
`&&(this.lineIndex+=1,this.characterInLineIndex=-1),this.index+=1,this.characterInLineIndex+=1;continue}else break}}while(!0);return c.length>0?this.SucceedRule(y,String(c)):this.FailRule(y)}}o.StringParser=e,e.ParseSuccess=o.ParseSuccess,e.numbersCharacterSet=new n.CharacterSet("0123456789")})(mi)),mi}var _r;function Ta(){if(_r)return Fe;_r=1,Object.defineProperty(Fe,"__esModule",{value:!0}),Fe.CommentEliminator=void 0;const o=ai(),n=Gs();let a=class extends n.StringParser{constructor(){super(...arguments),this._commentOrNewlineStartCharacter=new o.CharacterSet(`/\r
|
|
12
12
|
`),this._commentBlockEndCharacter=new o.CharacterSet("*"),this._newlineCharacters=new o.CharacterSet(`
|
|
13
13
|
\r`),this.Process=()=>{const f=this.Interleave(this.Optional(this.CommentsAndNewlines),this.Optional(this.MainInk));return f!==null?f.join(""):""},this.MainInk=()=>this.ParseUntil(this.CommentsAndNewlines,this._commentOrNewlineStartCharacter,null),this.CommentsAndNewlines=()=>{let f=this.Interleave(this.Optional(this.ParseNewline),this.Optional(this.ParseSingleComment));return f!==null?f.join(""):null},this.ParseSingleComment=()=>this.OneOf([this.EndOfLineComment,this.BlockComment]),this.EndOfLineComment=()=>this.ParseString("//")===null?null:(this.ParseUntilCharactersFromCharSet(this._newlineCharacters),""),this.BlockComment=()=>{if(this.ParseString("/*")===null)return null;const f=this.lineIndex,t=this.ParseUntil(this.String("*/"),this._commentBlockEndCharacter,null);return this.endOfInput||this.ParseString("*/"),t!=null?`
|
|
14
|
-
`.repeat(this.lineIndex-f):null}}PreProcessInputString(f){return f}};return Re.CommentEliminator=a,Re}var Ve={},Er;function Ii(){if(Er)return Ve;Er=1,Object.defineProperty(Ve,"__esModule",{value:!0}),Ve.Conditional=void 0;const o=ot(),n=pt(),a=et();let e=class extends a.ParsedObject{constructor(t,p){super(),this.initialCondition=t,this.branches=p,this._reJoinTarget=null,this.GenerateRuntimeObject=()=>{const r=new o.Container;this.initialCondition&&r.AddContent(this.initialCondition.runtimeObject);for(const y of this.branches){const s=y.runtimeObject;r.AddContent(s)}return this.initialCondition!==null&&this.branches[0].ownExpression!==null&&!this.branches[this.branches.length-1].isElse&&r.AddContent(n.ControlCommand.PopEvaluatedValue()),this._reJoinTarget=n.ControlCommand.NoOp(),r.AddContent(this._reJoinTarget),r},this.initialCondition&&this.AddContent(this.initialCondition),this.branches!==null&&this.AddContent(this.branches)}get typeName(){return"Conditional"}ResolveReferences(t){const p=this._reJoinTarget.path;for(const r of this.branches){if(!r.returnDivert)throw new Error;r.returnDivert.targetPath=p}super.ResolveReferences(t)}};return Ve.Conditional=e,Ve}var We={},Le={},wr;function $t(){if(wr)return Le;wr=1,Object.defineProperty(Le,"__esModule",{value:!0}),Le.Text=void 0;const o=et(),n=it();let a=class extends o.ParsedObject{constructor(f){super(),this.text=f,this.GenerateRuntimeObject=()=>new n.StringValue(this.text),this.toString=()=>this.text}get typeName(){return"Text"}};return Le.Text=a,Le}var je={},Me={},Pr;function Ai(){if(Pr)return Me;Pr=1,Object.defineProperty(Me,"__esModule",{value:!0}),Me.ConstantDeclaration=void 0;const o=et(),n=Wt();let a=class extends o.ParsedObject{get constantName(){var f;return(f=this.constantIdentifier)===null||f===void 0?void 0:f.name}get expression(){if(!this._expression)throw new Error;return this._expression}constructor(f,t){super(),this._expression=null,this.GenerateRuntimeObject=()=>null,this.constantIdentifier=f,t&&(this._expression=this.AddContent(t))}get typeName(){return"CONST"}ResolveReferences(f){super.ResolveReferences(f),f.CheckForNamingCollisions(this,this.constantIdentifier,n.SymbolType.Var)}};return Me.ConstantDeclaration=a,Me}var Be={},qe={},Ge={},$e={},Or;function Un(){if(Or)return $e;Or=1,Object.defineProperty($e,"__esModule",{value:!0}),$e.FlowLevel=void 0;var o;return(function(n){n[n.Story=0]="Story",n[n.Knot=1]="Knot",n[n.Stitch=2]="Stitch",n[n.WeavePoint=3]="WeavePoint"})(o||($e.FlowLevel=o={})),$e}var Ue={},xr;function li(){if(xr)return Ue;xr=1,Object.defineProperty(Ue,"__esModule",{value:!0}),Ue.Gather=void 0;const o=ot(),n=et(),a=Wt();let e=class extends n.ParsedObject{get name(){var t;return((t=this.identifier)===null||t===void 0?void 0:t.name)||null}get runtimeContainer(){return this.runtimeObject}constructor(t,p){super(),this.indentationDepth=p,this.GenerateRuntimeObject=()=>{const r=new o.Container;if(r.name=this.name,this.story.countAllVisits&&(r.visitsShouldBeCounted=!0),r.countingAtStartOnly=!0,this.content)for(const y of this.content)r.AddContent(y.runtimeObject);return r},this.toString=()=>{var r,y;return`- ${!((r=this.identifier)===null||r===void 0)&&r.name?"("+((y=this.identifier)===null||y===void 0?void 0:y.name)+")":"gather"}`},t&&(this.identifier=t)}get typeName(){return"Gather"}ResolveReferences(t){super.ResolveReferences(t),this.identifier&&(this.identifier.name||"").length>0&&t.CheckForNamingCollisions(this,this.identifier,a.SymbolType.SubFlowAndWeave)}};return Ue.Gather=e,Ue}var Ke={},Tr;function ne(){if(Tr)return Ke;Tr=1,Object.defineProperty(Ke,"__esModule",{value:!0}),Ke.Path=void 0;const o=Z(),n=kt(),a=Un(),e=ie();let f=class{get baseTargetLevel(){return this.baseLevelIsAmbiguous?a.FlowLevel.Story:this._baseTargetLevel}get baseLevelIsAmbiguous(){return!this._baseTargetLevel}get firstComponent(){return this.components==null||!this.components.length?null:this.components[0].name}get numberOfComponents(){return this.components?this.components.length:0}get dotSeparatedComponents(){return this._dotSeparatedComponents==null&&(this._dotSeparatedComponents=(this.components?this.components:[]).map(p=>p.name).filter(o.filterUndef).join(".")),this._dotSeparatedComponents}constructor(p,r){this._dotSeparatedComponents=null,this.toString=()=>this.components===null||this.components.length===0?this.baseTargetLevel===a.FlowLevel.WeavePoint?"-> <next gather point>":"<invalid Path>":`-> ${this.dotSeparatedComponents}`,this.ResolveFromContext=y=>{if(this.components==null||this.components.length==0)return null;let s=this.ResolveBaseTarget(y);return s===null?null:this.components.length>1?this.ResolveTailComponents(s):s},this.ResolveBaseTarget=y=>{const s=this.firstComponent;let c=y;for(;c;){const i=c===y,l=this.GetChildFromContext(c,s,null,i);if(l)return l;c=c.parent}return null},this.ResolveTailComponents=y=>{let s=y;if(!this.components)return null;for(let c=1;c<this.components.length;++c){const i=this.components[c].name;let l,S=(0,o.asOrNull)(s,n.FlowBase);if(S!==null?l=S.flowLevel+1:l=a.FlowLevel.WeavePoint,s=this.GetChildFromContext(s,i,l),s===null)break}return s},this.GetChildFromContext=(y,s,c,i=!1)=>{const l=c===null,S=(0,o.asOrNull)(y,e.Weave);if(s&&S!==null&&(l||c===a.FlowLevel.WeavePoint))return S.WeavePointNamed(s);let P=(0,o.asOrNull)(y,n.FlowBase);if(s&&P!==null){const N=i||P.flowLevel===a.FlowLevel.Knot;return P.ContentWithNameAtLevel(s,c,N)}return null},Object.values(a.FlowLevel).includes(p)?(this._baseTargetLevel=p,this.components=r||[]):Array.isArray(p)?(this._baseTargetLevel=null,this.components=p||[]):(this._baseTargetLevel=null,this.components=[p])}get typeName(){return"Path"}};return Ke.Path=f,Ke}var He={},Nr;function $s(){if(Nr)return He;Nr=1,Object.defineProperty(He,"__esModule",{value:!0}),He.ReturnType=void 0;const o=et(),n=ot(),a=pt(),e=te();let f=class extends o.ParsedObject{constructor(p=null){super(),this.returnedExpression=null,this.GenerateRuntimeObject=()=>{const r=new n.Container;return this.returnedExpression?r.AddContent(this.returnedExpression.runtimeObject):(r.AddContent(a.ControlCommand.EvalStart()),r.AddContent(new e.Void),r.AddContent(a.ControlCommand.EvalEnd())),r.AddContent(a.ControlCommand.PopFunction()),r},p&&(this.returnedExpression=this.AddContent(p))}get typeName(){return"ReturnType"}};return He.ReturnType=f,He}var Je={},Ir;function ui(){if(Ir)return Je;Ir=1,Object.defineProperty(Je,"__esModule",{value:!0}),Je.ClosestFlowBase=void 0;function o(n){let a=n.parent;for(;a;){if(a.hasOwnProperty("iamFlowbase")&&a.iamFlowbase())return a;a=a.parent}return null}return Je.ClosestFlowBase=o,Je}var ze={},Ar;function Fi(){if(Ar)return ze;Ar=1,Object.defineProperty(ze,"__esModule",{value:!0}),ze.Identifier=void 0;let o=class Us{constructor(a){this.debugMetadata=null,this.toString=()=>this.name||"undefined identifer",this.name=a}get typeName(){return"Identifier"}static Done(){return new Us("DONE")}};return ze.Identifier=o,ze}var Fr;function kt(){if(Fr)return Ge;Fr=1,Object.defineProperty(Ge,"__esModule",{value:!0}),Ge.FlowBase=void 0;const o=$n(),n=zn(),a=Jn(),e=Un(),f=li(),t=et(),p=ne(),r=$s(),y=ot(),s=Rt(),c=Gt(),i=Wt(),l=ie(),S=ui(),P=Fi(),N=Z();let O=class yi extends t.ParsedObject{get hasParameters(){return this.args!==null&&this.args.length>0}get subFlowsByName(){return this._subFlowsByName}get typeName(){return this.isFunction?"Function":String(this.flowLevel)}get name(){var w;return((w=this.identifier)===null||w===void 0?void 0:w.name)||null}constructor(w,F=null,k=null,m=!1,g=!1){super(),this.isFunction=m,this._rootWeave=null,this._subFlowsByName=new Map,this._startingSubFlowDivert=null,this._startingSubFlowRuntime=null,this._firstChildFlow=null,this.variableDeclarations=new Map,this.identifier=null,this.args=null,this.iamFlowbase=()=>!0,this.SplitWeaveAndSubFlowContent=(v,u)=>{var h,b;const R=[],V=[];this._subFlowsByName=new Map;for(const L of v){const C=(0,N.asOrNull)(L,yi);C?(this._firstChildFlow===null&&(this._firstChildFlow=C),V.push(L),!((h=C.identifier)===null||h===void 0)&&h.name&&this._subFlowsByName.set((b=C.identifier)===null||b===void 0?void 0:b.name,C)):R.push(L)}u&&R.push(new f.Gather(null,1),new n.Divert(new p.Path(P.Identifier.Done())));const j=[];return R.length>0&&(this._rootWeave=new l.Weave(R,0),j.push(this._rootWeave)),V.length>0&&j.push(...V),j},this.ResolveVariableWithName=(v,u)=>{var h;const b={},R=u===null?this:(0,S.ClosestFlowBase)(u);if(R){if(R.args!==null){for(const V of R.args)if(((h=V.identifier)===null||h===void 0?void 0:h.name)===v)return b.found=!0,b.isArgument=!0,b.ownerFlow=R,b}if(R!==this.story&&R.variableDeclarations.has(v))return b.found=!0,b.ownerFlow=R,b.isTemporary=!0,b}return this.story.variableDeclarations.has(v)?(b.found=!0,b.ownerFlow=this.story,b.isGlobal=!0,b):(b.found=!1,b)},this.AddNewVariableDeclaration=v=>{const u=v.variableName;if(this.variableDeclarations.has(u)){const h=this.variableDeclarations.get(u);let b="";h.debugMetadata&&(b=` (${h.debugMetadata})`),this.Error(`found declaration variable '${u}' that was already declared${b}`,v,!1);return}this.variableDeclarations.set(v.variableName,v)},this.ResolveWeavePointNaming=()=>{this._rootWeave&&this._rootWeave.ResolveWeavePointNaming();for(const[,v]of this._subFlowsByName)v.hasOwnProperty("ResolveWeavePointNaming")&&v.ResolveWeavePointNaming()},this.GenerateRuntimeObject=()=>{var v;let u=null;this.isFunction?this.CheckForDisallowedFunctionFlowControl():(this.flowLevel===e.FlowLevel.Knot||this.flowLevel===e.FlowLevel.Stitch)&&(u=this.Find(r.ReturnType)(),u!==null&&this.Error(`Return statements can only be used in knots that are declared as functions: == function ${this.identifier} ==`,u));const h=new y.Container;h.name=(v=this.identifier)===null||v===void 0?void 0:v.name,this.story.countAllVisits&&(h.visitsShouldBeCounted=!0),this.GenerateArgumentVariableAssignments(h);let b=0;for(;this.content!==null&&b<this.content.length;){const R=this.content[b];if(R instanceof yi){const V=R,j=V.runtimeObject;b===0&&!V.hasParameters&&this.flowLevel===e.FlowLevel.Knot&&(this._startingSubFlowDivert=new s.Divert,h.AddContent(this._startingSubFlowDivert),this._startingSubFlowRuntime=j);const L=j,C=h.namedContent.get(L.name)||null;if(C){const E=`${this.GetType()} already contains flow named '${L.name}' (at ${C.debugMetadata})`;this.Error(E,V)}h.AddToNamedContentOnly(L)}else R&&h.AddContent(R.runtimeObject);b+=1}return this.flowLevel!==e.FlowLevel.Story&&!this.isFunction&&this._rootWeave!==null&&u===null&&this._rootWeave.ValidateTermination(this.WarningInTermination),h},this.GenerateArgumentVariableAssignments=v=>{var u;if(!(this.args===null||this.args.length===0))for(let h=this.args.length-1;h>=0;--h){const b=((u=this.args[h].identifier)===null||u===void 0?void 0:u.name)||null,R=new c.VariableAssignment(b,!0);v.AddContent(R)}},this.ContentWithNameAtLevel=(v,u=null,h=!1)=>{var b;if((u===this.flowLevel||u===null)&&v===((b=this.identifier)===null||b===void 0?void 0:b.name))return this;if(u===e.FlowLevel.WeavePoint||u===null){let V=null;if(this._rootWeave&&(V=this._rootWeave.WeavePointNamed(v),V))return V;if(u===e.FlowLevel.WeavePoint)return h?this.DeepSearchForAnyLevelContent(v):null}if(u!==null&&u<this.flowLevel)return null;let R=this._subFlowsByName.get(v)||null;return R&&(u===null||u===R.flowLevel)?R:h?this.DeepSearchForAnyLevelContent(v):null},this.DeepSearchForAnyLevelContent=v=>{const u=this.ContentWithNameAtLevel(v,e.FlowLevel.WeavePoint,!1);if(u)return u;for(const[,h]of this._subFlowsByName){const b=h.ContentWithNameAtLevel(v,null,!0);if(b)return b}return null},this.CheckForDisallowedFunctionFlowControl=()=>{this.flowLevel!==e.FlowLevel.Knot&&this.Error("Functions cannot be stitches - i.e. they should be defined as '== function myFunc ==' rather than internal to another knot.");for(const[h,b]of this._subFlowsByName)this.Error(`Functions may not contain stitches, but saw '${h}' within the function '${this.identifier}'`,b);if(!this._rootWeave)throw new Error;const v=this._rootWeave.FindAll(n.Divert)();for(const h of v)!h.isFunctionCall&&!(h.parent instanceof a.DivertTarget)&&this.Error(`Functions may not contain diverts, but saw '${h}'`,h);const u=this._rootWeave.FindAll(o.Choice)();for(const h of u)this.Error(`Functions may not contain choices, but saw '${h}'`,h)},this.WarningInTermination=v=>{let u="Apparent loose end exists where the flow runs out. Do you need a '-> DONE' statement, choice or divert?";v.parent===this._rootWeave&&this._firstChildFlow&&(u=`${u} Note that if you intend to enter '${this._firstChildFlow.identifier}' next, you need to divert to it explicitly.`);const h=(0,N.asOrNull)(v,n.Divert);h&&h.isTunnel&&(u+=` When final tunnel to '${h.target} ->' returns it won't have anywhere to go.`),this.Warning(u,v)},this.toString=()=>`${this.typeName} '${this.identifier}'`,this.identifier=w,this.args=k,F===null&&(F=[]),this.PreProcessTopLevelObjects(F),F=this.SplitWeaveAndSubFlowContent(F,this.GetType()=="Story"&&!g),this.AddContent(F)}PreProcessTopLevelObjects(w){}ResolveReferences(w){var F,k;if(this._startingSubFlowDivert){if(!this._startingSubFlowRuntime)throw new Error;this._startingSubFlowDivert.targetPath=this._startingSubFlowRuntime.path}if(super.ResolveReferences(w),this.args!==null){for(const m of this.args)w.CheckForNamingCollisions(this,m.identifier,i.SymbolType.Arg,"argument");for(let m=0;m<this.args.length;m+=1)for(let g=m+1;g<this.args.length;g+=1)((F=this.args[m].identifier)===null||F===void 0?void 0:F.name)==((k=this.args[g].identifier)===null||k===void 0?void 0:k.name)&&this.Error(`Multiple arguments with the same name: '${this.args[m].identifier}'`)}if(this.flowLevel!==e.FlowLevel.Story){const m=this.flowLevel===e.FlowLevel.Knot?i.SymbolType.Knot:i.SymbolType.SubFlowAndWeave;w.CheckForNamingCollisions(this,this.identifier,m)}}};return Ge.FlowBase=O,Ge}var Xe={},Ye={},Ze={},Rr;function Ri(){if(Rr)return Ze;Rr=1,Object.defineProperty(Ze,"__esModule",{value:!0}),Ze.ContentList=void 0;const o=ot(),n=et(),a=$t(),e=Z();let f=class extends n.ParsedObject{get runtimeContainer(){return this.runtimeObject}constructor(p,...r){super(),this.dontFlatten=!1,this.TrimTrailingWhitespace=()=>{for(let y=this.content.length-1;y>=0;--y){const s=(0,e.asOrNull)(this.content[y],a.Text);if(s===null)break;if(s.text=s.text.replace(new RegExp(/[ \t]/g),""),s.text.length===0)this.content.splice(y,1);else break}},this.GenerateRuntimeObject=()=>{const y=new o.Container;if(this.content!==null)for(const s of this.content){const c=s.runtimeObject;c&&y.AddContent(c)}return this.dontFlatten&&this.story.DontFlattenContainer(y),y},this.toString=()=>`ContentList(${this.content.join(", ")})`,p&&this.AddContent(p),r&&this.AddContent(r)}get typeName(){return"ContentList"}};return Ze.ContentList=f,Ze}var Qe={},kr;function Kn(){if(kr)return Qe;kr=1,Object.defineProperty(Qe,"__esModule",{value:!0}),Qe.VariableReference=void 0;const o=yt(),n=St();let a=class extends o.InkObject{get containerForCount(){return this.pathForCount===null?null:this.ResolvePath(this.pathForCount).container}get pathStringForCount(){return this.pathForCount===null?null:this.CompactPathString(this.pathForCount)}set pathStringForCount(f){f===null?this.pathForCount=null:this.pathForCount=new n.Path(f)}constructor(f=null){super(),this.pathForCount=null,this.name=f}toString(){return this.name!=null?"var("+this.name+")":"read_count("+this.pathStringForCount+")"}};return Qe.VariableReference=a,Qe}var Dr;function Hn(){if(Dr)return Ye;Dr=1,Object.defineProperty(Ye,"__esModule",{value:!0}),Ye.VariableReference=void 0;const o=Ri(),n=Ot(),a=kt(),e=ne(),f=Kn(),t=ie(),p=Fi(),r=Z();class y extends n.Expression{get name(){return this.path.join(".")}get path(){return this.pathIdentifiers.map(c=>c.name).filter(r.filterUndef)}get identifier(){if(!this.pathIdentifiers||this.pathIdentifiers.length==0)return null;const c=this.path.join(".");return new p.Identifier(c)}get runtimeVarRef(){return this._runtimeVarRef}constructor(c){super(),this.pathIdentifiers=c,this._runtimeVarRef=null,this.isConstantReference=!1,this.isListItemReference=!1,this.GenerateIntoContainer=i=>{let l=this.story.constants.get(this.name);if(l){l.GenerateConstantIntoContainer(i),this.isConstantReference=!0;return}if(this._runtimeVarRef=new f.VariableReference(this.name),this.path.length===1||this.path.length===2){let S="",P="";this.path.length===1?S=this.path[0]:(P=this.path[0],S=this.path[1]),this.story.ResolveListItem(P,S,this)&&(this.isListItemReference=!0)}i.AddContent(this._runtimeVarRef)},this.toString=()=>`{${this.path.join(".")}}`}get typeName(){return"ref"}ResolveReferences(c){if(super.ResolveReferences(c),this.isConstantReference||this.isListItemReference)return;const i=new e.Path(this.pathIdentifiers),l=i.ResolveFromContext(this);if(l){if(!l.containerForCounting)throw new Error;if(l.containerForCounting.visitsShouldBeCounted=!0,this._runtimeVarRef===null)return;this._runtimeVarRef.pathForCount=l.runtimePath,this._runtimeVarRef.name=null;let S=(0,r.asOrNull)(l,a.FlowBase);S&&S.isFunction&&(this.parent instanceof t.Weave||this.parent instanceof o.ContentList||this.parent instanceof a.FlowBase)&&this.Warning(`'${S.identifier}' being used as read count rather than being called as function. Perhaps you intended to write ${S.identifier}()`);return}if(this.path.length>1){let S=`Could not find target for read count: ${i}`;this.path.length<=2&&(S+=`, or couldn't find list item with the name ${this.path.join(",")}`),this.Error(S);return}c.ResolveVariableWithName(this.name,this).found||this.Error(`Unresolved variable: ${this.name}`,this)}}return Ye.VariableReference=y,Ye}var Vr;function hi(){if(Vr)return Xe;Vr=1,Object.defineProperty(Xe,"__esModule",{value:!0}),Xe.FunctionCall=void 0;const o=pt(),n=zn(),a=Jn(),e=Ot(),f=vt(),t=it(),p=Ft(),r=Ti(),y=ne(),s=it(),c=Hn(),i=Z();let l=class bi extends e.Expression{get proxyDivert(){return this._proxyDivert}get name(){return this._proxyDivert.target.firstComponent||""}get args(){return this._proxyDivert.args}get runtimeDivert(){return this._proxyDivert.runtimeDivert}get isChoiceCount(){return this.name==="CHOICE_COUNT"}get isTurns(){return this.name==="TURNS"}get isTurnsSince(){return this.name==="TURNS_SINCE"}get isRandom(){return this.name==="RANDOM"}get isSeedRandom(){return this.name==="SEED_RANDOM"}get isListRange(){return this.name==="LIST_RANGE"}get isListRandom(){return this.name==="LIST_RANDOM"}get isReadCount(){return this.name==="READ_COUNT"}constructor(P,N){super(),this._divertTargetToCount=null,this._variableReferenceToCount=null,this.shouldPopReturnedValue=!1,this.GenerateIntoContainer=O=>{const I=this.story.ResolveList(this.name);let w=!1;if(this.isChoiceCount)this.args.length>0&&this.Error("The CHOICE_COUNT() function shouldn't take any arguments"),O.AddContent(o.ControlCommand.ChoiceCount());else if(this.isTurns)this.args.length>0&&this.Error("The TURNS() function shouldn't take any arguments"),O.AddContent(o.ControlCommand.Turns());else if(this.isTurnsSince||this.isReadCount){const F=(0,i.asOrNull)(this.args[0],a.DivertTarget),k=(0,i.asOrNull)(this.args[0],c.VariableReference);if(this.args.length!==1||F===null&&k===null){this.Error(`The ${this.name}() function should take one argument: a divert target to the target knot, stitch, gather or choice you want to check. e.g. TURNS_SINCE(-> myKnot)`);return}F?(this._divertTargetToCount=F,this.AddContent(this._divertTargetToCount),this._divertTargetToCount.GenerateIntoContainer(O)):k&&(this._variableReferenceToCount=k,this.AddContent(this._variableReferenceToCount),this._variableReferenceToCount.GenerateIntoContainer(O)),this.isTurnsSince?O.AddContent(o.ControlCommand.TurnsSince()):O.AddContent(o.ControlCommand.ReadCount())}else if(this.isRandom){this.args.length!==2&&this.Error("RANDOM should take 2 parameters: a minimum and a maximum integer");for(let F=0;F<this.args.length;F+=1){const k=(0,i.asOrNull)(this.args[F],r.NumberExpression);if(k&&!k.isInt()){const m=F===0?"minimum":"maximum";this.Error(`RANDOM's ${m} parameter should be an integer`)}this.args[F].GenerateIntoContainer(O)}O.AddContent(o.ControlCommand.Random())}else if(this.isSeedRandom){this.args.length!==1&&this.Error("SEED_RANDOM should take 1 parameter - an integer seed");const F=(0,i.asOrNull)(this.args[0],r.NumberExpression);F&&!F.isInt()&&this.Error("SEED_RANDOM's parameter should be an integer seed"),this.args[0].GenerateIntoContainer(O),O.AddContent(o.ControlCommand.SeedRandom())}else if(this.isListRange){this.args.length!==3&&this.Error("LIST_RANGE should take 3 parameters - a list, a min and a max");for(let F=0;F<this.args.length;F+=1)this.args[F].GenerateIntoContainer(O);O.AddContent(o.ControlCommand.ListRange())}else if(this.isListRandom)this.args.length!==1&&this.Error("LIST_RANDOM should take 1 parameter - a list"),this.args[0].GenerateIntoContainer(O),O.AddContent(o.ControlCommand.ListRandom());else if(p.NativeFunctionCall.CallExistsWithName(this.name)){const F=p.NativeFunctionCall.CallWithName(this.name);if(F.numberOfParameters!==this.args.length){let k=`${bi.name} should take ${F.numberOfParameters} parameter`;F.numberOfParameters>1&&(k+="s"),this.Error(k)}for(let k=0;k<this.args.length;k+=1)this.args[k].GenerateIntoContainer(O);O.AddContent(p.NativeFunctionCall.CallWithName(this.name))}else if(I!==null)if(this.args.length>1&&this.Error("Can currently only construct a list from one integer (or an empty list from a given list definition)"),this.args.length===1)O.AddContent(new s.StringValue(this.name)),this.args[0].GenerateIntoContainer(O),O.AddContent(o.ControlCommand.ListFromInt());else{const F=new f.InkList;F.SetInitialOriginName(this.name),O.AddContent(new t.ListValue(F))}else O.AddContent(this._proxyDivert.runtimeObject),w=!0;w||this.content.splice(this.content.indexOf(this._proxyDivert),1),this.shouldPopReturnedValue&&O.AddContent(o.ControlCommand.PopEvaluatedValue())},this.toString=()=>{const O=this.args.join(", ");return`${this.name}(${O})`},this._proxyDivert=new n.Divert(new y.Path(P),N),this._proxyDivert.isFunctionCall=!0,this.AddContent(this._proxyDivert)}get typeName(){return"FunctionCall"}ResolveReferences(P){if(super.ResolveReferences(P),!this.content.includes(this._proxyDivert)&&this.args!==null)for(const N of this.args)N.ResolveReferences(P);if(this._divertTargetToCount){const N=this._divertTargetToCount.divert,O=N.runtimeDivert.variableDivertName!=null;if(O){this.Error(`When getting the TURNS_SINCE() of a variable target, remove the '->' - i.e. it should just be TURNS_SINCE(${N.runtimeDivert.variableDivertName})`);return}const I=N.targetContent;if(I===null)O||this.Error(`Failed to find target for TURNS_SINCE: '${N.target}'`);else{if(!I.containerForCounting)throw new Error;I.containerForCounting.turnIndexShouldBeCounted=!0}}else if(this._variableReferenceToCount){const N=this._variableReferenceToCount.runtimeVarRef;if(!N)throw new Error;N.pathForCount!==null&&this.Error(`Should be '${bi.name}'(-> '${this._variableReferenceToCount.name}). Usage without the '->' only makes sense for variable targets.`)}}};return Xe.FunctionCall=l,l.IsBuiltIn=S=>p.NativeFunctionCall.CallExistsWithName(S)?!0:S==="CHOICE_COUNT"||S==="TURNS_SINCE"||S==="TURNS"||S==="RANDOM"||S==="SEED_RANDOM"||S==="LIST_VALUE"||S==="LIST_RANDOM"||S==="READ_COUNT",Xe}var tn={},Wr;function Ks(){if(Wr)return tn;Wr=1,Object.defineProperty(tn,"__esModule",{value:!0}),tn.MultipleConditionExpression=void 0;const o=Ot(),n=Ft();let a=class extends o.Expression{get subExpressions(){return this.content}constructor(f){super(),this.GenerateIntoContainer=t=>{let p=!0;for(const r of this.subExpressions)r.GenerateIntoContainer(t),p||t.AddContent(n.NativeFunctionCall.CallWithName("&&")),p=!1},this.AddContent(f)}get typeName(){return"MultipleConditionExpression"}};return tn.MultipleConditionExpression=a,tn}var Lr;function Jn(){if(Lr)return qe;Lr=1,Object.defineProperty(qe,"__esModule",{value:!0}),qe.DivertTarget=void 0;const o=qs(),n=$n(),a=Ii(),e=Zs(),f=it(),t=Ot(),p=kt(),r=hi(),y=Ks(),s=Hn(),c=Z();let i=class Zn extends t.Expression{get runtimeDivert(){if(!this._runtimeDivert)throw new Error;return this._runtimeDivert}get runtimeDivertTargetValue(){if(!this._runtimeDivertTargetValue)throw new Error;return this._runtimeDivertTargetValue}constructor(S){super(),this._runtimeDivert=null,this._runtimeDivertTargetValue=null,this.GenerateIntoContainer=P=>{this.divert.GenerateRuntimeObject(),this._runtimeDivert=this.divert.runtimeDivert,this._runtimeDivertTargetValue=new f.DivertTargetValue,P.AddContent(this.runtimeDivertTargetValue)},this.Equals=P=>{const N=(0,c.asOrNull)(P,Zn);if(!N||!this.divert.target||!N.divert.target)return!1;const O=this.divert.target.dotSeparatedComponents,I=N.divert.target.dotSeparatedComponents;return O===I},this.divert=this.AddContent(S)}get typeName(){return"DivertTarget"}ResolveReferences(S){if(super.ResolveReferences(S),this.divert.isDone||this.divert.isEnd){this.Error("Can't use -> DONE or -> END as variable divert targets",this);return}let P=this;for(;P&&P instanceof t.Expression;){let O=!1,I=!1;const w=P.parent;if(w instanceof o.BinaryExpression){const F=w;F.opName!=="=="&&F.opName!=="!="?O=!0:(F.leftExpression instanceof Zn||F.leftExpression instanceof s.VariableReference)&&(F.rightExpression instanceof Zn||F.rightExpression instanceof s.VariableReference)||(O=!0),I=!0}else if(w instanceof r.FunctionCall){const F=w;!F.isTurnsSince&&!F.isReadCount&&(O=!0),I=!0}else(w instanceof t.Expression||w instanceof y.MultipleConditionExpression||w instanceof n.Choice&&w.condition===P||w instanceof a.Conditional||w instanceof e.ConditionalSingleBranch)&&(O=!0,I=!0);if(O&&this.Error(`Can't use a divert target like that. Did you intend to call '${this.divert.target}' as a function: likeThis(), or check the read count: likeThis, with no arrows?`,this),I)break;P=w}if(this.runtimeDivert.hasVariableTarget){if(!this.divert.target)throw new Error;this.Error(`Since '${this.divert.target.dotSeparatedComponents}' is a variable, it shouldn't be preceded by '->' here.`)}this.runtimeDivert.targetPath&&(this.runtimeDivertTargetValue.targetPath=this.runtimeDivert.targetPath);let N=this.divert.targetContent;if(N!==null){let O=N.containerForCounting;if(O!==null){const w=(0,c.asOrNull)(this.parent,r.FunctionCall);w&&w.isTurnsSince||(O.visitsShouldBeCounted=!0),O.turnIndexShouldBeCounted=!0}let I=(0,c.asOrNull)(N,p.FlowBase);if(I!=null&&I.args!==null)for(const w of I.args)w.isByReference&&this.Error(`Can't store a divert target to a knot or function that has by-reference arguments ('${I.identifier}' has 'ref ${w.identifier}').`)}}};return qe.DivertTarget=i,qe}var jr;function zn(){if(jr)return Be;jr=1,Object.defineProperty(Be,"__esModule",{value:!0}),Be.Divert=void 0;const o=ot(),n=pt(),a=Rt(),e=Jn(),f=kt(),t=hi(),p=et(),r=ne(),y=St(),s=ee(),c=it(),i=Hn(),l=ui(),S=Z();let P=class extends p.ParsedObject{get runtimeDivert(){if(!this._runtimeDivert)throw new Error;return this._runtimeDivert}set runtimeDivert(O){this._runtimeDivert=O}get isEnd(){return!!(this.target&&this.target.dotSeparatedComponents==="END")}get isDone(){return!!(this.target&&this.target.dotSeparatedComponents==="DONE")}constructor(O,I){super(),this.args=[],this.target=null,this.targetContent=null,this._runtimeDivert=null,this.isFunctionCall=!1,this.isEmpty=!1,this.isTunnel=!1,this.isThread=!1,this.GenerateRuntimeObject=()=>{if(this.isEnd)return n.ControlCommand.End();if(this.isDone)return n.ControlCommand.Done();this.runtimeDivert=new a.Divert,this.ResolveTargetContent(),this.CheckArgumentValidity();const w=this.args!==null&&this.args.length>0;if(w||this.isFunctionCall||this.isTunnel||this.isThread){const F=new o.Container;if(w){this.isFunctionCall||F.AddContent(n.ControlCommand.EvalStart());let k=null;this.targetContent&&(k=this.targetContent.args);for(let m=0;m<this.args.length;++m){const g=this.args[m];let v=null;if(k&&m<k.length&&(v=k[m]),v&&v.isByReference){const u=(0,S.asOrNull)(g,i.VariableReference);if(!u){this.Error(`Expected variable name to pass by reference to 'ref ${v.identifier}' but saw ${g}`);break}const h=new r.Path(u.pathIdentifiers);if(h.ResolveFromContext(this)){this.Error(`can't pass a read count by reference. '${h.dotSeparatedComponents}' is a knot/stitch/label, but '${this.target.dotSeparatedComponents}' requires the name of a VAR to be passed.`);break}const R=new c.VariablePointerValue(u.name);F.AddContent(R)}else g.GenerateIntoContainer(F)}this.isFunctionCall||F.AddContent(n.ControlCommand.EvalEnd())}return this.isThread?F.AddContent(n.ControlCommand.StartThread()):(this.isFunctionCall||this.isTunnel)&&(this.runtimeDivert.pushesToStack=!0,this.runtimeDivert.stackPushType=this.isFunctionCall?s.PushPopType.Function:s.PushPopType.Tunnel),F.AddContent(this.runtimeDivert),F}return this.runtimeDivert},this.PathAsVariableName=()=>this.target?this.target.firstComponent:null,this.ResolveTargetContent=()=>{if(!(this.isEmpty||this.isEnd)&&this.targetContent===null){let w=this.PathAsVariableName();if(w!==null){const F=(0,S.asOrNull)((0,l.ClosestFlowBase)(this),f.FlowBase);if(F){const k=F.ResolveVariableWithName(w,this);if(k.found){if(k.isArgument&&k.ownerFlow&&k.ownerFlow.args){let m=k.ownerFlow.args.find(g=>{var v;return((v=g.identifier)===null||v===void 0?void 0:v.name)==w});m&&!m.isDivertTarget&&this.Error(`Since '${m.identifier}' is used as a variable divert target (on ${this.debugMetadata}), it should be marked as: -> ${m.identifier}`,k.ownerFlow)}this.runtimeDivert.variableDivertName=w;return}}}if(!this.target)throw new Error;this.targetContent=this.target.ResolveFromContext(this)}},this.CheckArgumentValidity=()=>{if(this.isEmpty)return;let w=0;if(this.args!==null&&this.args.length>0&&(w=this.args.length),this.targetContent===null)return;const F=(0,S.asOrNull)(this.targetContent,f.FlowBase);if(w===0&&(F===null||!F.hasParameters))return;if(F===null&&w>0){this.Error("target needs to be a knot or stitch in order to pass arguments");return}else if(F!==null&&(F.args===null||!F.args&&w>0)){this.Error(`target (${F.name}) doesn't take parameters`);return}else if(this.parent instanceof e.DivertTarget){w>0&&this.Error("can't store arguments in a divert target variable");return}const k=F.args.length;if(k!==w){let m;w===0?m="but there weren't any passed to it":w<k?m=`but only got ${w}`:m=`but got ${w}`,this.Error(`to '${F.identifier}' requires ${k} arguments, ${m}`);return}for(let m=0;m<k;++m){const g=F.args[m],v=this.args[m];if(g.isDivertTarget){let u=(0,S.asOrNull)(v,i.VariableReference);if(!(v instanceof e.DivertTarget)&&u===null)this.Error(`Target '${F.identifier}' expects a divert target for the parameter named -> ${g.identifier} but saw ${v}`,v);else if(u){const h=new r.Path(u.pathIdentifiers);h.ResolveFromContext(u)&&this.Error(`Passing read count of '${h.dotSeparatedComponents}' instead of a divert target. You probably meant '${h}'`)}}}if(F===null){this.Error("Can't call as a function or with arguments unless it's a knot or stitch");return}},this.CheckExternalArgumentValidity=w=>{const F=this.target?this.target.firstComponent:null,k=w.externals.get(F);if(!k)throw new Error("external not found");const m=k.argumentNames.length;let g=0;this.args&&(g=this.args.length),g!==m&&this.Error(`incorrect number of arguments sent to external function '${F}'. Expected ${m} but got ${g}`)},this.toString=()=>{let w="";if(this.target!==null)w+=this.target.toString();else return"-> <empty divert>";return this.isTunnel&&(w+=" ->"),this.isFunctionCall&&(w+=" ()"),w},O&&(this.target=O),I&&(this.args=I,this.AddContent(I))}get typeName(){return"Divert"}ResolveReferences(O){if(this.isEmpty||this.isEnd||this.isDone)return;if(!this.runtimeDivert)throw new Error;this.targetContent&&(this.runtimeDivert.targetPath=this.targetContent.runtimePath),super.ResolveReferences(O);let I=(0,S.asOrNull)(this.targetContent,f.FlowBase);I&&(!I.isFunction&&this.isFunctionCall?super.Error(`${I.identifier} hasn't been marked as a function, but it's being called as one. Do you need to declare the knot as '== function ${I.identifier} =='?`):I.isFunction&&!this.isFunctionCall&&!(this.parent instanceof e.DivertTarget)&&super.Error(I.identifier+" can't be diverted to. It can only be called as a function since it's been marked as such: '"+I.identifier+"(...)'"));const w=this.targetContent!==null;let F=!1,k=!1;if(this.target){if(this.target.numberOfComponents===1){if(!this.target.firstComponent)throw new Error;if(F=t.FunctionCall.IsBuiltIn(this.target.firstComponent),k=O.IsExternal(this.target.firstComponent),F||k){this.isFunctionCall||super.Error(`${this.target.firstComponent} must be called as a function: ~ ${this.target.firstComponent}()`),k&&(this.runtimeDivert.isExternal=!0,this.args!==null&&(this.runtimeDivert.externalArgs=this.args.length),this.runtimeDivert.pushesToStack=!1,this.runtimeDivert.targetPath=new y.Path(this.target.firstComponent),this.CheckExternalArgumentValidity(O));return}}}else throw new Error;this.runtimeDivert.variableDivertName==null&&!w&&!F&&!k&&this.Error(`target not found: '${this.target}'`)}Error(O,I=null,w=!1){if(I!==this&&I){super.Error(O,I);return}this.isFunctionCall?super.Error(`Function call ${O}`,I,w):super.Error(`Divert ${O}`,I,w)}};return Be.Divert=P,Be}var en={},Mr;function Na(){if(Mr)return en;Mr=1,Object.defineProperty(en,"__esModule",{value:!0}),en.GatherPointToResolve=void 0;let o=class{constructor(a,e){this.divert=a,this.targetRuntimeObj=e}};return en.GatherPointToResolve=o,en}var nn={},rn={},Br;function Ia(){if(Br)return rn;Br=1,Object.defineProperty(rn,"__esModule",{value:!0}),rn.SequenceDivertToResolve=void 0;let o=class{constructor(a,e){this.divert=a,this.targetContent=e}};return rn.SequenceDivertToResolve=o,rn}var sn={},qr;function Hs(){if(qr)return sn;qr=1,Object.defineProperty(sn,"__esModule",{value:!0}),sn.SequenceType=void 0;var o;return(function(n){n[n.Stopping=1]="Stopping",n[n.Cycle=2]="Cycle",n[n.Shuffle=4]="Shuffle",n[n.Once=8]="Once"})(o||(sn.SequenceType=o={})),sn}var Gr;function Js(){if(Gr)return nn;Gr=1,Object.defineProperty(nn,"__esModule",{value:!0}),nn.Sequence=void 0;const o=ot(),n=pt(),a=Rt(),e=it(),f=Ft(),t=et(),p=Ia(),r=Hs(),y=ie();let s=class extends t.ParsedObject{constructor(i,l){super(),this.sequenceType=l,this._sequenceDivertsToResolve=[],this.GenerateRuntimeObject=()=>{const S=new o.Container;S.visitsShouldBeCounted=!0,S.countingAtStartOnly=!0,this._sequenceDivertsToResolve=[],S.AddContent(n.ControlCommand.EvalStart()),S.AddContent(n.ControlCommand.VisitIndex());const P=(this.sequenceType&r.SequenceType.Once)>0,N=(this.sequenceType&r.SequenceType.Cycle)>0,O=(this.sequenceType&r.SequenceType.Stopping)>0,I=(this.sequenceType&r.SequenceType.Shuffle)>0;let w=this.sequenceElements.length;if(P&&(w+=1),O||P?(S.AddContent(new e.IntValue(w-1)),S.AddContent(f.NativeFunctionCall.CallWithName("MIN"))):N&&(S.AddContent(new e.IntValue(this.sequenceElements.length)),S.AddContent(f.NativeFunctionCall.CallWithName("%"))),I){const k=n.ControlCommand.NoOp();if(P||O){const g=O?this.sequenceElements.length-1:this.sequenceElements.length;S.AddContent(n.ControlCommand.Duplicate()),S.AddContent(new e.IntValue(g)),S.AddContent(f.NativeFunctionCall.CallWithName("=="));const v=new a.Divert;v.isConditional=!0,S.AddContent(v),this.AddDivertToResolve(v,k)}let m=this.sequenceElements.length;O&&(m-=1),S.AddContent(new e.IntValue(m)),S.AddContent(n.ControlCommand.SequenceShuffleIndex()),(P||O)&&S.AddContent(k)}S.AddContent(n.ControlCommand.EvalEnd());const F=n.ControlCommand.NoOp();for(let k=0;k<w;k+=1){S.AddContent(n.ControlCommand.EvalStart()),S.AddContent(n.ControlCommand.Duplicate()),S.AddContent(new e.IntValue(k)),S.AddContent(f.NativeFunctionCall.CallWithName("==")),S.AddContent(n.ControlCommand.EvalEnd());const m=new a.Divert;m.isConditional=!0,S.AddContent(m);let g;k<this.sequenceElements.length?g=this.sequenceElements[k].runtimeObject:g=new o.Container,g.name=`s${k}`,g.InsertContent(n.ControlCommand.PopEvaluatedValue(),0);const v=new a.Divert;g.AddContent(v),S.AddToNamedContentOnly(g),this.AddDivertToResolve(m,g),this.AddDivertToResolve(v,F)}return S.AddContent(F),S},this.AddDivertToResolve=(S,P)=>{this._sequenceDivertsToResolve.push(new p.SequenceDivertToResolve(S,P))},this.sequenceType=l,this.sequenceElements=[];for(const S of i){const P=S.content;let N=null;P===null||P.length===0?N=S:N=new y.Weave(P),this.sequenceElements.push(N),this.AddContent(N)}}get typeName(){return"Sequence"}ResolveReferences(i){super.ResolveReferences(i);for(const l of this._sequenceDivertsToResolve)l.divert.targetPath=l.targetContent.path}};return nn.Sequence=s,nn}var an={},$r;function zs(){if($r)return an;$r=1,Object.defineProperty(an,"__esModule",{value:!0}),an.TunnelOnwards=void 0;const o=ot(),n=pt(),a=Rt(),e=it(),f=et(),t=te(),p=Z(),r=Kn();let y=class extends f.ParsedObject{constructor(){super(...arguments),this._overrideDivertTarget=null,this._divertAfter=null,this.GenerateRuntimeObject=()=>{const c=new o.Container;if(c.AddContent(n.ControlCommand.EvalStart()),this.divertAfter){const i=this.divertAfter.GenerateRuntimeObject(),l=i;if(l){const P=this.divertAfter.args;if(P!==null&&P.length>0){let N=-1,O=-1;for(let I=0;I<l.content.length;I+=1){const w=l.content[I];w&&(N==-1&&w.commandType===n.ControlCommand.CommandType.EvalStart?N=I:w.commandType===n.ControlCommand.CommandType.EvalEnd&&(O=I))}for(let I=N+1;I<O;I+=1){const w=l.content[I];w.parent=null,c.AddContent(l.content[I])}}}let S=(0,p.asOrNull)(i,a.Divert);if(S!=null&&S.hasVariableTarget){let P=new r.VariableReference(S.variableDivertName);c.AddContent(P)}else this._overrideDivertTarget=new e.DivertTargetValue,c.AddContent(this._overrideDivertTarget)}else c.AddContent(new t.Void);return c.AddContent(n.ControlCommand.EvalEnd()),c.AddContent(n.ControlCommand.PopTunnel()),c},this.toString=()=>` -> ${this._divertAfter}`}get divertAfter(){return this._divertAfter}set divertAfter(c){this._divertAfter=c,this._divertAfter&&this.AddContent(this._divertAfter)}get typeName(){return"TunnelOnwards"}ResolveReferences(c){super.ResolveReferences(c),this.divertAfter&&this.divertAfter.targetContent&&(this._overrideDivertTarget.targetPath=this.divertAfter.targetContent.runtimePath)}};return an.TunnelOnwards=y,an}var on={},ln={},un={},Ur;function Xs(){if(Ur)return un;Ur=1,Object.defineProperty(un,"__esModule",{value:!0}),un.ListDefinition=void 0;const o=vt();let n=class{constructor(e,f){this._name=e||"",this._items=null,this._itemNameToValues=f||new Map}get name(){return this._name}get items(){if(this._items==null){this._items=new Map;for(let[e,f]of this._itemNameToValues){let t=new o.InkListItem(this.name,e);this._items.set(t.serialized(),f)}}return this._items}ValueForItem(e){if(!e.itemName)return 0;let f=this._itemNameToValues.get(e.itemName);return typeof f<"u"?f:0}ContainsItem(e){return!e.itemName||e.originName!=this.name?!1:this._itemNameToValues.has(e.itemName)}ContainsItemWithName(e){return this._itemNameToValues.has(e)}TryGetItemWithValue(e,f){for(let[t,p]of this._itemNameToValues)if(p==e)return f=new o.InkListItem(this.name,t),{result:f,exists:!0};return f=o.InkListItem.Null,{result:f,exists:!1}}TryGetValueForItem(e,f){if(!e.itemName)return{result:0,exists:!1};let t=this._itemNameToValues.get(e.itemName);return t?{result:t,exists:!0}:{result:0,exists:!1}}};return un.ListDefinition=n,un}var Kr;function ki(){if(Kr)return ln;Kr=1,Object.defineProperty(ln,"__esModule",{value:!0}),ln.ListDefinition=void 0;const o=vt(),n=vt(),a=Xs(),e=it(),f=et(),t=Wt();class p extends f.ParsedObject{get typeName(){return"ListDefinition"}get runtimeListDefinition(){var y;const s=new Map;for(const c of this.itemDefinitions)s.has(c.name)?this.Error(`List '${this.identifier}' contains duplicate items called '${c.name}'`):s.set(c.name,c.seriesValue);return new a.ListDefinition(((y=this.identifier)===null||y===void 0?void 0:y.name)||"",s)}constructor(y){super(),this.itemDefinitions=y,this.identifier=null,this.variableAssignment=null,this._elementsByName=null,this.ItemNamed=c=>{if(this._elementsByName===null){this._elementsByName=new Map;for(const l of this.itemDefinitions)this._elementsByName.set(l.name,l)}return this._elementsByName.get(c)||null},this.GenerateRuntimeObject=()=>{var c,i;const l=new o.InkList;for(const S of this.itemDefinitions)if(S.inInitialList){const P=new n.InkListItem(((c=this.identifier)===null||c===void 0?void 0:c.name)||null,S.name||null);l.Add(P,S.seriesValue)}return l.SetInitialOriginName(((i=this.identifier)===null||i===void 0?void 0:i.name)||""),new e.ListValue(l)};let s=1;for(const c of this.itemDefinitions)c.explicitValue!==null&&(s=c.explicitValue),c.seriesValue=s,s+=1;this.AddContent(y)}ResolveReferences(y){super.ResolveReferences(y),y.CheckForNamingCollisions(this,this.identifier,t.SymbolType.List)}}return ln.ListDefinition=p,ln}var Hr;function Ys(){if(Hr)return on;Hr=1,Object.defineProperty(on,"__esModule",{value:!0}),on.VariableAssignment=void 0;const o=ot(),n=ui(),a=ki(),e=et(),f=Wt(),t=Gt(),p=Hn(),r=Z();let y=class extends e.ParsedObject{get variableName(){return this.variableIdentifier.name}get typeName(){return this.isNewTemporaryDeclaration?"temp":this.isGlobalDeclaration?this.listDefinition!==null?"LIST":"VAR":"variable assignment"}get isDeclaration(){return this.isGlobalDeclaration||this.isNewTemporaryDeclaration}constructor({assignedExpression:c,isGlobalDeclaration:i,isTemporaryNewDeclaration:l,listDef:S,variableIdentifier:P}){super(),this._runtimeAssignment=null,this.expression=null,this.listDefinition=null,this.GenerateRuntimeObject=()=>{let N=null;if(this.isGlobalDeclaration?N=this.story:this.isNewTemporaryDeclaration&&(N=(0,n.ClosestFlowBase)(this)),N&&N.AddNewVariableDeclaration(this),this.isGlobalDeclaration)return null;const O=new o.Container;return this.expression?O.AddContent(this.expression.runtimeObject):this.listDefinition&&O.AddContent(this.listDefinition.runtimeObject),this._runtimeAssignment=new t.VariableAssignment(this.variableName,this.isNewTemporaryDeclaration),O.AddContent(this._runtimeAssignment),O},this.toString=()=>`${this.isGlobalDeclaration?"VAR":this.isNewTemporaryDeclaration?"~ temp":""} ${this.variableName}`,this.variableIdentifier=P,this.isGlobalDeclaration=!!i,this.isNewTemporaryDeclaration=!!l,S instanceof a.ListDefinition?(this.listDefinition=this.AddContent(S),this.listDefinition.variableAssignment=this,this.isGlobalDeclaration=!0):c&&(this.expression=this.AddContent(c))}ResolveReferences(c){if(super.ResolveReferences(c),this.isDeclaration&&this.listDefinition===null&&c.CheckForNamingCollisions(this,this.variableIdentifier,this.isGlobalDeclaration?f.SymbolType.Var:f.SymbolType.Temp),this.isGlobalDeclaration){const i=(0,r.asOrNull)(this.expression,p.VariableReference);i&&!i.isConstantReference&&!i.isListItemReference&&this.Error("global variable assignments cannot refer to other variables, only literal values, constants and list items")}if(!this.isNewTemporaryDeclaration){const i=c.ResolveVariableWithName(this.variableName,this);i.found||(this.variableName in this.story.constants?this.Error(`Can't re-assign to a constant (do you need to use VAR when declaring '${this.variableName}'?)`,this):this.Error(`Variable could not be found to assign to: '${this.variableName}'`,this)),this._runtimeAssignment&&(this._runtimeAssignment.isGlobal=i.isGlobal)}}};return on.VariableAssignment=y,on}var Jr;function ie(){if(Jr)return je;Jr=1,Object.defineProperty(je,"__esModule",{value:!0}),je.Weave=void 0;const o=xi(),n=$n(),a=Ii(),e=Ai(),f=ot(),t=zn(),p=Rt(),r=Jn(),y=kt(),s=li(),c=Na(),i=et(),l=Js(),S=$t(),P=zs(),N=Ys(),O=Z();let I=class qt extends i.ParsedObject{get rootContainer(){return this._rootContainer||(this._rootContainer=this.GenerateRuntimeObject()),this._rootContainer}get namedWeavePoints(){return this._namedWeavePoints}get lastParsedSignificantObject(){if(this.content.length===0)return null;let F=null;for(let m=this.content.length-1;m>=0;--m){F=this.content[m];let g=(0,O.asOrNull)(F,S.Text);if(!(g&&g.text===`
|
|
15
|
-
`)&&!this.IsGlobalDeclaration(F))break}const k=(0,O.asOrNull)(F,qt);return k&&(F=k.lastParsedSignificantObject),F}constructor(F,k=-1){super(),this.previousWeavePoint=null,this.addContentToPreviousWeavePoint=!1,this.hasSeenChoiceInSection=!1,this.currentContainer=null,this._unnamedGatherCount=0,this._choiceCount=0,this._rootContainer=null,this._namedWeavePoints=new Map,this.looseEnds=[],this.gatherPointsToResolve=[],this.ResolveWeavePointNaming=()=>{var m,g,v;const u=[...this.FindAll(s.Gather)(h=>!(h.name===null||h.name===void 0)),...this.FindAll(n.Choice)(h=>!(h.name===null||h.name===void 0))];this._namedWeavePoints=new Map;for(const h of u){const b=this.namedWeavePoints.get(((m=h.identifier)===null||m===void 0?void 0:m.name)||"");if(b){const R=b instanceof s.Gather?"gather":"choice",V=b;this.Error(`A ${R} with the same label name '${h.name}' already exists in this context on line ${V.debugMetadata?V.debugMetadata.startLineNumber:"NO DEBUG METADATA AVAILABLE"}`,h)}!((g=h.identifier)===null||g===void 0)&&g.name&&this.namedWeavePoints.set((v=h.identifier)===null||v===void 0?void 0:v.name,h)}},this.ConstructWeaveHierarchyFromIndentation=()=>{let m=0;for(;m<this.content.length;){const g=this.content[m];if(g instanceof n.Choice||g instanceof s.Gather){const u=g.indentationDepth-1;if(u>this.baseIndentIndex){let h=m;for(;m<this.content.length;){const j=(0,O.asOrNull)(this.content[m],n.Choice)||(0,O.asOrNull)(this.content[m],s.Gather);if(j!==null&&j.indentationDepth-1<=this.baseIndentIndex)break;m+=1}const b=m-h,R=this.content.slice(h,h+b);this.content.splice(h,b);const V=new qt(R,u);this.InsertContent(h,V),m=h}}m+=1}},this.DetermineBaseIndentationFromContent=m=>{for(const g of m)if(g instanceof n.Choice||g instanceof s.Gather)return g.indentationDepth-1;return 0},this.GenerateRuntimeObject=()=>{this._rootContainer=new f.Container,this.currentContainer=this._rootContainer,this.looseEnds=[],this.gatherPointsToResolve=[];for(const m of this.content)if(m instanceof n.Choice||m instanceof s.Gather)this.AddRuntimeForWeavePoint(m);else if(m instanceof qt){const g=m;this.AddRuntimeForNestedWeave(g),this.gatherPointsToResolve.splice(0,0,...g.gatherPointsToResolve)}else this.AddGeneralRuntimeContent(m.runtimeObject);return this.PassLooseEndsToAncestors(),this._rootContainer},this.AddRuntimeForGather=m=>{const g=!this.hasSeenChoiceInSection;this.hasSeenChoiceInSection=!1;const v=m.runtimeContainer;if(m.name||(v.name=`g-${this._unnamedGatherCount}`,this._unnamedGatherCount+=1),g){if(!this.currentContainer)throw new Error;this.currentContainer.AddContent(v)}else this.rootContainer.AddToNamedContentOnly(v);for(const u of this.looseEnds){const h=u;if(h instanceof s.Gather&&h.indentationDepth==m.indentationDepth)continue;let b=null;if(h instanceof t.Divert)b=h.runtimeObject;else{b=new p.Divert;const R=h;if(!R.runtimeContainer)throw new Error;R.runtimeContainer.AddContent(b)}this.gatherPointsToResolve.push(new c.GatherPointToResolve(b,v))}this.looseEnds=[],this.currentContainer=v},this.AddRuntimeForWeavePoint=m=>{if(m instanceof s.Gather)this.AddRuntimeForGather(m);else if(m instanceof n.Choice){if(!this.currentContainer)throw new Error;this.previousWeavePoint instanceof s.Gather&&this.looseEnds.splice(this.looseEnds.indexOf(this.previousWeavePoint),1);const g=m;if(this.currentContainer.AddContent(g.runtimeObject),!g.innerContentContainer)throw new Error;g.innerContentContainer.name=`c-${this._choiceCount}`,this.currentContainer.AddToNamedContentOnly(g.innerContentContainer),this._choiceCount+=1,this.hasSeenChoiceInSection=!0}this.addContentToPreviousWeavePoint=!1,this.WeavePointHasLooseEnd(m)&&(this.looseEnds.push(m),(0,O.asOrNull)(m,n.Choice)&&(this.addContentToPreviousWeavePoint=!0)),this.previousWeavePoint=m},this.AddRuntimeForNestedWeave=m=>{this.AddGeneralRuntimeContent(m.rootContainer),this.previousWeavePoint!==null&&(this.looseEnds.splice(this.looseEnds.indexOf(this.previousWeavePoint),1),this.addContentToPreviousWeavePoint=!1)},this.AddGeneralRuntimeContent=m=>{if(m!==null)if(this.addContentToPreviousWeavePoint){if(!this.previousWeavePoint||!this.previousWeavePoint.runtimeContainer)throw new Error;this.previousWeavePoint.runtimeContainer.AddContent(m)}else{if(!this.currentContainer)throw new Error;this.currentContainer.AddContent(m)}},this.PassLooseEndsToAncestors=()=>{if(this.looseEnds.length===0)return;let m=null,g=null,v=!1;for(let u=this.parent;u!==null;u=u.parent){const h=(0,O.asOrNull)(u,qt);h&&(!v&&m===null&&(m=h),v&&g===null&&(g=h)),(u instanceof l.Sequence||u instanceof a.Conditional)&&(v=!0)}if(!(m===null&&g===null))for(let u=this.looseEnds.length-1;u>=0;u-=1){const h=this.looseEnds[u];let b=!1;if(v){if(h instanceof n.Choice&&m!==null)m.ReceiveLooseEnd(h),b=!0;else if(!(h instanceof n.Choice)){const R=m||g;R!==null&&(R.ReceiveLooseEnd(h),b=!0)}}else m!=null&&m.hasOwnProperty("ReceiveLooseEnd")&&m.ReceiveLooseEnd(h),b=!0;b&&this.looseEnds.splice(u,1)}},this.ReceiveLooseEnd=m=>{this.looseEnds.push(m)},this.WeavePointNamed=m=>{if(!this.namedWeavePoints)return null;let g=this.namedWeavePoints.get(m);return g||null},this.IsGlobalDeclaration=m=>{const g=(0,O.asOrNull)(m,N.VariableAssignment);return!!(g&&g.isGlobalDeclaration&&g.isDeclaration||(0,O.asOrNull)(m,e.ConstantDeclaration))},this.ContentThatFollowsWeavePoint=m=>{const g=[],v=m;if(v.content!==null)for(const b of v.content)this.IsGlobalDeclaration(b)||g.push(b);const u=(0,O.asOrNull)(v.parent,qt);if(u===null)throw new Error("Expected weave point parent to be weave?");const h=u.content.indexOf(v);for(let b=h+1;b<u.content.length;b+=1){const R=u.content[b];if(!this.IsGlobalDeclaration(R)){if(R instanceof n.Choice||R instanceof s.Gather||R instanceof qt)break;g.push(R)}}return g},this.ValidateTermination=m=>{if(this.lastParsedSignificantObject instanceof o.AuthorWarning)return;if(this.looseEnds!==null&&this.looseEnds.length>0)for(const v of this.looseEnds){const u=this.ContentThatFollowsWeavePoint(v);this.ValidateFlowOfObjectsTerminates(u,v,m)}else{for(const v of this.content)if(v instanceof n.Choice||v instanceof t.Divert)return;this.ValidateFlowOfObjectsTerminates(this.content,this,m)}},this.BadNestedTerminationHandler=m=>{let g=null;for(let u=m.parent;u!==null;u=u.parent)if(u instanceof l.Sequence||u instanceof a.Conditional){g=(0,O.asOrNull)(u,a.Conditional);break}let v="Choices nested in conditionals or sequences need to explicitly divert afterwards.";g!==null&&g.FindAll(n.Choice)().length===1&&(v=`Choices with conditions should be written: '* {condition} choice'. Otherwise, ${v.toLowerCase()}`),this.Error(v,m)},this.ValidateFlowOfObjectsTerminates=(m,g,v)=>{let u=!1,h=g;for(const b of m){if(b.Find(t.Divert)(V=>!V.isThread&&!V.isTunnel&&!V.isFunctionCall&&!(V.parent instanceof r.DivertTarget))!==null&&(u=!0),b.Find(P.TunnelOnwards)()!=null){u=!0;break}h=b}if(!u){if(h instanceof o.AuthorWarning)return;v(h)}},this.WeavePointHasLooseEnd=m=>{if(m.content===null)return!0;for(let g=m.content.length-1;g>=0;--g){let v=(0,O.asOrNull)(m.content[g],t.Divert);if(v&&!(v.isThread||v.isTunnel||v.isFunctionCall))return!1}return!0},this.CheckForWeavePointNamingCollisions=()=>{if(!this.namedWeavePoints)return;const m=[];for(const g of this.ancestry){const v=(0,O.asOrNull)(g,y.FlowBase);if(v)m.push(v);else break}for(const[g,v]of this.namedWeavePoints)for(const u of m){const h=u.ContentWithNameAtLevel(g);if(h&&h!==v){const b=`${v.GetType()} '${g}' has the same label name as a ${h.GetType()} (on ${h.debugMetadata})`;this.Error(b,v)}}},k==-1?this.baseIndentIndex=this.DetermineBaseIndentationFromContent(F):this.baseIndentIndex=k,this.AddContent(F),this.ConstructWeaveHierarchyFromIndentation()}get typeName(){return"Weave"}ResolveReferences(F){if(super.ResolveReferences(F),this.looseEnds!==null&&this.looseEnds.length>0){let k=!1;for(let m=this.parent;m!==null;m=m.parent)if(m instanceof l.Sequence||m instanceof a.Conditional){k=!0;break}k&&this.ValidateTermination(this.BadNestedTerminationHandler)}for(const k of this.gatherPointsToResolve)k.divert.targetPath=k.targetRuntimeObj.path;this.CheckForWeavePointNamingCollisions()}};return
|
|
16
|
-
`),0),(S||this.isElse&&this.matchingEquality)&&this._contentContainer.InsertContent(n.ControlCommand.PopEvaluatedValue(),0),l.AddToNamedContentOnly(this._contentContainer),this.returnDivert=new a.Divert,this._contentContainer.AddContent(this.returnDivert),l},this.GenerateRuntimeForContent=()=>this._innerWeave===null?new o.Container:this._innerWeave.rootContainer,i&&(this._innerWeave=new r.Weave(i),this.AddContent(this._innerWeave))}get typeName(){return"ConditionalSingleBranch"}ResolveReferences(i){if(!this._conditionalDivert||!this._contentContainer)throw new Error;this._conditionalDivert.targetPath=this._contentContainer.path,super.ResolveReferences(i)}};return We.ConditionalSingleBranch=s,We}var hn={},Xr;function Aa(){if(Xr)return hn;Xr=1,Object.defineProperty(hn,"__esModule",{value:!0}),hn.CustomFlags=void 0;var o;return(function(n){n[n.ParsingString=1]="ParsingString",n[n.TagActive=2]="TagActive"})(o||(hn.CustomFlags=o={})),hn}var cn={},Yr;function Fa(){if(Yr)return cn;Yr=1,Object.defineProperty(cn,"__esModule",{value:!0}),cn.DebugMetadata=void 0;let o=class Qs{constructor(){this.startLineNumber=0,this.endLineNumber=0,this.startCharacterNumber=0,this.endCharacterNumber=0,this.fileName=null,this.sourceName=null}Merge(a){let e=new Qs;return e.fileName=this.fileName,e.sourceName=this.sourceName,this.startLineNumber<a.startLineNumber?(e.startLineNumber=this.startLineNumber,e.startCharacterNumber=this.startCharacterNumber):this.startLineNumber>a.startLineNumber?(e.startLineNumber=a.startLineNumber,e.startCharacterNumber=a.startCharacterNumber):(e.startLineNumber=this.startLineNumber,e.startCharacterNumber=Math.min(this.startCharacterNumber,a.startCharacterNumber)),this.endLineNumber>a.endLineNumber?(e.endLineNumber=this.endLineNumber,e.endCharacterNumber=this.endCharacterNumber):this.endLineNumber<a.endLineNumber?(e.endLineNumber=a.endLineNumber,e.endCharacterNumber=a.endCharacterNumber):(e.endLineNumber=this.endLineNumber,e.endCharacterNumber=Math.max(this.endCharacterNumber,a.endCharacterNumber)),e}toString(){return this.fileName!==null?`line ${this.startLineNumber} of ${this.fileName}"`:"line "+this.startLineNumber}};return cn.DebugMetadata=o,cn}var dn={},Zr;function Ra(){if(Zr)return dn;Zr=1,Object.defineProperty(dn,"__esModule",{value:!0}),dn.ExternalDeclaration=void 0;const o=et();let n=class extends o.ParsedObject{get name(){var e;return((e=this.identifier)===null||e===void 0?void 0:e.name)||null}constructor(e,f){super(),this.identifier=e,this.argumentNames=f,this.GenerateRuntimeObject=()=>(this.story.AddExternal(this),null)}get typeName(){return"EXTERNAL"}toString(){var e;return`EXTERNAL ${(e=this.identifier)===null||e===void 0?void 0:e.name}`}};return dn.ExternalDeclaration=n,dn}var fn={},Qr;function ka(){if(Qr)return fn;Qr=1,Object.defineProperty(fn,"__esModule",{value:!0}),fn.FlowDecl=void 0;let o=class{constructor(a,e,f){this.name=a,this.args=e,this.isFunction=f}};return fn.FlowDecl=o,fn}var pn={},mn={},ts;function ta(){if(ts)return mn;ts=1,Object.defineProperty(mn,"__esModule",{value:!0}),mn.Wrap=void 0;const o=et();let n=class extends o.ParsedObject{constructor(e){super(),this._objToWrap=e,this.GenerateRuntimeObject=()=>this._objToWrap}};return mn.Wrap=n,mn}var es;function Da(){if(es)return pn;es=1,Object.defineProperty(pn,"__esModule",{value:!0}),pn.Glue=void 0;const o=ta();class n extends o.Wrap{constructor(e){super(e)}get typeName(){return"Glue"}}return pn.Glue=n,pn}var gn={},ns;function Di(){if(ns)return gn;ns=1,Object.defineProperty(gn,"__esModule",{value:!0}),gn.Glue=void 0;const o=yt();let n=class extends o.InkObject{toString(){return"Glue"}};return gn.Glue=n,gn}var Cn={},is;function Va(){if(is)return Cn;is=1,Object.defineProperty(Cn,"__esModule",{value:!0}),Cn.IncDecExpression=void 0;const o=Ri(),n=Ot(),a=kt(),e=Ft(),f=it(),t=Gt(),p=Kn(),r=ie();let y=class extends n.Expression{constructor(c,i,l){super(),this.varIdentifier=c,this._runtimeAssignment=null,this.expression=null,this.GenerateIntoContainer=S=>{var P,N;S.AddContent(new p.VariableReference(((P=this.varIdentifier)===null||P===void 0?void 0:P.name)||null)),this.expression?this.expression.GenerateIntoContainer(S):S.AddContent(new f.IntValue(1)),S.AddContent(e.NativeFunctionCall.CallWithName(this.isInc?"+":"-")),this._runtimeAssignment=new t.VariableAssignment(((N=this.varIdentifier)===null||N===void 0?void 0:N.name)||null,!1),S.AddContent(this._runtimeAssignment)},this.toString=()=>{var S,P;return this.expression?`${(S=this.varIdentifier)===null||S===void 0?void 0:S.name}${this.isInc?" += ":" -= "}${this.expression}`:`${(P=this.varIdentifier)===null||P===void 0?void 0:P.name}`+(this.isInc?"++":"--")},i instanceof n.Expression?(this.expression=i,this.AddContent(this.expression),this.isInc=!!l):this.isInc=i}get typeName(){return"IncDecExpression"}ResolveReferences(c){var i;super.ResolveReferences(c);const l=c.ResolveVariableWithName(((i=this.varIdentifier)===null||i===void 0?void 0:i.name)||"",this);if(l.found||this.Error(`variable for ${this.incrementDecrementWord} could not be found: '${this.varIdentifier}' after searching: {this.descriptionOfScope}`),!this._runtimeAssignment)throw new Error;this._runtimeAssignment.isGlobal=l.isGlobal,!(this.parent instanceof r.Weave)&&!(this.parent instanceof a.FlowBase)&&!(this.parent instanceof o.ContentList)&&this.Error(`Can't use ${this.incrementDecrementWord} as sub-expression`)}get incrementDecrementWord(){return this.isInc?"increment":"decrement"}};return Cn.IncDecExpression=y,Cn}var vn={},rs;function ea(){if(rs)return vn;rs=1,Object.defineProperty(vn,"__esModule",{value:!0}),vn.IncludedFile=void 0;const o=et();let n=class extends o.ParsedObject{constructor(e){super(),this.includedStory=e,this.GenerateRuntimeObject=()=>null}get typeName(){return"IncludedFile"}};return vn.IncludedFile=n,vn}var Sn={},ss;function Wa(){if(ss)return Sn;ss=1,Object.defineProperty(Sn,"__esModule",{value:!0}),Sn.InfixOperator=void 0;let o=class{constructor(a,e,f){this.type=a,this.precedence=e,this.requireWhitespace=f,this.toString=()=>this.type}};return Sn.InfixOperator=o,Sn}var yn={},as;function na(){if(as)return yn;as=1,Object.defineProperty(yn,"__esModule",{value:!0}),yn.Knot=void 0;const o=kt(),n=Un();let a=class extends o.FlowBase{get flowLevel(){return n.FlowLevel.Knot}constructor(f,t,p,r){super(f,t,p,r)}get typeName(){return this.isFunction?"Function":"Knot"}ResolveReferences(f){super.ResolveReferences(f);let t=this.story;for(const p in this.subFlowsByName){const r=t.ContentWithNameAtLevel(p,n.FlowLevel.Knot,!1);if(r){const y=this.subFlowsByName.get(p),s=`Stitch '${y?y.name:"NO STITCH FOUND"}' has the same name as a knot (on ${r.debugMetadata})`;this.Error(s,y)}}}};return yn.Knot=a,yn}var bn={},os;function La(){if(os)return bn;os=1,Object.defineProperty(bn,"__esModule",{value:!0}),bn.List=void 0;const o=Ot(),n=vt(),a=vt(),e=it();let f=class extends o.Expression{constructor(p){super(),this.itemIdentifierList=p,this.GenerateIntoContainer=r=>{var y,s;const c=new n.InkList;if(this.itemIdentifierList!=null)for(const i of this.itemIdentifierList){const l=((y=i==null?void 0:i.name)===null||y===void 0?void 0:y.split("."))||[];let S=null,P="";l.length>1?(S=l[0],P=l[1]):P=l[0];const N=this.story.ResolveListItem(S,P,this);if(N===null)S===null?this.Error(`Could not find list definition that contains item '${i}'`):this.Error(`Could not find list item ${i}`);else{if(N.parent==null){this.Error(`Could not find list definition for item ${i}`);return}S||(S=((s=N.parent.identifier)===null||s===void 0?void 0:s.name)||null);const O=new a.InkListItem(S,N.name||null);c.has(O.serialized())?this.Warning(`Duplicate of item '${i}' in list.`):c.Add(O,N.seriesValue)}}r.AddContent(new e.ListValue(c))}}get typeName(){return"List"}};return bn.List=f,bn}var _n={},ls;function ia(){if(ls)return _n;ls=1,Object.defineProperty(_n,"__esModule",{value:!0}),_n.ListElementDefinition=void 0;const o=et(),n=Wt();let a=class extends o.ParsedObject{get fullName(){var f;const t=this.parent;if(t===null)throw new Error("Can't get full name without a parent list.");return`${(f=t.identifier)===null||f===void 0?void 0:f.name}.${this.name}`}get typeName(){return"ListElement"}get name(){var f;return((f=this.indentifier)===null||f===void 0?void 0:f.name)||null}constructor(f,t,p=null){super(),this.indentifier=f,this.inInitialList=t,this.explicitValue=p,this.seriesValue=0,this.parent=null,this.GenerateRuntimeObject=()=>{throw new Error("Not implemented.")},this.toString=()=>this.fullName,this.parent=this.parent}ResolveReferences(f){super.ResolveReferences(f),f.CheckForNamingCollisions(this,this.indentifier,n.SymbolType.ListItem)}};return _n.ListElementDefinition=a,_n}var En={},us;function ra(){if(us)return En;us=1,Object.defineProperty(En,"__esModule",{value:!0}),En.StatementLevel=void 0;var o;return(function(n){n[n.InnerBlock=0]="InnerBlock",n[n.Stitch=1]="Stitch",n[n.Knot=2]="Knot",n[n.Top=3]="Top"})(o||(En.StatementLevel=o={})),En}var wn={},hs;function sa(){if(hs)return wn;hs=1,Object.defineProperty(wn,"__esModule",{value:!0}),wn.Stitch=void 0;const o=kt(),n=Un();let a=class extends o.FlowBase{get flowLevel(){return n.FlowLevel.Stitch}constructor(f,t,p,r){super(f,t,p,r),this.baseToString=this.toString,this.toString=()=>`${this.parent!==null?this.parent+" > ":""}${this.baseToString()}`}get typeName(){return"Stitch"}};return wn.Stitch=a,wn}var Pn={},gi={},On={},xn={},cs;function Vi(){if(cs)return xn;cs=1,Object.defineProperty(xn,"__esModule",{value:!0}),xn.Tag=void 0;const o=yt();class n extends o.InkObject{constructor(e){super(),this.text=e.toString()||""}toString(){return"# "+this.text}}return xn.Tag=n,xn}var Tn={},ds;function oa(){if(ds)return Tn;ds=1,Object.defineProperty(Tn,"__esModule",{value:!0}),Tn.Choice=void 0;const o=St(),n=ft(),a=yt();let e=class aa extends a.InkObject{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 this.targetPath===null?(0,n.throwNullException)("Choice.targetPath"):this.targetPath.toString()}set pathStringOnChoice(t){this.targetPath=new o.Path(t)}Clone(){let t=new aa;return t.text=this.text,t.sourcePath=this.sourcePath,t.index=this.index,t.targetPath=this.targetPath,t.originalThreadIndex=this.originalThreadIndex,t.isInvisibleDefault=this.isInvisibleDefault,this.threadAtGeneration!==null&&(t.threadAtGeneration=this.threadAtGeneration.Copy()),t}};return Tn.Choice=e,Tn}var Nn={},fs;function la(){if(fs)return Nn;fs=1,Object.defineProperty(Nn,"__esModule",{value:!0}),Nn.ListDefinitionsOrigin=void 0;const o=vt(),n=it(),a=ft();let e=class{constructor(t){this._lists=new Map,this._allUnambiguousListValueCache=new Map;for(let p of t){this._lists.set(p.name,p);for(let[r,y]of p.items){let s=o.InkListItem.fromSerializedKey(r),c=new n.ListValue(s,y);if(!s.itemName)throw new Error("item.itemName is null or undefined.");this._allUnambiguousListValueCache.set(s.itemName,c),this._allUnambiguousListValueCache.set(s.fullName,c)}}}get lists(){let t=[];for(let[,p]of this._lists)t.push(p);return t}TryListGetDefinition(t,p){if(t===null)return{result:p,exists:!1};let r=this._lists.get(t);return r?{result:r,exists:!0}:{result:p,exists:!1}}FindSingleItemListWithName(t){if(t===null)return(0,a.throwNullException)("name");let p=this._allUnambiguousListValueCache.get(t);return typeof p<"u"?p:null}};return Nn.ListDefinitionsOrigin=e,Nn}var ps;function Xn(){if(ps)return On;ps=1,Object.defineProperty(On,"__esModule",{value:!0}),On.JsonSerialisation=void 0;const o=ot(),n=it(),a=Di(),e=pt(),f=ee(),t=Rt(),p=Ni(),r=Kn(),y=Gt(),s=Ft(),c=te(),i=Vi(),l=St(),S=oa(),P=Xs(),N=la(),O=vt(),I=Z(),w=ft();let F=class Qn{static JArrayToRuntimeObjList(m,g=!1){let v=m.length;g&&v--;let u=[];for(let h=0;h<v;h++){let b=m[h],R=this.JTokenToRuntimeObject(b);if(R===null)return(0,w.throwNullException)("runtimeObj");u.push(R)}return u}static WriteDictionaryRuntimeObjs(m,g){m.WriteObjectStart();for(let[v,u]of g)m.WritePropertyStart(v),this.WriteRuntimeObject(m,u),m.WritePropertyEnd();m.WriteObjectEnd()}static WriteListRuntimeObjs(m,g){m.WriteArrayStart();for(let v of g)this.WriteRuntimeObject(m,v);m.WriteArrayEnd()}static WriteIntDictionary(m,g){m.WriteObjectStart();for(let[v,u]of g)m.WriteIntProperty(v,u);m.WriteObjectEnd()}static WriteRuntimeObject(m,g){let v=(0,I.asOrNull)(g,o.Container);if(v){this.WriteRuntimeContainer(m,v);return}let u=(0,I.asOrNull)(g,t.Divert);if(u){let Y="->";u.isExternal?Y="x()":u.pushesToStack&&(u.stackPushType==f.PushPopType.Function?Y="f()":u.stackPushType==f.PushPopType.Tunnel&&(Y="->t->"));let mt;u.hasVariableTarget?mt=u.variableDivertName:mt=u.targetPathString,m.WriteObjectStart(),m.WriteProperty(Y,mt),u.hasVariableTarget&&m.WriteProperty("var",!0),u.isConditional&&m.WriteProperty("c",!0),u.externalArgs>0&&m.WriteIntProperty("exArgs",u.externalArgs),m.WriteObjectEnd();return}let h=(0,I.asOrNull)(g,p.ChoicePoint);if(h){m.WriteObjectStart(),m.WriteProperty("*",h.pathStringOnChoice),m.WriteIntProperty("flg",h.flags),m.WriteObjectEnd();return}let b=(0,I.asOrNull)(g,n.BoolValue);if(b){m.WriteBool(b.value);return}let R=(0,I.asOrNull)(g,n.IntValue);if(R){m.WriteInt(R.value);return}let V=(0,I.asOrNull)(g,n.FloatValue);if(V){m.WriteFloat(V.value);return}let j=(0,I.asOrNull)(g,n.StringValue);if(j){j.isNewline?m.Write(`
|
|
14
|
+
`.repeat(this.lineIndex-f):null}}PreProcessInputString(f){return f}};return Fe.CommentEliminator=a,Fe}var De={},Er;function Ii(){if(Er)return De;Er=1,Object.defineProperty(De,"__esModule",{value:!0}),De.Conditional=void 0;const o=ot(),n=pt(),a=et();let e=class extends a.ParsedObject{constructor(t,p){super(),this.initialCondition=t,this.branches=p,this._reJoinTarget=null,this.GenerateRuntimeObject=()=>{const r=new o.Container;this.initialCondition&&r.AddContent(this.initialCondition.runtimeObject);for(const y of this.branches){const s=y.runtimeObject;r.AddContent(s)}return this.initialCondition!==null&&this.branches[0].ownExpression!==null&&!this.branches[this.branches.length-1].isElse&&r.AddContent(n.ControlCommand.PopEvaluatedValue()),this._reJoinTarget=n.ControlCommand.NoOp(),r.AddContent(this._reJoinTarget),r},this.initialCondition&&this.AddContent(this.initialCondition),this.branches!==null&&this.AddContent(this.branches)}get typeName(){return"Conditional"}ResolveReferences(t){const p=this._reJoinTarget.path;for(const r of this.branches){if(!r.returnDivert)throw new Error;r.returnDivert.targetPath=p}super.ResolveReferences(t)}};return De.Conditional=e,De}var Ve={},We={},wr;function $t(){if(wr)return We;wr=1,Object.defineProperty(We,"__esModule",{value:!0}),We.Text=void 0;const o=et(),n=it();let a=class extends o.ParsedObject{constructor(f){super(),this.text=f,this.GenerateRuntimeObject=()=>new n.StringValue(this.text),this.toString=()=>this.text}get typeName(){return"Text"}};return We.Text=a,We}var Le={},je={},Pr;function Ai(){if(Pr)return je;Pr=1,Object.defineProperty(je,"__esModule",{value:!0}),je.ConstantDeclaration=void 0;const o=et(),n=Wt();let a=class extends o.ParsedObject{get constantName(){var f;return(f=this.constantIdentifier)===null||f===void 0?void 0:f.name}get expression(){if(!this._expression)throw new Error;return this._expression}constructor(f,t){super(),this._expression=null,this.GenerateRuntimeObject=()=>null,this.constantIdentifier=f,t&&(this._expression=this.AddContent(t))}get typeName(){return"CONST"}ResolveReferences(f){super.ResolveReferences(f),f.CheckForNamingCollisions(this,this.constantIdentifier,n.SymbolType.Var)}};return je.ConstantDeclaration=a,je}var Me={},Be={},qe={},Ge={},Or;function Un(){if(Or)return Ge;Or=1,Object.defineProperty(Ge,"__esModule",{value:!0}),Ge.FlowLevel=void 0;var o;return(function(n){n[n.Story=0]="Story",n[n.Knot=1]="Knot",n[n.Stitch=2]="Stitch",n[n.WeavePoint=3]="WeavePoint"})(o||(Ge.FlowLevel=o={})),Ge}var $e={},xr;function li(){if(xr)return $e;xr=1,Object.defineProperty($e,"__esModule",{value:!0}),$e.Gather=void 0;const o=ot(),n=et(),a=Wt();let e=class extends n.ParsedObject{get name(){var t;return((t=this.identifier)===null||t===void 0?void 0:t.name)||null}get runtimeContainer(){return this.runtimeObject}constructor(t,p){super(),this.indentationDepth=p,this.GenerateRuntimeObject=()=>{const r=new o.Container;if(r.name=this.name,this.story.countAllVisits&&(r.visitsShouldBeCounted=!0),r.countingAtStartOnly=!0,this.content)for(const y of this.content)r.AddContent(y.runtimeObject);return r},this.toString=()=>{var r,y;return`- ${!((r=this.identifier)===null||r===void 0)&&r.name?"("+((y=this.identifier)===null||y===void 0?void 0:y.name)+")":"gather"}`},t&&(this.identifier=t)}get typeName(){return"Gather"}ResolveReferences(t){super.ResolveReferences(t),this.identifier&&(this.identifier.name||"").length>0&&t.CheckForNamingCollisions(this,this.identifier,a.SymbolType.SubFlowAndWeave)}};return $e.Gather=e,$e}var Ue={},Tr;function ee(){if(Tr)return Ue;Tr=1,Object.defineProperty(Ue,"__esModule",{value:!0}),Ue.Path=void 0;const o=Z(),n=kt(),a=Un(),e=ne();let f=class{get baseTargetLevel(){return this.baseLevelIsAmbiguous?a.FlowLevel.Story:this._baseTargetLevel}get baseLevelIsAmbiguous(){return!this._baseTargetLevel}get firstComponent(){return this.components==null||!this.components.length?null:this.components[0].name}get numberOfComponents(){return this.components?this.components.length:0}get dotSeparatedComponents(){return this._dotSeparatedComponents==null&&(this._dotSeparatedComponents=(this.components?this.components:[]).map(p=>p.name).filter(o.filterUndef).join(".")),this._dotSeparatedComponents}constructor(p,r){this._dotSeparatedComponents=null,this.toString=()=>this.components===null||this.components.length===0?this.baseTargetLevel===a.FlowLevel.WeavePoint?"-> <next gather point>":"<invalid Path>":`-> ${this.dotSeparatedComponents}`,this.ResolveFromContext=y=>{if(this.components==null||this.components.length==0)return null;let s=this.ResolveBaseTarget(y);return s===null?null:this.components.length>1?this.ResolveTailComponents(s):s},this.ResolveBaseTarget=y=>{const s=this.firstComponent;let c=y;for(;c;){const i=c===y,l=this.GetChildFromContext(c,s,null,i);if(l)return l;c=c.parent}return null},this.ResolveTailComponents=y=>{let s=y;if(!this.components)return null;for(let c=1;c<this.components.length;++c){const i=this.components[c].name;let l,S=(0,o.asOrNull)(s,n.FlowBase);if(S!==null?l=S.flowLevel+1:l=a.FlowLevel.WeavePoint,s=this.GetChildFromContext(s,i,l),s===null)break}return s},this.GetChildFromContext=(y,s,c,i=!1)=>{const l=c===null,S=(0,o.asOrNull)(y,e.Weave);if(s&&S!==null&&(l||c===a.FlowLevel.WeavePoint))return S.WeavePointNamed(s);let P=(0,o.asOrNull)(y,n.FlowBase);if(s&&P!==null){const N=i||P.flowLevel===a.FlowLevel.Knot;return P.ContentWithNameAtLevel(s,c,N)}return null},Object.values(a.FlowLevel).includes(p)?(this._baseTargetLevel=p,this.components=r||[]):Array.isArray(p)?(this._baseTargetLevel=null,this.components=p||[]):(this._baseTargetLevel=null,this.components=[p])}get typeName(){return"Path"}};return Ue.Path=f,Ue}var He={},Nr;function $s(){if(Nr)return He;Nr=1,Object.defineProperty(He,"__esModule",{value:!0}),He.ReturnType=void 0;const o=et(),n=ot(),a=pt(),e=Qt();let f=class extends o.ParsedObject{constructor(p=null){super(),this.returnedExpression=null,this.GenerateRuntimeObject=()=>{const r=new n.Container;return this.returnedExpression?r.AddContent(this.returnedExpression.runtimeObject):(r.AddContent(a.ControlCommand.EvalStart()),r.AddContent(new e.Void),r.AddContent(a.ControlCommand.EvalEnd())),r.AddContent(a.ControlCommand.PopFunction()),r},p&&(this.returnedExpression=this.AddContent(p))}get typeName(){return"ReturnType"}};return He.ReturnType=f,He}var Ke={},Ir;function ui(){if(Ir)return Ke;Ir=1,Object.defineProperty(Ke,"__esModule",{value:!0}),Ke.ClosestFlowBase=void 0;function o(n){let a=n.parent;for(;a;){if(a.hasOwnProperty("iamFlowbase")&&a.iamFlowbase())return a;a=a.parent}return null}return Ke.ClosestFlowBase=o,Ke}var Je={},Ar;function Fi(){if(Ar)return Je;Ar=1,Object.defineProperty(Je,"__esModule",{value:!0}),Je.Identifier=void 0;let o=class Us{constructor(a){this.debugMetadata=null,this.toString=()=>this.name||"undefined identifer",this.name=a}get typeName(){return"Identifier"}static Done(){return new Us("DONE")}};return Je.Identifier=o,Je}var Fr;function kt(){if(Fr)return qe;Fr=1,Object.defineProperty(qe,"__esModule",{value:!0}),qe.FlowBase=void 0;const o=$n(),n=zn(),a=Jn(),e=Un(),f=li(),t=et(),p=ee(),r=$s(),y=ot(),s=Rt(),c=Gt(),i=Wt(),l=ne(),S=ui(),P=Fi(),N=Z();let O=class yi extends t.ParsedObject{get hasParameters(){return this.args!==null&&this.args.length>0}get subFlowsByName(){return this._subFlowsByName}get typeName(){return this.isFunction?"Function":String(this.flowLevel)}get name(){var w;return((w=this.identifier)===null||w===void 0?void 0:w.name)||null}constructor(w,F=null,k=null,m=!1,g=!1){super(),this.isFunction=m,this._rootWeave=null,this._subFlowsByName=new Map,this._startingSubFlowDivert=null,this._startingSubFlowRuntime=null,this._firstChildFlow=null,this.variableDeclarations=new Map,this.identifier=null,this.args=null,this.iamFlowbase=()=>!0,this.SplitWeaveAndSubFlowContent=(v,u)=>{var h,b;const R=[],V=[];this._subFlowsByName=new Map;for(const L of v){const C=(0,N.asOrNull)(L,yi);C?(this._firstChildFlow===null&&(this._firstChildFlow=C),V.push(L),!((h=C.identifier)===null||h===void 0)&&h.name&&this._subFlowsByName.set((b=C.identifier)===null||b===void 0?void 0:b.name,C)):R.push(L)}u&&R.push(new f.Gather(null,1),new n.Divert(new p.Path(P.Identifier.Done())));const j=[];return R.length>0&&(this._rootWeave=new l.Weave(R,0),j.push(this._rootWeave)),V.length>0&&j.push(...V),j},this.ResolveVariableWithName=(v,u)=>{var h;const b={},R=u===null?this:(0,S.ClosestFlowBase)(u);if(R){if(R.args!==null){for(const V of R.args)if(((h=V.identifier)===null||h===void 0?void 0:h.name)===v)return b.found=!0,b.isArgument=!0,b.ownerFlow=R,b}if(R!==this.story&&R.variableDeclarations.has(v))return b.found=!0,b.ownerFlow=R,b.isTemporary=!0,b}return this.story.variableDeclarations.has(v)?(b.found=!0,b.ownerFlow=this.story,b.isGlobal=!0,b):(b.found=!1,b)},this.AddNewVariableDeclaration=v=>{const u=v.variableName;if(this.variableDeclarations.has(u)){const h=this.variableDeclarations.get(u);let b="";h.debugMetadata&&(b=` (${h.debugMetadata})`),this.Error(`found declaration variable '${u}' that was already declared${b}`,v,!1);return}this.variableDeclarations.set(v.variableName,v)},this.ResolveWeavePointNaming=()=>{this._rootWeave&&this._rootWeave.ResolveWeavePointNaming();for(const[,v]of this._subFlowsByName)v.hasOwnProperty("ResolveWeavePointNaming")&&v.ResolveWeavePointNaming()},this.GenerateRuntimeObject=()=>{var v;let u=null;this.isFunction?this.CheckForDisallowedFunctionFlowControl():(this.flowLevel===e.FlowLevel.Knot||this.flowLevel===e.FlowLevel.Stitch)&&(u=this.Find(r.ReturnType)(),u!==null&&this.Error(`Return statements can only be used in knots that are declared as functions: == function ${this.identifier} ==`,u));const h=new y.Container;h.name=(v=this.identifier)===null||v===void 0?void 0:v.name,this.story.countAllVisits&&(h.visitsShouldBeCounted=!0),this.GenerateArgumentVariableAssignments(h);let b=0;for(;this.content!==null&&b<this.content.length;){const R=this.content[b];if(R instanceof yi){const V=R,j=V.runtimeObject;b===0&&!V.hasParameters&&this.flowLevel===e.FlowLevel.Knot&&(this._startingSubFlowDivert=new s.Divert,h.AddContent(this._startingSubFlowDivert),this._startingSubFlowRuntime=j);const L=j,C=h.namedContent.get(L.name)||null;if(C){const E=`${this.GetType()} already contains flow named '${L.name}' (at ${C.debugMetadata})`;this.Error(E,V)}h.AddToNamedContentOnly(L)}else R&&h.AddContent(R.runtimeObject);b+=1}return this.flowLevel!==e.FlowLevel.Story&&!this.isFunction&&this._rootWeave!==null&&u===null&&this._rootWeave.ValidateTermination(this.WarningInTermination),h},this.GenerateArgumentVariableAssignments=v=>{var u;if(!(this.args===null||this.args.length===0))for(let h=this.args.length-1;h>=0;--h){const b=((u=this.args[h].identifier)===null||u===void 0?void 0:u.name)||null,R=new c.VariableAssignment(b,!0);v.AddContent(R)}},this.ContentWithNameAtLevel=(v,u=null,h=!1)=>{var b;if((u===this.flowLevel||u===null)&&v===((b=this.identifier)===null||b===void 0?void 0:b.name))return this;if(u===e.FlowLevel.WeavePoint||u===null){let V=null;if(this._rootWeave&&(V=this._rootWeave.WeavePointNamed(v),V))return V;if(u===e.FlowLevel.WeavePoint)return h?this.DeepSearchForAnyLevelContent(v):null}if(u!==null&&u<this.flowLevel)return null;let R=this._subFlowsByName.get(v)||null;return R&&(u===null||u===R.flowLevel)?R:h?this.DeepSearchForAnyLevelContent(v):null},this.DeepSearchForAnyLevelContent=v=>{const u=this.ContentWithNameAtLevel(v,e.FlowLevel.WeavePoint,!1);if(u)return u;for(const[,h]of this._subFlowsByName){const b=h.ContentWithNameAtLevel(v,null,!0);if(b)return b}return null},this.CheckForDisallowedFunctionFlowControl=()=>{this.flowLevel!==e.FlowLevel.Knot&&this.Error("Functions cannot be stitches - i.e. they should be defined as '== function myFunc ==' rather than internal to another knot.");for(const[h,b]of this._subFlowsByName)this.Error(`Functions may not contain stitches, but saw '${h}' within the function '${this.identifier}'`,b);if(!this._rootWeave)throw new Error;const v=this._rootWeave.FindAll(n.Divert)();for(const h of v)!h.isFunctionCall&&!(h.parent instanceof a.DivertTarget)&&this.Error(`Functions may not contain diverts, but saw '${h}'`,h);const u=this._rootWeave.FindAll(o.Choice)();for(const h of u)this.Error(`Functions may not contain choices, but saw '${h}'`,h)},this.WarningInTermination=v=>{let u="Apparent loose end exists where the flow runs out. Do you need a '-> DONE' statement, choice or divert?";v.parent===this._rootWeave&&this._firstChildFlow&&(u=`${u} Note that if you intend to enter '${this._firstChildFlow.identifier}' next, you need to divert to it explicitly.`);const h=(0,N.asOrNull)(v,n.Divert);h&&h.isTunnel&&(u+=` When final tunnel to '${h.target} ->' returns it won't have anywhere to go.`),this.Warning(u,v)},this.toString=()=>`${this.typeName} '${this.identifier}'`,this.identifier=w,this.args=k,F===null&&(F=[]),this.PreProcessTopLevelObjects(F),F=this.SplitWeaveAndSubFlowContent(F,this.GetType()=="Story"&&!g),this.AddContent(F)}PreProcessTopLevelObjects(w){}ResolveReferences(w){var F,k;if(this._startingSubFlowDivert){if(!this._startingSubFlowRuntime)throw new Error;this._startingSubFlowDivert.targetPath=this._startingSubFlowRuntime.path}if(super.ResolveReferences(w),this.args!==null){for(const m of this.args)w.CheckForNamingCollisions(this,m.identifier,i.SymbolType.Arg,"argument");for(let m=0;m<this.args.length;m+=1)for(let g=m+1;g<this.args.length;g+=1)((F=this.args[m].identifier)===null||F===void 0?void 0:F.name)==((k=this.args[g].identifier)===null||k===void 0?void 0:k.name)&&this.Error(`Multiple arguments with the same name: '${this.args[m].identifier}'`)}if(this.flowLevel!==e.FlowLevel.Story){const m=this.flowLevel===e.FlowLevel.Knot?i.SymbolType.Knot:i.SymbolType.SubFlowAndWeave;w.CheckForNamingCollisions(this,this.identifier,m)}}};return qe.FlowBase=O,qe}var ze={},Xe={},Ye={},Rr;function Ri(){if(Rr)return Ye;Rr=1,Object.defineProperty(Ye,"__esModule",{value:!0}),Ye.ContentList=void 0;const o=ot(),n=et(),a=$t(),e=Z();let f=class extends n.ParsedObject{get runtimeContainer(){return this.runtimeObject}constructor(p,...r){super(),this.dontFlatten=!1,this.TrimTrailingWhitespace=()=>{for(let y=this.content.length-1;y>=0;--y){const s=(0,e.asOrNull)(this.content[y],a.Text);if(s===null)break;if(s.text=s.text.replace(new RegExp(/[ \t]/g),""),s.text.length===0)this.content.splice(y,1);else break}},this.GenerateRuntimeObject=()=>{const y=new o.Container;if(this.content!==null)for(const s of this.content){const c=s.runtimeObject;c&&y.AddContent(c)}return this.dontFlatten&&this.story.DontFlattenContainer(y),y},this.toString=()=>`ContentList(${this.content.join(", ")})`,p&&this.AddContent(p),r&&this.AddContent(r)}get typeName(){return"ContentList"}};return Ye.ContentList=f,Ye}var Ze={},kr;function Hn(){if(kr)return Ze;kr=1,Object.defineProperty(Ze,"__esModule",{value:!0}),Ze.VariableReference=void 0;const o=yt(),n=St();let a=class extends o.InkObject{get containerForCount(){return this.pathForCount===null?null:this.ResolvePath(this.pathForCount).container}get pathStringForCount(){return this.pathForCount===null?null:this.CompactPathString(this.pathForCount)}set pathStringForCount(f){f===null?this.pathForCount=null:this.pathForCount=new n.Path(f)}constructor(f=null){super(),this.pathForCount=null,this.name=f}toString(){return this.name!=null?"var("+this.name+")":"read_count("+this.pathStringForCount+")"}};return Ze.VariableReference=a,Ze}var Dr;function Kn(){if(Dr)return Xe;Dr=1,Object.defineProperty(Xe,"__esModule",{value:!0}),Xe.VariableReference=void 0;const o=Ri(),n=Ot(),a=kt(),e=ee(),f=Hn(),t=ne(),p=Fi(),r=Z();class y extends n.Expression{get name(){return this.path.join(".")}get path(){return this.pathIdentifiers.map(c=>c.name).filter(r.filterUndef)}get identifier(){if(!this.pathIdentifiers||this.pathIdentifiers.length==0)return null;const c=this.path.join(".");return new p.Identifier(c)}get runtimeVarRef(){return this._runtimeVarRef}constructor(c){super(),this.pathIdentifiers=c,this._runtimeVarRef=null,this.isConstantReference=!1,this.isListItemReference=!1,this.GenerateIntoContainer=i=>{let l=this.story.constants.get(this.name);if(l){l.GenerateConstantIntoContainer(i),this.isConstantReference=!0;return}if(this._runtimeVarRef=new f.VariableReference(this.name),this.path.length===1||this.path.length===2){let S="",P="";this.path.length===1?S=this.path[0]:(P=this.path[0],S=this.path[1]),this.story.ResolveListItem(P,S,this)&&(this.isListItemReference=!0)}i.AddContent(this._runtimeVarRef)},this.toString=()=>`{${this.path.join(".")}}`}get typeName(){return"ref"}ResolveReferences(c){if(super.ResolveReferences(c),this.isConstantReference||this.isListItemReference)return;const i=new e.Path(this.pathIdentifiers),l=i.ResolveFromContext(this);if(l){if(!l.containerForCounting)throw new Error;if(l.containerForCounting.visitsShouldBeCounted=!0,this._runtimeVarRef===null)return;this._runtimeVarRef.pathForCount=l.runtimePath,this._runtimeVarRef.name=null;let S=(0,r.asOrNull)(l,a.FlowBase);S&&S.isFunction&&(this.parent instanceof t.Weave||this.parent instanceof o.ContentList||this.parent instanceof a.FlowBase)&&this.Warning(`'${S.identifier}' being used as read count rather than being called as function. Perhaps you intended to write ${S.identifier}()`);return}if(this.path.length>1){let S=`Could not find target for read count: ${i}`;this.path.length<=2&&(S+=`, or couldn't find list item with the name ${this.path.join(",")}`),this.Error(S);return}c.ResolveVariableWithName(this.name,this).found||this.Error(`Unresolved variable: ${this.name}`,this)}}return Xe.VariableReference=y,Xe}var Vr;function hi(){if(Vr)return ze;Vr=1,Object.defineProperty(ze,"__esModule",{value:!0}),ze.FunctionCall=void 0;const o=pt(),n=zn(),a=Jn(),e=Ot(),f=vt(),t=it(),p=Ft(),r=Ti(),y=ee(),s=it(),c=Kn(),i=Z();let l=class bi extends e.Expression{get proxyDivert(){return this._proxyDivert}get name(){return this._proxyDivert.target.firstComponent||""}get args(){return this._proxyDivert.args}get runtimeDivert(){return this._proxyDivert.runtimeDivert}get isChoiceCount(){return this.name==="CHOICE_COUNT"}get isTurns(){return this.name==="TURNS"}get isTurnsSince(){return this.name==="TURNS_SINCE"}get isRandom(){return this.name==="RANDOM"}get isSeedRandom(){return this.name==="SEED_RANDOM"}get isListRange(){return this.name==="LIST_RANGE"}get isListRandom(){return this.name==="LIST_RANDOM"}get isReadCount(){return this.name==="READ_COUNT"}constructor(P,N){super(),this._divertTargetToCount=null,this._variableReferenceToCount=null,this.shouldPopReturnedValue=!1,this.GenerateIntoContainer=O=>{const I=this.story.ResolveList(this.name);let w=!1;if(this.isChoiceCount)this.args.length>0&&this.Error("The CHOICE_COUNT() function shouldn't take any arguments"),O.AddContent(o.ControlCommand.ChoiceCount());else if(this.isTurns)this.args.length>0&&this.Error("The TURNS() function shouldn't take any arguments"),O.AddContent(o.ControlCommand.Turns());else if(this.isTurnsSince||this.isReadCount){const F=(0,i.asOrNull)(this.args[0],a.DivertTarget),k=(0,i.asOrNull)(this.args[0],c.VariableReference);if(this.args.length!==1||F===null&&k===null){this.Error(`The ${this.name}() function should take one argument: a divert target to the target knot, stitch, gather or choice you want to check. e.g. TURNS_SINCE(-> myKnot)`);return}F?(this._divertTargetToCount=F,this.AddContent(this._divertTargetToCount),this._divertTargetToCount.GenerateIntoContainer(O)):k&&(this._variableReferenceToCount=k,this.AddContent(this._variableReferenceToCount),this._variableReferenceToCount.GenerateIntoContainer(O)),this.isTurnsSince?O.AddContent(o.ControlCommand.TurnsSince()):O.AddContent(o.ControlCommand.ReadCount())}else if(this.isRandom){this.args.length!==2&&this.Error("RANDOM should take 2 parameters: a minimum and a maximum integer");for(let F=0;F<this.args.length;F+=1){const k=(0,i.asOrNull)(this.args[F],r.NumberExpression);if(k&&!k.isInt()){const m=F===0?"minimum":"maximum";this.Error(`RANDOM's ${m} parameter should be an integer`)}this.args[F].GenerateIntoContainer(O)}O.AddContent(o.ControlCommand.Random())}else if(this.isSeedRandom){this.args.length!==1&&this.Error("SEED_RANDOM should take 1 parameter - an integer seed");const F=(0,i.asOrNull)(this.args[0],r.NumberExpression);F&&!F.isInt()&&this.Error("SEED_RANDOM's parameter should be an integer seed"),this.args[0].GenerateIntoContainer(O),O.AddContent(o.ControlCommand.SeedRandom())}else if(this.isListRange){this.args.length!==3&&this.Error("LIST_RANGE should take 3 parameters - a list, a min and a max");for(let F=0;F<this.args.length;F+=1)this.args[F].GenerateIntoContainer(O);O.AddContent(o.ControlCommand.ListRange())}else if(this.isListRandom)this.args.length!==1&&this.Error("LIST_RANDOM should take 1 parameter - a list"),this.args[0].GenerateIntoContainer(O),O.AddContent(o.ControlCommand.ListRandom());else if(p.NativeFunctionCall.CallExistsWithName(this.name)){const F=p.NativeFunctionCall.CallWithName(this.name);if(F.numberOfParameters!==this.args.length){let k=`${bi.name} should take ${F.numberOfParameters} parameter`;F.numberOfParameters>1&&(k+="s"),this.Error(k)}for(let k=0;k<this.args.length;k+=1)this.args[k].GenerateIntoContainer(O);O.AddContent(p.NativeFunctionCall.CallWithName(this.name))}else if(I!==null)if(this.args.length>1&&this.Error("Can currently only construct a list from one integer (or an empty list from a given list definition)"),this.args.length===1)O.AddContent(new s.StringValue(this.name)),this.args[0].GenerateIntoContainer(O),O.AddContent(o.ControlCommand.ListFromInt());else{const F=new f.InkList;F.SetInitialOriginName(this.name),O.AddContent(new t.ListValue(F))}else O.AddContent(this._proxyDivert.runtimeObject),w=!0;w||this.content.splice(this.content.indexOf(this._proxyDivert),1),this.shouldPopReturnedValue&&O.AddContent(o.ControlCommand.PopEvaluatedValue())},this.toString=()=>{const O=this.args.join(", ");return`${this.name}(${O})`},this._proxyDivert=new n.Divert(new y.Path(P),N),this._proxyDivert.isFunctionCall=!0,this.AddContent(this._proxyDivert)}get typeName(){return"FunctionCall"}ResolveReferences(P){if(super.ResolveReferences(P),!this.content.includes(this._proxyDivert)&&this.args!==null)for(const N of this.args)N.ResolveReferences(P);if(this._divertTargetToCount){const N=this._divertTargetToCount.divert,O=N.runtimeDivert.variableDivertName!=null;if(O){this.Error(`When getting the TURNS_SINCE() of a variable target, remove the '->' - i.e. it should just be TURNS_SINCE(${N.runtimeDivert.variableDivertName})`);return}const I=N.targetContent;if(I===null)O||this.Error(`Failed to find target for TURNS_SINCE: '${N.target}'`);else{if(!I.containerForCounting)throw new Error;I.containerForCounting.turnIndexShouldBeCounted=!0}}else if(this._variableReferenceToCount){const N=this._variableReferenceToCount.runtimeVarRef;if(!N)throw new Error;N.pathForCount!==null&&this.Error(`Should be '${bi.name}'(-> '${this._variableReferenceToCount.name}). Usage without the '->' only makes sense for variable targets.`)}}};return ze.FunctionCall=l,l.IsBuiltIn=S=>p.NativeFunctionCall.CallExistsWithName(S)?!0:S==="CHOICE_COUNT"||S==="TURNS_SINCE"||S==="TURNS"||S==="RANDOM"||S==="SEED_RANDOM"||S==="LIST_VALUE"||S==="LIST_RANDOM"||S==="READ_COUNT",ze}var Qe={},Wr;function Hs(){if(Wr)return Qe;Wr=1,Object.defineProperty(Qe,"__esModule",{value:!0}),Qe.MultipleConditionExpression=void 0;const o=Ot(),n=Ft();let a=class extends o.Expression{get subExpressions(){return this.content}constructor(f){super(),this.GenerateIntoContainer=t=>{let p=!0;for(const r of this.subExpressions)r.GenerateIntoContainer(t),p||t.AddContent(n.NativeFunctionCall.CallWithName("&&")),p=!1},this.AddContent(f)}get typeName(){return"MultipleConditionExpression"}};return Qe.MultipleConditionExpression=a,Qe}var Lr;function Jn(){if(Lr)return Be;Lr=1,Object.defineProperty(Be,"__esModule",{value:!0}),Be.DivertTarget=void 0;const o=qs(),n=$n(),a=Ii(),e=Zs(),f=it(),t=Ot(),p=kt(),r=hi(),y=Hs(),s=Kn(),c=Z();let i=class Zn extends t.Expression{get runtimeDivert(){if(!this._runtimeDivert)throw new Error;return this._runtimeDivert}get runtimeDivertTargetValue(){if(!this._runtimeDivertTargetValue)throw new Error;return this._runtimeDivertTargetValue}constructor(S){super(),this._runtimeDivert=null,this._runtimeDivertTargetValue=null,this.GenerateIntoContainer=P=>{this.divert.GenerateRuntimeObject(),this._runtimeDivert=this.divert.runtimeDivert,this._runtimeDivertTargetValue=new f.DivertTargetValue,P.AddContent(this.runtimeDivertTargetValue)},this.Equals=P=>{const N=(0,c.asOrNull)(P,Zn);if(!N||!this.divert.target||!N.divert.target)return!1;const O=this.divert.target.dotSeparatedComponents,I=N.divert.target.dotSeparatedComponents;return O===I},this.divert=this.AddContent(S)}get typeName(){return"DivertTarget"}ResolveReferences(S){if(super.ResolveReferences(S),this.divert.isDone||this.divert.isEnd){this.Error("Can't use -> DONE or -> END as variable divert targets",this);return}let P=this;for(;P&&P instanceof t.Expression;){let O=!1,I=!1;const w=P.parent;if(w instanceof o.BinaryExpression){const F=w;F.opName!=="=="&&F.opName!=="!="?O=!0:(F.leftExpression instanceof Zn||F.leftExpression instanceof s.VariableReference)&&(F.rightExpression instanceof Zn||F.rightExpression instanceof s.VariableReference)||(O=!0),I=!0}else if(w instanceof r.FunctionCall){const F=w;!F.isTurnsSince&&!F.isReadCount&&(O=!0),I=!0}else(w instanceof t.Expression||w instanceof y.MultipleConditionExpression||w instanceof n.Choice&&w.condition===P||w instanceof a.Conditional||w instanceof e.ConditionalSingleBranch)&&(O=!0,I=!0);if(O&&this.Error(`Can't use a divert target like that. Did you intend to call '${this.divert.target}' as a function: likeThis(), or check the read count: likeThis, with no arrows?`,this),I)break;P=w}if(this.runtimeDivert.hasVariableTarget){if(!this.divert.target)throw new Error;this.Error(`Since '${this.divert.target.dotSeparatedComponents}' is a variable, it shouldn't be preceded by '->' here.`)}this.runtimeDivert.targetPath&&(this.runtimeDivertTargetValue.targetPath=this.runtimeDivert.targetPath);let N=this.divert.targetContent;if(N!==null){let O=N.containerForCounting;if(O!==null){const w=(0,c.asOrNull)(this.parent,r.FunctionCall);w&&w.isTurnsSince||(O.visitsShouldBeCounted=!0),O.turnIndexShouldBeCounted=!0}let I=(0,c.asOrNull)(N,p.FlowBase);if(I!=null&&I.args!==null)for(const w of I.args)w.isByReference&&this.Error(`Can't store a divert target to a knot or function that has by-reference arguments ('${I.identifier}' has 'ref ${w.identifier}').`)}}};return Be.DivertTarget=i,Be}var jr;function zn(){if(jr)return Me;jr=1,Object.defineProperty(Me,"__esModule",{value:!0}),Me.Divert=void 0;const o=ot(),n=pt(),a=Rt(),e=Jn(),f=kt(),t=hi(),p=et(),r=ee(),y=St(),s=te(),c=it(),i=Kn(),l=ui(),S=Z();let P=class extends p.ParsedObject{get runtimeDivert(){if(!this._runtimeDivert)throw new Error;return this._runtimeDivert}set runtimeDivert(O){this._runtimeDivert=O}get isEnd(){return!!(this.target&&this.target.dotSeparatedComponents==="END")}get isDone(){return!!(this.target&&this.target.dotSeparatedComponents==="DONE")}constructor(O,I){super(),this.args=[],this.target=null,this.targetContent=null,this._runtimeDivert=null,this.isFunctionCall=!1,this.isEmpty=!1,this.isTunnel=!1,this.isThread=!1,this.GenerateRuntimeObject=()=>{if(this.isEnd)return n.ControlCommand.End();if(this.isDone)return n.ControlCommand.Done();this.runtimeDivert=new a.Divert,this.ResolveTargetContent(),this.CheckArgumentValidity();const w=this.args!==null&&this.args.length>0;if(w||this.isFunctionCall||this.isTunnel||this.isThread){const F=new o.Container;if(w){this.isFunctionCall||F.AddContent(n.ControlCommand.EvalStart());let k=null;this.targetContent&&(k=this.targetContent.args);for(let m=0;m<this.args.length;++m){const g=this.args[m];let v=null;if(k&&m<k.length&&(v=k[m]),v&&v.isByReference){const u=(0,S.asOrNull)(g,i.VariableReference);if(!u){this.Error(`Expected variable name to pass by reference to 'ref ${v.identifier}' but saw ${g}`);break}const h=new r.Path(u.pathIdentifiers);if(h.ResolveFromContext(this)){this.Error(`can't pass a read count by reference. '${h.dotSeparatedComponents}' is a knot/stitch/label, but '${this.target.dotSeparatedComponents}' requires the name of a VAR to be passed.`);break}const R=new c.VariablePointerValue(u.name);F.AddContent(R)}else g.GenerateIntoContainer(F)}this.isFunctionCall||F.AddContent(n.ControlCommand.EvalEnd())}return this.isThread?F.AddContent(n.ControlCommand.StartThread()):(this.isFunctionCall||this.isTunnel)&&(this.runtimeDivert.pushesToStack=!0,this.runtimeDivert.stackPushType=this.isFunctionCall?s.PushPopType.Function:s.PushPopType.Tunnel),F.AddContent(this.runtimeDivert),F}return this.runtimeDivert},this.PathAsVariableName=()=>this.target?this.target.firstComponent:null,this.ResolveTargetContent=()=>{if(!(this.isEmpty||this.isEnd)&&this.targetContent===null){let w=this.PathAsVariableName();if(w!==null){const F=(0,S.asOrNull)((0,l.ClosestFlowBase)(this),f.FlowBase);if(F){const k=F.ResolveVariableWithName(w,this);if(k.found){if(k.isArgument&&k.ownerFlow&&k.ownerFlow.args){let m=k.ownerFlow.args.find(g=>{var v;return((v=g.identifier)===null||v===void 0?void 0:v.name)==w});m&&!m.isDivertTarget&&this.Error(`Since '${m.identifier}' is used as a variable divert target (on ${this.debugMetadata}), it should be marked as: -> ${m.identifier}`,k.ownerFlow)}this.runtimeDivert.variableDivertName=w;return}}}if(!this.target)throw new Error;this.targetContent=this.target.ResolveFromContext(this)}},this.CheckArgumentValidity=()=>{if(this.isEmpty)return;let w=0;if(this.args!==null&&this.args.length>0&&(w=this.args.length),this.targetContent===null)return;const F=(0,S.asOrNull)(this.targetContent,f.FlowBase);if(w===0&&(F===null||!F.hasParameters))return;if(F===null&&w>0){this.Error("target needs to be a knot or stitch in order to pass arguments");return}else if(F!==null&&(F.args===null||!F.args&&w>0)){this.Error(`target (${F.name}) doesn't take parameters`);return}else if(this.parent instanceof e.DivertTarget){w>0&&this.Error("can't store arguments in a divert target variable");return}const k=F.args.length;if(k!==w){let m;w===0?m="but there weren't any passed to it":w<k?m=`but only got ${w}`:m=`but got ${w}`,this.Error(`to '${F.identifier}' requires ${k} arguments, ${m}`);return}for(let m=0;m<k;++m){const g=F.args[m],v=this.args[m];if(g.isDivertTarget){let u=(0,S.asOrNull)(v,i.VariableReference);if(!(v instanceof e.DivertTarget)&&u===null)this.Error(`Target '${F.identifier}' expects a divert target for the parameter named -> ${g.identifier} but saw ${v}`,v);else if(u){const h=new r.Path(u.pathIdentifiers);h.ResolveFromContext(u)&&this.Error(`Passing read count of '${h.dotSeparatedComponents}' instead of a divert target. You probably meant '${h}'`)}}}if(F===null){this.Error("Can't call as a function or with arguments unless it's a knot or stitch");return}},this.CheckExternalArgumentValidity=w=>{const F=this.target?this.target.firstComponent:null,k=w.externals.get(F);if(!k)throw new Error("external not found");const m=k.argumentNames.length;let g=0;this.args&&(g=this.args.length),g!==m&&this.Error(`incorrect number of arguments sent to external function '${F}'. Expected ${m} but got ${g}`)},this.toString=()=>{let w="";if(this.target!==null)w+=this.target.toString();else return"-> <empty divert>";return this.isTunnel&&(w+=" ->"),this.isFunctionCall&&(w+=" ()"),w},O&&(this.target=O),I&&(this.args=I,this.AddContent(I))}get typeName(){return"Divert"}ResolveReferences(O){if(this.isEmpty||this.isEnd||this.isDone)return;if(!this.runtimeDivert)throw new Error;this.targetContent&&(this.runtimeDivert.targetPath=this.targetContent.runtimePath),super.ResolveReferences(O);let I=(0,S.asOrNull)(this.targetContent,f.FlowBase);I&&(!I.isFunction&&this.isFunctionCall?super.Error(`${I.identifier} hasn't been marked as a function, but it's being called as one. Do you need to declare the knot as '== function ${I.identifier} =='?`):I.isFunction&&!this.isFunctionCall&&!(this.parent instanceof e.DivertTarget)&&super.Error(I.identifier+" can't be diverted to. It can only be called as a function since it's been marked as such: '"+I.identifier+"(...)'"));const w=this.targetContent!==null;let F=!1,k=!1;if(this.target){if(this.target.numberOfComponents===1){if(!this.target.firstComponent)throw new Error;if(F=t.FunctionCall.IsBuiltIn(this.target.firstComponent),k=O.IsExternal(this.target.firstComponent),F||k){this.isFunctionCall||super.Error(`${this.target.firstComponent} must be called as a function: ~ ${this.target.firstComponent}()`),k&&(this.runtimeDivert.isExternal=!0,this.args!==null&&(this.runtimeDivert.externalArgs=this.args.length),this.runtimeDivert.pushesToStack=!1,this.runtimeDivert.targetPath=new y.Path(this.target.firstComponent),this.CheckExternalArgumentValidity(O));return}}}else throw new Error;this.runtimeDivert.variableDivertName==null&&!w&&!F&&!k&&this.Error(`target not found: '${this.target}'`)}Error(O,I=null,w=!1){if(I!==this&&I){super.Error(O,I);return}this.isFunctionCall?super.Error(`Function call ${O}`,I,w):super.Error(`Divert ${O}`,I,w)}};return Me.Divert=P,Me}var tn={},Mr;function Na(){if(Mr)return tn;Mr=1,Object.defineProperty(tn,"__esModule",{value:!0}),tn.GatherPointToResolve=void 0;let o=class{constructor(a,e){this.divert=a,this.targetRuntimeObj=e}};return tn.GatherPointToResolve=o,tn}var en={},nn={},Br;function Ia(){if(Br)return nn;Br=1,Object.defineProperty(nn,"__esModule",{value:!0}),nn.SequenceDivertToResolve=void 0;let o=class{constructor(a,e){this.divert=a,this.targetContent=e}};return nn.SequenceDivertToResolve=o,nn}var rn={},qr;function Ks(){if(qr)return rn;qr=1,Object.defineProperty(rn,"__esModule",{value:!0}),rn.SequenceType=void 0;var o;return(function(n){n[n.Stopping=1]="Stopping",n[n.Cycle=2]="Cycle",n[n.Shuffle=4]="Shuffle",n[n.Once=8]="Once"})(o||(rn.SequenceType=o={})),rn}var Gr;function Js(){if(Gr)return en;Gr=1,Object.defineProperty(en,"__esModule",{value:!0}),en.Sequence=void 0;const o=ot(),n=pt(),a=Rt(),e=it(),f=Ft(),t=et(),p=Ia(),r=Ks(),y=ne();let s=class extends t.ParsedObject{constructor(i,l){super(),this.sequenceType=l,this._sequenceDivertsToResolve=[],this.GenerateRuntimeObject=()=>{const S=new o.Container;S.visitsShouldBeCounted=!0,S.countingAtStartOnly=!0,this._sequenceDivertsToResolve=[],S.AddContent(n.ControlCommand.EvalStart()),S.AddContent(n.ControlCommand.VisitIndex());const P=(this.sequenceType&r.SequenceType.Once)>0,N=(this.sequenceType&r.SequenceType.Cycle)>0,O=(this.sequenceType&r.SequenceType.Stopping)>0,I=(this.sequenceType&r.SequenceType.Shuffle)>0;let w=this.sequenceElements.length;if(P&&(w+=1),O||P?(S.AddContent(new e.IntValue(w-1)),S.AddContent(f.NativeFunctionCall.CallWithName("MIN"))):N&&(S.AddContent(new e.IntValue(this.sequenceElements.length)),S.AddContent(f.NativeFunctionCall.CallWithName("%"))),I){const k=n.ControlCommand.NoOp();if(P||O){const g=O?this.sequenceElements.length-1:this.sequenceElements.length;S.AddContent(n.ControlCommand.Duplicate()),S.AddContent(new e.IntValue(g)),S.AddContent(f.NativeFunctionCall.CallWithName("=="));const v=new a.Divert;v.isConditional=!0,S.AddContent(v),this.AddDivertToResolve(v,k)}let m=this.sequenceElements.length;O&&(m-=1),S.AddContent(new e.IntValue(m)),S.AddContent(n.ControlCommand.SequenceShuffleIndex()),(P||O)&&S.AddContent(k)}S.AddContent(n.ControlCommand.EvalEnd());const F=n.ControlCommand.NoOp();for(let k=0;k<w;k+=1){S.AddContent(n.ControlCommand.EvalStart()),S.AddContent(n.ControlCommand.Duplicate()),S.AddContent(new e.IntValue(k)),S.AddContent(f.NativeFunctionCall.CallWithName("==")),S.AddContent(n.ControlCommand.EvalEnd());const m=new a.Divert;m.isConditional=!0,S.AddContent(m);let g;k<this.sequenceElements.length?g=this.sequenceElements[k].runtimeObject:g=new o.Container,g.name=`s${k}`,g.InsertContent(n.ControlCommand.PopEvaluatedValue(),0);const v=new a.Divert;g.AddContent(v),S.AddToNamedContentOnly(g),this.AddDivertToResolve(m,g),this.AddDivertToResolve(v,F)}return S.AddContent(F),S},this.AddDivertToResolve=(S,P)=>{this._sequenceDivertsToResolve.push(new p.SequenceDivertToResolve(S,P))},this.sequenceType=l,this.sequenceElements=[];for(const S of i){const P=S.content;let N=null;P===null||P.length===0?N=S:N=new y.Weave(P),this.sequenceElements.push(N),this.AddContent(N)}}get typeName(){return"Sequence"}ResolveReferences(i){super.ResolveReferences(i);for(const l of this._sequenceDivertsToResolve)l.divert.targetPath=l.targetContent.path}};return en.Sequence=s,en}var sn={},$r;function zs(){if($r)return sn;$r=1,Object.defineProperty(sn,"__esModule",{value:!0}),sn.TunnelOnwards=void 0;const o=ot(),n=pt(),a=Rt(),e=it(),f=et(),t=Qt(),p=Z(),r=Hn();let y=class extends f.ParsedObject{constructor(){super(...arguments),this._overrideDivertTarget=null,this._divertAfter=null,this.GenerateRuntimeObject=()=>{const c=new o.Container;if(c.AddContent(n.ControlCommand.EvalStart()),this.divertAfter){const i=this.divertAfter.GenerateRuntimeObject(),l=i;if(l){const P=this.divertAfter.args;if(P!==null&&P.length>0){let N=-1,O=-1;for(let I=0;I<l.content.length;I+=1){const w=l.content[I];w&&(N==-1&&w.commandType===n.ControlCommand.CommandType.EvalStart?N=I:w.commandType===n.ControlCommand.CommandType.EvalEnd&&(O=I))}for(let I=N+1;I<O;I+=1){const w=l.content[I];w.parent=null,c.AddContent(l.content[I])}}}let S=(0,p.asOrNull)(i,a.Divert);if(S!=null&&S.hasVariableTarget){let P=new r.VariableReference(S.variableDivertName);c.AddContent(P)}else this._overrideDivertTarget=new e.DivertTargetValue,c.AddContent(this._overrideDivertTarget)}else c.AddContent(new t.Void);return c.AddContent(n.ControlCommand.EvalEnd()),c.AddContent(n.ControlCommand.PopTunnel()),c},this.toString=()=>` -> ${this._divertAfter}`}get divertAfter(){return this._divertAfter}set divertAfter(c){this._divertAfter=c,this._divertAfter&&this.AddContent(this._divertAfter)}get typeName(){return"TunnelOnwards"}ResolveReferences(c){super.ResolveReferences(c),this.divertAfter&&this.divertAfter.targetContent&&(this._overrideDivertTarget.targetPath=this.divertAfter.targetContent.runtimePath)}};return sn.TunnelOnwards=y,sn}var an={},on={},ln={},Ur;function Xs(){if(Ur)return ln;Ur=1,Object.defineProperty(ln,"__esModule",{value:!0}),ln.ListDefinition=void 0;const o=vt();let n=class{constructor(e,f){this._name=e||"",this._items=null,this._itemNameToValues=f||new Map}get name(){return this._name}get items(){if(this._items==null){this._items=new Map;for(let[e,f]of this._itemNameToValues){let t=new o.InkListItem(this.name,e);this._items.set(t.serialized(),f)}}return this._items}ValueForItem(e){if(!e.itemName)return 0;let f=this._itemNameToValues.get(e.itemName);return typeof f<"u"?f:0}ContainsItem(e){return!e.itemName||e.originName!=this.name?!1:this._itemNameToValues.has(e.itemName)}ContainsItemWithName(e){return this._itemNameToValues.has(e)}TryGetItemWithValue(e,f){for(let[t,p]of this._itemNameToValues)if(p==e)return f=new o.InkListItem(this.name,t),{result:f,exists:!0};return f=o.InkListItem.Null,{result:f,exists:!1}}TryGetValueForItem(e,f){if(!e.itemName)return{result:0,exists:!1};let t=this._itemNameToValues.get(e.itemName);return t?{result:t,exists:!0}:{result:0,exists:!1}}};return ln.ListDefinition=n,ln}var Hr;function ki(){if(Hr)return on;Hr=1,Object.defineProperty(on,"__esModule",{value:!0}),on.ListDefinition=void 0;const o=vt(),n=vt(),a=Xs(),e=it(),f=et(),t=Wt();class p extends f.ParsedObject{get typeName(){return"ListDefinition"}get runtimeListDefinition(){var y;const s=new Map;for(const c of this.itemDefinitions)s.has(c.name)?this.Error(`List '${this.identifier}' contains duplicate items called '${c.name}'`):s.set(c.name,c.seriesValue);return new a.ListDefinition(((y=this.identifier)===null||y===void 0?void 0:y.name)||"",s)}constructor(y){super(),this.itemDefinitions=y,this.identifier=null,this.variableAssignment=null,this._elementsByName=null,this.ItemNamed=c=>{if(this._elementsByName===null){this._elementsByName=new Map;for(const l of this.itemDefinitions)this._elementsByName.set(l.name,l)}return this._elementsByName.get(c)||null},this.GenerateRuntimeObject=()=>{var c,i;const l=new o.InkList;for(const S of this.itemDefinitions)if(S.inInitialList){const P=new n.InkListItem(((c=this.identifier)===null||c===void 0?void 0:c.name)||null,S.name||null);l.Add(P,S.seriesValue)}return l.SetInitialOriginName(((i=this.identifier)===null||i===void 0?void 0:i.name)||""),new e.ListValue(l)};let s=1;for(const c of this.itemDefinitions)c.explicitValue!==null&&(s=c.explicitValue),c.seriesValue=s,s+=1;this.AddContent(y)}ResolveReferences(y){super.ResolveReferences(y),y.CheckForNamingCollisions(this,this.identifier,t.SymbolType.List)}}return on.ListDefinition=p,on}var Kr;function Ys(){if(Kr)return an;Kr=1,Object.defineProperty(an,"__esModule",{value:!0}),an.VariableAssignment=void 0;const o=ot(),n=ui(),a=ki(),e=et(),f=Wt(),t=Gt(),p=Kn(),r=Z();let y=class extends e.ParsedObject{get variableName(){return this.variableIdentifier.name}get typeName(){return this.isNewTemporaryDeclaration?"temp":this.isGlobalDeclaration?this.listDefinition!==null?"LIST":"VAR":"variable assignment"}get isDeclaration(){return this.isGlobalDeclaration||this.isNewTemporaryDeclaration}constructor({assignedExpression:c,isGlobalDeclaration:i,isTemporaryNewDeclaration:l,listDef:S,variableIdentifier:P}){super(),this._runtimeAssignment=null,this.expression=null,this.listDefinition=null,this.GenerateRuntimeObject=()=>{let N=null;if(this.isGlobalDeclaration?N=this.story:this.isNewTemporaryDeclaration&&(N=(0,n.ClosestFlowBase)(this)),N&&N.AddNewVariableDeclaration(this),this.isGlobalDeclaration)return null;const O=new o.Container;return this.expression?O.AddContent(this.expression.runtimeObject):this.listDefinition&&O.AddContent(this.listDefinition.runtimeObject),this._runtimeAssignment=new t.VariableAssignment(this.variableName,this.isNewTemporaryDeclaration),O.AddContent(this._runtimeAssignment),O},this.toString=()=>`${this.isGlobalDeclaration?"VAR":this.isNewTemporaryDeclaration?"~ temp":""} ${this.variableName}`,this.variableIdentifier=P,this.isGlobalDeclaration=!!i,this.isNewTemporaryDeclaration=!!l,S instanceof a.ListDefinition?(this.listDefinition=this.AddContent(S),this.listDefinition.variableAssignment=this,this.isGlobalDeclaration=!0):c&&(this.expression=this.AddContent(c))}ResolveReferences(c){if(super.ResolveReferences(c),this.isDeclaration&&this.listDefinition===null&&c.CheckForNamingCollisions(this,this.variableIdentifier,this.isGlobalDeclaration?f.SymbolType.Var:f.SymbolType.Temp),this.isGlobalDeclaration){const i=(0,r.asOrNull)(this.expression,p.VariableReference);i&&!i.isConstantReference&&!i.isListItemReference&&this.Error("global variable assignments cannot refer to other variables, only literal values, constants and list items")}if(!this.isNewTemporaryDeclaration){const i=c.ResolveVariableWithName(this.variableName,this);i.found||(this.variableName in this.story.constants?this.Error(`Can't re-assign to a constant (do you need to use VAR when declaring '${this.variableName}'?)`,this):this.Error(`Variable could not be found to assign to: '${this.variableName}'`,this)),this._runtimeAssignment&&(this._runtimeAssignment.isGlobal=i.isGlobal)}}};return an.VariableAssignment=y,an}var Jr;function ne(){if(Jr)return Le;Jr=1,Object.defineProperty(Le,"__esModule",{value:!0}),Le.Weave=void 0;const o=xi(),n=$n(),a=Ii(),e=Ai(),f=ot(),t=zn(),p=Rt(),r=Jn(),y=kt(),s=li(),c=Na(),i=et(),l=Js(),S=$t(),P=zs(),N=Ys(),O=Z();let I=class qt extends i.ParsedObject{get rootContainer(){return this._rootContainer||(this._rootContainer=this.GenerateRuntimeObject()),this._rootContainer}get namedWeavePoints(){return this._namedWeavePoints}get lastParsedSignificantObject(){if(this.content.length===0)return null;let F=null;for(let m=this.content.length-1;m>=0;--m){F=this.content[m];let g=(0,O.asOrNull)(F,S.Text);if(!(g&&g.text===`
|
|
15
|
+
`)&&!this.IsGlobalDeclaration(F))break}const k=(0,O.asOrNull)(F,qt);return k&&(F=k.lastParsedSignificantObject),F}constructor(F,k=-1){super(),this.previousWeavePoint=null,this.addContentToPreviousWeavePoint=!1,this.hasSeenChoiceInSection=!1,this.currentContainer=null,this._unnamedGatherCount=0,this._choiceCount=0,this._rootContainer=null,this._namedWeavePoints=new Map,this.looseEnds=[],this.gatherPointsToResolve=[],this.ResolveWeavePointNaming=()=>{var m,g,v;const u=[...this.FindAll(s.Gather)(h=>!(h.name===null||h.name===void 0)),...this.FindAll(n.Choice)(h=>!(h.name===null||h.name===void 0))];this._namedWeavePoints=new Map;for(const h of u){const b=this.namedWeavePoints.get(((m=h.identifier)===null||m===void 0?void 0:m.name)||"");if(b){const R=b instanceof s.Gather?"gather":"choice",V=b;this.Error(`A ${R} with the same label name '${h.name}' already exists in this context on line ${V.debugMetadata?V.debugMetadata.startLineNumber:"NO DEBUG METADATA AVAILABLE"}`,h)}!((g=h.identifier)===null||g===void 0)&&g.name&&this.namedWeavePoints.set((v=h.identifier)===null||v===void 0?void 0:v.name,h)}},this.ConstructWeaveHierarchyFromIndentation=()=>{let m=0;for(;m<this.content.length;){const g=this.content[m];if(g instanceof n.Choice||g instanceof s.Gather){const u=g.indentationDepth-1;if(u>this.baseIndentIndex){let h=m;for(;m<this.content.length;){const j=(0,O.asOrNull)(this.content[m],n.Choice)||(0,O.asOrNull)(this.content[m],s.Gather);if(j!==null&&j.indentationDepth-1<=this.baseIndentIndex)break;m+=1}const b=m-h,R=this.content.slice(h,h+b);this.content.splice(h,b);const V=new qt(R,u);this.InsertContent(h,V),m=h}}m+=1}},this.DetermineBaseIndentationFromContent=m=>{for(const g of m)if(g instanceof n.Choice||g instanceof s.Gather)return g.indentationDepth-1;return 0},this.GenerateRuntimeObject=()=>{this._rootContainer=new f.Container,this.currentContainer=this._rootContainer,this.looseEnds=[],this.gatherPointsToResolve=[];for(const m of this.content)if(m instanceof n.Choice||m instanceof s.Gather)this.AddRuntimeForWeavePoint(m);else if(m instanceof qt){const g=m;this.AddRuntimeForNestedWeave(g),this.gatherPointsToResolve.splice(0,0,...g.gatherPointsToResolve)}else this.AddGeneralRuntimeContent(m.runtimeObject);return this.PassLooseEndsToAncestors(),this._rootContainer},this.AddRuntimeForGather=m=>{const g=!this.hasSeenChoiceInSection;this.hasSeenChoiceInSection=!1;const v=m.runtimeContainer;if(m.name||(v.name=`g-${this._unnamedGatherCount}`,this._unnamedGatherCount+=1),g){if(!this.currentContainer)throw new Error;this.currentContainer.AddContent(v)}else this.rootContainer.AddToNamedContentOnly(v);for(const u of this.looseEnds){const h=u;if(h instanceof s.Gather&&h.indentationDepth==m.indentationDepth)continue;let b=null;if(h instanceof t.Divert)b=h.runtimeObject;else{b=new p.Divert;const R=h;if(!R.runtimeContainer)throw new Error;R.runtimeContainer.AddContent(b)}this.gatherPointsToResolve.push(new c.GatherPointToResolve(b,v))}this.looseEnds=[],this.currentContainer=v},this.AddRuntimeForWeavePoint=m=>{if(m instanceof s.Gather)this.AddRuntimeForGather(m);else if(m instanceof n.Choice){if(!this.currentContainer)throw new Error;this.previousWeavePoint instanceof s.Gather&&this.looseEnds.splice(this.looseEnds.indexOf(this.previousWeavePoint),1);const g=m;if(this.currentContainer.AddContent(g.runtimeObject),!g.innerContentContainer)throw new Error;g.innerContentContainer.name=`c-${this._choiceCount}`,this.currentContainer.AddToNamedContentOnly(g.innerContentContainer),this._choiceCount+=1,this.hasSeenChoiceInSection=!0}this.addContentToPreviousWeavePoint=!1,this.WeavePointHasLooseEnd(m)&&(this.looseEnds.push(m),(0,O.asOrNull)(m,n.Choice)&&(this.addContentToPreviousWeavePoint=!0)),this.previousWeavePoint=m},this.AddRuntimeForNestedWeave=m=>{this.AddGeneralRuntimeContent(m.rootContainer),this.previousWeavePoint!==null&&(this.looseEnds.splice(this.looseEnds.indexOf(this.previousWeavePoint),1),this.addContentToPreviousWeavePoint=!1)},this.AddGeneralRuntimeContent=m=>{if(m!==null)if(this.addContentToPreviousWeavePoint){if(!this.previousWeavePoint||!this.previousWeavePoint.runtimeContainer)throw new Error;this.previousWeavePoint.runtimeContainer.AddContent(m)}else{if(!this.currentContainer)throw new Error;this.currentContainer.AddContent(m)}},this.PassLooseEndsToAncestors=()=>{if(this.looseEnds.length===0)return;let m=null,g=null,v=!1;for(let u=this.parent;u!==null;u=u.parent){const h=(0,O.asOrNull)(u,qt);h&&(!v&&m===null&&(m=h),v&&g===null&&(g=h)),(u instanceof l.Sequence||u instanceof a.Conditional)&&(v=!0)}if(!(m===null&&g===null))for(let u=this.looseEnds.length-1;u>=0;u-=1){const h=this.looseEnds[u];let b=!1;if(v){if(h instanceof n.Choice&&m!==null)m.ReceiveLooseEnd(h),b=!0;else if(!(h instanceof n.Choice)){const R=m||g;R!==null&&(R.ReceiveLooseEnd(h),b=!0)}}else m!=null&&m.hasOwnProperty("ReceiveLooseEnd")&&m.ReceiveLooseEnd(h),b=!0;b&&this.looseEnds.splice(u,1)}},this.ReceiveLooseEnd=m=>{this.looseEnds.push(m)},this.WeavePointNamed=m=>{if(!this.namedWeavePoints)return null;let g=this.namedWeavePoints.get(m);return g||null},this.IsGlobalDeclaration=m=>{const g=(0,O.asOrNull)(m,N.VariableAssignment);return!!(g&&g.isGlobalDeclaration&&g.isDeclaration||(0,O.asOrNull)(m,e.ConstantDeclaration))},this.ContentThatFollowsWeavePoint=m=>{const g=[],v=m;if(v.content!==null)for(const b of v.content)this.IsGlobalDeclaration(b)||g.push(b);const u=(0,O.asOrNull)(v.parent,qt);if(u===null)throw new Error("Expected weave point parent to be weave?");const h=u.content.indexOf(v);for(let b=h+1;b<u.content.length;b+=1){const R=u.content[b];if(!this.IsGlobalDeclaration(R)){if(R instanceof n.Choice||R instanceof s.Gather||R instanceof qt)break;g.push(R)}}return g},this.ValidateTermination=m=>{if(this.lastParsedSignificantObject instanceof o.AuthorWarning)return;if(this.looseEnds!==null&&this.looseEnds.length>0)for(const v of this.looseEnds){const u=this.ContentThatFollowsWeavePoint(v);this.ValidateFlowOfObjectsTerminates(u,v,m)}else{for(const v of this.content)if(v instanceof n.Choice||v instanceof t.Divert)return;this.ValidateFlowOfObjectsTerminates(this.content,this,m)}},this.BadNestedTerminationHandler=m=>{let g=null;for(let u=m.parent;u!==null;u=u.parent)if(u instanceof l.Sequence||u instanceof a.Conditional){g=(0,O.asOrNull)(u,a.Conditional);break}let v="Choices nested in conditionals or sequences need to explicitly divert afterwards.";g!==null&&g.FindAll(n.Choice)().length===1&&(v=`Choices with conditions should be written: '* {condition} choice'. Otherwise, ${v.toLowerCase()}`),this.Error(v,m)},this.ValidateFlowOfObjectsTerminates=(m,g,v)=>{let u=!1,h=g;for(const b of m){if(b.Find(t.Divert)(V=>!V.isThread&&!V.isTunnel&&!V.isFunctionCall&&!(V.parent instanceof r.DivertTarget))!==null&&(u=!0),b.Find(P.TunnelOnwards)()!=null){u=!0;break}h=b}if(!u){if(h instanceof o.AuthorWarning)return;v(h)}},this.WeavePointHasLooseEnd=m=>{if(m.content===null)return!0;for(let g=m.content.length-1;g>=0;--g){let v=(0,O.asOrNull)(m.content[g],t.Divert);if(v&&!(v.isThread||v.isTunnel||v.isFunctionCall))return!1}return!0},this.CheckForWeavePointNamingCollisions=()=>{if(!this.namedWeavePoints)return;const m=[];for(const g of this.ancestry){const v=(0,O.asOrNull)(g,y.FlowBase);if(v)m.push(v);else break}for(const[g,v]of this.namedWeavePoints)for(const u of m){const h=u.ContentWithNameAtLevel(g);if(h&&h!==v){const b=`${v.GetType()} '${g}' has the same label name as a ${h.GetType()} (on ${h.debugMetadata})`;this.Error(b,v)}}},k==-1?this.baseIndentIndex=this.DetermineBaseIndentationFromContent(F):this.baseIndentIndex=k,this.AddContent(F),this.ConstructWeaveHierarchyFromIndentation()}get typeName(){return"Weave"}ResolveReferences(F){if(super.ResolveReferences(F),this.looseEnds!==null&&this.looseEnds.length>0){let k=!1;for(let m=this.parent;m!==null;m=m.parent)if(m instanceof l.Sequence||m instanceof a.Conditional){k=!0;break}k&&this.ValidateTermination(this.BadNestedTerminationHandler)}for(const k of this.gatherPointsToResolve)k.divert.targetPath=k.targetRuntimeObj.path;this.CheckForWeavePointNamingCollisions()}};return Le.Weave=I,Le}var zr;function Zs(){if(zr)return Ve;zr=1,Object.defineProperty(Ve,"__esModule",{value:!0}),Ve.ConditionalSingleBranch=void 0;const o=ot(),n=pt(),a=Rt(),e=et(),f=Ft(),t=it(),p=$t(),r=ne(),y=Z();let s=class extends e.ParsedObject{get ownExpression(){return this._ownExpression}set ownExpression(i){this._ownExpression=i,this._ownExpression&&this.AddContent(this._ownExpression)}constructor(i){super(),this._contentContainer=null,this._conditionalDivert=null,this._ownExpression=null,this._innerWeave=null,this.isTrueBranch=!1,this.matchingEquality=!1,this.isElse=!1,this.isInline=!1,this.returnDivert=null,this.GenerateRuntimeObject=()=>{if(this._innerWeave)for(const P of this._innerWeave.content){const N=(0,y.asOrNull)(P,p.Text);N&&N.text.startsWith("else:")&&this.Warning("Saw the text 'else:' which is being treated as content. Did you mean '- else:'?",N)}const l=new o.Container,S=this.matchingEquality&&!this.isElse;if(S&&l.AddContent(n.ControlCommand.Duplicate()),this._conditionalDivert=new a.Divert,this._conditionalDivert.isConditional=!this.isElse,!this.isTrueBranch&&!this.isElse){const P=this.ownExpression!==null;P&&l.AddContent(n.ControlCommand.EvalStart()),this.ownExpression&&this.ownExpression.GenerateIntoContainer(l),this.matchingEquality&&l.AddContent(f.NativeFunctionCall.CallWithName("==")),P&&l.AddContent(n.ControlCommand.EvalEnd())}return l.AddContent(this._conditionalDivert),this._contentContainer=this.GenerateRuntimeForContent(),this._contentContainer.name="b",this.isInline||this._contentContainer.InsertContent(new t.StringValue(`
|
|
16
|
+
`),0),(S||this.isElse&&this.matchingEquality)&&this._contentContainer.InsertContent(n.ControlCommand.PopEvaluatedValue(),0),l.AddToNamedContentOnly(this._contentContainer),this.returnDivert=new a.Divert,this._contentContainer.AddContent(this.returnDivert),l},this.GenerateRuntimeForContent=()=>this._innerWeave===null?new o.Container:this._innerWeave.rootContainer,i&&(this._innerWeave=new r.Weave(i),this.AddContent(this._innerWeave))}get typeName(){return"ConditionalSingleBranch"}ResolveReferences(i){if(!this._conditionalDivert||!this._contentContainer)throw new Error;this._conditionalDivert.targetPath=this._contentContainer.path,super.ResolveReferences(i)}};return Ve.ConditionalSingleBranch=s,Ve}var un={},Xr;function Aa(){if(Xr)return un;Xr=1,Object.defineProperty(un,"__esModule",{value:!0}),un.CustomFlags=void 0;var o;return(function(n){n[n.ParsingString=1]="ParsingString",n[n.TagActive=2]="TagActive"})(o||(un.CustomFlags=o={})),un}var hn={},Yr;function Fa(){if(Yr)return hn;Yr=1,Object.defineProperty(hn,"__esModule",{value:!0}),hn.DebugMetadata=void 0;let o=class Qs{constructor(){this.startLineNumber=0,this.endLineNumber=0,this.startCharacterNumber=0,this.endCharacterNumber=0,this.fileName=null,this.sourceName=null}Merge(a){let e=new Qs;return e.fileName=this.fileName,e.sourceName=this.sourceName,this.startLineNumber<a.startLineNumber?(e.startLineNumber=this.startLineNumber,e.startCharacterNumber=this.startCharacterNumber):this.startLineNumber>a.startLineNumber?(e.startLineNumber=a.startLineNumber,e.startCharacterNumber=a.startCharacterNumber):(e.startLineNumber=this.startLineNumber,e.startCharacterNumber=Math.min(this.startCharacterNumber,a.startCharacterNumber)),this.endLineNumber>a.endLineNumber?(e.endLineNumber=this.endLineNumber,e.endCharacterNumber=this.endCharacterNumber):this.endLineNumber<a.endLineNumber?(e.endLineNumber=a.endLineNumber,e.endCharacterNumber=a.endCharacterNumber):(e.endLineNumber=this.endLineNumber,e.endCharacterNumber=Math.max(this.endCharacterNumber,a.endCharacterNumber)),e}toString(){return this.fileName!==null?`line ${this.startLineNumber} of ${this.fileName}"`:"line "+this.startLineNumber}};return hn.DebugMetadata=o,hn}var cn={},Zr;function Ra(){if(Zr)return cn;Zr=1,Object.defineProperty(cn,"__esModule",{value:!0}),cn.ExternalDeclaration=void 0;const o=et();let n=class extends o.ParsedObject{get name(){var e;return((e=this.identifier)===null||e===void 0?void 0:e.name)||null}constructor(e,f){super(),this.identifier=e,this.argumentNames=f,this.GenerateRuntimeObject=()=>(this.story.AddExternal(this),null)}get typeName(){return"EXTERNAL"}toString(){var e;return`EXTERNAL ${(e=this.identifier)===null||e===void 0?void 0:e.name}`}};return cn.ExternalDeclaration=n,cn}var dn={},Qr;function ka(){if(Qr)return dn;Qr=1,Object.defineProperty(dn,"__esModule",{value:!0}),dn.FlowDecl=void 0;let o=class{constructor(a,e,f){this.name=a,this.args=e,this.isFunction=f}};return dn.FlowDecl=o,dn}var fn={},pn={},ts;function ta(){if(ts)return pn;ts=1,Object.defineProperty(pn,"__esModule",{value:!0}),pn.Wrap=void 0;const o=et();let n=class extends o.ParsedObject{constructor(e){super(),this._objToWrap=e,this.GenerateRuntimeObject=()=>this._objToWrap}};return pn.Wrap=n,pn}var es;function Da(){if(es)return fn;es=1,Object.defineProperty(fn,"__esModule",{value:!0}),fn.Glue=void 0;const o=ta();class n extends o.Wrap{constructor(e){super(e)}get typeName(){return"Glue"}}return fn.Glue=n,fn}var mn={},ns;function Di(){if(ns)return mn;ns=1,Object.defineProperty(mn,"__esModule",{value:!0}),mn.Glue=void 0;const o=yt();let n=class extends o.InkObject{toString(){return"Glue"}};return mn.Glue=n,mn}var gn={},is;function Va(){if(is)return gn;is=1,Object.defineProperty(gn,"__esModule",{value:!0}),gn.IncDecExpression=void 0;const o=Ri(),n=Ot(),a=kt(),e=Ft(),f=it(),t=Gt(),p=Hn(),r=ne();let y=class extends n.Expression{constructor(c,i,l){super(),this.varIdentifier=c,this._runtimeAssignment=null,this.expression=null,this.GenerateIntoContainer=S=>{var P,N;S.AddContent(new p.VariableReference(((P=this.varIdentifier)===null||P===void 0?void 0:P.name)||null)),this.expression?this.expression.GenerateIntoContainer(S):S.AddContent(new f.IntValue(1)),S.AddContent(e.NativeFunctionCall.CallWithName(this.isInc?"+":"-")),this._runtimeAssignment=new t.VariableAssignment(((N=this.varIdentifier)===null||N===void 0?void 0:N.name)||null,!1),S.AddContent(this._runtimeAssignment)},this.toString=()=>{var S,P;return this.expression?`${(S=this.varIdentifier)===null||S===void 0?void 0:S.name}${this.isInc?" += ":" -= "}${this.expression}`:`${(P=this.varIdentifier)===null||P===void 0?void 0:P.name}`+(this.isInc?"++":"--")},i instanceof n.Expression?(this.expression=i,this.AddContent(this.expression),this.isInc=!!l):this.isInc=i}get typeName(){return"IncDecExpression"}ResolveReferences(c){var i;super.ResolveReferences(c);const l=c.ResolveVariableWithName(((i=this.varIdentifier)===null||i===void 0?void 0:i.name)||"",this);if(l.found||this.Error(`variable for ${this.incrementDecrementWord} could not be found: '${this.varIdentifier}' after searching: {this.descriptionOfScope}`),!this._runtimeAssignment)throw new Error;this._runtimeAssignment.isGlobal=l.isGlobal,!(this.parent instanceof r.Weave)&&!(this.parent instanceof a.FlowBase)&&!(this.parent instanceof o.ContentList)&&this.Error(`Can't use ${this.incrementDecrementWord} as sub-expression`)}get incrementDecrementWord(){return this.isInc?"increment":"decrement"}};return gn.IncDecExpression=y,gn}var Cn={},rs;function ea(){if(rs)return Cn;rs=1,Object.defineProperty(Cn,"__esModule",{value:!0}),Cn.IncludedFile=void 0;const o=et();let n=class extends o.ParsedObject{constructor(e){super(),this.includedStory=e,this.GenerateRuntimeObject=()=>null}get typeName(){return"IncludedFile"}};return Cn.IncludedFile=n,Cn}var vn={},ss;function Wa(){if(ss)return vn;ss=1,Object.defineProperty(vn,"__esModule",{value:!0}),vn.InfixOperator=void 0;let o=class{constructor(a,e,f){this.type=a,this.precedence=e,this.requireWhitespace=f,this.toString=()=>this.type}};return vn.InfixOperator=o,vn}var Sn={},as;function na(){if(as)return Sn;as=1,Object.defineProperty(Sn,"__esModule",{value:!0}),Sn.Knot=void 0;const o=kt(),n=Un();let a=class extends o.FlowBase{get flowLevel(){return n.FlowLevel.Knot}constructor(f,t,p,r){super(f,t,p,r)}get typeName(){return this.isFunction?"Function":"Knot"}ResolveReferences(f){super.ResolveReferences(f);let t=this.story;for(const p in this.subFlowsByName){const r=t.ContentWithNameAtLevel(p,n.FlowLevel.Knot,!1);if(r){const y=this.subFlowsByName.get(p),s=`Stitch '${y?y.name:"NO STITCH FOUND"}' has the same name as a knot (on ${r.debugMetadata})`;this.Error(s,y)}}}};return Sn.Knot=a,Sn}var yn={},os;function La(){if(os)return yn;os=1,Object.defineProperty(yn,"__esModule",{value:!0}),yn.List=void 0;const o=Ot(),n=vt(),a=vt(),e=it();let f=class extends o.Expression{constructor(p){super(),this.itemIdentifierList=p,this.GenerateIntoContainer=r=>{var y,s;const c=new n.InkList;if(this.itemIdentifierList!=null)for(const i of this.itemIdentifierList){const l=((y=i==null?void 0:i.name)===null||y===void 0?void 0:y.split("."))||[];let S=null,P="";l.length>1?(S=l[0],P=l[1]):P=l[0];const N=this.story.ResolveListItem(S,P,this);if(N===null)S===null?this.Error(`Could not find list definition that contains item '${i}'`):this.Error(`Could not find list item ${i}`);else{if(N.parent==null){this.Error(`Could not find list definition for item ${i}`);return}S||(S=((s=N.parent.identifier)===null||s===void 0?void 0:s.name)||null);const O=new a.InkListItem(S,N.name||null);c.has(O.serialized())?this.Warning(`Duplicate of item '${i}' in list.`):c.Add(O,N.seriesValue)}}r.AddContent(new e.ListValue(c))}}get typeName(){return"List"}};return yn.List=f,yn}var bn={},ls;function ia(){if(ls)return bn;ls=1,Object.defineProperty(bn,"__esModule",{value:!0}),bn.ListElementDefinition=void 0;const o=et(),n=Wt();let a=class extends o.ParsedObject{get fullName(){var f;const t=this.parent;if(t===null)throw new Error("Can't get full name without a parent list.");return`${(f=t.identifier)===null||f===void 0?void 0:f.name}.${this.name}`}get typeName(){return"ListElement"}get name(){var f;return((f=this.indentifier)===null||f===void 0?void 0:f.name)||null}constructor(f,t,p=null){super(),this.indentifier=f,this.inInitialList=t,this.explicitValue=p,this.seriesValue=0,this.parent=null,this.GenerateRuntimeObject=()=>{throw new Error("Not implemented.")},this.toString=()=>this.fullName,this.parent=this.parent}ResolveReferences(f){super.ResolveReferences(f),f.CheckForNamingCollisions(this,this.indentifier,n.SymbolType.ListItem)}};return bn.ListElementDefinition=a,bn}var _n={},us;function ra(){if(us)return _n;us=1,Object.defineProperty(_n,"__esModule",{value:!0}),_n.StatementLevel=void 0;var o;return(function(n){n[n.InnerBlock=0]="InnerBlock",n[n.Stitch=1]="Stitch",n[n.Knot=2]="Knot",n[n.Top=3]="Top"})(o||(_n.StatementLevel=o={})),_n}var En={},hs;function sa(){if(hs)return En;hs=1,Object.defineProperty(En,"__esModule",{value:!0}),En.Stitch=void 0;const o=kt(),n=Un();let a=class extends o.FlowBase{get flowLevel(){return n.FlowLevel.Stitch}constructor(f,t,p,r){super(f,t,p,r),this.baseToString=this.toString,this.toString=()=>`${this.parent!==null?this.parent+" > ":""}${this.baseToString()}`}get typeName(){return"Stitch"}};return En.Stitch=a,En}var wn={},gi={},Pn={},On={},cs;function Vi(){if(cs)return On;cs=1,Object.defineProperty(On,"__esModule",{value:!0}),On.Tag=void 0;const o=yt();class n extends o.InkObject{constructor(e){super(),this.text=e.toString()||""}toString(){return"# "+this.text}}return On.Tag=n,On}var xn={},ds;function oa(){if(ds)return xn;ds=1,Object.defineProperty(xn,"__esModule",{value:!0}),xn.Choice=void 0;const o=St(),n=ft(),a=yt();let e=class aa extends a.InkObject{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 this.targetPath===null?(0,n.throwNullException)("Choice.targetPath"):this.targetPath.toString()}set pathStringOnChoice(t){this.targetPath=new o.Path(t)}Clone(){let t=new aa;return t.text=this.text,t.sourcePath=this.sourcePath,t.index=this.index,t.targetPath=this.targetPath,t.originalThreadIndex=this.originalThreadIndex,t.isInvisibleDefault=this.isInvisibleDefault,this.threadAtGeneration!==null&&(t.threadAtGeneration=this.threadAtGeneration.Copy()),t}};return xn.Choice=e,xn}var Tn={},fs;function la(){if(fs)return Tn;fs=1,Object.defineProperty(Tn,"__esModule",{value:!0}),Tn.ListDefinitionsOrigin=void 0;const o=vt(),n=it(),a=ft();let e=class{constructor(t){this._lists=new Map,this._allUnambiguousListValueCache=new Map;for(let p of t){this._lists.set(p.name,p);for(let[r,y]of p.items){let s=o.InkListItem.fromSerializedKey(r),c=new n.ListValue(s,y);if(!s.itemName)throw new Error("item.itemName is null or undefined.");this._allUnambiguousListValueCache.set(s.itemName,c),this._allUnambiguousListValueCache.set(s.fullName,c)}}}get lists(){let t=[];for(let[,p]of this._lists)t.push(p);return t}TryListGetDefinition(t,p){if(t===null)return{result:p,exists:!1};let r=this._lists.get(t);return r?{result:r,exists:!0}:{result:p,exists:!1}}FindSingleItemListWithName(t){if(t===null)return(0,a.throwNullException)("name");let p=this._allUnambiguousListValueCache.get(t);return typeof p<"u"?p:null}};return Tn.ListDefinitionsOrigin=e,Tn}var ps;function Xn(){if(ps)return Pn;ps=1,Object.defineProperty(Pn,"__esModule",{value:!0}),Pn.JsonSerialisation=void 0;const o=ot(),n=it(),a=Di(),e=pt(),f=te(),t=Rt(),p=Ni(),r=Hn(),y=Gt(),s=Ft(),c=Qt(),i=Vi(),l=St(),S=oa(),P=Xs(),N=la(),O=vt(),I=Z(),w=ft();let F=class Qn{static JArrayToRuntimeObjList(m,g=!1){let v=m.length;g&&v--;let u=[];for(let h=0;h<v;h++){let b=m[h],R=this.JTokenToRuntimeObject(b);if(R===null)return(0,w.throwNullException)("runtimeObj");u.push(R)}return u}static WriteDictionaryRuntimeObjs(m,g){m.WriteObjectStart();for(let[v,u]of g)m.WritePropertyStart(v),this.WriteRuntimeObject(m,u),m.WritePropertyEnd();m.WriteObjectEnd()}static WriteListRuntimeObjs(m,g){m.WriteArrayStart();for(let v of g)this.WriteRuntimeObject(m,v);m.WriteArrayEnd()}static WriteIntDictionary(m,g){m.WriteObjectStart();for(let[v,u]of g)m.WriteIntProperty(v,u);m.WriteObjectEnd()}static WriteRuntimeObject(m,g){let v=(0,I.asOrNull)(g,o.Container);if(v){this.WriteRuntimeContainer(m,v);return}let u=(0,I.asOrNull)(g,t.Divert);if(u){let Y="->";u.isExternal?Y="x()":u.pushesToStack&&(u.stackPushType==f.PushPopType.Function?Y="f()":u.stackPushType==f.PushPopType.Tunnel&&(Y="->t->"));let mt;u.hasVariableTarget?mt=u.variableDivertName:mt=u.targetPathString,m.WriteObjectStart(),m.WriteProperty(Y,mt),u.hasVariableTarget&&m.WriteProperty("var",!0),u.isConditional&&m.WriteProperty("c",!0),u.externalArgs>0&&m.WriteIntProperty("exArgs",u.externalArgs),m.WriteObjectEnd();return}let h=(0,I.asOrNull)(g,p.ChoicePoint);if(h){m.WriteObjectStart(),m.WriteProperty("*",h.pathStringOnChoice),m.WriteIntProperty("flg",h.flags),m.WriteObjectEnd();return}let b=(0,I.asOrNull)(g,n.BoolValue);if(b){m.WriteBool(b.value);return}let R=(0,I.asOrNull)(g,n.IntValue);if(R){m.WriteInt(R.value);return}let V=(0,I.asOrNull)(g,n.FloatValue);if(V){m.WriteFloat(V.value);return}let j=(0,I.asOrNull)(g,n.StringValue);if(j){j.isNewline?m.Write(`
|
|
17
17
|
`,!1):(m.WriteStringStart(),m.WriteStringInner("^"),m.WriteStringInner(j.value),m.WriteStringEnd());return}let L=(0,I.asOrNull)(g,n.ListValue);if(L){this.WriteInkList(m,L);return}let C=(0,I.asOrNull)(g,n.DivertTargetValue);if(C){if(m.WriteObjectStart(),C.value===null)return(0,w.throwNullException)("divTargetVal.value");m.WriteProperty("^->",C.value.componentsString),m.WriteObjectEnd();return}let E=(0,I.asOrNull)(g,n.VariablePointerValue);if(E){m.WriteObjectStart(),m.WriteProperty("^var",E.value),m.WriteIntProperty("ci",E.contextIndex),m.WriteObjectEnd();return}if((0,I.asOrNull)(g,a.Glue)){m.Write("<>");return}let A=(0,I.asOrNull)(g,e.ControlCommand);if(A){m.Write(Qn._controlCommandNames[A.commandType]);return}let W=(0,I.asOrNull)(g,s.NativeFunctionCall);if(W){let Y=W.name;Y=="^"&&(Y="L^"),m.Write(Y);return}let M=(0,I.asOrNull)(g,r.VariableReference);if(M){m.WriteObjectStart();let Y=M.pathStringForCount;Y!=null?m.WriteProperty("CNT?",Y):m.WriteProperty("VAR?",M.name),m.WriteObjectEnd();return}let G=(0,I.asOrNull)(g,y.VariableAssignment);if(G){m.WriteObjectStart();let Y=G.isGlobal?"VAR=":"temp=";m.WriteProperty(Y,G.variableName),G.isNewDeclaration||m.WriteProperty("re",!0),m.WriteObjectEnd();return}if((0,I.asOrNull)(g,c.Void)){m.Write("void");return}let Q=(0,I.asOrNull)(g,i.Tag);if(Q){m.WriteObjectStart(),m.WriteProperty("#",Q.text),m.WriteObjectEnd();return}let ut=(0,I.asOrNull)(g,S.Choice);if(ut){this.WriteChoice(m,ut);return}throw new Error("Failed to convert runtime object to Json token: "+g)}static JObjectToDictionaryRuntimeObjs(m){let g=new Map;for(let v in m)if(m.hasOwnProperty(v)){let u=this.JTokenToRuntimeObject(m[v]);if(u===null)return(0,w.throwNullException)("inkObject");g.set(v,u)}return g}static JObjectToIntDictionary(m){let g=new Map;for(let v in m)m.hasOwnProperty(v)&&g.set(v,parseInt(m[v]));return g}static JTokenToRuntimeObject(m){if(typeof m=="number"&&!isNaN(m)||typeof m=="boolean")return n.Value.Create(m);if(typeof m=="string"){let g=m.toString();const v=/^([0-9]+.[0-9]+f)$/.exec(g);if(v)return new n.FloatValue(parseFloat(v[0]));let u=g[0];if(u=="^")return new n.StringValue(g.substring(1));if(u==`
|
|
18
18
|
`&&g.length==1)return new n.StringValue(`
|
|
19
|
-
`);if(g=="<>")return new a.Glue;for(let h=0;h<Qn._controlCommandNames.length;++h){let b=Qn._controlCommandNames[h];if(g==b)return new e.ControlCommand(h)}if(g=="L^"&&(g="^"),s.NativeFunctionCall.CallExistsWithName(g))return s.NativeFunctionCall.CallWithName(g);if(g=="->->")return e.ControlCommand.PopTunnel();if(g=="~ret")return e.ControlCommand.PopFunction();if(g=="void")return new c.Void}if(typeof m=="object"&&!Array.isArray(m)){let g=m,v;if(g["^->"])return v=g["^->"],new n.DivertTargetValue(new l.Path(v.toString()));if(g["^var"]){v=g["^var"];let L=new n.VariablePointerValue(v.toString());return"ci"in g&&(v=g.ci,L.contextIndex=parseInt(v)),L}let u=!1,h=!1,b=f.PushPopType.Function,R=!1;if((v=g["->"])?u=!0:(v=g["f()"])?(u=!0,h=!0,b=f.PushPopType.Function):(v=g["->t->"])?(u=!0,h=!0,b=f.PushPopType.Tunnel):(v=g["x()"])&&(u=!0,R=!0,h=!1,b=f.PushPopType.Function),u){let L=new t.Divert;L.pushesToStack=h,L.stackPushType=b,L.isExternal=R;let C=v.toString();return(v=g.var)?L.variableDivertName=C:L.targetPathString=C,L.isConditional=!!g.c,R&&(v=g.exArgs)&&(L.externalArgs=parseInt(v)),L}if(v=g["*"]){let L=new p.ChoicePoint;return L.pathStringOnChoice=v.toString(),(v=g.flg)&&(L.flags=parseInt(v)),L}if(v=g["VAR?"])return new r.VariableReference(v.toString());if(v=g["CNT?"]){let L=new r.VariableReference;return L.pathStringForCount=v.toString(),L}let V=!1,j=!1;if((v=g["VAR="])?(V=!0,j=!0):(v=g["temp="])&&(V=!0,j=!1),V){let L=v.toString(),C=!g.re,E=new y.VariableAssignment(L,C);return E.isGlobal=j,E}if(g["#"]!==void 0)return v=g["#"],new i.Tag(v.toString());if(v=g.list){let L=v,C=new O.InkList;if(v=g.origins){let E=v;C.SetInitialOriginNames(E)}for(let E in L)if(L.hasOwnProperty(E)){let x=L[E],A=new O.InkListItem(E),W=parseInt(x);C.Add(A,W)}return new n.ListValue(C)}if(g.originalChoicePath!=null)return this.JObjectToChoice(g)}if(Array.isArray(m))return this.JArrayToContainer(m);if(m==null)return null;throw new Error("Failed to convert token to runtime object: "+this.toJson(m,["parent"]))}static toJson(m,g,v){return JSON.stringify(m,(u,h)=>g!=null&&g.some(b=>b===u)?void 0:h,v)}static WriteRuntimeContainer(m,g,v=!1){if(m.WriteArrayStart(),g===null)return(0,w.throwNullException)("container");for(let V of g.content)this.WriteRuntimeObject(m,V);let u=g.namedOnlyContent,h=g.countFlags,b=g.name!=null&&!v,R=u!=null||h>0||b;if(R&&m.WriteObjectStart(),u!=null)for(let[V,j]of u){let L=V,C=(0,I.asOrNull)(j,o.Container);m.WritePropertyStart(L),this.WriteRuntimeContainer(m,C,!0),m.WritePropertyEnd()}h>0&&m.WriteIntProperty("#f",h),b&&m.WriteProperty("#n",g.name),R?m.WriteObjectEnd():m.WriteNull(),m.WriteArrayEnd()}static JArrayToContainer(m){let g=new o.Container;g.content=this.JArrayToRuntimeObjList(m,!0);let v=m[m.length-1];if(v!=null){let u=new Map;for(let h in v)if(h=="#f")g.countFlags=parseInt(v[h]);else if(h=="#n")g.name=v[h].toString();else{let b=this.JTokenToRuntimeObject(v[h]),R=(0,I.asOrNull)(b,o.Container);R&&(R.name=h),u.set(h,b)}g.namedOnlyContent=u}return g}static JObjectToChoice(m){let g=new S.Choice;return g.text=m.text.toString(),g.index=parseInt(m.index),g.sourcePath=m.originalChoicePath.toString(),g.originalThreadIndex=parseInt(m.originalThreadIndex),g.pathStringOnChoice=m.targetPath.toString(),g.tags=this.JArrayToTags(m),g.isInvisibleDefault=!!m.isInvisibleDefault,g}static JArrayToTags(m){return m.tags?m.tags:null}static WriteChoice(m,g){m.WriteObjectStart(),m.WriteProperty("text",g.text),m.WriteIntProperty("index",g.index),m.WriteProperty("originalChoicePath",g.sourcePath),m.WriteIntProperty("originalThreadIndex",g.originalThreadIndex),m.WriteProperty("targetPath",g.pathStringOnChoice),m.WriteProperty("isInvisibleDefault",g.isInvisibleDefault),this.WriteChoiceTags(m,g),m.WriteObjectEnd()}static WriteChoiceTags(m,g){if(g.tags&&g.tags.length>0){m.WritePropertyStart("tags"),m.WriteArrayStart();for(const v of g.tags)m.Write(v);m.WriteArrayEnd(),m.WritePropertyEnd()}}static WriteInkList(m,g){let v=g.value;if(v===null)return(0,w.throwNullException)("rawList");m.WriteObjectStart(),m.WritePropertyStart("list"),m.WriteObjectStart();for(let[u,h]of v){let b=O.InkListItem.fromSerializedKey(u),R=h;if(b.itemName===null)return(0,w.throwNullException)("item.itemName");m.WritePropertyNameStart(),m.WritePropertyNameInner(b.originName?b.originName:"?"),m.WritePropertyNameInner("."),m.WritePropertyNameInner(b.itemName),m.WritePropertyNameEnd(),m.Write(R),m.WritePropertyEnd()}if(m.WriteObjectEnd(),m.WritePropertyEnd(),v.Count==0&&v.originNames!=null&&v.originNames.length>0){m.WritePropertyStart("origins"),m.WriteArrayStart();for(let u of v.originNames)m.Write(u);m.WriteArrayEnd(),m.WritePropertyEnd()}m.WriteObjectEnd()}static ListDefinitionsToJToken(m){let g={};for(let v of m.lists){let u={};for(let[h,b]of v.items){let R=O.InkListItem.fromSerializedKey(h);if(R.itemName===null)return(0,w.throwNullException)("item.itemName");u[R.itemName]=b}g[v.name]=u}return g}static JTokenToListDefinitions(m){let g=m,v=[];for(let u in g)if(g.hasOwnProperty(u)){let h=u.toString(),b=g[u],R=new Map;for(let j in b)if(g.hasOwnProperty(u)){let L=b[j];R.set(j,parseInt(L))}let V=new P.ListDefinition(h,R);v.push(V)}return new N.ListDefinitionsOrigin(v)}};return On.JsonSerialisation=F,F._controlCommandNames=(()=>{let k=[];k[e.ControlCommand.CommandType.EvalStart]="ev",k[e.ControlCommand.CommandType.EvalOutput]="out",k[e.ControlCommand.CommandType.EvalEnd]="/ev",k[e.ControlCommand.CommandType.Duplicate]="du",k[e.ControlCommand.CommandType.PopEvaluatedValue]="pop",k[e.ControlCommand.CommandType.PopFunction]="~ret",k[e.ControlCommand.CommandType.PopTunnel]="->->",k[e.ControlCommand.CommandType.BeginString]="str",k[e.ControlCommand.CommandType.EndString]="/str",k[e.ControlCommand.CommandType.NoOp]="nop",k[e.ControlCommand.CommandType.ChoiceCount]="choiceCnt",k[e.ControlCommand.CommandType.Turns]="turn",k[e.ControlCommand.CommandType.TurnsSince]="turns",k[e.ControlCommand.CommandType.ReadCount]="readc",k[e.ControlCommand.CommandType.Random]="rnd",k[e.ControlCommand.CommandType.SeedRandom]="srnd",k[e.ControlCommand.CommandType.VisitIndex]="visit",k[e.ControlCommand.CommandType.SequenceShuffleIndex]="seq",k[e.ControlCommand.CommandType.StartThread]="thread",k[e.ControlCommand.CommandType.Done]="done",k[e.ControlCommand.CommandType.End]="end",k[e.ControlCommand.CommandType.ListFromInt]="listInt",k[e.ControlCommand.CommandType.ListRange]="range",k[e.ControlCommand.CommandType.ListRandom]="lrnd",k[e.ControlCommand.CommandType.BeginTag]="#",k[e.ControlCommand.CommandType.EndTag]="/#";for(let m=0;m<e.ControlCommand.CommandType.TOTAL_VALUES;++m)if(k[m]==null)throw new Error("Control command not accounted for in serialisation");return k})(),On}var In={},zt={},ms;function ua(){if(ms)return zt;ms=1,Object.defineProperty(zt,"__esModule",{value:!0}),zt.CallStack=void 0;const o=ee(),n=St(),a=ci(),e=Xn(),f=it(),t=Qt(),p=oi(),r=ri(),y=Gn(),s=ft();let c=class Bn{get elements(){return this.callStack}get depth(){return this.elements.length}get currentElement(){let S=this._threads[this._threads.length-1].callstack;return S[S.length-1]}get currentElementIndex(){return this.callStack.length-1}get currentThread(){return this._threads[this._threads.length-1]}set currentThread(l){r.Debug.Assert(this._threads.length==1,"Shouldn't be directly setting the current thread when we have a stack of them"),this._threads.length=0,this._threads.push(l)}get canPop(){return this.callStack.length>1}constructor(){if(this._threadCounter=0,this._startOfRoot=p.Pointer.Null,arguments[0]instanceof a.Story){let l=arguments[0];this._startOfRoot=p.Pointer.StartOf(l.rootContentContainer),this.Reset()}else{let l=arguments[0];this._threads=[];for(let S of l._threads)this._threads.push(S.Copy());this._threadCounter=l._threadCounter,this._startOfRoot=l._startOfRoot.copy()}}Reset(){this._threads=[],this._threads.push(new Bn.Thread),this._threads[0].callstack.push(new Bn.Element(o.PushPopType.Tunnel,this._startOfRoot))}SetJsonToken(l,S){this._threads.length=0;let P=l.threads;for(let N of P){let O=N,I=new Bn.Thread(O,S);this._threads.push(I)}this._threadCounter=parseInt(l.threadCounter),this._startOfRoot=p.Pointer.StartOf(S.rootContentContainer)}WriteJson(l){l.WriteObject(S=>{S.WritePropertyStart("threads"),S.WriteArrayStart();for(let P of this._threads)P.WriteJson(S);S.WriteArrayEnd(),S.WritePropertyEnd(),S.WritePropertyStart("threadCounter"),S.WriteInt(this._threadCounter),S.WritePropertyEnd()})}PushThread(){let l=this.currentThread.Copy();this._threadCounter++,l.threadIndex=this._threadCounter,this._threads.push(l)}ForkThread(){let l=this.currentThread.Copy();return this._threadCounter++,l.threadIndex=this._threadCounter,l}PopThread(){if(this.canPopThread)this._threads.splice(this._threads.indexOf(this.currentThread),1);else throw new Error("Can't pop thread")}get canPopThread(){return this._threads.length>1&&!this.elementIsEvaluateFromGame}get elementIsEvaluateFromGame(){return this.currentElement.type==o.PushPopType.FunctionEvaluationFromGame}Push(l,S=0,P=0){let N=new Bn.Element(l,this.currentElement.currentPointer,!1);N.evaluationStackHeightWhenPushed=S,N.functionStartInOutputStream=P,this.callStack.push(N)}CanPop(l=null){return this.canPop?l==null?!0:this.currentElement.type==l:!1}Pop(l=null){if(this.CanPop(l)){this.callStack.pop();return}else throw new Error("Mismatched push/pop in Callstack")}GetTemporaryVariableWithName(l,S=-1){S==-1&&(S=this.currentElementIndex+1);let P=this.callStack[S-1],N=(0,y.tryGetValueFromMap)(P.temporaryVariables,l,null);return N.exists?N.result:null}SetTemporaryVariable(l,S,P,N=-1){N==-1&&(N=this.currentElementIndex+1);let O=this.callStack[N-1];if(!P&&!O.temporaryVariables.get(l))throw new Error("Could not find temporary variable to set: "+l);let I=(0,y.tryGetValueFromMap)(O.temporaryVariables,l,null);I.exists&&f.ListValue.RetainListOriginsForAssignment(I.result,S),O.temporaryVariables.set(l,S)}ContextForVariableNamed(l){return this.currentElement.temporaryVariables.get(l)?this.currentElementIndex+1:0}ThreadWithIndex(l){let S=this._threads.filter(P=>{if(P.threadIndex==l)return P});return S.length>0?S[0]:null}get callStack(){return this.currentThread.callstack}get callStackTrace(){let l=new t.StringBuilder;for(let S=0;S<this._threads.length;S++){let P=this._threads[S],N=S==this._threads.length-1;l.AppendFormat(`=== THREAD {0}/{1} {2}===
|
|
20
|
-
`,S+1,this._threads.length,N?"(current) ":"");for(let O=0;O<P.callstack.length;O++){P.callstack[O].type==o.PushPopType.Function?l.Append(" [FUNCTION] "):l.Append(" [TUNNEL] ");let I=P.callstack[O].currentPointer;if(!I.isNull){if(l.Append("<SOMEWHERE IN "),I.container===null)return(0,s.throwNullException)("pointer.container");l.Append(I.container.path.toString()),l.AppendLine(">")}}}return l.toString()}};return zt.CallStack=c,(function(i){class l{constructor(N,O,I=!1){this.evaluationStackHeightWhenPushed=0,this.functionStartInOutputStream=0,this.currentPointer=O.copy(),this.inExpressionEvaluation=I,this.temporaryVariables=new Map,this.type=N}Copy(){let N=new l(this.type,this.currentPointer,this.inExpressionEvaluation);return N.temporaryVariables=new Map(this.temporaryVariables),N.evaluationStackHeightWhenPushed=this.evaluationStackHeightWhenPushed,N.functionStartInOutputStream=this.functionStartInOutputStream,N}}i.Element=l;class S{constructor(){if(this.threadIndex=0,this.previousPointer=p.Pointer.Null,this.callstack=[],arguments[0]&&arguments[1]){let N=arguments[0],O=arguments[1];this.threadIndex=parseInt(N.threadIndex);let I=N.callstack;for(let F of I){let k=F,m=parseInt(k.type),g=p.Pointer.Null,v,u=k.cPath;if(typeof u<"u"){v=u.toString();let V=O.ContentAtPath(new n.Path(v));if(g.container=V.container,g.index=parseInt(k.idx),V.obj==null)throw new Error("When loading state, internal story location couldn't be found: "+v+". Has the story changed since this save data was created?");V.approximate&&(g.container!==null?O.Warning("When loading state, exact internal story location couldn't be found: '"+v+"', so it was approximated to '"+g.container.path.toString()+"' to recover. Has the story changed since this save data was created?"):O.Warning("When loading state, exact internal story location couldn't be found: '"+v+"' and it may not be recoverable. Has the story changed since this save data was created?"))}let h=!!k.exp,b=new l(m,g,h),R=k.temp;typeof R<"u"?b.temporaryVariables=e.JsonSerialisation.JObjectToDictionaryRuntimeObjs(R):b.temporaryVariables.clear(),this.callstack.push(b)}let w=N.previousContentObject;if(typeof w<"u"){let F=new n.Path(w.toString());this.previousPointer=O.PointerAtPath(F)}}}Copy(){let N=new S;N.threadIndex=this.threadIndex;for(let O of this.callstack)N.callstack.push(O.Copy());return N.previousPointer=this.previousPointer.copy(),N}WriteJson(N){N.WriteObjectStart(),N.WritePropertyStart("callstack"),N.WriteArrayStart();for(let O of this.callstack){if(N.WriteObjectStart(),!O.currentPointer.isNull){if(O.currentPointer.container===null)return(0,s.throwNullException)("el.currentPointer.container");N.WriteProperty("cPath",O.currentPointer.container.path.componentsString),N.WriteIntProperty("idx",O.currentPointer.index)}N.WriteProperty("exp",O.inExpressionEvaluation),N.WriteIntProperty("type",O.type),O.temporaryVariables.size>0&&(N.WritePropertyStart("temp"),e.JsonSerialisation.WriteDictionaryRuntimeObjs(N,O.temporaryVariables),N.WritePropertyEnd()),N.WriteObjectEnd()}if(N.WriteArrayEnd(),N.WritePropertyEnd(),N.WriteIntProperty("threadIndex",this.threadIndex),!this.previousPointer.isNull){let O=this.previousPointer.Resolve();if(O===null)return(0,s.throwNullException)("this.previousPointer.Resolve()");N.WriteProperty("previousContentObject",O.path.toString())}N.WriteObjectEnd()}}i.Thread=S})(c||(zt.CallStack=c={})),zt}var An={},gs;function ja(){if(gs)return An;gs=1,Object.defineProperty(An,"__esModule",{value:!0}),An.VariablesState=void 0;const o=it(),n=si(),a=Xn(),e=Z(),f=Gn(),t=ft();function p(){return class{}}let r=class ha extends p(){variableChangedEvent(s,c){for(let i of this.variableChangedEventCallbacks)i(s,c)}StartVariableObservation(){this._batchObservingVariableChanges=!0,this._changedVariablesForBatchObs=new Set}CompleteVariableObservation(){this._batchObservingVariableChanges=!1;let s=new Map;if(this._changedVariablesForBatchObs!=null)for(let c of this._changedVariablesForBatchObs){let i=this._globalVariables.get(c);this.variableChangedEvent(c,i)}if(this.patch!=null)for(let c of this.patch.changedVariables){let i=this.patch.TryGetGlobal(c,null);i.exists&&s.set(c,i)}return this._changedVariablesForBatchObs=null,s}NotifyObservers(s){for(const[c,i]of s)this.variableChangedEvent(c,i)}get callStack(){return this._callStack}set callStack(s){this._callStack=s}$(s,c){if(typeof c>"u"){let i=null;return this.patch!==null&&(i=this.patch.TryGetGlobal(s,null),i.exists)?i.result.valueObject:(i=this._globalVariables.get(s),typeof i>"u"&&(i=this._defaultGlobalVariables.get(s)),typeof i<"u"?i.valueObject:null)}else{if(typeof this._defaultGlobalVariables.get(s)>"u")throw new n.StoryException("Cannot assign to a variable ("+s+") that hasn't been declared in the story");let i=o.Value.Create(c);if(i==null)throw c==null?new Error("Cannot pass null to VariableState"):new Error("Invalid value passed to VariableState: "+c.toString());this.SetGlobal(s,i)}}constructor(s,c){super(),this.variableChangedEventCallbacks=[],this.patch=null,this._defaultGlobalVariables=new Map,this._changedVariablesForBatchObs=new Set,this._batchObservingVariableChanges=!1,this._globalVariables=new Map,this._callStack=s,this._listDefsOrigin=c;try{return new Proxy(this,{get(l,S){return S in l?l[S]:l.$(S)},set(l,S,P){return S in l?l[S]=P:l.$(S,P),!0},ownKeys(l){return[...new Set([...l._defaultGlobalVariables.keys(),...l._globalVariables.keys()])]},getOwnPropertyDescriptor(l,S){return{enumerable:!0,configurable:!0,value:l.$(S)}}})}catch{}}ApplyPatch(){if(this.patch===null)return(0,t.throwNullException)("this.patch");for(let[s,c]of this.patch.globals)this._globalVariables.set(s,c);if(this._changedVariablesForBatchObs!==null)for(let s of this.patch.changedVariables)this._changedVariablesForBatchObs.add(s);this.patch=null}SetJsonToken(s){this._globalVariables.clear();for(let[c,i]of this._defaultGlobalVariables){let l=s[c];if(typeof l<"u"){let S=a.JsonSerialisation.JTokenToRuntimeObject(l);if(S===null)return(0,t.throwNullException)("tokenInkObject");this._globalVariables.set(c,S)}else this._globalVariables.set(c,i)}}WriteJson(s){s.WriteObjectStart();for(let[c,i]of this._globalVariables){let l=c,S=i;if(ha.dontSaveDefaultValues&&this._defaultGlobalVariables.has(l)){let P=this._defaultGlobalVariables.get(l);if(this.RuntimeObjectsEqual(S,P))continue}s.WritePropertyStart(l),a.JsonSerialisation.WriteRuntimeObject(s,S),s.WritePropertyEnd()}s.WriteObjectEnd()}RuntimeObjectsEqual(s,c){if(s===null)return(0,t.throwNullException)("obj1");if(c===null)return(0,t.throwNullException)("obj2");if(s.constructor!==c.constructor)return!1;let i=(0,e.asOrNull)(s,o.BoolValue);if(i!==null)return i.value===(0,e.asOrThrows)(c,o.BoolValue).value;let l=(0,e.asOrNull)(s,o.IntValue);if(l!==null)return l.value===(0,e.asOrThrows)(c,o.IntValue).value;let S=(0,e.asOrNull)(s,o.FloatValue);if(S!==null)return S.value===(0,e.asOrThrows)(c,o.FloatValue).value;let P=(0,e.asOrNull)(s,o.Value),N=(0,e.asOrNull)(c,o.Value);if(P!==null&&N!==null)return(0,e.isEquatable)(P.valueObject)&&(0,e.isEquatable)(N.valueObject)?P.valueObject.Equals(N.valueObject):P.valueObject===N.valueObject;throw new Error("FastRoughDefinitelyEquals: Unsupported runtime object type: "+s.constructor.name)}GetVariableWithName(s,c=-1){let i=this.GetRawVariableWithName(s,c),l=(0,e.asOrNull)(i,o.VariablePointerValue);return l!==null&&(i=this.ValueAtVariablePointer(l)),i}TryGetDefaultVariableValue(s){let c=(0,f.tryGetValueFromMap)(this._defaultGlobalVariables,s,null);return c.exists?c.result:null}GlobalVariableExistsWithName(s){return this._globalVariables.has(s)||this._defaultGlobalVariables!==null&&this._defaultGlobalVariables.has(s)}GetRawVariableWithName(s,c){let i=null;if(c==0||c==-1){let l=null;if(this.patch!==null&&(l=this.patch.TryGetGlobal(s,null),l.exists)||(l=(0,f.tryGetValueFromMap)(this._globalVariables,s,null),l.exists)||this._defaultGlobalVariables!==null&&(l=(0,f.tryGetValueFromMap)(this._defaultGlobalVariables,s,null),l.exists))return l.result;if(this._listDefsOrigin===null)return(0,t.throwNullException)("VariablesState._listDefsOrigin");let S=this._listDefsOrigin.FindSingleItemListWithName(s);if(S)return S}return i=this._callStack.GetTemporaryVariableWithName(s,c),i}ValueAtVariablePointer(s){return this.GetVariableWithName(s.variableName,s.contextIndex)}Assign(s,c){let i=s.variableName;if(i===null)return(0,t.throwNullException)("name");let l=-1,S=!1;if(s.isNewDeclaration?S=s.isGlobal:S=this.GlobalVariableExistsWithName(i),s.isNewDeclaration){let P=(0,e.asOrNull)(c,o.VariablePointerValue);P!==null&&(c=this.ResolveVariablePointer(P))}else{let P=null;do P=(0,e.asOrNull)(this.GetRawVariableWithName(i,l),o.VariablePointerValue),P!=null&&(i=P.variableName,l=P.contextIndex,S=l==0);while(P!=null)}S?this.SetGlobal(i,c):this._callStack.SetTemporaryVariable(i,c,s.isNewDeclaration,l)}SnapshotDefaultGlobals(){this._defaultGlobalVariables=new Map(this._globalVariables)}RetainListOriginsForAssignment(s,c){let i=(0,e.asOrThrows)(s,o.ListValue),l=(0,e.asOrThrows)(c,o.ListValue);i.value&&l.value&&l.value.Count==0&&l.value.SetInitialOriginNames(i.value.originNames)}SetGlobal(s,c){let i=null;if(this.patch===null&&(i=(0,f.tryGetValueFromMap)(this._globalVariables,s,null)),this.patch!==null&&(i=this.patch.TryGetGlobal(s,null),i.exists||(i=(0,f.tryGetValueFromMap)(this._globalVariables,s,null))),o.ListValue.RetainListOriginsForAssignment(i.result,c),s===null)return(0,t.throwNullException)("variableName");if(this.patch!==null?this.patch.SetGlobal(s,c):this._globalVariables.set(s,c),this.variableChangedEvent!==null&&i!==null&&c!==i.result)if(this._batchObservingVariableChanges){if(this._changedVariablesForBatchObs===null)return(0,t.throwNullException)("this._changedVariablesForBatchObs");this.patch!==null?this.patch.AddChangedVariable(s):this._changedVariablesForBatchObs!==null&&this._changedVariablesForBatchObs.add(s)}else this.variableChangedEvent(s,c)}ResolveVariablePointer(s){let c=s.contextIndex;c==-1&&(c=this.GetContextIndexOfVariableNamed(s.variableName));let i=this.GetRawVariableWithName(s.variableName,c),l=(0,e.asOrNull)(i,o.VariablePointerValue);return l??new o.VariablePointerValue(s.variableName,c)}GetContextIndexOfVariableNamed(s){return this.GlobalVariableExistsWithName(s)?0:this._callStack.currentElementIndex}ObserveVariableChange(s){this.variableChangedEventCallbacks.push(s)}};return An.VariablesState=r,r.dontSaveDefaultValues=!0,An}var Fn={},Cs;function ca(){if(Cs)return Fn;Cs=1,Object.defineProperty(Fn,"__esModule",{value:!0}),Fn.PRNG=void 0;let o=class{constructor(a){this.seed=a%2147483647,this.seed<=0&&(this.seed+=2147483646)}next(){return this.seed=this.seed*48271%2147483647}nextFloat(){return(this.next()-1)/2147483646}};return Fn.PRNG=o,Fn}var Rn={},vs;function Ma(){if(vs)return Rn;vs=1,Object.defineProperty(Rn,"__esModule",{value:!0}),Rn.StatePatch=void 0;let o=class{get globals(){return this._globals}get changedVariables(){return this._changedVariables}get visitCounts(){return this._visitCounts}get turnIndices(){return this._turnIndices}constructor(){if(this._changedVariables=new Set,this._visitCounts=new Map,this._turnIndices=new Map,arguments.length===1&&arguments[0]!==null){let a=arguments[0];this._globals=new Map(a._globals),this._changedVariables=new Set(a._changedVariables),this._visitCounts=new Map(a._visitCounts),this._turnIndices=new Map(a._turnIndices)}else this._globals=new Map,this._changedVariables=new Set,this._visitCounts=new Map,this._turnIndices=new Map}TryGetGlobal(a,e){return a!==null&&this._globals.has(a)?{result:this._globals.get(a),exists:!0}:{result:e,exists:!1}}SetGlobal(a,e){this._globals.set(a,e)}AddChangedVariable(a){return this._changedVariables.add(a)}TryGetVisitCount(a,e){return this._visitCounts.has(a)?{result:this._visitCounts.get(a),exists:!0}:{result:e,exists:!1}}SetVisitCount(a,e){this._visitCounts.set(a,e)}SetTurnIndex(a,e){this._turnIndices.set(a,e)}TryGetTurnIndex(a,e){return this._turnIndices.has(a)?{result:this._turnIndices.get(a),exists:!0}:{result:e,exists:!1}}};return Rn.StatePatch=o,Rn}var Xt={},Ss;function da(){if(Ss)return Xt;Ss=1,Object.defineProperty(Xt,"__esModule",{value:!0}),Xt.SimpleJson=void 0;let o=class _i{static TextToDictionary(a){return new _i.Reader(a).ToDictionary()}static TextToArray(a){return new _i.Reader(a).ToArray()}};return Xt.SimpleJson=o,(function(n){class a{constructor(t){if(JSON.parse("0",(r,y,s)=>s!=null)){const r=(y,s,c)=>Number.isInteger(s)&&c.source.endsWith(".0")?c.source+"f":s;this._rootObject=JSON.parse(t,r)}else{const r=t.replace(/(,\s*)([0-9]+\.[0]+)([,]*)/g,'$1"$2f"$3');this._rootObject=JSON.parse(r)}}ToDictionary(){return this._rootObject}ToArray(){return this._rootObject}}n.Reader=a;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 t={};if(this.state===n.Writer.State.Property){this.Assert(this.currentCollection!==null),this.Assert(this.currentPropertyName!==null);let p=this._propertyNameStack.pop();this.currentCollection[p]=t,this._collectionStack.push(t)}else this.state===n.Writer.State.Array?(this.Assert(this.currentCollection!==null),this.currentCollection.push(t),this._collectionStack.push(t)):(this.Assert(this.state===n.Writer.State.None),this._jsonObject=t,this._collectionStack.push(t));this._stateStack.push(new n.Writer.StateElement(n.Writer.State.Object))}WriteObjectEnd(){this.Assert(this.state===n.Writer.State.Object),this._collectionStack.pop(),this._stateStack.pop()}WriteProperty(t,p){if(this.WritePropertyStart(t),arguments[1]instanceof Function){let r=arguments[1];r(this)}else{let r=arguments[1];this.Write(r)}this.WritePropertyEnd()}WriteIntProperty(t,p){this.WritePropertyStart(t),this.WriteInt(p),this.WritePropertyEnd()}WriteFloatProperty(t,p){this.WritePropertyStart(t),this.WriteFloat(p),this.WritePropertyEnd()}WritePropertyStart(t){this.Assert(this.state===n.Writer.State.Object),this._propertyNameStack.push(t),this.IncrementChildCount(),this._stateStack.push(new n.Writer.StateElement(n.Writer.State.Property))}WritePropertyEnd(){this.Assert(this.state===n.Writer.State.Property),this.Assert(this.childCount===1),this._stateStack.pop()}WritePropertyNameStart(){this.Assert(this.state===n.Writer.State.Object),this.IncrementChildCount(),this._currentPropertyName="",this._stateStack.push(new n.Writer.StateElement(n.Writer.State.Property)),this._stateStack.push(new n.Writer.StateElement(n.Writer.State.PropertyName))}WritePropertyNameEnd(){this.Assert(this.state===n.Writer.State.PropertyName),this.Assert(this._currentPropertyName!==null),this._propertyNameStack.push(this._currentPropertyName),this._currentPropertyName=null,this._stateStack.pop()}WritePropertyNameInner(t){this.Assert(this.state===n.Writer.State.PropertyName),this.Assert(this._currentPropertyName!==null),this._currentPropertyName+=t}WriteArrayStart(){this.StartNewObject(!0);let t=[];if(this.state===n.Writer.State.Property){this.Assert(this.currentCollection!==null),this.Assert(this.currentPropertyName!==null);let p=this._propertyNameStack.pop();this.currentCollection[p]=t,this._collectionStack.push(t)}else this.state===n.Writer.State.Array?(this.Assert(this.currentCollection!==null),this.currentCollection.push(t),this._collectionStack.push(t)):(this.Assert(this.state===n.Writer.State.None),this._jsonObject=t,this._collectionStack.push(t));this._stateStack.push(new n.Writer.StateElement(n.Writer.State.Array))}WriteArrayEnd(){this.Assert(this.state===n.Writer.State.Array),this._collectionStack.pop(),this._stateStack.pop()}Write(t,p=!0){if(t===null){console.error("Warning: trying to write a null value");return}this.StartNewObject(!1),this._addToCurrentObject(t)}WriteBool(t){t!==null&&(this.StartNewObject(!1),this._addToCurrentObject(t))}WriteInt(t){t!==null&&(this.StartNewObject(!1),this._addToCurrentObject(Math.floor(t)))}WriteFloat(t){t!==null&&(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 n.Writer.StateElement(n.Writer.State.String))}WriteStringEnd(){this.Assert(this.state==n.Writer.State.String),this._stateStack.pop(),this._addToCurrentObject(this._currentString),this._currentString=null}WriteStringInner(t,p=!0){if(this.Assert(this.state===n.Writer.State.String),t===null){console.error("Warning: trying to write a null string");return}this._currentString+=t}toString(){return this._jsonObject===null?"":JSON.stringify(this._jsonObject)}StartNewObject(t){t?this.Assert(this.state===n.Writer.State.None||this.state===n.Writer.State.Property||this.state===n.Writer.State.Array):this.Assert(this.state===n.Writer.State.Property||this.state===n.Writer.State.Array),this.state===n.Writer.State.Property&&this.Assert(this.childCount===0),(this.state===n.Writer.State.Array||this.state===n.Writer.State.Property)&&this.IncrementChildCount()}get state(){return this._stateStack.length>0?this._stateStack[this._stateStack.length-1].type:n.Writer.State.None}get childCount(){return this._stateStack.length>0?this._stateStack[this._stateStack.length-1].childCount:0}get currentCollection(){return this._collectionStack.length>0?this._collectionStack[this._collectionStack.length-1]:null}get currentPropertyName(){return this._propertyNameStack.length>0?this._propertyNameStack[this._propertyNameStack.length-1]:null}IncrementChildCount(){this.Assert(this._stateStack.length>0);let t=this._stateStack.pop();t.childCount++,this._stateStack.push(t)}Assert(t){if(!t)throw Error("Assert failed while writing JSON")}_addToCurrentObject(t){this.Assert(this.currentCollection!==null),this.state===n.Writer.State.Array?(this.Assert(Array.isArray(this.currentCollection)),this.currentCollection.push(t)):this.state===n.Writer.State.Property&&(this.Assert(!Array.isArray(this.currentCollection)),this.Assert(this.currentPropertyName!==null),this.currentCollection[this.currentPropertyName]=t,this._propertyNameStack.pop())}}n.Writer=e,(function(f){(function(p){p[p.None=0]="None",p[p.Object=1]="Object",p[p.Array=2]="Array",p[p.Property=3]="Property",p[p.PropertyName=4]="PropertyName",p[p.String=5]="String"})(f.State||(f.State={}));class t{constructor(r){this.type=n.Writer.State.None,this.childCount=0,this.type=r}}f.StateElement=t})(e=n.Writer||(n.Writer={}))})(o||(Xt.SimpleJson=o={})),Xt}var kn={},ys;function Ba(){if(ys)return kn;ys=1,Object.defineProperty(kn,"__esModule",{value:!0}),kn.Flow=void 0;const o=ua(),n=Xn(),a=ft();let e=class{constructor(){let t=arguments[0],p=arguments[1];if(this.name=t,this.callStack=new o.CallStack(p),arguments[2]){let r=arguments[2];this.callStack.SetJsonToken(r.callstack,p),this.outputStream=n.JsonSerialisation.JArrayToRuntimeObjList(r.outputStream),this.currentChoices=n.JsonSerialisation.JArrayToRuntimeObjList(r.currentChoices);let y=r.choiceThreads;typeof y<"u"&&this.LoadFlowChoiceThreads(y,p)}else this.outputStream=[],this.currentChoices=[]}WriteJson(t){t.WriteObjectStart(),t.WriteProperty("callstack",r=>this.callStack.WriteJson(r)),t.WriteProperty("outputStream",r=>n.JsonSerialisation.WriteListRuntimeObjs(r,this.outputStream));let p=!1;for(let r of this.currentChoices){if(r.threadAtGeneration===null)return(0,a.throwNullException)("c.threadAtGeneration");r.originalThreadIndex=r.threadAtGeneration.threadIndex,this.callStack.ThreadWithIndex(r.originalThreadIndex)===null&&(p||(p=!0,t.WritePropertyStart("choiceThreads"),t.WriteObjectStart()),t.WritePropertyStart(r.originalThreadIndex),r.threadAtGeneration.WriteJson(t),t.WritePropertyEnd())}p&&(t.WriteObjectEnd(),t.WritePropertyEnd()),t.WriteProperty("currentChoices",r=>{r.WriteArrayStart();for(let y of this.currentChoices)n.JsonSerialisation.WriteChoice(r,y);r.WriteArrayEnd()}),t.WriteObjectEnd()}LoadFlowChoiceThreads(t,p){for(let r of this.currentChoices){let y=this.callStack.ThreadWithIndex(r.originalThreadIndex);if(y!==null)r.threadAtGeneration=y.Copy();else{let s=t[`${r.originalThreadIndex}`];r.threadAtGeneration=new o.CallStack.Thread(s,p)}}}};return kn.Flow=e,kn}var bs;function qa(){if(bs)return In;bs=1,Object.defineProperty(In,"__esModule",{value:!0}),In.StoryState=void 0;const o=ua(),n=ja(),a=it(),e=ee(),f=Vi(),t=Di(),p=St(),r=pt(),y=Qt(),s=Xn(),c=ca(),i=te(),l=oi(),S=Gn(),P=Z(),N=ri(),O=ft(),I=ci(),w=Ma(),F=da(),k=Ba(),m=vt();let g=class fa{ToJson(u=!1){let h=new F.SimpleJson.Writer;return this.WriteJson(h),h.toString()}toJson(u=!1){return this.ToJson(u)}LoadJson(u){let h=F.SimpleJson.TextToDictionary(u);this.LoadJsonObj(h),this.onDidLoadState!==null&&this.onDidLoadState()}VisitCountAtPathString(u){let h;if(this._patch!==null){let b=this.story.ContentAtPath(new p.Path(u)).container;if(b===null)throw new Error("Content at path not found: "+u);if(h=this._patch.TryGetVisitCount(b,0),h.exists)return h.result}return h=(0,S.tryGetValueFromMap)(this._visitCounts,u,null),h.exists?h.result:0}VisitCountForContainer(u){if(u===null)return(0,O.throwNullException)("container");if(!u.visitsShouldBeCounted)return this.story.Error("Read count for target ("+u.name+" - on "+u.debugMetadata+") unknown. The story may need to be compiled with countAllVisits flag (-c)."),0;if(this._patch!==null){let R=this._patch.TryGetVisitCount(u,0);if(R.exists)return R.result}let h=u.path.toString(),b=(0,S.tryGetValueFromMap)(this._visitCounts,h,null);return b.exists?b.result:0}IncrementVisitCountForContainer(u){if(this._patch!==null){let R=this.VisitCountForContainer(u);R++,this._patch.SetVisitCount(u,R);return}let h=u.path.toString(),b=(0,S.tryGetValueFromMap)(this._visitCounts,h,null);b.exists?this._visitCounts.set(h,b.result+1):this._visitCounts.set(h,1)}RecordTurnIndexVisitToContainer(u){if(this._patch!==null){this._patch.SetTurnIndex(u,this.currentTurnIndex);return}let h=u.path.toString();this._turnIndices.set(h,this.currentTurnIndex)}TurnsSinceForContainer(u){if(u.turnIndexShouldBeCounted||this.story.Error("TURNS_SINCE() for target ("+u.name+" - on "+u.debugMetadata+") unknown. The story may need to be compiled with countAllVisits flag (-c)."),this._patch!==null){let R=this._patch.TryGetTurnIndex(u,0);if(R.exists)return this.currentTurnIndex-R.result}let h=u.path.toString(),b=(0,S.tryGetValueFromMap)(this._turnIndices,h,0);return b.exists?this.currentTurnIndex-b.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(u){this._variablesState=u}get callStack(){return this._currentFlow.callStack}get evaluationStack(){return this._evaluationStack}get currentTurnIndex(){return this._currentTurnIndex}set currentTurnIndex(u){this._currentTurnIndex=u}get currentPathString(){let u=this.currentPointer;return u.isNull?null:u.path===null?(0,O.throwNullException)("pointer.path"):u.path.toString()}get previousPathString(){let u=this.previousPointer;return u.isNull?null:u.path===null?(0,O.throwNullException)("previousPointer.path"):u.path.toString()}get currentPointer(){return this.callStack.currentElement.currentPointer.copy()}set currentPointer(u){this.callStack.currentElement.currentPointer=u.copy()}get previousPointer(){return this.callStack.currentThread.previousPointer.copy()}set previousPointer(u){this.callStack.currentThread.previousPointer=u.copy()}get canContinue(){return!this.currentPointer.isNull&&!this.hasError}get hasError(){return this.currentErrors!=null&&this.currentErrors.length>0}get hasWarning(){return this.currentWarnings!=null&&this.currentWarnings.length>0}get currentText(){if(this._outputStreamTextDirty){let u=new y.StringBuilder,h=!1;for(let b of this.outputStream){let R=(0,P.asOrNull)(b,a.StringValue);if(!h&&R!==null)u.Append(R.value);else{let V=(0,P.asOrNull)(b,r.ControlCommand);V!==null&&(V.commandType==r.ControlCommand.CommandType.BeginTag?h=!0:V.commandType==r.ControlCommand.CommandType.EndTag&&(h=!1))}}this._currentText=this.CleanOutputWhitespace(u.toString()),this._outputStreamTextDirty=!1}return this._currentText}CleanOutputWhitespace(u){let h=new y.StringBuilder,b=-1,R=0;for(let V=0;V<u.length;V++){let j=u.charAt(V),L=j==" "||j==" ";L&&b==-1&&(b=V),L||(j!=`
|
|
19
|
+
`);if(g=="<>")return new a.Glue;for(let h=0;h<Qn._controlCommandNames.length;++h){let b=Qn._controlCommandNames[h];if(g==b)return new e.ControlCommand(h)}if(g=="L^"&&(g="^"),s.NativeFunctionCall.CallExistsWithName(g))return s.NativeFunctionCall.CallWithName(g);if(g=="->->")return e.ControlCommand.PopTunnel();if(g=="~ret")return e.ControlCommand.PopFunction();if(g=="void")return new c.Void}if(typeof m=="object"&&!Array.isArray(m)){let g=m,v;if(g["^->"])return v=g["^->"],new n.DivertTargetValue(new l.Path(v.toString()));if(g["^var"]){v=g["^var"];let L=new n.VariablePointerValue(v.toString());return"ci"in g&&(v=g.ci,L.contextIndex=parseInt(v)),L}let u=!1,h=!1,b=f.PushPopType.Function,R=!1;if((v=g["->"])?u=!0:(v=g["f()"])?(u=!0,h=!0,b=f.PushPopType.Function):(v=g["->t->"])?(u=!0,h=!0,b=f.PushPopType.Tunnel):(v=g["x()"])&&(u=!0,R=!0,h=!1,b=f.PushPopType.Function),u){let L=new t.Divert;L.pushesToStack=h,L.stackPushType=b,L.isExternal=R;let C=v.toString();return(v=g.var)?L.variableDivertName=C:L.targetPathString=C,L.isConditional=!!g.c,R&&(v=g.exArgs)&&(L.externalArgs=parseInt(v)),L}if(v=g["*"]){let L=new p.ChoicePoint;return L.pathStringOnChoice=v.toString(),(v=g.flg)&&(L.flags=parseInt(v)),L}if(v=g["VAR?"])return new r.VariableReference(v.toString());if(v=g["CNT?"]){let L=new r.VariableReference;return L.pathStringForCount=v.toString(),L}let V=!1,j=!1;if((v=g["VAR="])?(V=!0,j=!0):(v=g["temp="])&&(V=!0,j=!1),V){let L=v.toString(),C=!g.re,E=new y.VariableAssignment(L,C);return E.isGlobal=j,E}if(g["#"]!==void 0)return v=g["#"],new i.Tag(v.toString());if(v=g.list){let L=v,C=new O.InkList;if(v=g.origins){let E=v;C.SetInitialOriginNames(E)}for(let E in L)if(L.hasOwnProperty(E)){let x=L[E],A=new O.InkListItem(E),W=parseInt(x);C.Add(A,W)}return new n.ListValue(C)}if(g.originalChoicePath!=null)return this.JObjectToChoice(g)}if(Array.isArray(m))return this.JArrayToContainer(m);if(m==null)return null;throw new Error("Failed to convert token to runtime object: "+this.toJson(m,["parent"]))}static toJson(m,g,v){return JSON.stringify(m,(u,h)=>g!=null&&g.some(b=>b===u)?void 0:h,v)}static WriteRuntimeContainer(m,g,v=!1){if(m.WriteArrayStart(),g===null)return(0,w.throwNullException)("container");for(let V of g.content)this.WriteRuntimeObject(m,V);let u=g.namedOnlyContent,h=g.countFlags,b=g.name!=null&&!v,R=u!=null||h>0||b;if(R&&m.WriteObjectStart(),u!=null)for(let[V,j]of u){let L=V,C=(0,I.asOrNull)(j,o.Container);m.WritePropertyStart(L),this.WriteRuntimeContainer(m,C,!0),m.WritePropertyEnd()}h>0&&m.WriteIntProperty("#f",h),b&&m.WriteProperty("#n",g.name),R?m.WriteObjectEnd():m.WriteNull(),m.WriteArrayEnd()}static JArrayToContainer(m){let g=new o.Container;g.content=this.JArrayToRuntimeObjList(m,!0);let v=m[m.length-1];if(v!=null){let u=new Map;for(let h in v)if(h=="#f")g.countFlags=parseInt(v[h]);else if(h=="#n")g.name=v[h].toString();else{let b=this.JTokenToRuntimeObject(v[h]),R=(0,I.asOrNull)(b,o.Container);R&&(R.name=h),u.set(h,b)}g.namedOnlyContent=u}return g}static JObjectToChoice(m){let g=new S.Choice;return g.text=m.text.toString(),g.index=parseInt(m.index),g.sourcePath=m.originalChoicePath.toString(),g.originalThreadIndex=parseInt(m.originalThreadIndex),g.pathStringOnChoice=m.targetPath.toString(),g.tags=this.JArrayToTags(m),g.isInvisibleDefault=!!m.isInvisibleDefault,g}static JArrayToTags(m){return m.tags?m.tags:null}static WriteChoice(m,g){m.WriteObjectStart(),m.WriteProperty("text",g.text),m.WriteIntProperty("index",g.index),m.WriteProperty("originalChoicePath",g.sourcePath),m.WriteIntProperty("originalThreadIndex",g.originalThreadIndex),m.WriteProperty("targetPath",g.pathStringOnChoice),m.WriteProperty("isInvisibleDefault",g.isInvisibleDefault),this.WriteChoiceTags(m,g),m.WriteObjectEnd()}static WriteChoiceTags(m,g){if(g.tags&&g.tags.length>0){m.WritePropertyStart("tags"),m.WriteArrayStart();for(const v of g.tags)m.Write(v);m.WriteArrayEnd(),m.WritePropertyEnd()}}static WriteInkList(m,g){let v=g.value;if(v===null)return(0,w.throwNullException)("rawList");m.WriteObjectStart(),m.WritePropertyStart("list"),m.WriteObjectStart();for(let[u,h]of v){let b=O.InkListItem.fromSerializedKey(u),R=h;if(b.itemName===null)return(0,w.throwNullException)("item.itemName");m.WritePropertyNameStart(),m.WritePropertyNameInner(b.originName?b.originName:"?"),m.WritePropertyNameInner("."),m.WritePropertyNameInner(b.itemName),m.WritePropertyNameEnd(),m.Write(R),m.WritePropertyEnd()}if(m.WriteObjectEnd(),m.WritePropertyEnd(),v.Count==0&&v.originNames!=null&&v.originNames.length>0){m.WritePropertyStart("origins"),m.WriteArrayStart();for(let u of v.originNames)m.Write(u);m.WriteArrayEnd(),m.WritePropertyEnd()}m.WriteObjectEnd()}static ListDefinitionsToJToken(m){let g={};for(let v of m.lists){let u={};for(let[h,b]of v.items){let R=O.InkListItem.fromSerializedKey(h);if(R.itemName===null)return(0,w.throwNullException)("item.itemName");u[R.itemName]=b}g[v.name]=u}return g}static JTokenToListDefinitions(m){let g=m,v=[];for(let u in g)if(g.hasOwnProperty(u)){let h=u.toString(),b=g[u],R=new Map;for(let j in b)if(g.hasOwnProperty(u)){let L=b[j];R.set(j,parseInt(L))}let V=new P.ListDefinition(h,R);v.push(V)}return new N.ListDefinitionsOrigin(v)}};return Pn.JsonSerialisation=F,F._controlCommandNames=(()=>{let k=[];k[e.ControlCommand.CommandType.EvalStart]="ev",k[e.ControlCommand.CommandType.EvalOutput]="out",k[e.ControlCommand.CommandType.EvalEnd]="/ev",k[e.ControlCommand.CommandType.Duplicate]="du",k[e.ControlCommand.CommandType.PopEvaluatedValue]="pop",k[e.ControlCommand.CommandType.PopFunction]="~ret",k[e.ControlCommand.CommandType.PopTunnel]="->->",k[e.ControlCommand.CommandType.BeginString]="str",k[e.ControlCommand.CommandType.EndString]="/str",k[e.ControlCommand.CommandType.NoOp]="nop",k[e.ControlCommand.CommandType.ChoiceCount]="choiceCnt",k[e.ControlCommand.CommandType.Turns]="turn",k[e.ControlCommand.CommandType.TurnsSince]="turns",k[e.ControlCommand.CommandType.ReadCount]="readc",k[e.ControlCommand.CommandType.Random]="rnd",k[e.ControlCommand.CommandType.SeedRandom]="srnd",k[e.ControlCommand.CommandType.VisitIndex]="visit",k[e.ControlCommand.CommandType.SequenceShuffleIndex]="seq",k[e.ControlCommand.CommandType.StartThread]="thread",k[e.ControlCommand.CommandType.Done]="done",k[e.ControlCommand.CommandType.End]="end",k[e.ControlCommand.CommandType.ListFromInt]="listInt",k[e.ControlCommand.CommandType.ListRange]="range",k[e.ControlCommand.CommandType.ListRandom]="lrnd",k[e.ControlCommand.CommandType.BeginTag]="#",k[e.ControlCommand.CommandType.EndTag]="/#";for(let m=0;m<e.ControlCommand.CommandType.TOTAL_VALUES;++m)if(k[m]==null)throw new Error("Control command not accounted for in serialisation");return k})(),Pn}var Nn={},zt={},ms;function ua(){if(ms)return zt;ms=1,Object.defineProperty(zt,"__esModule",{value:!0}),zt.CallStack=void 0;const o=te(),n=St(),a=ci(),e=Xn(),f=it(),t=Zt(),p=oi(),r=ri(),y=Gn(),s=ft();let c=class Bn{get elements(){return this.callStack}get depth(){return this.elements.length}get currentElement(){let S=this._threads[this._threads.length-1].callstack;return S[S.length-1]}get currentElementIndex(){return this.callStack.length-1}get currentThread(){return this._threads[this._threads.length-1]}set currentThread(l){r.Debug.Assert(this._threads.length==1,"Shouldn't be directly setting the current thread when we have a stack of them"),this._threads.length=0,this._threads.push(l)}get canPop(){return this.callStack.length>1}constructor(){if(this._threadCounter=0,this._startOfRoot=p.Pointer.Null,arguments[0]instanceof a.Story){let l=arguments[0];this._startOfRoot=p.Pointer.StartOf(l.rootContentContainer),this.Reset()}else{let l=arguments[0];this._threads=[];for(let S of l._threads)this._threads.push(S.Copy());this._threadCounter=l._threadCounter,this._startOfRoot=l._startOfRoot.copy()}}Reset(){this._threads=[],this._threads.push(new Bn.Thread),this._threads[0].callstack.push(new Bn.Element(o.PushPopType.Tunnel,this._startOfRoot))}SetJsonToken(l,S){this._threads.length=0;let P=l.threads;for(let N of P){let O=N,I=new Bn.Thread(O,S);this._threads.push(I)}this._threadCounter=parseInt(l.threadCounter),this._startOfRoot=p.Pointer.StartOf(S.rootContentContainer)}WriteJson(l){l.WriteObject(S=>{S.WritePropertyStart("threads"),S.WriteArrayStart();for(let P of this._threads)P.WriteJson(S);S.WriteArrayEnd(),S.WritePropertyEnd(),S.WritePropertyStart("threadCounter"),S.WriteInt(this._threadCounter),S.WritePropertyEnd()})}PushThread(){let l=this.currentThread.Copy();this._threadCounter++,l.threadIndex=this._threadCounter,this._threads.push(l)}ForkThread(){let l=this.currentThread.Copy();return this._threadCounter++,l.threadIndex=this._threadCounter,l}PopThread(){if(this.canPopThread)this._threads.splice(this._threads.indexOf(this.currentThread),1);else throw new Error("Can't pop thread")}get canPopThread(){return this._threads.length>1&&!this.elementIsEvaluateFromGame}get elementIsEvaluateFromGame(){return this.currentElement.type==o.PushPopType.FunctionEvaluationFromGame}Push(l,S=0,P=0){let N=new Bn.Element(l,this.currentElement.currentPointer,!1);N.evaluationStackHeightWhenPushed=S,N.functionStartInOutputStream=P,this.callStack.push(N)}CanPop(l=null){return this.canPop?l==null?!0:this.currentElement.type==l:!1}Pop(l=null){if(this.CanPop(l)){this.callStack.pop();return}else throw new Error("Mismatched push/pop in Callstack")}GetTemporaryVariableWithName(l,S=-1){S==-1&&(S=this.currentElementIndex+1);let P=this.callStack[S-1],N=(0,y.tryGetValueFromMap)(P.temporaryVariables,l,null);return N.exists?N.result:null}SetTemporaryVariable(l,S,P,N=-1){N==-1&&(N=this.currentElementIndex+1);let O=this.callStack[N-1];if(!P&&!O.temporaryVariables.get(l))throw new Error("Could not find temporary variable to set: "+l);let I=(0,y.tryGetValueFromMap)(O.temporaryVariables,l,null);I.exists&&f.ListValue.RetainListOriginsForAssignment(I.result,S),O.temporaryVariables.set(l,S)}ContextForVariableNamed(l){return this.currentElement.temporaryVariables.get(l)?this.currentElementIndex+1:0}ThreadWithIndex(l){let S=this._threads.filter(P=>{if(P.threadIndex==l)return P});return S.length>0?S[0]:null}get callStack(){return this.currentThread.callstack}get callStackTrace(){let l=new t.StringBuilder;for(let S=0;S<this._threads.length;S++){let P=this._threads[S],N=S==this._threads.length-1;l.AppendFormat(`=== THREAD {0}/{1} {2}===
|
|
20
|
+
`,S+1,this._threads.length,N?"(current) ":"");for(let O=0;O<P.callstack.length;O++){P.callstack[O].type==o.PushPopType.Function?l.Append(" [FUNCTION] "):l.Append(" [TUNNEL] ");let I=P.callstack[O].currentPointer;if(!I.isNull){if(l.Append("<SOMEWHERE IN "),I.container===null)return(0,s.throwNullException)("pointer.container");l.Append(I.container.path.toString()),l.AppendLine(">")}}}return l.toString()}};return zt.CallStack=c,(function(i){class l{constructor(N,O,I=!1){this.evaluationStackHeightWhenPushed=0,this.functionStartInOutputStream=0,this.currentPointer=O.copy(),this.inExpressionEvaluation=I,this.temporaryVariables=new Map,this.type=N}Copy(){let N=new l(this.type,this.currentPointer,this.inExpressionEvaluation);return N.temporaryVariables=new Map(this.temporaryVariables),N.evaluationStackHeightWhenPushed=this.evaluationStackHeightWhenPushed,N.functionStartInOutputStream=this.functionStartInOutputStream,N}}i.Element=l;class S{constructor(){if(this.threadIndex=0,this.previousPointer=p.Pointer.Null,this.callstack=[],arguments[0]&&arguments[1]){let N=arguments[0],O=arguments[1];this.threadIndex=parseInt(N.threadIndex);let I=N.callstack;for(let F of I){let k=F,m=parseInt(k.type),g=p.Pointer.Null,v,u=k.cPath;if(typeof u<"u"){v=u.toString();let V=O.ContentAtPath(new n.Path(v));if(g.container=V.container,g.index=parseInt(k.idx),V.obj==null)throw new Error("When loading state, internal story location couldn't be found: "+v+". Has the story changed since this save data was created?");V.approximate&&(g.container!==null?O.Warning("When loading state, exact internal story location couldn't be found: '"+v+"', so it was approximated to '"+g.container.path.toString()+"' to recover. Has the story changed since this save data was created?"):O.Warning("When loading state, exact internal story location couldn't be found: '"+v+"' and it may not be recoverable. Has the story changed since this save data was created?"))}let h=!!k.exp,b=new l(m,g,h),R=k.temp;typeof R<"u"?b.temporaryVariables=e.JsonSerialisation.JObjectToDictionaryRuntimeObjs(R):b.temporaryVariables.clear(),this.callstack.push(b)}let w=N.previousContentObject;if(typeof w<"u"){let F=new n.Path(w.toString());this.previousPointer=O.PointerAtPath(F)}}}Copy(){let N=new S;N.threadIndex=this.threadIndex;for(let O of this.callstack)N.callstack.push(O.Copy());return N.previousPointer=this.previousPointer.copy(),N}WriteJson(N){N.WriteObjectStart(),N.WritePropertyStart("callstack"),N.WriteArrayStart();for(let O of this.callstack){if(N.WriteObjectStart(),!O.currentPointer.isNull){if(O.currentPointer.container===null)return(0,s.throwNullException)("el.currentPointer.container");N.WriteProperty("cPath",O.currentPointer.container.path.componentsString),N.WriteIntProperty("idx",O.currentPointer.index)}N.WriteProperty("exp",O.inExpressionEvaluation),N.WriteIntProperty("type",O.type),O.temporaryVariables.size>0&&(N.WritePropertyStart("temp"),e.JsonSerialisation.WriteDictionaryRuntimeObjs(N,O.temporaryVariables),N.WritePropertyEnd()),N.WriteObjectEnd()}if(N.WriteArrayEnd(),N.WritePropertyEnd(),N.WriteIntProperty("threadIndex",this.threadIndex),!this.previousPointer.isNull){let O=this.previousPointer.Resolve();if(O===null)return(0,s.throwNullException)("this.previousPointer.Resolve()");N.WriteProperty("previousContentObject",O.path.toString())}N.WriteObjectEnd()}}i.Thread=S})(c||(zt.CallStack=c={})),zt}var In={},gs;function ja(){if(gs)return In;gs=1,Object.defineProperty(In,"__esModule",{value:!0}),In.VariablesState=void 0;const o=it(),n=si(),a=Xn(),e=Z(),f=Gn(),t=ft();function p(){return class{}}let r=class ha extends p(){variableChangedEvent(s,c){for(let i of this.variableChangedEventCallbacks)i(s,c)}StartVariableObservation(){this._batchObservingVariableChanges=!0,this._changedVariablesForBatchObs=new Set}CompleteVariableObservation(){this._batchObservingVariableChanges=!1;let s=new Map;if(this._changedVariablesForBatchObs!=null)for(let c of this._changedVariablesForBatchObs){let i=this._globalVariables.get(c);this.variableChangedEvent(c,i)}if(this.patch!=null)for(let c of this.patch.changedVariables){let i=this.patch.TryGetGlobal(c,null);i.exists&&s.set(c,i)}return this._changedVariablesForBatchObs=null,s}NotifyObservers(s){for(const[c,i]of s)this.variableChangedEvent(c,i)}get callStack(){return this._callStack}set callStack(s){this._callStack=s}$(s,c){if(typeof c>"u"){let i=null;return this.patch!==null&&(i=this.patch.TryGetGlobal(s,null),i.exists)?i.result.valueObject:(i=this._globalVariables.get(s),typeof i>"u"&&(i=this._defaultGlobalVariables.get(s)),typeof i<"u"?i.valueObject:null)}else{if(typeof this._defaultGlobalVariables.get(s)>"u")throw new n.StoryException("Cannot assign to a variable ("+s+") that hasn't been declared in the story");let i=o.Value.Create(c);if(i==null)throw c==null?new Error("Cannot pass null to VariableState"):new Error("Invalid value passed to VariableState: "+c.toString());this.SetGlobal(s,i)}}constructor(s,c){super(),this.variableChangedEventCallbacks=[],this.patch=null,this._defaultGlobalVariables=new Map,this._changedVariablesForBatchObs=new Set,this._batchObservingVariableChanges=!1,this._globalVariables=new Map,this._callStack=s,this._listDefsOrigin=c;try{return new Proxy(this,{get(l,S){return S in l?l[S]:l.$(S)},set(l,S,P){return S in l?l[S]=P:l.$(S,P),!0},ownKeys(l){return[...new Set([...l._defaultGlobalVariables.keys(),...l._globalVariables.keys()])]},getOwnPropertyDescriptor(l,S){return{enumerable:!0,configurable:!0,value:l.$(S)}}})}catch{}}ApplyPatch(){if(this.patch===null)return(0,t.throwNullException)("this.patch");for(let[s,c]of this.patch.globals)this._globalVariables.set(s,c);if(this._changedVariablesForBatchObs!==null)for(let s of this.patch.changedVariables)this._changedVariablesForBatchObs.add(s);this.patch=null}SetJsonToken(s){this._globalVariables.clear();for(let[c,i]of this._defaultGlobalVariables){let l=s[c];if(typeof l<"u"){let S=a.JsonSerialisation.JTokenToRuntimeObject(l);if(S===null)return(0,t.throwNullException)("tokenInkObject");this._globalVariables.set(c,S)}else this._globalVariables.set(c,i)}}WriteJson(s){s.WriteObjectStart();for(let[c,i]of this._globalVariables){let l=c,S=i;if(ha.dontSaveDefaultValues&&this._defaultGlobalVariables.has(l)){let P=this._defaultGlobalVariables.get(l);if(this.RuntimeObjectsEqual(S,P))continue}s.WritePropertyStart(l),a.JsonSerialisation.WriteRuntimeObject(s,S),s.WritePropertyEnd()}s.WriteObjectEnd()}RuntimeObjectsEqual(s,c){if(s===null)return(0,t.throwNullException)("obj1");if(c===null)return(0,t.throwNullException)("obj2");if(s.constructor!==c.constructor)return!1;let i=(0,e.asOrNull)(s,o.BoolValue);if(i!==null)return i.value===(0,e.asOrThrows)(c,o.BoolValue).value;let l=(0,e.asOrNull)(s,o.IntValue);if(l!==null)return l.value===(0,e.asOrThrows)(c,o.IntValue).value;let S=(0,e.asOrNull)(s,o.FloatValue);if(S!==null)return S.value===(0,e.asOrThrows)(c,o.FloatValue).value;let P=(0,e.asOrNull)(s,o.Value),N=(0,e.asOrNull)(c,o.Value);if(P!==null&&N!==null)return(0,e.isEquatable)(P.valueObject)&&(0,e.isEquatable)(N.valueObject)?P.valueObject.Equals(N.valueObject):P.valueObject===N.valueObject;throw new Error("FastRoughDefinitelyEquals: Unsupported runtime object type: "+s.constructor.name)}GetVariableWithName(s,c=-1){let i=this.GetRawVariableWithName(s,c),l=(0,e.asOrNull)(i,o.VariablePointerValue);return l!==null&&(i=this.ValueAtVariablePointer(l)),i}TryGetDefaultVariableValue(s){let c=(0,f.tryGetValueFromMap)(this._defaultGlobalVariables,s,null);return c.exists?c.result:null}GlobalVariableExistsWithName(s){return this._globalVariables.has(s)||this._defaultGlobalVariables!==null&&this._defaultGlobalVariables.has(s)}GetRawVariableWithName(s,c){let i=null;if(c==0||c==-1){let l=null;if(this.patch!==null&&(l=this.patch.TryGetGlobal(s,null),l.exists)||(l=(0,f.tryGetValueFromMap)(this._globalVariables,s,null),l.exists)||this._defaultGlobalVariables!==null&&(l=(0,f.tryGetValueFromMap)(this._defaultGlobalVariables,s,null),l.exists))return l.result;if(this._listDefsOrigin===null)return(0,t.throwNullException)("VariablesState._listDefsOrigin");let S=this._listDefsOrigin.FindSingleItemListWithName(s);if(S)return S}return i=this._callStack.GetTemporaryVariableWithName(s,c),i}ValueAtVariablePointer(s){return this.GetVariableWithName(s.variableName,s.contextIndex)}Assign(s,c){let i=s.variableName;if(i===null)return(0,t.throwNullException)("name");let l=-1,S=!1;if(s.isNewDeclaration?S=s.isGlobal:S=this.GlobalVariableExistsWithName(i),s.isNewDeclaration){let P=(0,e.asOrNull)(c,o.VariablePointerValue);P!==null&&(c=this.ResolveVariablePointer(P))}else{let P=null;do P=(0,e.asOrNull)(this.GetRawVariableWithName(i,l),o.VariablePointerValue),P!=null&&(i=P.variableName,l=P.contextIndex,S=l==0);while(P!=null)}S?this.SetGlobal(i,c):this._callStack.SetTemporaryVariable(i,c,s.isNewDeclaration,l)}SnapshotDefaultGlobals(){this._defaultGlobalVariables=new Map(this._globalVariables)}RetainListOriginsForAssignment(s,c){let i=(0,e.asOrThrows)(s,o.ListValue),l=(0,e.asOrThrows)(c,o.ListValue);i.value&&l.value&&l.value.Count==0&&l.value.SetInitialOriginNames(i.value.originNames)}SetGlobal(s,c){let i=null;if(this.patch===null&&(i=(0,f.tryGetValueFromMap)(this._globalVariables,s,null)),this.patch!==null&&(i=this.patch.TryGetGlobal(s,null),i.exists||(i=(0,f.tryGetValueFromMap)(this._globalVariables,s,null))),o.ListValue.RetainListOriginsForAssignment(i.result,c),s===null)return(0,t.throwNullException)("variableName");if(this.patch!==null?this.patch.SetGlobal(s,c):this._globalVariables.set(s,c),this.variableChangedEvent!==null&&i!==null&&c!==i.result)if(this._batchObservingVariableChanges){if(this._changedVariablesForBatchObs===null)return(0,t.throwNullException)("this._changedVariablesForBatchObs");this.patch!==null?this.patch.AddChangedVariable(s):this._changedVariablesForBatchObs!==null&&this._changedVariablesForBatchObs.add(s)}else this.variableChangedEvent(s,c)}ResolveVariablePointer(s){let c=s.contextIndex;c==-1&&(c=this.GetContextIndexOfVariableNamed(s.variableName));let i=this.GetRawVariableWithName(s.variableName,c),l=(0,e.asOrNull)(i,o.VariablePointerValue);return l??new o.VariablePointerValue(s.variableName,c)}GetContextIndexOfVariableNamed(s){return this.GlobalVariableExistsWithName(s)?0:this._callStack.currentElementIndex}ObserveVariableChange(s){this.variableChangedEventCallbacks.push(s)}};return In.VariablesState=r,r.dontSaveDefaultValues=!0,In}var An={},Cs;function ca(){if(Cs)return An;Cs=1,Object.defineProperty(An,"__esModule",{value:!0}),An.PRNG=void 0;let o=class{constructor(a){this.seed=a%2147483647,this.seed<=0&&(this.seed+=2147483646)}next(){return this.seed=this.seed*48271%2147483647}nextFloat(){return(this.next()-1)/2147483646}};return An.PRNG=o,An}var Fn={},vs;function Ma(){if(vs)return Fn;vs=1,Object.defineProperty(Fn,"__esModule",{value:!0}),Fn.StatePatch=void 0;let o=class{get globals(){return this._globals}get changedVariables(){return this._changedVariables}get visitCounts(){return this._visitCounts}get turnIndices(){return this._turnIndices}constructor(){if(this._changedVariables=new Set,this._visitCounts=new Map,this._turnIndices=new Map,arguments.length===1&&arguments[0]!==null){let a=arguments[0];this._globals=new Map(a._globals),this._changedVariables=new Set(a._changedVariables),this._visitCounts=new Map(a._visitCounts),this._turnIndices=new Map(a._turnIndices)}else this._globals=new Map,this._changedVariables=new Set,this._visitCounts=new Map,this._turnIndices=new Map}TryGetGlobal(a,e){return a!==null&&this._globals.has(a)?{result:this._globals.get(a),exists:!0}:{result:e,exists:!1}}SetGlobal(a,e){this._globals.set(a,e)}AddChangedVariable(a){return this._changedVariables.add(a)}TryGetVisitCount(a,e){return this._visitCounts.has(a)?{result:this._visitCounts.get(a),exists:!0}:{result:e,exists:!1}}SetVisitCount(a,e){this._visitCounts.set(a,e)}SetTurnIndex(a,e){this._turnIndices.set(a,e)}TryGetTurnIndex(a,e){return this._turnIndices.has(a)?{result:this._turnIndices.get(a),exists:!0}:{result:e,exists:!1}}};return Fn.StatePatch=o,Fn}var Xt={},Ss;function da(){if(Ss)return Xt;Ss=1,Object.defineProperty(Xt,"__esModule",{value:!0}),Xt.SimpleJson=void 0;let o=class _i{static TextToDictionary(a){return new _i.Reader(a).ToDictionary()}static TextToArray(a){return new _i.Reader(a).ToArray()}};return Xt.SimpleJson=o,(function(n){class a{constructor(t){if(JSON.parse("0",(r,y,s)=>s!=null)){const r=(y,s,c)=>Number.isInteger(s)&&c.source.endsWith(".0")?c.source+"f":s;this._rootObject=JSON.parse(t,r)}else{const r=t.replace(/(,\s*)([0-9]+\.[0]+)([,]*)/g,'$1"$2f"$3');this._rootObject=JSON.parse(r)}}ToDictionary(){return this._rootObject}ToArray(){return this._rootObject}}n.Reader=a;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 t={};if(this.state===n.Writer.State.Property){this.Assert(this.currentCollection!==null),this.Assert(this.currentPropertyName!==null);let p=this._propertyNameStack.pop();this.currentCollection[p]=t,this._collectionStack.push(t)}else this.state===n.Writer.State.Array?(this.Assert(this.currentCollection!==null),this.currentCollection.push(t),this._collectionStack.push(t)):(this.Assert(this.state===n.Writer.State.None),this._jsonObject=t,this._collectionStack.push(t));this._stateStack.push(new n.Writer.StateElement(n.Writer.State.Object))}WriteObjectEnd(){this.Assert(this.state===n.Writer.State.Object),this._collectionStack.pop(),this._stateStack.pop()}WriteProperty(t,p){if(this.WritePropertyStart(t),arguments[1]instanceof Function){let r=arguments[1];r(this)}else{let r=arguments[1];this.Write(r)}this.WritePropertyEnd()}WriteIntProperty(t,p){this.WritePropertyStart(t),this.WriteInt(p),this.WritePropertyEnd()}WriteFloatProperty(t,p){this.WritePropertyStart(t),this.WriteFloat(p),this.WritePropertyEnd()}WritePropertyStart(t){this.Assert(this.state===n.Writer.State.Object),this._propertyNameStack.push(t),this.IncrementChildCount(),this._stateStack.push(new n.Writer.StateElement(n.Writer.State.Property))}WritePropertyEnd(){this.Assert(this.state===n.Writer.State.Property),this.Assert(this.childCount===1),this._stateStack.pop()}WritePropertyNameStart(){this.Assert(this.state===n.Writer.State.Object),this.IncrementChildCount(),this._currentPropertyName="",this._stateStack.push(new n.Writer.StateElement(n.Writer.State.Property)),this._stateStack.push(new n.Writer.StateElement(n.Writer.State.PropertyName))}WritePropertyNameEnd(){this.Assert(this.state===n.Writer.State.PropertyName),this.Assert(this._currentPropertyName!==null),this._propertyNameStack.push(this._currentPropertyName),this._currentPropertyName=null,this._stateStack.pop()}WritePropertyNameInner(t){this.Assert(this.state===n.Writer.State.PropertyName),this.Assert(this._currentPropertyName!==null),this._currentPropertyName+=t}WriteArrayStart(){this.StartNewObject(!0);let t=[];if(this.state===n.Writer.State.Property){this.Assert(this.currentCollection!==null),this.Assert(this.currentPropertyName!==null);let p=this._propertyNameStack.pop();this.currentCollection[p]=t,this._collectionStack.push(t)}else this.state===n.Writer.State.Array?(this.Assert(this.currentCollection!==null),this.currentCollection.push(t),this._collectionStack.push(t)):(this.Assert(this.state===n.Writer.State.None),this._jsonObject=t,this._collectionStack.push(t));this._stateStack.push(new n.Writer.StateElement(n.Writer.State.Array))}WriteArrayEnd(){this.Assert(this.state===n.Writer.State.Array),this._collectionStack.pop(),this._stateStack.pop()}Write(t,p=!0){if(t===null){console.error("Warning: trying to write a null value");return}this.StartNewObject(!1),this._addToCurrentObject(t)}WriteBool(t){t!==null&&(this.StartNewObject(!1),this._addToCurrentObject(t))}WriteInt(t){t!==null&&(this.StartNewObject(!1),this._addToCurrentObject(Math.floor(t)))}WriteFloat(t){t!==null&&(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 n.Writer.StateElement(n.Writer.State.String))}WriteStringEnd(){this.Assert(this.state==n.Writer.State.String),this._stateStack.pop(),this._addToCurrentObject(this._currentString),this._currentString=null}WriteStringInner(t,p=!0){if(this.Assert(this.state===n.Writer.State.String),t===null){console.error("Warning: trying to write a null string");return}this._currentString+=t}toString(){return this._jsonObject===null?"":JSON.stringify(this._jsonObject)}StartNewObject(t){t?this.Assert(this.state===n.Writer.State.None||this.state===n.Writer.State.Property||this.state===n.Writer.State.Array):this.Assert(this.state===n.Writer.State.Property||this.state===n.Writer.State.Array),this.state===n.Writer.State.Property&&this.Assert(this.childCount===0),(this.state===n.Writer.State.Array||this.state===n.Writer.State.Property)&&this.IncrementChildCount()}get state(){return this._stateStack.length>0?this._stateStack[this._stateStack.length-1].type:n.Writer.State.None}get childCount(){return this._stateStack.length>0?this._stateStack[this._stateStack.length-1].childCount:0}get currentCollection(){return this._collectionStack.length>0?this._collectionStack[this._collectionStack.length-1]:null}get currentPropertyName(){return this._propertyNameStack.length>0?this._propertyNameStack[this._propertyNameStack.length-1]:null}IncrementChildCount(){this.Assert(this._stateStack.length>0);let t=this._stateStack.pop();t.childCount++,this._stateStack.push(t)}Assert(t){if(!t)throw Error("Assert failed while writing JSON")}_addToCurrentObject(t){this.Assert(this.currentCollection!==null),this.state===n.Writer.State.Array?(this.Assert(Array.isArray(this.currentCollection)),this.currentCollection.push(t)):this.state===n.Writer.State.Property&&(this.Assert(!Array.isArray(this.currentCollection)),this.Assert(this.currentPropertyName!==null),this.currentCollection[this.currentPropertyName]=t,this._propertyNameStack.pop())}}n.Writer=e,(function(f){(function(p){p[p.None=0]="None",p[p.Object=1]="Object",p[p.Array=2]="Array",p[p.Property=3]="Property",p[p.PropertyName=4]="PropertyName",p[p.String=5]="String"})(f.State||(f.State={}));class t{constructor(r){this.type=n.Writer.State.None,this.childCount=0,this.type=r}}f.StateElement=t})(e=n.Writer||(n.Writer={}))})(o||(Xt.SimpleJson=o={})),Xt}var Rn={},ys;function Ba(){if(ys)return Rn;ys=1,Object.defineProperty(Rn,"__esModule",{value:!0}),Rn.Flow=void 0;const o=ua(),n=Xn(),a=ft();let e=class{constructor(){let t=arguments[0],p=arguments[1];if(this.name=t,this.callStack=new o.CallStack(p),arguments[2]){let r=arguments[2];this.callStack.SetJsonToken(r.callstack,p),this.outputStream=n.JsonSerialisation.JArrayToRuntimeObjList(r.outputStream),this.currentChoices=n.JsonSerialisation.JArrayToRuntimeObjList(r.currentChoices);let y=r.choiceThreads;typeof y<"u"&&this.LoadFlowChoiceThreads(y,p)}else this.outputStream=[],this.currentChoices=[]}WriteJson(t){t.WriteObjectStart(),t.WriteProperty("callstack",r=>this.callStack.WriteJson(r)),t.WriteProperty("outputStream",r=>n.JsonSerialisation.WriteListRuntimeObjs(r,this.outputStream));let p=!1;for(let r of this.currentChoices){if(r.threadAtGeneration===null)return(0,a.throwNullException)("c.threadAtGeneration");r.originalThreadIndex=r.threadAtGeneration.threadIndex,this.callStack.ThreadWithIndex(r.originalThreadIndex)===null&&(p||(p=!0,t.WritePropertyStart("choiceThreads"),t.WriteObjectStart()),t.WritePropertyStart(r.originalThreadIndex),r.threadAtGeneration.WriteJson(t),t.WritePropertyEnd())}p&&(t.WriteObjectEnd(),t.WritePropertyEnd()),t.WriteProperty("currentChoices",r=>{r.WriteArrayStart();for(let y of this.currentChoices)n.JsonSerialisation.WriteChoice(r,y);r.WriteArrayEnd()}),t.WriteObjectEnd()}LoadFlowChoiceThreads(t,p){for(let r of this.currentChoices){let y=this.callStack.ThreadWithIndex(r.originalThreadIndex);if(y!==null)r.threadAtGeneration=y.Copy();else{let s=t[`${r.originalThreadIndex}`];r.threadAtGeneration=new o.CallStack.Thread(s,p)}}}};return Rn.Flow=e,Rn}var bs;function qa(){if(bs)return Nn;bs=1,Object.defineProperty(Nn,"__esModule",{value:!0}),Nn.StoryState=void 0;const o=ua(),n=ja(),a=it(),e=te(),f=Vi(),t=Di(),p=St(),r=pt(),y=Zt(),s=Xn(),c=ca(),i=Qt(),l=oi(),S=Gn(),P=Z(),N=ri(),O=ft(),I=ci(),w=Ma(),F=da(),k=Ba(),m=vt();let g=class fa{ToJson(u=!1){let h=new F.SimpleJson.Writer;return this.WriteJson(h),h.toString()}toJson(u=!1){return this.ToJson(u)}LoadJson(u){let h=F.SimpleJson.TextToDictionary(u);this.LoadJsonObj(h),this.onDidLoadState!==null&&this.onDidLoadState()}VisitCountAtPathString(u){let h;if(this._patch!==null){let b=this.story.ContentAtPath(new p.Path(u)).container;if(b===null)throw new Error("Content at path not found: "+u);if(h=this._patch.TryGetVisitCount(b,0),h.exists)return h.result}return h=(0,S.tryGetValueFromMap)(this._visitCounts,u,null),h.exists?h.result:0}VisitCountForContainer(u){if(u===null)return(0,O.throwNullException)("container");if(!u.visitsShouldBeCounted)return this.story.Error("Read count for target ("+u.name+" - on "+u.debugMetadata+") unknown. The story may need to be compiled with countAllVisits flag (-c)."),0;if(this._patch!==null){let R=this._patch.TryGetVisitCount(u,0);if(R.exists)return R.result}let h=u.path.toString(),b=(0,S.tryGetValueFromMap)(this._visitCounts,h,null);return b.exists?b.result:0}IncrementVisitCountForContainer(u){if(this._patch!==null){let R=this.VisitCountForContainer(u);R++,this._patch.SetVisitCount(u,R);return}let h=u.path.toString(),b=(0,S.tryGetValueFromMap)(this._visitCounts,h,null);b.exists?this._visitCounts.set(h,b.result+1):this._visitCounts.set(h,1)}RecordTurnIndexVisitToContainer(u){if(this._patch!==null){this._patch.SetTurnIndex(u,this.currentTurnIndex);return}let h=u.path.toString();this._turnIndices.set(h,this.currentTurnIndex)}TurnsSinceForContainer(u){if(u.turnIndexShouldBeCounted||this.story.Error("TURNS_SINCE() for target ("+u.name+" - on "+u.debugMetadata+") unknown. The story may need to be compiled with countAllVisits flag (-c)."),this._patch!==null){let R=this._patch.TryGetTurnIndex(u,0);if(R.exists)return this.currentTurnIndex-R.result}let h=u.path.toString(),b=(0,S.tryGetValueFromMap)(this._turnIndices,h,0);return b.exists?this.currentTurnIndex-b.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(u){this._variablesState=u}get callStack(){return this._currentFlow.callStack}get evaluationStack(){return this._evaluationStack}get currentTurnIndex(){return this._currentTurnIndex}set currentTurnIndex(u){this._currentTurnIndex=u}get currentPathString(){let u=this.currentPointer;return u.isNull?null:u.path===null?(0,O.throwNullException)("pointer.path"):u.path.toString()}get previousPathString(){let u=this.previousPointer;return u.isNull?null:u.path===null?(0,O.throwNullException)("previousPointer.path"):u.path.toString()}get currentPointer(){return this.callStack.currentElement.currentPointer.copy()}set currentPointer(u){this.callStack.currentElement.currentPointer=u.copy()}get previousPointer(){return this.callStack.currentThread.previousPointer.copy()}set previousPointer(u){this.callStack.currentThread.previousPointer=u.copy()}get canContinue(){return!this.currentPointer.isNull&&!this.hasError}get hasError(){return this.currentErrors!=null&&this.currentErrors.length>0}get hasWarning(){return this.currentWarnings!=null&&this.currentWarnings.length>0}get currentText(){if(this._outputStreamTextDirty){let u=new y.StringBuilder,h=!1;for(let b of this.outputStream){let R=(0,P.asOrNull)(b,a.StringValue);if(!h&&R!==null)u.Append(R.value);else{let V=(0,P.asOrNull)(b,r.ControlCommand);V!==null&&(V.commandType==r.ControlCommand.CommandType.BeginTag?h=!0:V.commandType==r.ControlCommand.CommandType.EndTag&&(h=!1))}}this._currentText=this.CleanOutputWhitespace(u.toString()),this._outputStreamTextDirty=!1}return this._currentText}CleanOutputWhitespace(u){let h=new y.StringBuilder,b=-1,R=0;for(let V=0;V<u.length;V++){let j=u.charAt(V),L=j==" "||j==" ";L&&b==-1&&(b=V),L||(j!=`
|
|
21
21
|
`&&b>0&&b!=R&&h.Append(" "),b=-1),j==`
|
|
22
22
|
`&&(R=V+1),L||h.Append(j)}return h.toString()}get currentTags(){if(this._outputStreamTagsDirty){this._currentTags=[];let u=!1,h=new y.StringBuilder;for(let b of this.outputStream){let R=(0,P.asOrNull)(b,r.ControlCommand);if(R!=null){if(R.commandType==r.ControlCommand.CommandType.BeginTag){if(u&&h.Length>0){let V=this.CleanOutputWhitespace(h.toString());this._currentTags.push(V),h.Clear()}u=!0}else if(R.commandType==r.ControlCommand.CommandType.EndTag){if(h.Length>0){let V=this.CleanOutputWhitespace(h.toString());this._currentTags.push(V),h.Clear()}u=!1}}else if(u){let V=(0,P.asOrNull)(b,a.StringValue);V!==null&&h.Append(V.value)}else{let V=(0,P.asOrNull)(b,f.Tag);V!=null&&V.text!=null&&V.text.length>0&&this._currentTags.push(V.text)}}if(h.Length>0){let b=this.CleanOutputWhitespace(h.toString());this._currentTags.push(b),h.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=[],this._namedFlows!=null)for(let u of this._namedFlows.keys())u!=this.kDefaultFlowName&&this._aliveFlowNames.push(u);this._aliveFlowNamesDirty=!1}return this._aliveFlowNames}get inExpressionEvaluation(){return this.callStack.currentElement.inExpressionEvaluation}set inExpressionEvaluation(u){this.callStack.currentElement.inExpressionEvaluation=u}constructor(u){this.kInkSaveStateVersion=10,this.kMinCompatibleLoadVersion=8,this.onDidLoadState=null,this._currentErrors=null,this._currentWarnings=null,this.divertedPointer=l.Pointer.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=u,this._currentFlow=new k.Flow(this.kDefaultFlowName,u),this.OutputStreamDirty(),this._aliveFlowNamesDirty=!0,this._evaluationStack=[],this._variablesState=new n.VariablesState(this.callStack,u.listDefinitions),this._visitCounts=new Map,this._turnIndices=new Map,this.currentTurnIndex=-1;let h=new Date().getTime();this.storySeed=new c.PRNG(h).next()%100,this.previousRandom=0,this.GoToStart()}GoToStart(){this.callStack.currentElement.currentPointer=l.Pointer.StartOf(this.story.mainContentContainer)}SwitchFlow_Internal(u){if(u===null)throw new Error("Must pass a non-null string to Story.SwitchFlow");if(this._namedFlows===null&&(this._namedFlows=new Map,this._namedFlows.set(this.kDefaultFlowName,this._currentFlow)),u===this._currentFlow.name)return;let h,b=(0,S.tryGetValueFromMap)(this._namedFlows,u,null);b.exists?h=b.result:(h=new k.Flow(u,this.story),this._namedFlows.set(u,h),this._aliveFlowNamesDirty=!0),this._currentFlow=h,this.variablesState.callStack=this._currentFlow.callStack,this.OutputStreamDirty()}SwitchToDefaultFlow_Internal(){this._namedFlows!==null&&this.SwitchFlow_Internal(this.kDefaultFlowName)}RemoveFlow_Internal(u){if(u===null)throw new Error("Must pass a non-null string to Story.DestroyFlow");if(u===this.kDefaultFlowName)throw new Error("Cannot destroy default flow");if(this._currentFlow.name===u&&this.SwitchToDefaultFlow_Internal(),this._namedFlows===null)return(0,O.throwNullException)("this._namedFlows");this._namedFlows.delete(u),this._aliveFlowNamesDirty=!0}CopyAndStartPatching(u){let h=new fa(this.story);if(h._patch=new w.StatePatch(this._patch),h._currentFlow.name=this._currentFlow.name,h._currentFlow.callStack=new o.CallStack(this._currentFlow.callStack),h._currentFlow.outputStream.push(...this._currentFlow.outputStream),h.OutputStreamDirty(),u)for(let b of this._currentFlow.currentChoices)h._currentFlow.currentChoices.push(b.Clone());else h._currentFlow.currentChoices.push(...this._currentFlow.currentChoices);if(this._namedFlows!==null){h._namedFlows=new Map;for(let[b,R]of this._namedFlows)h._namedFlows.set(b,R),h._aliveFlowNamesDirty=!0;h._namedFlows.set(this._currentFlow.name,h._currentFlow)}return this.hasError&&(h._currentErrors=[],h._currentErrors.push(...this.currentErrors||[])),this.hasWarning&&(h._currentWarnings=[],h._currentWarnings.push(...this.currentWarnings||[])),h.variablesState=this.variablesState,h.variablesState.callStack=h.callStack,h.variablesState.patch=h._patch,h.evaluationStack.push(...this.evaluationStack),this.divertedPointer.isNull||(h.divertedPointer=this.divertedPointer.copy()),h.previousPointer=this.previousPointer.copy(),h._visitCounts=this._visitCounts,h._turnIndices=this._turnIndices,h.currentTurnIndex=this.currentTurnIndex,h.storySeed=this.storySeed,h.previousRandom=this.previousRandom,h.didSafeExit=this.didSafeExit,h}RestoreAfterPatch(){this.variablesState.callStack=this.callStack,this.variablesState.patch=this._patch}ApplyAnyPatch(){if(this._patch!==null){this.variablesState.ApplyPatch();for(let[u,h]of this._patch.visitCounts)this.ApplyCountChanges(u,h,!0);for(let[u,h]of this._patch.turnIndices)this.ApplyCountChanges(u,h,!1);this._patch=null}}ApplyCountChanges(u,h,b){(b?this._visitCounts:this._turnIndices).set(u.path.toString(),h)}WriteJson(u){if(u.WriteObjectStart(),u.WritePropertyStart("flows"),u.WriteObjectStart(),this._namedFlows!==null)for(let[h,b]of this._namedFlows)u.WriteProperty(h,R=>b.WriteJson(R));else u.WriteProperty(this._currentFlow.name,h=>this._currentFlow.WriteJson(h));if(u.WriteObjectEnd(),u.WritePropertyEnd(),u.WriteProperty("currentFlowName",this._currentFlow.name),u.WriteProperty("variablesState",h=>this.variablesState.WriteJson(h)),u.WriteProperty("evalStack",h=>s.JsonSerialisation.WriteListRuntimeObjs(h,this.evaluationStack)),!this.divertedPointer.isNull){if(this.divertedPointer.path===null)return(0,O.throwNullException)("divertedPointer");u.WriteProperty("currentDivertTarget",this.divertedPointer.path.componentsString)}u.WriteProperty("visitCounts",h=>s.JsonSerialisation.WriteIntDictionary(h,this._visitCounts)),u.WriteProperty("turnIndices",h=>s.JsonSerialisation.WriteIntDictionary(h,this._turnIndices)),u.WriteIntProperty("turnIdx",this.currentTurnIndex),u.WriteIntProperty("storySeed",this.storySeed),u.WriteIntProperty("previousRandom",this.previousRandom),u.WriteIntProperty("inkSaveVersion",this.kInkSaveStateVersion),u.WriteIntProperty("inkFormatVersion",I.Story.inkVersionCurrent),u.WriteObjectEnd()}LoadJsonObj(u){let h=u,b=h.inkSaveVersion;if(b==null)throw new Error("ink save format incorrect, can't load.");if(parseInt(b)<this.kMinCompatibleLoadVersion)throw new Error("Ink save format isn't compatible with the current version (saw '"+b+"', but minimum is "+this.kMinCompatibleLoadVersion+"), so can't load.");let R=h.flows;if(R!=null){let j=R;Object.keys(j).length===1?this._namedFlows=null:this._namedFlows===null?this._namedFlows=new Map:this._namedFlows.clear();let L=Object.entries(j);for(let[C,E]of L){let x=C,A=E,W=new k.Flow(x,this.story,A);if(Object.keys(j).length===1)this._currentFlow=new k.Flow(x,this.story,A);else{if(this._namedFlows===null)return(0,O.throwNullException)("this._namedFlows");this._namedFlows.set(x,W)}}if(this._namedFlows!=null&&this._namedFlows.size>1){let C=h.currentFlowName;this._currentFlow=this._namedFlows.get(C)}}else{this._namedFlows=null,this._currentFlow.name=this.kDefaultFlowName,this._currentFlow.callStack.SetJsonToken(h.callstackThreads,this.story),this._currentFlow.outputStream=s.JsonSerialisation.JArrayToRuntimeObjList(h.outputStream),this._currentFlow.currentChoices=s.JsonSerialisation.JArrayToRuntimeObjList(h.currentChoices);let j=h.choiceThreads;this._currentFlow.LoadFlowChoiceThreads(j,this.story)}this.OutputStreamDirty(),this._aliveFlowNamesDirty=!0,this.variablesState.SetJsonToken(h.variablesState),this.variablesState.callStack=this._currentFlow.callStack,this._evaluationStack=s.JsonSerialisation.JArrayToRuntimeObjList(h.evalStack);let V=h.currentDivertTarget;if(V!=null){let j=new p.Path(V.toString());this.divertedPointer=this.story.PointerAtPath(j)}this._visitCounts=s.JsonSerialisation.JObjectToIntDictionary(h.visitCounts),this._turnIndices=s.JsonSerialisation.JObjectToIntDictionary(h.turnIndices),this.currentTurnIndex=parseInt(h.turnIdx),this.storySeed=parseInt(h.storySeed),this.previousRandom=parseInt(h.previousRandom)}ResetErrors(){this._currentErrors=null,this._currentWarnings=null}ResetOutput(u=null){this.outputStream.length=0,u!==null&&this.outputStream.push(...u),this.OutputStreamDirty()}PushToOutputStream(u){let h=(0,P.asOrNull)(u,a.StringValue);if(h!==null){let b=this.TrySplittingHeadTailWhitespace(h);if(b!==null){for(let R of b)this.PushToOutputStreamIndividual(R);this.OutputStreamDirty();return}}this.PushToOutputStreamIndividual(u),this.OutputStreamDirty()}PopFromOutputStream(u){this.outputStream.splice(this.outputStream.length-u,u),this.OutputStreamDirty()}TrySplittingHeadTailWhitespace(u){let h=u.value;if(h===null)return(0,O.throwNullException)("single.value");let b=-1,R=-1;for(let x=0;x<h.length;x++){let A=h[x];if(A==`
|
|
23
23
|
`)b==-1&&(b=x),R=x;else{if(A==" "||A==" ")continue;break}}let V=-1,j=-1;for(let x=h.length-1;x>=0;x--){let A=h[x];if(A==`
|
|
24
24
|
`)V==-1&&(V=x),j=x;else{if(A==" "||A==" ")continue;break}}if(b==-1&&V==-1)return null;let L=[],C=0,E=h.length;if(b!=-1){if(b>0){let x=new a.StringValue(h.substring(0,b));L.push(x)}L.push(new a.StringValue(`
|
|
25
25
|
`)),C=R+1}if(V!=-1&&(E=j),E>C){let x=h.substring(C,E);L.push(new a.StringValue(x))}if(V!=-1&&j>R&&(L.push(new a.StringValue(`
|
|
26
|
-
`)),V<h.length-1)){let x=h.length-V-1,A=new a.StringValue(h.substring(V+1,V+1+x));L.push(A)}return L}PushToOutputStreamIndividual(u){let h=(0,P.asOrNull)(u,t.Glue),b=(0,P.asOrNull)(u,a.StringValue),R=!0;if(h)this.TrimNewlinesFromOutputStream(),R=!0;else if(b){let V=-1,j=this.callStack.currentElement;j.type==e.PushPopType.Function&&(V=j.functionStartInOutputStream);let L=-1;for(let E=this.outputStream.length-1;E>=0;E--){let x=this.outputStream[E],A=x instanceof r.ControlCommand?x:null;if((x instanceof t.Glue?x:null)!=null){L=E;break}else if(A!=null&&A.commandType==r.ControlCommand.CommandType.BeginString){E>=V&&(V=-1);break}}let C=-1;if(L!=-1&&V!=-1?C=Math.min(V,L):L!=-1?C=L:C=V,C!=-1){if(b.isNewline)R=!1;else if(b.isNonWhitespace&&(L>-1&&this.RemoveExistingGlue(),V>-1)){let E=this.callStack.elements;for(let x=E.length-1;x>=0;x--){let A=E[x];if(A.type==e.PushPopType.Function)A.functionStartInOutputStream=-1;else break}}}else b.isNewline&&(this.outputStreamEndsInNewline||!this.outputStreamContainsContent)&&(R=!1)}if(R){if(u===null)return(0,O.throwNullException)("obj");this.outputStream.push(u),this.OutputStreamDirty()}}TrimNewlinesFromOutputStream(){let u=-1,h=this.outputStream.length-1;for(;h>=0;){let b=this.outputStream[h],R=(0,P.asOrNull)(b,r.ControlCommand),V=(0,P.asOrNull)(b,a.StringValue);if(R!=null||V!=null&&V.isNonWhitespace)break;V!=null&&V.isNewline&&(u=h),h--}if(u>=0)for(h=u;h<this.outputStream.length;)(0,P.asOrNull)(this.outputStream[h],a.StringValue)?this.outputStream.splice(h,1):h++;this.OutputStreamDirty()}RemoveExistingGlue(){for(let u=this.outputStream.length-1;u>=0;u--){let h=this.outputStream[u];if(h instanceof t.Glue)this.outputStream.splice(u,1);else if(h instanceof r.ControlCommand)break}this.OutputStreamDirty()}get outputStreamEndsInNewline(){if(this.outputStream.length>0)for(let u=this.outputStream.length-1;u>=0&&!(this.outputStream[u]instanceof r.ControlCommand);u--){let b=this.outputStream[u];if(b instanceof a.StringValue){if(b.isNewline)return!0;if(b.isNonWhitespace)break}}return!1}get outputStreamContainsContent(){for(let u of this.outputStream)if(u instanceof a.StringValue)return!0;return!1}get inStringEvaluation(){for(let u=this.outputStream.length-1;u>=0;u--){let h=(0,P.asOrNull)(this.outputStream[u],r.ControlCommand);if(h instanceof r.ControlCommand&&h.commandType==r.ControlCommand.CommandType.BeginString)return!0}return!1}PushEvaluationStack(u){let h=(0,P.asOrNull)(u,a.ListValue);if(h){let b=h.value;if(b===null)return(0,O.throwNullException)("rawList");if(b.originNames!=null){b.origins||(b.origins=[]),b.origins.length=0;for(let R of b.originNames){if(this.story.listDefinitions===null)return(0,O.throwNullException)("StoryState.story.listDefinitions");let V=this.story.listDefinitions.TryListGetDefinition(R,null);if(V.result===null)return(0,O.throwNullException)("StoryState def.result");b.origins.indexOf(V.result)<0&&b.origins.push(V.result)}}}if(u===null)return(0,O.throwNullException)("obj");this.evaluationStack.push(u)}PopEvaluationStack(u){if(typeof u>"u"){let h=this.evaluationStack.pop();return(0,P.nullIfUndefined)(h)}else{if(u>this.evaluationStack.length)throw new Error("trying to pop too many objects");let h=this.evaluationStack.splice(this.evaluationStack.length-u,u);return(0,P.nullIfUndefined)(h)}}PeekEvaluationStack(){return this.evaluationStack[this.evaluationStack.length-1]}ForceEnd(){this.callStack.Reset(),this._currentFlow.currentChoices.length=0,this.currentPointer=l.Pointer.Null,this.previousPointer=l.Pointer.Null,this.didSafeExit=!0}TrimWhitespaceFromFunctionEnd(){N.Debug.Assert(this.callStack.currentElement.type==e.PushPopType.Function);let u=this.callStack.currentElement.functionStartInOutputStream;u==-1&&(u=0);for(let h=this.outputStream.length-1;h>=u;h--){let b=this.outputStream[h],R=(0,P.asOrNull)(b,a.StringValue),V=(0,P.asOrNull)(b,r.ControlCommand);if(R!=null){if(V)break;if(R.isNewline||R.isInlineWhitespace)this.outputStream.splice(h,1),this.OutputStreamDirty();else break}}}PopCallStack(u=null){this.callStack.currentElement.type==e.PushPopType.Function&&this.TrimWhitespaceFromFunctionEnd(),this.callStack.Pop(u)}SetChosenPath(u,h){this._currentFlow.currentChoices.length=0;let b=this.story.PointerAtPath(u);!b.isNull&&b.index==-1&&(b.index=0),this.currentPointer=b,h&&this.currentTurnIndex++}StartFunctionEvaluationFromGame(u,h){this.callStack.Push(e.PushPopType.FunctionEvaluationFromGame,this.evaluationStack.length),this.callStack.currentElement.currentPointer=l.Pointer.StartOf(u),this.PassArgumentsToEvaluationStack(h)}PassArgumentsToEvaluationStack(u){if(u!==null)for(let h=0;h<u.length;h++){if(!(typeof u[h]=="number"||typeof u[h]=="string"||typeof u[h]=="boolean"||u[h]instanceof m.InkList))throw new Error("ink arguments when calling EvaluateFunction / ChoosePathStringWithParameters must benumber, string, bool or InkList. Argument was "+((0,P.nullIfUndefined)(u[h])===null?"null":u[h].constructor.name));this.PushEvaluationStack(a.Value.Create(u[h]))}}TryExitFunctionEvaluationFromGame(){return this.callStack.currentElement.type==e.PushPopType.FunctionEvaluationFromGame?(this.currentPointer=l.Pointer.Null,this.didSafeExit=!0,!0):!1}CompleteFunctionEvaluationFromGame(){if(this.callStack.currentElement.type!=e.PushPopType.FunctionEvaluationFromGame)throw new Error("Expected external function evaluation to be complete. Stack trace: "+this.callStack.callStackTrace);let u=this.callStack.currentElement.evaluationStackHeightWhenPushed,h=null;for(;this.evaluationStack.length>u;){let b=this.PopEvaluationStack();h===null&&(h=b)}if(this.PopCallStack(e.PushPopType.FunctionEvaluationFromGame),h){if(h instanceof i.Void)return null;let b=(0,P.asOrThrows)(h,a.Value);return b.valueType==a.ValueType.DivertTarget?"-> "+b.valueObject.toString():b.valueObject}return null}AddError(u,h){h?(this._currentWarnings==null&&(this._currentWarnings=[]),this._currentWarnings.push(u)):(this._currentErrors==null&&(this._currentErrors=[]),this._currentErrors.push(u))}OutputStreamDirty(){this._outputStreamTextDirty=!0,this._outputStreamTagsDirty=!0}};return In.StoryState=g,In}var Dn={},_s;function Ga(){if(_s)return Dn;_s=1,Object.defineProperty(Dn,"__esModule",{value:!0}),Dn.Stopwatch=void 0;class o{constructor(){this.startTime=void 0}get ElapsedMilliseconds(){return typeof this.startTime>"u"?0:new Date().getTime()-this.startTime}Start(){this.startTime=new Date().getTime()}Stop(){this.startTime=void 0}}return Dn.Stopwatch=o,Dn}var Vn={},Es;function $a(){if(Es)return Vn;Es=1,Object.defineProperty(Vn,"__esModule",{value:!0}),Vn.ErrorType=void 0;var o;return(function(n){n[n.Author=0]="Author",n[n.Warning=1]="Warning",n[n.Error=2]="Error"})(o||(Vn.ErrorType=o={})),Vn}var ws;function ci(){return ws||(ws=1,(function(o){Object.defineProperty(o,"__esModule",{value:!0}),o.Story=o.InkList=void 0;const n=ot(),a=yt(),e=Xn(),f=qa(),t=pt(),p=ee(),r=Ni(),y=oa(),s=Rt(),c=it(),i=St(),l=te(),S=Vi(),P=Gt(),N=Kn(),O=Ft(),I=si(),w=ca(),F=Qt(),k=la(),m=Ga(),g=oi(),v=vt(),u=Z(),h=ft(),b=da(),R=$a();var V=vt();Object.defineProperty(o,"InkList",{enumerable:!0,get:function(){return V.InkList}}),Number.isInteger||(Number.isInteger=function(C){return typeof C=="number"&&isFinite(C)&&C>-9007199254740992&&C<9007199254740992&&Math.floor(C)===C});class j extends a.InkObject{get currentChoices(){let C=[];if(this._state===null)return(0,h.throwNullException)("this._state");for(let E of this._state.currentChoices)E.isInvisibleDefault||(E.index=C.length,C.push(E));return C}get currentText(){return this.IfAsyncWeCant("call currentText since it's a work in progress"),this.state.currentText}get currentTags(){return this.IfAsyncWeCant("call currentTags since it's a work in progress"),this.state.currentTags}get currentErrors(){return this.state.currentErrors}get currentWarnings(){return this.state.currentWarnings}get currentFlowName(){return this.state.currentFlowName}get currentFlowIsDefaultFlow(){return this.state.currentFlowIsDefaultFlow}get aliveFlowNames(){return this.state.aliveFlowNames}get hasError(){return this.state.hasError}get hasWarning(){return this.state.hasWarning}get variablesState(){return this.state.variablesState}get listDefinitions(){return this._listDefinitions}get state(){return this._state}StartProfiling(){}EndProfiling(){}constructor(){super(),this.inkVersionMinimumCompatible=18,this.onError=null,this.onDidContinue=null,this.onMakeChoice=null,this.onEvaluateFunction=null,this.onCompleteEvaluateFunction=null,this.onChoosePathString=null,this._prevContainers=[],this.allowExternalFunctionFallbacks=!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 C,E=null,x=null;if(arguments[0]instanceof n.Container)C=arguments[0],typeof arguments[1]<"u"&&(E=arguments[1]),this._mainContentContainer=C;else if(typeof arguments[0]=="string"){let A=arguments[0];x=b.SimpleJson.TextToDictionary(A)}else x=arguments[0];if(E!=null&&(this._listDefinitions=new k.ListDefinitionsOrigin(E)),this._externals=new Map,x!==null){let A=x,W=A.inkVersion;if(W==null)throw new Error("ink version number not found. Are you sure it's a valid .ink.json file?");let M=parseInt(W);if(M>j.inkVersionCurrent)throw new Error("Version of ink used to build story was newer than the current version of the engine");if(M<this.inkVersionMinimumCompatible)throw new Error("Version of ink used to build story is too old to be loaded by this version of the engine");M!=j.inkVersionCurrent&&console.warn(`WARNING: Version of ink ${j.inkVersionCurrent} used to build story doesn't match current version of engine (${M}). Non-critical, but recommend synchronising.`);let G=A.root;if(G==null)throw new Error("Root node for ink not found. Are you sure it's a valid .ink.json file?");let K;(K=A.listDefs)&&(this._listDefinitions=e.JsonSerialisation.JTokenToListDefinitions(K)),this._mainContentContainer=(0,u.asOrThrows)(e.JsonSerialisation.JTokenToRuntimeObject(G),n.Container),this.ResetState()}}ToJson(C){let E=!1;if(C||(E=!0,C=new b.SimpleJson.Writer),C.WriteObjectStart(),C.WriteIntProperty("inkVersion",j.inkVersionCurrent),C.WriteProperty("root",x=>e.JsonSerialisation.WriteRuntimeContainer(x,this._mainContentContainer)),this._listDefinitions!=null){C.WritePropertyStart("listDefs"),C.WriteObjectStart();for(let x of this._listDefinitions.lists){C.WritePropertyStart(x.name),C.WriteObjectStart();for(let[A,W]of x.items){let M=v.InkListItem.fromSerializedKey(A),G=W;C.WriteIntProperty(M.itemName,G)}C.WriteObjectEnd(),C.WritePropertyEnd()}C.WriteObjectEnd(),C.WritePropertyEnd()}if(C.WriteObjectEnd(),E)return C.toString()}ResetState(){this.IfAsyncWeCant("ResetState"),this._state=new f.StoryState(this),this._state.variablesState.ObserveVariableChange(this.VariableStateDidChangeEvent.bind(this)),this.ResetGlobals()}ResetErrors(){if(this._state===null)return(0,h.throwNullException)("this._state");this._state.ResetErrors()}ResetCallstack(){if(this.IfAsyncWeCant("ResetCallstack"),this._state===null)return(0,h.throwNullException)("this._state");this._state.ForceEnd()}ResetGlobals(){if(this._mainContentContainer.namedContent.get("global decl")){let C=this.state.currentPointer.copy();this.ChoosePath(new i.Path("global decl"),!1),this.ContinueInternal(),this.state.currentPointer=C}this.state.variablesState.SnapshotDefaultGlobals()}SwitchFlow(C){if(this.IfAsyncWeCant("switch flow"),this._asyncSaving)throw new Error("Story is already in background saving mode, can't switch flow to "+C);this.state.SwitchFlow_Internal(C)}RemoveFlow(C){this.state.RemoveFlow_Internal(C)}SwitchToDefaultFlow(){this.state.SwitchToDefaultFlow_Internal()}Continue(){return this.ContinueAsync(0),this.currentText}get canContinue(){return this.state.canContinue}get asyncContinueComplete(){return!this._asyncContinueActive}ContinueAsync(C){this._hasValidatedExternals||this.ValidateExternalBindings(),this.ContinueInternal(C)}ContinueInternal(C=0){this._profiler!=null&&this._profiler.PreContinue();let E=C>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(),this._recursiveContinueCount==1&&this._state.variablesState.StartVariableObservation()}let x=new m.Stopwatch;x.Start();let A=!1;this._sawLookaheadUnsafeFunctionAfterNewline=!1;do{try{A=this.ContinueSingleStep()}catch(M){if(!(M instanceof I.StoryException))throw M;this.AddError(M.message,void 0,M.useEndLineNumber);break}if(A||this._asyncContinueActive&&x.ElapsedMilliseconds>C)break}while(this.canContinue);x.Stop();let W=null;if((A||!this.canContinue)&&(this._stateSnapshotAtLastNewline!==null&&this.RestoreStateSnapshot(),this.canContinue||(this.state.callStack.canPopThread&&this.AddError("Thread available to pop, threads should always be flat by the end of evaluation?"),this.state.generatedChoices.length==0&&!this.state.didSafeExit&&this._temporaryEvaluationContainer==null&&(this.state.callStack.CanPop(p.PushPopType.Tunnel)?this.AddError("unexpectedly reached end of content. Do you need a '->->' to return from a tunnel?"):this.state.callStack.CanPop(p.PushPopType.Function)?this.AddError("unexpectedly reached end of content. Do you need a '~ return'?"):this.state.callStack.canPop?this.AddError("unexpectedly reached end of content for unknown reason. Please debug compiler!"):this.AddError("ran out of content. Do you need a '-> DONE' or '-> END'?"))),this.state.didSafeExit=!1,this._sawLookaheadUnsafeFunctionAfterNewline=!1,this._recursiveContinueCount==1&&(W=this._state.variablesState.CompleteVariableObservation()),this._asyncContinueActive=!1,this.onDidContinue!==null&&this.onDidContinue()),this._recursiveContinueCount--,this._profiler!=null&&this._profiler.PostContinue(),this.state.hasError||this.state.hasWarning)if(this.onError!==null){if(this.state.hasError)for(let M of this.state.currentErrors)this.onError(M,R.ErrorType.Error);if(this.state.hasWarning)for(let M of this.state.currentWarnings)this.onError(M,R.ErrorType.Warning);this.ResetErrors()}else{let M=new F.StringBuilder;throw M.Append("Ink had "),this.state.hasError&&(M.Append(`${this.state.currentErrors.length}`),M.Append(this.state.currentErrors.length==1?" error":" errors"),this.state.hasWarning&&M.Append(" and ")),this.state.hasWarning&&(M.Append(`${this.state.currentWarnings.length}`),M.Append(this.state.currentWarnings.length==1?" warning":" warnings"),this.state.hasWarning&&M.Append(" and ")),M.Append(". It is strongly suggested that you assign an error handler to story.onError. The first issue was: "),M.Append(this.state.hasError?this.state.currentErrors[0]:this.state.currentWarnings[0]),new I.StoryException(M.toString())}W!=null&&Object.keys(W).length>0&&this._state.variablesState.NotifyObservers(W)}ContinueSingleStep(){if(this._profiler!=null&&this._profiler.PreStep(),this.Step(),this._profiler!=null&&this._profiler.PostStep(),!this.canContinue&&!this.state.callStack.elementIsEvaluateFromGame&&this.TryFollowDefaultInvisibleChoice(),this._profiler!=null&&this._profiler.PreSnapshot(),!this.state.inStringEvaluation){if(this._stateSnapshotAtLastNewline!==null){if(this._stateSnapshotAtLastNewline.currentTags===null)return(0,h.throwNullException)("this._stateAtLastNewline.currentTags");if(this.state.currentTags===null)return(0,h.throwNullException)("this.state.currentTags");let C=this.CalculateNewlineOutputStateChange(this._stateSnapshotAtLastNewline.currentText,this.state.currentText,this._stateSnapshotAtLastNewline.currentTags.length,this.state.currentTags.length);if(C==j.OutputStateChange.ExtendedBeyondNewline||this._sawLookaheadUnsafeFunctionAfterNewline)return this.RestoreStateSnapshot(),!0;C==j.OutputStateChange.NewlineRemoved&&this.DiscardSnapshot()}this.state.outputStreamEndsInNewline&&(this.canContinue?this._stateSnapshotAtLastNewline==null&&this.StateSnapshot():this.DiscardSnapshot())}return this._profiler!=null&&this._profiler.PostSnapshot(),!1}CalculateNewlineOutputStateChange(C,E,x,A){if(C===null)return(0,h.throwNullException)("prevText");if(E===null)return(0,h.throwNullException)("currText");let W=E.length>=C.length&&C.length>0&&E.charAt(C.length-1)==`
|
|
27
|
-
`;if(x==A&&C.length==E.length&&W)return j.OutputStateChange.NoChange;if(!W)return j.OutputStateChange.NewlineRemoved;if(A>x)return j.OutputStateChange.ExtendedBeyondNewline;for(let M=C.length;M<E.length;M++){let G=E.charAt(M);if(G!=" "&&G!=" ")return j.OutputStateChange.ExtendedBeyondNewline}return j.OutputStateChange.NoChange}ContinueMaximally(){this.IfAsyncWeCant("ContinueMaximally");let C=new F.StringBuilder;for(;this.canContinue;)C.Append(this.Continue());return C.toString()}ContentAtPath(C){return this.mainContentContainer.ContentAtPath(C)}KnotContainerWithName(C){let E=this.mainContentContainer.namedContent.get(C);return E instanceof n.Container?E:null}PointerAtPath(C){if(C.length==0)return g.Pointer.Null;let E=new g.Pointer,x=C.length,A=null;return C.lastComponent===null?(0,h.throwNullException)("path.lastComponent"):(C.lastComponent.isIndex?(x=C.length-1,A=this.mainContentContainer.ContentAtPath(C,void 0,x),E.container=A.container,E.index=C.lastComponent.index):(A=this.mainContentContainer.ContentAtPath(C),E.container=A.container,E.index=-1),A.obj==null||A.obj==this.mainContentContainer&&x>0?this.Error("Failed to find content at path '"+C+"', and no approximation of it was possible."):A.approximate&&this.Warning("Failed to find content at path '"+C+"', so it was approximated to: '"+A.obj.path+"'."),E)}StateSnapshot(){this._stateSnapshotAtLastNewline=this._state,this._state=this._state.CopyAndStartPatching(!1)}RestoreStateSnapshot(){this._stateSnapshotAtLastNewline===null&&(0,h.throwNullException)("_stateSnapshotAtLastNewline"),this._stateSnapshotAtLastNewline.RestoreAfterPatch(),this._state=this._stateSnapshotAtLastNewline,this._stateSnapshotAtLastNewline=null,this._asyncSaving||this._state.ApplyAnyPatch()}DiscardSnapshot(){this._asyncSaving||this._state.ApplyAnyPatch(),this._stateSnapshotAtLastNewline=null}CopyStateForBackgroundThreadSave(){if(this.IfAsyncWeCant("start saving on a background thread"),this._asyncSaving)throw new Error("Story is already in background saving mode, can't call CopyStateForBackgroundThreadSave again!");let C=this._state;return this._state=this._state.CopyAndStartPatching(!0),this._asyncSaving=!0,C}BackgroundSaveComplete(){this._stateSnapshotAtLastNewline===null&&this._state.ApplyAnyPatch(),this._asyncSaving=!1}Step(){let C=!0,E=this.state.currentPointer.copy();if(E.isNull)return;let x=(0,u.asOrNull)(E.Resolve(),n.Container);for(;x&&(this.VisitContainer(x,!0),x.content.length!=0);)E=g.Pointer.StartOf(x),x=(0,u.asOrNull)(E.Resolve(),n.Container);this.state.currentPointer=E.copy(),this._profiler!=null&&this._profiler.Step(this.state.callStack);let A=E.Resolve(),W=this.PerformLogicAndFlowControl(A);if(this.state.currentPointer.isNull)return;W&&(C=!1);let M=(0,u.asOrNull)(A,r.ChoicePoint);if(M){let K=this.ProcessChoice(M);K&&this.state.generatedChoices.push(K),A=null,C=!1}if(A instanceof n.Container&&(C=!1),C){let K=(0,u.asOrNull)(A,c.VariablePointerValue);if(K&&K.contextIndex==-1){let Q=this.state.callStack.ContextForVariableNamed(K.variableName);A=new c.VariablePointerValue(K.variableName,Q)}this.state.inExpressionEvaluation?this.state.PushEvaluationStack(A):this.state.PushToOutputStream(A)}this.NextContent();let G=(0,u.asOrNull)(A,t.ControlCommand);G&&G.commandType==t.ControlCommand.CommandType.StartThread&&this.state.callStack.PushThread()}VisitContainer(C,E){(!C.countingAtStartOnly||E)&&(C.visitsShouldBeCounted&&this.state.IncrementVisitCountForContainer(C),C.turnIndexShouldBeCounted&&this.state.RecordTurnIndexVisitToContainer(C))}VisitChangedContainersDueToDivert(){let C=this.state.previousPointer.copy(),E=this.state.currentPointer.copy();if(E.isNull||E.index==-1)return;if(this._prevContainers.length=0,!C.isNull){let M=C.Resolve(),G=(0,u.asOrNull)(M,n.Container)||(0,u.asOrNull)(C.container,n.Container);for(;G;)this._prevContainers.push(G),G=(0,u.asOrNull)(G.parent,n.Container)}let x=E.Resolve();if(x==null)return;let A=(0,u.asOrNull)(x.parent,n.Container),W=!0;for(;A&&(this._prevContainers.indexOf(A)<0||A.countingAtStartOnly);){let M=A.content.length>0&&x==A.content[0]&&W;M||(W=!1),this.VisitContainer(A,M),x=A,A=(0,u.asOrNull)(A.parent,n.Container)}}PopChoiceStringAndTags(C){let E=(0,u.asOrThrows)(this.state.PopEvaluationStack(),c.StringValue);for(;this.state.evaluationStack.length>0&&(0,u.asOrNull)(this.state.PeekEvaluationStack(),S.Tag)!=null;){let x=(0,u.asOrNull)(this.state.PopEvaluationStack(),S.Tag);x&&C.push(x.text)}return E.value}ProcessChoice(C){let E=!0;if(C.hasCondition){let G=this.state.PopEvaluationStack();this.IsTruthy(G)||(E=!1)}let x="",A="",W=[];if(C.hasChoiceOnlyContent&&(A=this.PopChoiceStringAndTags(W)||""),C.hasStartContent&&(x=this.PopChoiceStringAndTags(W)||""),C.onceOnly&&this.state.VisitCountForContainer(C.choiceTarget)>0&&(E=!1),!E)return null;let M=new y.Choice;return M.targetPath=C.pathOnChoice,M.sourcePath=C.path.toString(),M.isInvisibleDefault=C.isInvisibleDefault,M.threadAtGeneration=this.state.callStack.ForkThread(),M.tags=W.reverse(),M.text=(x+A).replace(/^[ \t]+|[ \t]+$/g,""),M}IsTruthy(C){let E=!1;if(C instanceof c.Value){let x=C;if(x instanceof c.DivertTargetValue){let A=x;return this.Error("Shouldn't use a divert target (to "+A.targetPath+") as a conditional value. Did you intend a function call 'likeThis()' or a read count check 'likeThis'? (no arrows)"),!1}return x.isTruthy}return E}PerformLogicAndFlowControl(C){if(C==null)return!1;if(C instanceof s.Divert){let E=C;if(E.isConditional){let x=this.state.PopEvaluationStack();if(!this.IsTruthy(x))return!0}if(E.hasVariableTarget){let x=E.variableDivertName,A=this.state.variablesState.GetVariableWithName(x);if(A==null)this.Error("Tried to divert using a target from a variable that could not be found ("+x+")");else if(!(A instanceof c.DivertTargetValue)){let M=(0,u.asOrNull)(A,c.IntValue),G="Tried to divert to a target from a variable, but the variable ("+x+") didn't contain a divert target, it ";M instanceof c.IntValue&&M.value==0?G+="was empty/null (the value 0).":G+="contained '"+A+"'.",this.Error(G)}let W=(0,u.asOrThrows)(A,c.DivertTargetValue);this.state.divertedPointer=this.PointerAtPath(W.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&&E.debugMetadata.sourceName!=null?this.Error("Divert target doesn't exist: "+E.debugMetadata.sourceName):this.Error("Divert resolution failed: "+E)),!0}else if(C instanceof t.ControlCommand){let E=C;switch(E.commandType){case t.ControlCommand.CommandType.EvalStart:this.Assert(this.state.inExpressionEvaluation===!1,"Already in expression evaluation?"),this.state.inExpressionEvaluation=!0;break;case t.ControlCommand.CommandType.EvalEnd:this.Assert(this.state.inExpressionEvaluation===!0,"Not in expression evaluation mode"),this.state.inExpressionEvaluation=!1;break;case t.ControlCommand.CommandType.EvalOutput:if(this.state.evaluationStack.length>0){let B=this.state.PopEvaluationStack();if(!(B instanceof l.Void)){let nt=new c.StringValue(B.toString());this.state.PushToOutputStream(nt)}}break;case t.ControlCommand.CommandType.NoOp:break;case t.ControlCommand.CommandType.Duplicate:this.state.PushEvaluationStack(this.state.PeekEvaluationStack());break;case t.ControlCommand.CommandType.PopEvaluatedValue:this.state.PopEvaluationStack();break;case t.ControlCommand.CommandType.PopFunction:case t.ControlCommand.CommandType.PopTunnel:let x=E.commandType==t.ControlCommand.CommandType.PopFunction?p.PushPopType.Function:p.PushPopType.Tunnel,A=null;if(x==p.PushPopType.Tunnel){let B=this.state.PopEvaluationStack();A=(0,u.asOrNull)(B,c.DivertTargetValue),A===null&&this.Assert(B instanceof l.Void,"Expected void if ->-> doesn't override target")}if(this.state.TryExitFunctionEvaluationFromGame())break;if(this.state.callStack.currentElement.type!=x||!this.state.callStack.canPop){let B=new Map;B.set(p.PushPopType.Function,"function return statement (~ return)"),B.set(p.PushPopType.Tunnel,"tunnel onwards statement (->->)");let nt=B.get(this.state.callStack.currentElement.type);this.state.callStack.canPop||(nt="end of flow (-> END or choice)");let H="Found "+B.get(x)+", when expected "+nt;this.Error(H)}else this.state.PopCallStack(),A&&(this.state.divertedPointer=this.PointerAtPath(A.targetPath));break;case t.ControlCommand.CommandType.BeginString:this.state.PushToOutputStream(E),this.Assert(this.state.inExpressionEvaluation===!0,"Expected to be in an expression when evaluating a string"),this.state.inExpressionEvaluation=!1;break;case t.ControlCommand.CommandType.BeginTag:this.state.PushToOutputStream(E);break;case t.ControlCommand.CommandType.EndTag:{if(this.state.inStringEvaluation){let B=[],nt=0;for(let ht=this.state.outputStream.length-1;ht>=0;--ht){let lt=this.state.outputStream[ht];nt++;let bt=(0,u.asOrNull)(lt,t.ControlCommand);if(bt!=null){if(bt.commandType==t.ControlCommand.CommandType.BeginTag)break;this.Error("Unexpected ControlCommand while extracting tag from choice");break}lt instanceof c.StringValue&&B.push(lt)}this.state.PopFromOutputStream(nt);let H=new F.StringBuilder;for(let ht of B.reverse())H.Append(ht.toString());let wt=new S.Tag(this.state.CleanOutputWhitespace(H.toString()));this.state.PushEvaluationStack(wt)}else this.state.PushToOutputStream(E);break}case t.ControlCommand.CommandType.EndString:{let B=[],nt=[],H=0;for(let ht=this.state.outputStream.length-1;ht>=0;--ht){let lt=this.state.outputStream[ht];H++;let bt=(0,u.asOrNull)(lt,t.ControlCommand);if(bt&&bt.commandType==t.ControlCommand.CommandType.BeginString)break;lt instanceof S.Tag&&nt.push(lt),lt instanceof c.StringValue&&B.push(lt)}this.state.PopFromOutputStream(H);for(let ht of nt)this.state.PushToOutputStream(ht);B=B.reverse();let wt=new F.StringBuilder;for(let ht of B)wt.Append(ht.toString());this.state.inExpressionEvaluation=!0,this.state.PushEvaluationStack(new c.StringValue(wt.toString()));break}case t.ControlCommand.CommandType.ChoiceCount:let W=this.state.generatedChoices.length;this.state.PushEvaluationStack(new c.IntValue(W));break;case t.ControlCommand.CommandType.Turns:this.state.PushEvaluationStack(new c.IntValue(this.state.currentTurnIndex+1));break;case t.ControlCommand.CommandType.TurnsSince:case t.ControlCommand.CommandType.ReadCount:let M=this.state.PopEvaluationStack();if(!(M instanceof c.DivertTargetValue)){let B="";M instanceof c.IntValue&&(B=". 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 "+M+B);break}let G=(0,u.asOrThrows)(M,c.DivertTargetValue),K=(0,u.asOrNull)(this.ContentAtPath(G.targetPath).correctObj,n.Container),Q;K!=null?E.commandType==t.ControlCommand.CommandType.TurnsSince?Q=this.state.TurnsSinceForContainer(K):Q=this.state.VisitCountForContainer(K):(E.commandType==t.ControlCommand.CommandType.TurnsSince?Q=-1:Q=0,this.Warning("Failed to find container for "+E.toString()+" lookup at "+G.targetPath.toString())),this.state.PushEvaluationStack(new c.IntValue(Q));break;case t.ControlCommand.CommandType.Random:{let B=(0,u.asOrNull)(this.state.PopEvaluationStack(),c.IntValue),nt=(0,u.asOrNull)(this.state.PopEvaluationStack(),c.IntValue);if(nt==null||!(nt instanceof c.IntValue))return this.Error("Invalid value for minimum parameter of RANDOM(min, max)");if(B==null||!(B instanceof c.IntValue))return this.Error("Invalid value for maximum parameter of RANDOM(min, max)");if(B.value===null)return(0,h.throwNullException)("maxInt.value");if(nt.value===null)return(0,h.throwNullException)("minInt.value");let H=B.value-nt.value+1;(!isFinite(H)||H>Number.MAX_SAFE_INTEGER)&&(H=Number.MAX_SAFE_INTEGER,this.Error("RANDOM was called with a range that exceeds the size that ink numbers can use.")),H<=0&&this.Error("RANDOM was called with minimum as "+nt.value+" and maximum as "+B.value+". The maximum must be larger");let wt=this.state.storySeed+this.state.previousRandom,lt=new w.PRNG(wt).next(),bt=lt%H+nt.value;this.state.PushEvaluationStack(new c.IntValue(bt)),this.state.previousRandom=lt;break}case t.ControlCommand.CommandType.SeedRandom:let ut=(0,u.asOrNull)(this.state.PopEvaluationStack(),c.IntValue);if(ut==null||!(ut instanceof c.IntValue))return this.Error("Invalid value passed to SEED_RANDOM");if(ut.value===null)return(0,h.throwNullException)("minInt.value");this.state.storySeed=ut.value,this.state.previousRandom=0,this.state.PushEvaluationStack(new l.Void);break;case t.ControlCommand.CommandType.VisitIndex:let Y=this.state.VisitCountForContainer(this.state.currentPointer.container)-1;this.state.PushEvaluationStack(new c.IntValue(Y));break;case t.ControlCommand.CommandType.SequenceShuffleIndex:let mt=this.NextSequenceShuffleIndex();this.state.PushEvaluationStack(new c.IntValue(mt));break;case t.ControlCommand.CommandType.StartThread:break;case t.ControlCommand.CommandType.Done:this.state.callStack.canPopThread?this.state.callStack.PopThread():(this.state.didSafeExit=!0,this.state.currentPointer=g.Pointer.Null);break;case t.ControlCommand.CommandType.End:this.state.ForceEnd();break;case t.ControlCommand.CommandType.ListFromInt:let rt=(0,u.asOrNull)(this.state.PopEvaluationStack(),c.IntValue),_t=(0,u.asOrThrows)(this.state.PopEvaluationStack(),c.StringValue);if(rt===null)throw new I.StoryException("Passed non-integer when creating a list element from a numerical value.");let Dt=null;if(this.listDefinitions===null)return(0,h.throwNullException)("this.listDefinitions");let Et=this.listDefinitions.TryListGetDefinition(_t.value,null);if(Et.exists){if(rt.value===null)return(0,h.throwNullException)("minInt.value");let B=Et.result.TryGetItemWithValue(rt.value,v.InkListItem.Null);B.exists&&(Dt=new c.ListValue(B.result,rt.value))}else throw new I.StoryException("Failed to find LIST called "+_t.value);Dt==null&&(Dt=new c.ListValue),this.state.PushEvaluationStack(Dt);break;case t.ControlCommand.CommandType.ListRange:let Vt=(0,u.asOrNull)(this.state.PopEvaluationStack(),c.Value),xt=(0,u.asOrNull)(this.state.PopEvaluationStack(),c.Value),Ut=(0,u.asOrNull)(this.state.PopEvaluationStack(),c.ListValue);if(Ut===null||xt===null||Vt===null)throw new I.StoryException("Expected list, minimum and maximum for LIST_RANGE");if(Ut.value===null)return(0,h.throwNullException)("targetList.value");let di=Ut.value.ListWithSubRange(xt.valueObject,Vt.valueObject);this.state.PushEvaluationStack(new c.ListValue(di));break;case t.ControlCommand.CommandType.ListRandom:{let B=this.state.PopEvaluationStack();if(B===null)throw new I.StoryException("Expected list for LIST_RANDOM");let nt=B.value,H=null;if(nt===null)throw(0,h.throwNullException)("list");if(nt.Count==0)H=new v.InkList;else{let wt=this.state.storySeed+this.state.previousRandom,lt=new w.PRNG(wt).next(),bt=lt%nt.Count,d=nt.entries();for(let D=0;D<=bt-1;D++)d.next();let _=d.next().value,T={Key:v.InkListItem.fromSerializedKey(_[0]),Value:_[1]};if(T.Key.originName===null)return(0,h.throwNullException)("randomItem.Key.originName");H=new v.InkList(T.Key.originName,this),H.Add(T.Key,T.Value),this.state.previousRandom=lt}this.state.PushEvaluationStack(new c.ListValue(H));break}default:this.Error("unhandled ControlCommand: "+E);break}return!0}else if(C instanceof P.VariableAssignment){let E=C,x=this.state.PopEvaluationStack();return this.state.variablesState.Assign(E,x),!0}else if(C instanceof N.VariableReference){let E=C,x=null;if(E.pathForCount!=null){let A=E.containerForCount,W=this.state.VisitCountForContainer(A);x=new c.IntValue(W)}else x=this.state.variablesState.GetVariableWithName(E.name),x==null&&(this.Warning("Variable not found: '"+E.name+"'. Using default value of 0 (false). This can happen with temporary variables if the declaration hasn't yet been hit. Globals are always given a default value on load if a value doesn't exist in the save state."),x=new c.IntValue(0));return this.state.PushEvaluationStack(x),!0}else if(C instanceof O.NativeFunctionCall){let E=C,x=this.state.PopEvaluationStack(E.numberOfParameters),A=E.Call(x);return this.state.PushEvaluationStack(A),!0}return!1}ChoosePathString(C,E=!0,x=[]){if(this.IfAsyncWeCant("call ChoosePathString right now"),this.onChoosePathString!==null&&this.onChoosePathString(C,x),E)this.ResetCallstack();else if(this.state.callStack.currentElement.type==p.PushPopType.Function){let A="",W=this.state.callStack.currentElement.currentPointer.container;throw W!=null&&(A="("+W.path.toString()+") "),new Error("Story was running a function "+A+"when you called ChoosePathString("+C+`) - this is almost certainly not not what you want! Full stack trace:
|
|
28
|
-
`+this.state.callStack.callStackTrace)}this.state.PassArgumentsToEvaluationStack(x),this.ChoosePath(new i.Path(C))}IfAsyncWeCant(C){if(this._asyncContinueActive)throw new Error("Can't "+C+". Story is in the middle of a ContinueAsync(). Make more ContinueAsync() calls or a single Continue() call beforehand.")}ChoosePath(C,E=!0){this.state.SetChosenPath(C,E),this.VisitChangedContainersDueToDivert()}ChooseChoiceIndex(C){C=C;let E=this.currentChoices;this.Assert(C>=0&&C<E.length,"choice out of range");let x=E[C];if(this.onMakeChoice!==null&&this.onMakeChoice(x),x.threadAtGeneration===null)return(0,h.throwNullException)("choiceToChoose.threadAtGeneration");if(x.targetPath===null)return(0,h.throwNullException)("choiceToChoose.targetPath");this.state.callStack.currentThread=x.threadAtGeneration,this.ChoosePath(x.targetPath)}HasFunction(C){try{return this.KnotContainerWithName(C)!=null}catch{return!1}}EvaluateFunction(C,E=[],x=!1){if(this.onEvaluateFunction!==null&&this.onEvaluateFunction(C,E),this.IfAsyncWeCant("evaluate a function"),C==null)throw new Error("Function is null");if(C==""||C.trim()=="")throw new Error("Function is empty or white space.");let A=this.KnotContainerWithName(C);if(A==null)throw new Error("Function doesn't exist: '"+C+"'");let W=[];W.push(...this.state.outputStream),this._state.ResetOutput(),this.state.StartFunctionEvaluationFromGame(A,E);let M=new F.StringBuilder;for(;this.canContinue;)M.Append(this.Continue());let G=M.toString();this._state.ResetOutput(W);let K=this.state.CompleteFunctionEvaluationFromGame();return this.onCompleteEvaluateFunction!=null&&this.onCompleteEvaluateFunction(C,E,G,K),x?{returned:K,output:G}:K}EvaluateExpression(C){let E=this.state.callStack.elements.length;this.state.callStack.Push(p.PushPopType.Tunnel),this._temporaryEvaluationContainer=C,this.state.GoToStart();let x=this.state.evaluationStack.length;return this.Continue(),this._temporaryEvaluationContainer=null,this.state.callStack.elements.length>E&&this.state.PopCallStack(),this.state.evaluationStack.length>x?this.state.PopEvaluationStack():null}CallExternalFunction(C,E){if(C===null)return(0,h.throwNullException)("funcName");let x=this._externals.get(C),A=null,W=typeof x<"u";if(W&&!x.lookAheadSafe&&this._state.inStringEvaluation&&this.Error("External function "+C+` 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 = `+C+"()"),W&&!x.lookAheadSafe&&this._stateSnapshotAtLastNewline!==null){this._sawLookaheadUnsafeFunctionAfterNewline=!0;return}if(!W)if(this.allowExternalFunctionFallbacks){A=this.KnotContainerWithName(C),this.Assert(A!==null,"Trying to call EXTERNAL function '"+C+"' which has not been bound, and fallback ink function could not be found."),this.state.callStack.Push(p.PushPopType.Function,void 0,this.state.outputStream.length),this.state.divertedPointer=g.Pointer.StartOf(A);return}else this.Assert(!1,"Trying to call EXTERNAL function '"+C+"' which has not been bound (and ink fallbacks disabled).");let M=[];for(let Q=0;Q<E;++Q){let Y=(0,u.asOrThrows)(this.state.PopEvaluationStack(),c.Value).valueObject;M.push(Y)}M.reverse();let G=x.function(M),K=null;G!=null?(K=c.Value.Create(G),this.Assert(K!==null,"Could not create ink value from returned object of type "+typeof G)):K=new l.Void,this.state.PushEvaluationStack(K)}BindExternalFunctionGeneral(C,E,x=!0){this.IfAsyncWeCant("bind an external function"),this.Assert(!this._externals.has(C),"Function '"+C+"' has already been bound."),this._externals.set(C,{function:E,lookAheadSafe:x})}TryCoerce(C){return C}BindExternalFunction(C,E,x=!1){this.Assert(E!=null,"Can't bind a null function"),this.BindExternalFunctionGeneral(C,A=>{this.Assert(A.length>=E.length,"External function expected "+E.length+" arguments");let W=[];for(let M=0,G=A.length;M<G;M++)W[M]=this.TryCoerce(A[M]);return E.apply(null,W)},x)}UnbindExternalFunction(C){this.IfAsyncWeCant("unbind an external a function"),this.Assert(this._externals.has(C),"Function '"+C+"' has not been bound."),this._externals.delete(C)}ValidateExternalBindings(){let C=null,E=null,x=arguments[1]||new Set;if(arguments[0]instanceof n.Container&&(C=arguments[0]),arguments[0]instanceof a.InkObject&&(E=arguments[0]),C===null&&E===null)if(this.ValidateExternalBindings(this._mainContentContainer,x),this._hasValidatedExternals=!0,x.size==0)this._hasValidatedExternals=!0;else{let A="Error: Missing function binding for external";A+=x.size>1?"s":"",A+=": '",A+=Array.from(x).join("', '"),A+="' ",A+=this.allowExternalFunctionFallbacks?", and no fallback ink function found.":" (ink fallbacks disabled)",this.Error(A)}else if(C!=null){for(let A of C.content){let W=A;(W==null||!W.hasValidName)&&this.ValidateExternalBindings(A,x)}for(let[,A]of C.namedContent)this.ValidateExternalBindings((0,u.asOrNull)(A,a.InkObject),x)}else if(E!=null){let A=(0,u.asOrNull)(E,s.Divert);if(A&&A.isExternal){let W=A.targetPathString;if(W===null)return(0,h.throwNullException)("name");this._externals.has(W)||this.allowExternalFunctionFallbacks&&this.mainContentContainer.namedContent.has(W)||x.add(W)}}}ObserveVariable(C,E){if(this.IfAsyncWeCant("observe a new variable"),this._variableObservers===null&&(this._variableObservers=new Map),!this.state.variablesState.GlobalVariableExistsWithName(C))throw new Error("Cannot observe variable '"+C+"' because it wasn't declared in the ink story.");this._variableObservers.has(C)?this._variableObservers.get(C).push(E):this._variableObservers.set(C,[E])}ObserveVariables(C,E){for(let x=0,A=C.length;x<A;x++)this.ObserveVariable(C[x],E[x])}RemoveVariableObserver(C,E){if(this.IfAsyncWeCant("remove a variable observer"),this._variableObservers!==null){if(E!=null){if(this._variableObservers.has(E))if(C!=null){let x=this._variableObservers.get(E);x!=null&&(x.splice(x.indexOf(C),1),x.length===0&&this._variableObservers.delete(E))}else this._variableObservers.delete(E)}else if(C!=null){let x=this._variableObservers.keys();for(let A of x){let W=this._variableObservers.get(A);W!=null&&(W.splice(W.indexOf(C),1),W.length===0&&this._variableObservers.delete(A))}}}}VariableStateDidChangeEvent(C,E){if(this._variableObservers===null)return;let x=this._variableObservers.get(C);if(typeof x<"u"){if(!(E instanceof c.Value))throw new Error("Tried to get the value of a variable that isn't a standard type");let A=(0,u.asOrThrows)(E,c.Value);for(let W of x)W(C,A.valueObject)}}get globalTags(){return this.TagsAtStartOfFlowContainerWithPathString("")}TagsForContentAtPath(C){return this.TagsAtStartOfFlowContainerWithPathString(C)}TagsAtStartOfFlowContainerWithPathString(C){let E=new i.Path(C),x=this.ContentAtPath(E).container;if(x===null)return(0,h.throwNullException)("flowContainer");for(;;){let M=x.content[0];if(M instanceof n.Container)x=M;else break}let A=!1,W=null;for(let M of x.content){let G=(0,u.asOrNull)(M,t.ControlCommand);if(G!=null)G.commandType==t.ControlCommand.CommandType.BeginTag?A=!0:G.commandType==t.ControlCommand.CommandType.EndTag&&(A=!1);else if(A){let K=(0,u.asOrNull)(M,c.StringValue);K!==null?(W===null&&(W=[]),K.value!==null&&W.push(K.value)):this.Error("Tag contained non-text content. Only plain text is allowed when using globalTags or TagsAtContentPath. If you want to evaluate dynamic content, you need to use story.Continue().")}else break}return W}BuildStringOfHierarchy(){let C=new F.StringBuilder;return this.mainContentContainer.BuildStringOfHierarchy(C,0,this.state.currentPointer.Resolve()),C.toString()}BuildStringOfContainer(C){let E=new F.StringBuilder;return C.BuildStringOfHierarchy(E,0,this.state.currentPointer.Resolve()),E.toString()}NextContent(){if(this.state.previousPointer=this.state.currentPointer.copy(),!this.state.divertedPointer.isNull&&(this.state.currentPointer=this.state.divertedPointer.copy(),this.state.divertedPointer=g.Pointer.Null,this.VisitChangedContainersDueToDivert(),!this.state.currentPointer.isNull))return;if(!this.IncrementContentPointer()){let E=!1;this.state.callStack.CanPop(p.PushPopType.Function)?(this.state.PopCallStack(p.PushPopType.Function),this.state.inExpressionEvaluation&&this.state.PushEvaluationStack(new l.Void),E=!0):this.state.callStack.canPopThread?(this.state.callStack.PopThread(),E=!0):this.state.TryExitFunctionEvaluationFromGame(),E&&!this.state.currentPointer.isNull&&this.NextContent()}}IncrementContentPointer(){let C=!0,E=this.state.callStack.currentElement.currentPointer.copy();if(E.index++,E.container===null)return(0,h.throwNullException)("pointer.container");for(;E.index>=E.container.content.length;){C=!1;let x=(0,u.asOrNull)(E.container.parent,n.Container);if(!(x instanceof n.Container))break;let A=x.content.indexOf(E.container);if(A==-1)break;if(E=new g.Pointer(x,A),E.index++,C=!0,E.container===null)return(0,h.throwNullException)("pointer.container")}return C||(E=g.Pointer.Null),this.state.callStack.currentElement.currentPointer=E.copy(),C}TryFollowDefaultInvisibleChoice(){let C=this._state.currentChoices,E=C.filter(A=>A.isInvisibleDefault);if(E.length==0||C.length>E.length)return!1;let x=E[0];return x.targetPath===null?(0,h.throwNullException)("choice.targetPath"):x.threadAtGeneration===null?(0,h.throwNullException)("choice.threadAtGeneration"):(this.state.callStack.currentThread=x.threadAtGeneration,this._stateSnapshotAtLastNewline!==null&&(this.state.callStack.currentThread=this.state.callStack.ForkThread()),this.ChoosePath(x.targetPath,!1),!0)}NextSequenceShuffleIndex(){let C=(0,u.asOrNull)(this.state.PopEvaluationStack(),c.IntValue);if(!(C instanceof c.IntValue))return this.Error("expected number of elements in sequence for shuffle index"),0;let E=this.state.currentPointer.container;if(E===null)return(0,h.throwNullException)("seqContainer");if(C.value===null)return(0,h.throwNullException)("numElementsIntVal.value");let x=C.value,W=(0,u.asOrThrows)(this.state.PopEvaluationStack(),c.IntValue).value;if(W===null)return(0,h.throwNullException)("seqCount");let M=W/x,G=W%x,K=E.path.toString(),Q=0;for(let rt=0,_t=K.length;rt<_t;rt++)Q+=K.charCodeAt(rt)||0;let ut=Q+M+this.state.storySeed,Y=new w.PRNG(Math.floor(ut)),mt=[];for(let rt=0;rt<x;++rt)mt.push(rt);for(let rt=0;rt<=G;++rt){let _t=Y.next()%mt.length,Dt=mt[_t];if(mt.splice(_t,1),rt==G)return Dt}throw new Error("Should never reach here")}Error(C,E=!1){let x=new I.StoryException(C);throw x.useEndLineNumber=E,x}Warning(C){this.AddError(C,!0)}AddError(C,E=!1,x=!1){let A=this.currentDebugMetadata,W=E?"WARNING":"ERROR";if(A!=null){let M=x?A.endLineNumber:A.startLineNumber;C="RUNTIME "+W+": '"+A.fileName+"' line "+M+": "+C}else this.state.currentPointer.isNull?C="RUNTIME "+W+": "+C:C="RUNTIME "+W+": ("+this.state.currentPointer+"): "+C;this.state.AddError(C,E),E||this.state.ForceEnd()}Assert(C,E=null){if(C==!1)throw E==null&&(E="Story assert"),new Error(E+" "+this.currentDebugMetadata)}get currentDebugMetadata(){let C,E=this.state.currentPointer;if(!E.isNull&&E.Resolve()!==null&&(C=E.Resolve().debugMetadata,C!==null))return C;for(let x=this.state.callStack.elements.length-1;x>=0;--x)if(E=this.state.callStack.elements[x].currentPointer,!E.isNull&&E.Resolve()!==null&&(C=E.Resolve().debugMetadata,C!==null))return C;for(let x=this.state.outputStream.length-1;x>=0;--x)if(C=this.state.outputStream[x].debugMetadata,C!==null)return C;return null}get mainContentContainer(){return this._temporaryEvaluationContainer?this._temporaryEvaluationContainer:this._mainContentContainer}}o.Story=j,j.inkVersionCurrent=21,(function(L){(function(C){C[C.NoChange=0]="NoChange",C[C.ExtendedBeyondNewline=1]="ExtendedBeyondNewline",C[C.NewlineRemoved=2]="NewlineRemoved"})(L.OutputStateChange||(L.OutputStateChange={}))})(j||(o.Story=j={}))})(gi)),gi}var Ps;function Ua(){if(Ps)return Pn;Ps=1,Object.defineProperty(Pn,"__esModule",{value:!0}),Pn.Story=void 0;const o=xi(),n=Ai(),a=ot(),e=pt(),f=Oi(),t=kt(),p=Un(),r=ea(),y=ki(),s=ia(),c=ci(),i=Wt(),l=$t(),S=Gt(),P=Z(),N=ui(),O=hi(),I=ne();class w extends t.FlowBase{get flowLevel(){return p.FlowLevel.Story}get hadError(){return this._hadError}get hadWarning(){return this._hadWarning}constructor(k,m=!1){super(null,k,null,!1,m),this._errorHandler=null,this._hadError=!1,this._hadWarning=!1,this._dontFlattenContainers=new Set,this._listDefs=new Map,this.constants=new Map,this.externals=new Map,this.countAllVisits=!1,this.ExportRuntime=(g=null)=>{var v,u;this._errorHandler=g,this.constants=new Map;for(const j of this.FindAll(n.ConstantDeclaration)()){const L=this.constants.get(j.constantName);if(L&&!L.Equals(j.expression)){const C=`CONST '${j.constantName}' has been redefined with a different value. Multiple definitions of the same CONST are valid so long as they contain the same value. Initial definition was on ${L.debugMetadata}.`;this.Error(C,j,!1)}this.constants.set(j.constantName,j.expression)}this._listDefs=new Map;for(const j of this.FindAll(y.ListDefinition)())!((v=j.identifier)===null||v===void 0)&&v.name&&this._listDefs.set((u=j.identifier)===null||u===void 0?void 0:u.name,j);this.externals=new Map,this.ResolveWeavePointNaming();const h=this.runtimeObject,b=new a.Container;b.AddContent(e.ControlCommand.EvalStart());const R=[];for(const[j,L]of this.variableDeclarations)if(L.isGlobalDeclaration){if(L.listDefinition)this._listDefs.set(j,L.listDefinition),b.AddContent(L.listDefinition.runtimeObject),R.push(L.listDefinition.runtimeListDefinition);else{if(!L.expression)throw new Error;L.expression.GenerateIntoContainer(b)}const C=new S.VariableAssignment(j,!0);C.isGlobal=!0,b.AddContent(C)}b.AddContent(e.ControlCommand.EvalEnd()),b.AddContent(e.ControlCommand.End()),this.variableDeclarations.size>0&&(b.name="global decl",h.AddToNamedContentOnly(b)),h.AddContent(e.ControlCommand.Done());const V=new c.Story(h,R);return this.runtimeObject=V,this.hadError||(this.FlattenContainersIn(h),this.ResolveReferences(this),this.hadError)?null:(V.ResetState(),V)},this.ResolveList=g=>{let v=this._listDefs.get(g);return v||null},this.ResolveListItem=(g,v,u=null)=>{let h=null;if(g)return(h=this._listDefs.get(g))?h.ItemNamed(v):null;{let b=null,R=null;for(const[,V]of this._listDefs.entries()){const j=V.ItemNamed(v);j&&(b?this.Error(`Ambiguous item name '${v}' found in multiple sets, including ${R.identifier} and ${V.identifier}`,u,!1):(b=j,R=V))}return b}},this.FlattenContainersIn=g=>{const v=new Set;if(g.content)for(const u of g.content){const h=(0,P.asOrNull)(u,a.Container);h&&v.add(h)}if(g.namedContent)for(const[,u]of g.namedContent){const h=(0,P.asOrNull)(u,a.Container);h&&v.add(h)}for(const u of v)this.TryFlattenContainer(u),this.FlattenContainersIn(u)},this.TryFlattenContainer=g=>{if(g.namedContent&&g.namedContent.size>0||g.hasValidName||this._dontFlattenContainers.has(g))return;const v=(0,P.asOrNull)(g.parent,a.Container);if(v){let u=v.content.indexOf(g);v.content.splice(u,1);const h=g.ownDebugMetadata;if(g.content)for(const b of g.content)b.parent=null,h!==null&&b.ownDebugMetadata===null&&(b.debugMetadata=h),v.InsertContent(b,u),u+=1}},this.Error=(g,v,u)=>{let h=u?f.ErrorType.Warning:f.ErrorType.Error,b="";if(v instanceof o.AuthorWarning?(b+="TODO: ",h=f.ErrorType.Author):u?b+="WARNING: ":b+="ERROR: ",v&&v.debugMetadata!==null&&v.debugMetadata.startLineNumber>=1&&(v.debugMetadata.fileName!=null&&(b+=`'${v.debugMetadata.fileName}' `),b+=`line ${v.debugMetadata.startLineNumber}: `),b+=g,g=b,this._errorHandler!==null)this._errorHandler(g,h);else throw new Error(g);this._hadError=h===f.ErrorType.Error,this._hadWarning=h===f.ErrorType.Warning},this.ResetError=()=>{this._hadError=!1,this._hadWarning=!1},this.IsExternal=g=>this.externals.has(g),this.AddExternal=g=>{this.externals.has(g.name)?this.Error(`Duplicate EXTERNAL definition of '${g.name}'`,g,!1):g.name&&this.externals.set(g.name,g)},this.DontFlattenContainer=g=>{this._dontFlattenContainers.add(g)},this.NameConflictError=(g,v,u,h)=>{g.Error(`${h} '${v}': name has already been used for a ${u.typeName.toLowerCase()} on ${u.debugMetadata}`)},this.CheckForNamingCollisions=(g,v,u,h="")=>{var b;const R=h||g.typeName;if(w.IsReservedKeyword(v==null?void 0:v.name)){g.Error(`'${v}' cannot be used for the name of a ${R.toLowerCase()} because it's a reserved keyword`);return}else if(O.FunctionCall.IsBuiltIn((v==null?void 0:v.name)||"")){g.Error(`'${v}' cannot be used for the name of a ${R.toLowerCase()} because it's a built in function`);return}const V=this.ContentWithNameAtLevel((v==null?void 0:v.name)||"",p.FlowLevel.Knot),j=(0,P.asOrNull)(V,t.FlowBase);if(j&&(j!==g||u===i.SymbolType.Arg)){this.NameConflictError(g,(v==null?void 0:v.name)||"",j,R);return}if(u<i.SymbolType.List)return;for(const[x,A]of this._listDefs)if((v==null?void 0:v.name)===x&&g!==A&&A.variableAssignment!==g&&this.NameConflictError(g,v==null?void 0:v.name,A,R),!(g instanceof s.ListElementDefinition))for(const W of A.itemDefinitions)(v==null?void 0:v.name)===W.name&&this.NameConflictError(g,(v==null?void 0:v.name)||"",W,R);if(u<=i.SymbolType.Var)return;const L=(v==null?void 0:v.name)&&this.variableDeclarations.get(v==null?void 0:v.name)||null;if(L&&L!==g&&L.isGlobalDeclaration&&L.listDefinition==null&&this.NameConflictError(g,(v==null?void 0:v.name)||"",L,R),u<i.SymbolType.SubFlowAndWeave)return;const E=new I.Path(v).ResolveFromContext(g);if(E&&E!==g){this.NameConflictError(g,(v==null?void 0:v.name)||"",E,R);return}if(!(u<i.SymbolType.Arg)&&u!==i.SymbolType.Arg){let x=(0,P.asOrNull)(g,t.FlowBase);if(x||(x=(0,N.ClosestFlowBase)(g)),x&&x.hasParameters&&x.args){for(const A of x.args)if(((b=A.identifier)===null||b===void 0?void 0:b.name)===(v==null?void 0:v.name)){g.Error(`${R} '${v}': name has already been used for a argument to ${x.identifier} on ${x.debugMetadata}`);return}}}}}get typeName(){return"Story"}PreProcessTopLevelObjects(k){super.PreProcessTopLevelObjects(k);const m=[];for(let g of k)if(g instanceof r.IncludedFile){const v=g,u=k.indexOf(g);if(k.splice(u,1),v.includedStory){const h=[],b=v.includedStory;if(b.content!=null){for(const R of b.content)R instanceof t.FlowBase?m.push(R):h.push(R);h.push(new l.Text(`
|
|
29
|
-
`)),k.splice(u,0,...h)}}continue}k.splice(0,0,...m)}}return
|
|
30
|
-
\r`);return _?new n.AuthorWarning(_):null},this.ExtendIdentifierCharacterRanges=d=>{const _=Ei.ListAllCharacterRanges();for(const T of _)d.AddCharacters(T.ToCharacterSet())},this._parsingChoice=!1,this.Choice=()=>{let d=!0,_=this.Interleave(this.OptionalExclude(this.Whitespace),this.String("*"));if(!_){if(_=this.Interleave(this.OptionalExclude(this.Whitespace),this.String("+")),_===null)return null;d=!1}const T=this.Parse(this.BracketedName);this.Whitespace(),T!=null&&this.Newline();const D=this.Parse(this.ChoiceCondition);if(this.Whitespace(),this._parsingChoice)throw new Error("Already parsing a choice - shouldn't have nested choices");this._parsingChoice=!0;let U=null;const $=this.Parse(this.MixedTextAndLogic);$&&(U=new s.ContentList($));let J=null,X=null;const Tt=this.ParseString("[")!==null;if(Tt){this.EndTagIfNecessary(U);const
|
|
26
|
+
`)),V<h.length-1)){let x=h.length-V-1,A=new a.StringValue(h.substring(V+1,V+1+x));L.push(A)}return L}PushToOutputStreamIndividual(u){let h=(0,P.asOrNull)(u,t.Glue),b=(0,P.asOrNull)(u,a.StringValue),R=!0;if(h)this.TrimNewlinesFromOutputStream(),R=!0;else if(b){let V=-1,j=this.callStack.currentElement;j.type==e.PushPopType.Function&&(V=j.functionStartInOutputStream);let L=-1;for(let E=this.outputStream.length-1;E>=0;E--){let x=this.outputStream[E],A=x instanceof r.ControlCommand?x:null;if((x instanceof t.Glue?x:null)!=null){L=E;break}else if(A!=null&&A.commandType==r.ControlCommand.CommandType.BeginString){E>=V&&(V=-1);break}}let C=-1;if(L!=-1&&V!=-1?C=Math.min(V,L):L!=-1?C=L:C=V,C!=-1){if(b.isNewline)R=!1;else if(b.isNonWhitespace&&(L>-1&&this.RemoveExistingGlue(),V>-1)){let E=this.callStack.elements;for(let x=E.length-1;x>=0;x--){let A=E[x];if(A.type==e.PushPopType.Function)A.functionStartInOutputStream=-1;else break}}}else b.isNewline&&(this.outputStreamEndsInNewline||!this.outputStreamContainsContent)&&(R=!1)}if(R){if(u===null)return(0,O.throwNullException)("obj");this.outputStream.push(u),this.OutputStreamDirty()}}TrimNewlinesFromOutputStream(){let u=-1,h=this.outputStream.length-1;for(;h>=0;){let b=this.outputStream[h],R=(0,P.asOrNull)(b,r.ControlCommand),V=(0,P.asOrNull)(b,a.StringValue);if(R!=null||V!=null&&V.isNonWhitespace)break;V!=null&&V.isNewline&&(u=h),h--}if(u>=0)for(h=u;h<this.outputStream.length;)(0,P.asOrNull)(this.outputStream[h],a.StringValue)?this.outputStream.splice(h,1):h++;this.OutputStreamDirty()}RemoveExistingGlue(){for(let u=this.outputStream.length-1;u>=0;u--){let h=this.outputStream[u];if(h instanceof t.Glue)this.outputStream.splice(u,1);else if(h instanceof r.ControlCommand)break}this.OutputStreamDirty()}get outputStreamEndsInNewline(){if(this.outputStream.length>0)for(let u=this.outputStream.length-1;u>=0&&!(this.outputStream[u]instanceof r.ControlCommand);u--){let b=this.outputStream[u];if(b instanceof a.StringValue){if(b.isNewline)return!0;if(b.isNonWhitespace)break}}return!1}get outputStreamContainsContent(){for(let u of this.outputStream)if(u instanceof a.StringValue)return!0;return!1}get inStringEvaluation(){for(let u=this.outputStream.length-1;u>=0;u--){let h=(0,P.asOrNull)(this.outputStream[u],r.ControlCommand);if(h instanceof r.ControlCommand&&h.commandType==r.ControlCommand.CommandType.BeginString)return!0}return!1}PushEvaluationStack(u){let h=(0,P.asOrNull)(u,a.ListValue);if(h){let b=h.value;if(b===null)return(0,O.throwNullException)("rawList");if(b.originNames!=null){b.origins||(b.origins=[]),b.origins.length=0;for(let R of b.originNames){if(this.story.listDefinitions===null)return(0,O.throwNullException)("StoryState.story.listDefinitions");let V=this.story.listDefinitions.TryListGetDefinition(R,null);if(V.result===null)return(0,O.throwNullException)("StoryState def.result");b.origins.indexOf(V.result)<0&&b.origins.push(V.result)}}}if(u===null)return(0,O.throwNullException)("obj");this.evaluationStack.push(u)}PopEvaluationStack(u){if(typeof u>"u"){let h=this.evaluationStack.pop();return(0,P.nullIfUndefined)(h)}else{if(u>this.evaluationStack.length)throw new Error("trying to pop too many objects");let h=this.evaluationStack.splice(this.evaluationStack.length-u,u);return(0,P.nullIfUndefined)(h)}}PeekEvaluationStack(){return this.evaluationStack[this.evaluationStack.length-1]}ForceEnd(){this.callStack.Reset(),this._currentFlow.currentChoices.length=0,this.currentPointer=l.Pointer.Null,this.previousPointer=l.Pointer.Null,this.didSafeExit=!0}TrimWhitespaceFromFunctionEnd(){N.Debug.Assert(this.callStack.currentElement.type==e.PushPopType.Function);let u=this.callStack.currentElement.functionStartInOutputStream;u==-1&&(u=0);for(let h=this.outputStream.length-1;h>=u;h--){let b=this.outputStream[h],R=(0,P.asOrNull)(b,a.StringValue),V=(0,P.asOrNull)(b,r.ControlCommand);if(R!=null){if(V)break;if(R.isNewline||R.isInlineWhitespace)this.outputStream.splice(h,1),this.OutputStreamDirty();else break}}}PopCallStack(u=null){this.callStack.currentElement.type==e.PushPopType.Function&&this.TrimWhitespaceFromFunctionEnd(),this.callStack.Pop(u)}SetChosenPath(u,h){this._currentFlow.currentChoices.length=0;let b=this.story.PointerAtPath(u);!b.isNull&&b.index==-1&&(b.index=0),this.currentPointer=b,h&&this.currentTurnIndex++}StartFunctionEvaluationFromGame(u,h){this.callStack.Push(e.PushPopType.FunctionEvaluationFromGame,this.evaluationStack.length),this.callStack.currentElement.currentPointer=l.Pointer.StartOf(u),this.PassArgumentsToEvaluationStack(h)}PassArgumentsToEvaluationStack(u){if(u!==null)for(let h=0;h<u.length;h++){if(!(typeof u[h]=="number"||typeof u[h]=="string"||typeof u[h]=="boolean"||u[h]instanceof m.InkList))throw new Error("ink arguments when calling EvaluateFunction / ChoosePathStringWithParameters must benumber, string, bool or InkList. Argument was "+((0,P.nullIfUndefined)(u[h])===null?"null":u[h].constructor.name));this.PushEvaluationStack(a.Value.Create(u[h]))}}TryExitFunctionEvaluationFromGame(){return this.callStack.currentElement.type==e.PushPopType.FunctionEvaluationFromGame?(this.currentPointer=l.Pointer.Null,this.didSafeExit=!0,!0):!1}CompleteFunctionEvaluationFromGame(){if(this.callStack.currentElement.type!=e.PushPopType.FunctionEvaluationFromGame)throw new Error("Expected external function evaluation to be complete. Stack trace: "+this.callStack.callStackTrace);let u=this.callStack.currentElement.evaluationStackHeightWhenPushed,h=null;for(;this.evaluationStack.length>u;){let b=this.PopEvaluationStack();h===null&&(h=b)}if(this.PopCallStack(e.PushPopType.FunctionEvaluationFromGame),h){if(h instanceof i.Void)return null;let b=(0,P.asOrThrows)(h,a.Value);return b.valueType==a.ValueType.DivertTarget?"-> "+b.valueObject.toString():b.valueObject}return null}AddError(u,h){h?(this._currentWarnings==null&&(this._currentWarnings=[]),this._currentWarnings.push(u)):(this._currentErrors==null&&(this._currentErrors=[]),this._currentErrors.push(u))}OutputStreamDirty(){this._outputStreamTextDirty=!0,this._outputStreamTagsDirty=!0}};return Nn.StoryState=g,Nn}var kn={},_s;function Ga(){if(_s)return kn;_s=1,Object.defineProperty(kn,"__esModule",{value:!0}),kn.Stopwatch=void 0;class o{constructor(){this.startTime=void 0}get ElapsedMilliseconds(){return typeof this.startTime>"u"?0:new Date().getTime()-this.startTime}Start(){this.startTime=new Date().getTime()}Stop(){this.startTime=void 0}}return kn.Stopwatch=o,kn}var Dn={},Es;function $a(){if(Es)return Dn;Es=1,Object.defineProperty(Dn,"__esModule",{value:!0}),Dn.ErrorType=void 0;var o;return(function(n){n[n.Author=0]="Author",n[n.Warning=1]="Warning",n[n.Error=2]="Error"})(o||(Dn.ErrorType=o={})),Dn}var ws;function ci(){return ws||(ws=1,(function(o){Object.defineProperty(o,"__esModule",{value:!0}),o.Story=o.InkList=void 0;const n=ot(),a=yt(),e=Xn(),f=qa(),t=pt(),p=te(),r=Ni(),y=oa(),s=Rt(),c=it(),i=St(),l=Qt(),S=Vi(),P=Gt(),N=Hn(),O=Ft(),I=si(),w=ca(),F=Zt(),k=la(),m=Ga(),g=oi(),v=vt(),u=Z(),h=ft(),b=da(),R=$a();var V=vt();Object.defineProperty(o,"InkList",{enumerable:!0,get:function(){return V.InkList}}),Number.isInteger||(Number.isInteger=function(C){return typeof C=="number"&&isFinite(C)&&C>-9007199254740992&&C<9007199254740992&&Math.floor(C)===C});class j extends a.InkObject{get currentChoices(){let C=[];if(this._state===null)return(0,h.throwNullException)("this._state");for(let E of this._state.currentChoices)E.isInvisibleDefault||(E.index=C.length,C.push(E));return C}get currentText(){return this.IfAsyncWeCant("call currentText since it's a work in progress"),this.state.currentText}get currentTags(){return this.IfAsyncWeCant("call currentTags since it's a work in progress"),this.state.currentTags}get currentErrors(){return this.state.currentErrors}get currentWarnings(){return this.state.currentWarnings}get currentFlowName(){return this.state.currentFlowName}get currentFlowIsDefaultFlow(){return this.state.currentFlowIsDefaultFlow}get aliveFlowNames(){return this.state.aliveFlowNames}get hasError(){return this.state.hasError}get hasWarning(){return this.state.hasWarning}get variablesState(){return this.state.variablesState}get listDefinitions(){return this._listDefinitions}get state(){return this._state}StartProfiling(){}EndProfiling(){}constructor(){super(),this.inkVersionMinimumCompatible=18,this.onError=null,this.onDidContinue=null,this.onMakeChoice=null,this.onEvaluateFunction=null,this.onCompleteEvaluateFunction=null,this.onChoosePathString=null,this._prevContainers=[],this.allowExternalFunctionFallbacks=!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 C,E=null,x=null;if(arguments[0]instanceof n.Container)C=arguments[0],typeof arguments[1]<"u"&&(E=arguments[1]),this._mainContentContainer=C;else if(typeof arguments[0]=="string"){let A=arguments[0];x=b.SimpleJson.TextToDictionary(A)}else x=arguments[0];if(E!=null&&(this._listDefinitions=new k.ListDefinitionsOrigin(E)),this._externals=new Map,x!==null){let A=x,W=A.inkVersion;if(W==null)throw new Error("ink version number not found. Are you sure it's a valid .ink.json file?");let M=parseInt(W);if(M>j.inkVersionCurrent)throw new Error("Version of ink used to build story was newer than the current version of the engine");if(M<this.inkVersionMinimumCompatible)throw new Error("Version of ink used to build story is too old to be loaded by this version of the engine");M!=j.inkVersionCurrent&&console.warn(`WARNING: Version of ink ${j.inkVersionCurrent} used to build story doesn't match current version of engine (${M}). Non-critical, but recommend synchronising.`);let G=A.root;if(G==null)throw new Error("Root node for ink not found. Are you sure it's a valid .ink.json file?");let H;(H=A.listDefs)&&(this._listDefinitions=e.JsonSerialisation.JTokenToListDefinitions(H)),this._mainContentContainer=(0,u.asOrThrows)(e.JsonSerialisation.JTokenToRuntimeObject(G),n.Container),this.ResetState()}}ToJson(C){let E=!1;if(C||(E=!0,C=new b.SimpleJson.Writer),C.WriteObjectStart(),C.WriteIntProperty("inkVersion",j.inkVersionCurrent),C.WriteProperty("root",x=>e.JsonSerialisation.WriteRuntimeContainer(x,this._mainContentContainer)),this._listDefinitions!=null){C.WritePropertyStart("listDefs"),C.WriteObjectStart();for(let x of this._listDefinitions.lists){C.WritePropertyStart(x.name),C.WriteObjectStart();for(let[A,W]of x.items){let M=v.InkListItem.fromSerializedKey(A),G=W;C.WriteIntProperty(M.itemName,G)}C.WriteObjectEnd(),C.WritePropertyEnd()}C.WriteObjectEnd(),C.WritePropertyEnd()}if(C.WriteObjectEnd(),E)return C.toString()}ResetState(){this.IfAsyncWeCant("ResetState"),this._state=new f.StoryState(this),this._state.variablesState.ObserveVariableChange(this.VariableStateDidChangeEvent.bind(this)),this.ResetGlobals()}ResetErrors(){if(this._state===null)return(0,h.throwNullException)("this._state");this._state.ResetErrors()}ResetCallstack(){if(this.IfAsyncWeCant("ResetCallstack"),this._state===null)return(0,h.throwNullException)("this._state");this._state.ForceEnd()}ResetGlobals(){if(this._mainContentContainer.namedContent.get("global decl")){let C=this.state.currentPointer.copy();this.ChoosePath(new i.Path("global decl"),!1),this.ContinueInternal(),this.state.currentPointer=C}this.state.variablesState.SnapshotDefaultGlobals()}SwitchFlow(C){if(this.IfAsyncWeCant("switch flow"),this._asyncSaving)throw new Error("Story is already in background saving mode, can't switch flow to "+C);this.state.SwitchFlow_Internal(C)}RemoveFlow(C){this.state.RemoveFlow_Internal(C)}SwitchToDefaultFlow(){this.state.SwitchToDefaultFlow_Internal()}Continue(){return this.ContinueAsync(0),this.currentText}get canContinue(){return this.state.canContinue}get asyncContinueComplete(){return!this._asyncContinueActive}ContinueAsync(C){this._hasValidatedExternals||this.ValidateExternalBindings(),this.ContinueInternal(C)}ContinueInternal(C=0){this._profiler!=null&&this._profiler.PreContinue();let E=C>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(),this._recursiveContinueCount==1&&this._state.variablesState.StartVariableObservation()}let x=new m.Stopwatch;x.Start();let A=!1;this._sawLookaheadUnsafeFunctionAfterNewline=!1;do{try{A=this.ContinueSingleStep()}catch(M){if(!(M instanceof I.StoryException))throw M;this.AddError(M.message,void 0,M.useEndLineNumber);break}if(A||this._asyncContinueActive&&x.ElapsedMilliseconds>C)break}while(this.canContinue);x.Stop();let W=null;if((A||!this.canContinue)&&(this._stateSnapshotAtLastNewline!==null&&this.RestoreStateSnapshot(),this.canContinue||(this.state.callStack.canPopThread&&this.AddError("Thread available to pop, threads should always be flat by the end of evaluation?"),this.state.generatedChoices.length==0&&!this.state.didSafeExit&&this._temporaryEvaluationContainer==null&&(this.state.callStack.CanPop(p.PushPopType.Tunnel)?this.AddError("unexpectedly reached end of content. Do you need a '->->' to return from a tunnel?"):this.state.callStack.CanPop(p.PushPopType.Function)?this.AddError("unexpectedly reached end of content. Do you need a '~ return'?"):this.state.callStack.canPop?this.AddError("unexpectedly reached end of content for unknown reason. Please debug compiler!"):this.AddError("ran out of content. Do you need a '-> DONE' or '-> END'?"))),this.state.didSafeExit=!1,this._sawLookaheadUnsafeFunctionAfterNewline=!1,this._recursiveContinueCount==1&&(W=this._state.variablesState.CompleteVariableObservation()),this._asyncContinueActive=!1,this.onDidContinue!==null&&this.onDidContinue()),this._recursiveContinueCount--,this._profiler!=null&&this._profiler.PostContinue(),this.state.hasError||this.state.hasWarning)if(this.onError!==null){if(this.state.hasError)for(let M of this.state.currentErrors)this.onError(M,R.ErrorType.Error);if(this.state.hasWarning)for(let M of this.state.currentWarnings)this.onError(M,R.ErrorType.Warning);this.ResetErrors()}else{let M=new F.StringBuilder;throw M.Append("Ink had "),this.state.hasError&&(M.Append(`${this.state.currentErrors.length}`),M.Append(this.state.currentErrors.length==1?" error":" errors"),this.state.hasWarning&&M.Append(" and ")),this.state.hasWarning&&(M.Append(`${this.state.currentWarnings.length}`),M.Append(this.state.currentWarnings.length==1?" warning":" warnings"),this.state.hasWarning&&M.Append(" and ")),M.Append(". It is strongly suggested that you assign an error handler to story.onError. The first issue was: "),M.Append(this.state.hasError?this.state.currentErrors[0]:this.state.currentWarnings[0]),new I.StoryException(M.toString())}W!=null&&Object.keys(W).length>0&&this._state.variablesState.NotifyObservers(W)}ContinueSingleStep(){if(this._profiler!=null&&this._profiler.PreStep(),this.Step(),this._profiler!=null&&this._profiler.PostStep(),!this.canContinue&&!this.state.callStack.elementIsEvaluateFromGame&&this.TryFollowDefaultInvisibleChoice(),this._profiler!=null&&this._profiler.PreSnapshot(),!this.state.inStringEvaluation){if(this._stateSnapshotAtLastNewline!==null){if(this._stateSnapshotAtLastNewline.currentTags===null)return(0,h.throwNullException)("this._stateAtLastNewline.currentTags");if(this.state.currentTags===null)return(0,h.throwNullException)("this.state.currentTags");let C=this.CalculateNewlineOutputStateChange(this._stateSnapshotAtLastNewline.currentText,this.state.currentText,this._stateSnapshotAtLastNewline.currentTags.length,this.state.currentTags.length);if(C==j.OutputStateChange.ExtendedBeyondNewline||this._sawLookaheadUnsafeFunctionAfterNewline)return this.RestoreStateSnapshot(),!0;C==j.OutputStateChange.NewlineRemoved&&this.DiscardSnapshot()}this.state.outputStreamEndsInNewline&&(this.canContinue?this._stateSnapshotAtLastNewline==null&&this.StateSnapshot():this.DiscardSnapshot())}return this._profiler!=null&&this._profiler.PostSnapshot(),!1}CalculateNewlineOutputStateChange(C,E,x,A){if(C===null)return(0,h.throwNullException)("prevText");if(E===null)return(0,h.throwNullException)("currText");let W=E.length>=C.length&&C.length>0&&E.charAt(C.length-1)==`
|
|
27
|
+
`;if(x==A&&C.length==E.length&&W)return j.OutputStateChange.NoChange;if(!W)return j.OutputStateChange.NewlineRemoved;if(A>x)return j.OutputStateChange.ExtendedBeyondNewline;for(let M=C.length;M<E.length;M++){let G=E.charAt(M);if(G!=" "&&G!=" ")return j.OutputStateChange.ExtendedBeyondNewline}return j.OutputStateChange.NoChange}ContinueMaximally(){this.IfAsyncWeCant("ContinueMaximally");let C=new F.StringBuilder;for(;this.canContinue;)C.Append(this.Continue());return C.toString()}ContentAtPath(C){return this.mainContentContainer.ContentAtPath(C)}KnotContainerWithName(C){let E=this.mainContentContainer.namedContent.get(C);return E instanceof n.Container?E:null}PointerAtPath(C){if(C.length==0)return g.Pointer.Null;let E=new g.Pointer,x=C.length,A=null;return C.lastComponent===null?(0,h.throwNullException)("path.lastComponent"):(C.lastComponent.isIndex?(x=C.length-1,A=this.mainContentContainer.ContentAtPath(C,void 0,x),E.container=A.container,E.index=C.lastComponent.index):(A=this.mainContentContainer.ContentAtPath(C),E.container=A.container,E.index=-1),A.obj==null||A.obj==this.mainContentContainer&&x>0?this.Error("Failed to find content at path '"+C+"', and no approximation of it was possible."):A.approximate&&this.Warning("Failed to find content at path '"+C+"', so it was approximated to: '"+A.obj.path+"'."),E)}StateSnapshot(){this._stateSnapshotAtLastNewline=this._state,this._state=this._state.CopyAndStartPatching(!1)}RestoreStateSnapshot(){this._stateSnapshotAtLastNewline===null&&(0,h.throwNullException)("_stateSnapshotAtLastNewline"),this._stateSnapshotAtLastNewline.RestoreAfterPatch(),this._state=this._stateSnapshotAtLastNewline,this._stateSnapshotAtLastNewline=null,this._asyncSaving||this._state.ApplyAnyPatch()}DiscardSnapshot(){this._asyncSaving||this._state.ApplyAnyPatch(),this._stateSnapshotAtLastNewline=null}CopyStateForBackgroundThreadSave(){if(this.IfAsyncWeCant("start saving on a background thread"),this._asyncSaving)throw new Error("Story is already in background saving mode, can't call CopyStateForBackgroundThreadSave again!");let C=this._state;return this._state=this._state.CopyAndStartPatching(!0),this._asyncSaving=!0,C}BackgroundSaveComplete(){this._stateSnapshotAtLastNewline===null&&this._state.ApplyAnyPatch(),this._asyncSaving=!1}Step(){let C=!0,E=this.state.currentPointer.copy();if(E.isNull)return;let x=(0,u.asOrNull)(E.Resolve(),n.Container);for(;x&&(this.VisitContainer(x,!0),x.content.length!=0);)E=g.Pointer.StartOf(x),x=(0,u.asOrNull)(E.Resolve(),n.Container);this.state.currentPointer=E.copy(),this._profiler!=null&&this._profiler.Step(this.state.callStack);let A=E.Resolve(),W=this.PerformLogicAndFlowControl(A);if(this.state.currentPointer.isNull)return;W&&(C=!1);let M=(0,u.asOrNull)(A,r.ChoicePoint);if(M){let H=this.ProcessChoice(M);H&&this.state.generatedChoices.push(H),A=null,C=!1}if(A instanceof n.Container&&(C=!1),C){let H=(0,u.asOrNull)(A,c.VariablePointerValue);if(H&&H.contextIndex==-1){let Q=this.state.callStack.ContextForVariableNamed(H.variableName);A=new c.VariablePointerValue(H.variableName,Q)}this.state.inExpressionEvaluation?this.state.PushEvaluationStack(A):this.state.PushToOutputStream(A)}this.NextContent();let G=(0,u.asOrNull)(A,t.ControlCommand);G&&G.commandType==t.ControlCommand.CommandType.StartThread&&this.state.callStack.PushThread()}VisitContainer(C,E){(!C.countingAtStartOnly||E)&&(C.visitsShouldBeCounted&&this.state.IncrementVisitCountForContainer(C),C.turnIndexShouldBeCounted&&this.state.RecordTurnIndexVisitToContainer(C))}VisitChangedContainersDueToDivert(){let C=this.state.previousPointer.copy(),E=this.state.currentPointer.copy();if(E.isNull||E.index==-1)return;if(this._prevContainers.length=0,!C.isNull){let M=C.Resolve(),G=(0,u.asOrNull)(M,n.Container)||(0,u.asOrNull)(C.container,n.Container);for(;G;)this._prevContainers.push(G),G=(0,u.asOrNull)(G.parent,n.Container)}let x=E.Resolve();if(x==null)return;let A=(0,u.asOrNull)(x.parent,n.Container),W=!0;for(;A&&(this._prevContainers.indexOf(A)<0||A.countingAtStartOnly);){let M=A.content.length>0&&x==A.content[0]&&W;M||(W=!1),this.VisitContainer(A,M),x=A,A=(0,u.asOrNull)(A.parent,n.Container)}}PopChoiceStringAndTags(C){let E=(0,u.asOrThrows)(this.state.PopEvaluationStack(),c.StringValue);for(;this.state.evaluationStack.length>0&&(0,u.asOrNull)(this.state.PeekEvaluationStack(),S.Tag)!=null;){let x=(0,u.asOrNull)(this.state.PopEvaluationStack(),S.Tag);x&&C.push(x.text)}return E.value}ProcessChoice(C){let E=!0;if(C.hasCondition){let G=this.state.PopEvaluationStack();this.IsTruthy(G)||(E=!1)}let x="",A="",W=[];if(C.hasChoiceOnlyContent&&(A=this.PopChoiceStringAndTags(W)||""),C.hasStartContent&&(x=this.PopChoiceStringAndTags(W)||""),C.onceOnly&&this.state.VisitCountForContainer(C.choiceTarget)>0&&(E=!1),!E)return null;let M=new y.Choice;return M.targetPath=C.pathOnChoice,M.sourcePath=C.path.toString(),M.isInvisibleDefault=C.isInvisibleDefault,M.threadAtGeneration=this.state.callStack.ForkThread(),M.tags=W.reverse(),M.text=(x+A).replace(/^[ \t]+|[ \t]+$/g,""),M}IsTruthy(C){let E=!1;if(C instanceof c.Value){let x=C;if(x instanceof c.DivertTargetValue){let A=x;return this.Error("Shouldn't use a divert target (to "+A.targetPath+") as a conditional value. Did you intend a function call 'likeThis()' or a read count check 'likeThis'? (no arrows)"),!1}return x.isTruthy}return E}PerformLogicAndFlowControl(C){if(C==null)return!1;if(C instanceof s.Divert){let E=C;if(E.isConditional){let x=this.state.PopEvaluationStack();if(!this.IsTruthy(x))return!0}if(E.hasVariableTarget){let x=E.variableDivertName,A=this.state.variablesState.GetVariableWithName(x);if(A==null)this.Error("Tried to divert using a target from a variable that could not be found ("+x+")");else if(!(A instanceof c.DivertTargetValue)){let M=(0,u.asOrNull)(A,c.IntValue),G="Tried to divert to a target from a variable, but the variable ("+x+") didn't contain a divert target, it ";M instanceof c.IntValue&&M.value==0?G+="was empty/null (the value 0).":G+="contained '"+A+"'.",this.Error(G)}let W=(0,u.asOrThrows)(A,c.DivertTargetValue);this.state.divertedPointer=this.PointerAtPath(W.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&&E.debugMetadata.sourceName!=null?this.Error("Divert target doesn't exist: "+E.debugMetadata.sourceName):this.Error("Divert resolution failed: "+E)),!0}else if(C instanceof t.ControlCommand){let E=C;switch(E.commandType){case t.ControlCommand.CommandType.EvalStart:this.Assert(this.state.inExpressionEvaluation===!1,"Already in expression evaluation?"),this.state.inExpressionEvaluation=!0;break;case t.ControlCommand.CommandType.EvalEnd:this.Assert(this.state.inExpressionEvaluation===!0,"Not in expression evaluation mode"),this.state.inExpressionEvaluation=!1;break;case t.ControlCommand.CommandType.EvalOutput:if(this.state.evaluationStack.length>0){let B=this.state.PopEvaluationStack();if(!(B instanceof l.Void)){let nt=new c.StringValue(B.toString());this.state.PushToOutputStream(nt)}}break;case t.ControlCommand.CommandType.NoOp:break;case t.ControlCommand.CommandType.Duplicate:this.state.PushEvaluationStack(this.state.PeekEvaluationStack());break;case t.ControlCommand.CommandType.PopEvaluatedValue:this.state.PopEvaluationStack();break;case t.ControlCommand.CommandType.PopFunction:case t.ControlCommand.CommandType.PopTunnel:let x=E.commandType==t.ControlCommand.CommandType.PopFunction?p.PushPopType.Function:p.PushPopType.Tunnel,A=null;if(x==p.PushPopType.Tunnel){let B=this.state.PopEvaluationStack();A=(0,u.asOrNull)(B,c.DivertTargetValue),A===null&&this.Assert(B instanceof l.Void,"Expected void if ->-> doesn't override target")}if(this.state.TryExitFunctionEvaluationFromGame())break;if(this.state.callStack.currentElement.type!=x||!this.state.callStack.canPop){let B=new Map;B.set(p.PushPopType.Function,"function return statement (~ return)"),B.set(p.PushPopType.Tunnel,"tunnel onwards statement (->->)");let nt=B.get(this.state.callStack.currentElement.type);this.state.callStack.canPop||(nt="end of flow (-> END or choice)");let K="Found "+B.get(x)+", when expected "+nt;this.Error(K)}else this.state.PopCallStack(),A&&(this.state.divertedPointer=this.PointerAtPath(A.targetPath));break;case t.ControlCommand.CommandType.BeginString:this.state.PushToOutputStream(E),this.Assert(this.state.inExpressionEvaluation===!0,"Expected to be in an expression when evaluating a string"),this.state.inExpressionEvaluation=!1;break;case t.ControlCommand.CommandType.BeginTag:this.state.PushToOutputStream(E);break;case t.ControlCommand.CommandType.EndTag:{if(this.state.inStringEvaluation){let B=[],nt=0;for(let ht=this.state.outputStream.length-1;ht>=0;--ht){let lt=this.state.outputStream[ht];nt++;let bt=(0,u.asOrNull)(lt,t.ControlCommand);if(bt!=null){if(bt.commandType==t.ControlCommand.CommandType.BeginTag)break;this.Error("Unexpected ControlCommand while extracting tag from choice");break}lt instanceof c.StringValue&&B.push(lt)}this.state.PopFromOutputStream(nt);let K=new F.StringBuilder;for(let ht of B.reverse())K.Append(ht.toString());let wt=new S.Tag(this.state.CleanOutputWhitespace(K.toString()));this.state.PushEvaluationStack(wt)}else this.state.PushToOutputStream(E);break}case t.ControlCommand.CommandType.EndString:{let B=[],nt=[],K=0;for(let ht=this.state.outputStream.length-1;ht>=0;--ht){let lt=this.state.outputStream[ht];K++;let bt=(0,u.asOrNull)(lt,t.ControlCommand);if(bt&&bt.commandType==t.ControlCommand.CommandType.BeginString)break;lt instanceof S.Tag&&nt.push(lt),lt instanceof c.StringValue&&B.push(lt)}this.state.PopFromOutputStream(K);for(let ht of nt)this.state.PushToOutputStream(ht);B=B.reverse();let wt=new F.StringBuilder;for(let ht of B)wt.Append(ht.toString());this.state.inExpressionEvaluation=!0,this.state.PushEvaluationStack(new c.StringValue(wt.toString()));break}case t.ControlCommand.CommandType.ChoiceCount:let W=this.state.generatedChoices.length;this.state.PushEvaluationStack(new c.IntValue(W));break;case t.ControlCommand.CommandType.Turns:this.state.PushEvaluationStack(new c.IntValue(this.state.currentTurnIndex+1));break;case t.ControlCommand.CommandType.TurnsSince:case t.ControlCommand.CommandType.ReadCount:let M=this.state.PopEvaluationStack();if(!(M instanceof c.DivertTargetValue)){let B="";M instanceof c.IntValue&&(B=". 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 "+M+B);break}let G=(0,u.asOrThrows)(M,c.DivertTargetValue),H=(0,u.asOrNull)(this.ContentAtPath(G.targetPath).correctObj,n.Container),Q;H!=null?E.commandType==t.ControlCommand.CommandType.TurnsSince?Q=this.state.TurnsSinceForContainer(H):Q=this.state.VisitCountForContainer(H):(E.commandType==t.ControlCommand.CommandType.TurnsSince?Q=-1:Q=0,this.Warning("Failed to find container for "+E.toString()+" lookup at "+G.targetPath.toString())),this.state.PushEvaluationStack(new c.IntValue(Q));break;case t.ControlCommand.CommandType.Random:{let B=(0,u.asOrNull)(this.state.PopEvaluationStack(),c.IntValue),nt=(0,u.asOrNull)(this.state.PopEvaluationStack(),c.IntValue);if(nt==null||!(nt instanceof c.IntValue))return this.Error("Invalid value for minimum parameter of RANDOM(min, max)");if(B==null||!(B instanceof c.IntValue))return this.Error("Invalid value for maximum parameter of RANDOM(min, max)");if(B.value===null)return(0,h.throwNullException)("maxInt.value");if(nt.value===null)return(0,h.throwNullException)("minInt.value");let K=B.value-nt.value+1;(!isFinite(K)||K>Number.MAX_SAFE_INTEGER)&&(K=Number.MAX_SAFE_INTEGER,this.Error("RANDOM was called with a range that exceeds the size that ink numbers can use.")),K<=0&&this.Error("RANDOM was called with minimum as "+nt.value+" and maximum as "+B.value+". The maximum must be larger");let wt=this.state.storySeed+this.state.previousRandom,lt=new w.PRNG(wt).next(),bt=lt%K+nt.value;this.state.PushEvaluationStack(new c.IntValue(bt)),this.state.previousRandom=lt;break}case t.ControlCommand.CommandType.SeedRandom:let ut=(0,u.asOrNull)(this.state.PopEvaluationStack(),c.IntValue);if(ut==null||!(ut instanceof c.IntValue))return this.Error("Invalid value passed to SEED_RANDOM");if(ut.value===null)return(0,h.throwNullException)("minInt.value");this.state.storySeed=ut.value,this.state.previousRandom=0,this.state.PushEvaluationStack(new l.Void);break;case t.ControlCommand.CommandType.VisitIndex:let Y=this.state.VisitCountForContainer(this.state.currentPointer.container)-1;this.state.PushEvaluationStack(new c.IntValue(Y));break;case t.ControlCommand.CommandType.SequenceShuffleIndex:let mt=this.NextSequenceShuffleIndex();this.state.PushEvaluationStack(new c.IntValue(mt));break;case t.ControlCommand.CommandType.StartThread:break;case t.ControlCommand.CommandType.Done:this.state.callStack.canPopThread?this.state.callStack.PopThread():(this.state.didSafeExit=!0,this.state.currentPointer=g.Pointer.Null);break;case t.ControlCommand.CommandType.End:this.state.ForceEnd();break;case t.ControlCommand.CommandType.ListFromInt:let rt=(0,u.asOrNull)(this.state.PopEvaluationStack(),c.IntValue),_t=(0,u.asOrThrows)(this.state.PopEvaluationStack(),c.StringValue);if(rt===null)throw new I.StoryException("Passed non-integer when creating a list element from a numerical value.");let Dt=null;if(this.listDefinitions===null)return(0,h.throwNullException)("this.listDefinitions");let Et=this.listDefinitions.TryListGetDefinition(_t.value,null);if(Et.exists){if(rt.value===null)return(0,h.throwNullException)("minInt.value");let B=Et.result.TryGetItemWithValue(rt.value,v.InkListItem.Null);B.exists&&(Dt=new c.ListValue(B.result,rt.value))}else throw new I.StoryException("Failed to find LIST called "+_t.value);Dt==null&&(Dt=new c.ListValue),this.state.PushEvaluationStack(Dt);break;case t.ControlCommand.CommandType.ListRange:let Vt=(0,u.asOrNull)(this.state.PopEvaluationStack(),c.Value),xt=(0,u.asOrNull)(this.state.PopEvaluationStack(),c.Value),Ut=(0,u.asOrNull)(this.state.PopEvaluationStack(),c.ListValue);if(Ut===null||xt===null||Vt===null)throw new I.StoryException("Expected list, minimum and maximum for LIST_RANGE");if(Ut.value===null)return(0,h.throwNullException)("targetList.value");let di=Ut.value.ListWithSubRange(xt.valueObject,Vt.valueObject);this.state.PushEvaluationStack(new c.ListValue(di));break;case t.ControlCommand.CommandType.ListRandom:{let B=this.state.PopEvaluationStack();if(B===null)throw new I.StoryException("Expected list for LIST_RANDOM");let nt=B.value,K=null;if(nt===null)throw(0,h.throwNullException)("list");if(nt.Count==0)K=new v.InkList;else{let wt=this.state.storySeed+this.state.previousRandom,lt=new w.PRNG(wt).next(),bt=lt%nt.Count,d=nt.entries();for(let D=0;D<=bt-1;D++)d.next();let _=d.next().value,T={Key:v.InkListItem.fromSerializedKey(_[0]),Value:_[1]};if(T.Key.originName===null)return(0,h.throwNullException)("randomItem.Key.originName");K=new v.InkList(T.Key.originName,this),K.Add(T.Key,T.Value),this.state.previousRandom=lt}this.state.PushEvaluationStack(new c.ListValue(K));break}default:this.Error("unhandled ControlCommand: "+E);break}return!0}else if(C instanceof P.VariableAssignment){let E=C,x=this.state.PopEvaluationStack();return this.state.variablesState.Assign(E,x),!0}else if(C instanceof N.VariableReference){let E=C,x=null;if(E.pathForCount!=null){let A=E.containerForCount,W=this.state.VisitCountForContainer(A);x=new c.IntValue(W)}else x=this.state.variablesState.GetVariableWithName(E.name),x==null&&(this.Warning("Variable not found: '"+E.name+"'. Using default value of 0 (false). This can happen with temporary variables if the declaration hasn't yet been hit. Globals are always given a default value on load if a value doesn't exist in the save state."),x=new c.IntValue(0));return this.state.PushEvaluationStack(x),!0}else if(C instanceof O.NativeFunctionCall){let E=C,x=this.state.PopEvaluationStack(E.numberOfParameters),A=E.Call(x);return this.state.PushEvaluationStack(A),!0}return!1}ChoosePathString(C,E=!0,x=[]){if(this.IfAsyncWeCant("call ChoosePathString right now"),this.onChoosePathString!==null&&this.onChoosePathString(C,x),E)this.ResetCallstack();else if(this.state.callStack.currentElement.type==p.PushPopType.Function){let A="",W=this.state.callStack.currentElement.currentPointer.container;throw W!=null&&(A="("+W.path.toString()+") "),new Error("Story was running a function "+A+"when you called ChoosePathString("+C+`) - this is almost certainly not not what you want! Full stack trace:
|
|
28
|
+
`+this.state.callStack.callStackTrace)}this.state.PassArgumentsToEvaluationStack(x),this.ChoosePath(new i.Path(C))}IfAsyncWeCant(C){if(this._asyncContinueActive)throw new Error("Can't "+C+". Story is in the middle of a ContinueAsync(). Make more ContinueAsync() calls or a single Continue() call beforehand.")}ChoosePath(C,E=!0){this.state.SetChosenPath(C,E),this.VisitChangedContainersDueToDivert()}ChooseChoiceIndex(C){C=C;let E=this.currentChoices;this.Assert(C>=0&&C<E.length,"choice out of range");let x=E[C];if(this.onMakeChoice!==null&&this.onMakeChoice(x),x.threadAtGeneration===null)return(0,h.throwNullException)("choiceToChoose.threadAtGeneration");if(x.targetPath===null)return(0,h.throwNullException)("choiceToChoose.targetPath");this.state.callStack.currentThread=x.threadAtGeneration,this.ChoosePath(x.targetPath)}HasFunction(C){try{return this.KnotContainerWithName(C)!=null}catch{return!1}}EvaluateFunction(C,E=[],x=!1){if(this.onEvaluateFunction!==null&&this.onEvaluateFunction(C,E),this.IfAsyncWeCant("evaluate a function"),C==null)throw new Error("Function is null");if(C==""||C.trim()=="")throw new Error("Function is empty or white space.");let A=this.KnotContainerWithName(C);if(A==null)throw new Error("Function doesn't exist: '"+C+"'");let W=[];W.push(...this.state.outputStream),this._state.ResetOutput(),this.state.StartFunctionEvaluationFromGame(A,E);let M=new F.StringBuilder;for(;this.canContinue;)M.Append(this.Continue());let G=M.toString();this._state.ResetOutput(W);let H=this.state.CompleteFunctionEvaluationFromGame();return this.onCompleteEvaluateFunction!=null&&this.onCompleteEvaluateFunction(C,E,G,H),x?{returned:H,output:G}:H}EvaluateExpression(C){let E=this.state.callStack.elements.length;this.state.callStack.Push(p.PushPopType.Tunnel),this._temporaryEvaluationContainer=C,this.state.GoToStart();let x=this.state.evaluationStack.length;return this.Continue(),this._temporaryEvaluationContainer=null,this.state.callStack.elements.length>E&&this.state.PopCallStack(),this.state.evaluationStack.length>x?this.state.PopEvaluationStack():null}CallExternalFunction(C,E){if(C===null)return(0,h.throwNullException)("funcName");let x=this._externals.get(C),A=null,W=typeof x<"u";if(W&&!x.lookAheadSafe&&this._state.inStringEvaluation&&this.Error("External function "+C+` 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 = `+C+"()"),W&&!x.lookAheadSafe&&this._stateSnapshotAtLastNewline!==null){this._sawLookaheadUnsafeFunctionAfterNewline=!0;return}if(!W)if(this.allowExternalFunctionFallbacks){A=this.KnotContainerWithName(C),this.Assert(A!==null,"Trying to call EXTERNAL function '"+C+"' which has not been bound, and fallback ink function could not be found."),this.state.callStack.Push(p.PushPopType.Function,void 0,this.state.outputStream.length),this.state.divertedPointer=g.Pointer.StartOf(A);return}else this.Assert(!1,"Trying to call EXTERNAL function '"+C+"' which has not been bound (and ink fallbacks disabled).");let M=[];for(let Q=0;Q<E;++Q){let Y=(0,u.asOrThrows)(this.state.PopEvaluationStack(),c.Value).valueObject;M.push(Y)}M.reverse();let G=x.function(M),H=null;G!=null?(H=c.Value.Create(G),this.Assert(H!==null,"Could not create ink value from returned object of type "+typeof G)):H=new l.Void,this.state.PushEvaluationStack(H)}BindExternalFunctionGeneral(C,E,x=!0){this.IfAsyncWeCant("bind an external function"),this.Assert(!this._externals.has(C),"Function '"+C+"' has already been bound."),this._externals.set(C,{function:E,lookAheadSafe:x})}TryCoerce(C){return C}BindExternalFunction(C,E,x=!1){this.Assert(E!=null,"Can't bind a null function"),this.BindExternalFunctionGeneral(C,A=>{this.Assert(A.length>=E.length,"External function expected "+E.length+" arguments");let W=[];for(let M=0,G=A.length;M<G;M++)W[M]=this.TryCoerce(A[M]);return E.apply(null,W)},x)}UnbindExternalFunction(C){this.IfAsyncWeCant("unbind an external a function"),this.Assert(this._externals.has(C),"Function '"+C+"' has not been bound."),this._externals.delete(C)}ValidateExternalBindings(){let C=null,E=null,x=arguments[1]||new Set;if(arguments[0]instanceof n.Container&&(C=arguments[0]),arguments[0]instanceof a.InkObject&&(E=arguments[0]),C===null&&E===null)if(this.ValidateExternalBindings(this._mainContentContainer,x),this._hasValidatedExternals=!0,x.size==0)this._hasValidatedExternals=!0;else{let A="Error: Missing function binding for external";A+=x.size>1?"s":"",A+=": '",A+=Array.from(x).join("', '"),A+="' ",A+=this.allowExternalFunctionFallbacks?", and no fallback ink function found.":" (ink fallbacks disabled)",this.Error(A)}else if(C!=null){for(let A of C.content){let W=A;(W==null||!W.hasValidName)&&this.ValidateExternalBindings(A,x)}for(let[,A]of C.namedContent)this.ValidateExternalBindings((0,u.asOrNull)(A,a.InkObject),x)}else if(E!=null){let A=(0,u.asOrNull)(E,s.Divert);if(A&&A.isExternal){let W=A.targetPathString;if(W===null)return(0,h.throwNullException)("name");this._externals.has(W)||this.allowExternalFunctionFallbacks&&this.mainContentContainer.namedContent.has(W)||x.add(W)}}}ObserveVariable(C,E){if(this.IfAsyncWeCant("observe a new variable"),this._variableObservers===null&&(this._variableObservers=new Map),!this.state.variablesState.GlobalVariableExistsWithName(C))throw new Error("Cannot observe variable '"+C+"' because it wasn't declared in the ink story.");this._variableObservers.has(C)?this._variableObservers.get(C).push(E):this._variableObservers.set(C,[E])}ObserveVariables(C,E){for(let x=0,A=C.length;x<A;x++)this.ObserveVariable(C[x],E[x])}RemoveVariableObserver(C,E){if(this.IfAsyncWeCant("remove a variable observer"),this._variableObservers!==null){if(E!=null){if(this._variableObservers.has(E))if(C!=null){let x=this._variableObservers.get(E);x!=null&&(x.splice(x.indexOf(C),1),x.length===0&&this._variableObservers.delete(E))}else this._variableObservers.delete(E)}else if(C!=null){let x=this._variableObservers.keys();for(let A of x){let W=this._variableObservers.get(A);W!=null&&(W.splice(W.indexOf(C),1),W.length===0&&this._variableObservers.delete(A))}}}}VariableStateDidChangeEvent(C,E){if(this._variableObservers===null)return;let x=this._variableObservers.get(C);if(typeof x<"u"){if(!(E instanceof c.Value))throw new Error("Tried to get the value of a variable that isn't a standard type");let A=(0,u.asOrThrows)(E,c.Value);for(let W of x)W(C,A.valueObject)}}get globalTags(){return this.TagsAtStartOfFlowContainerWithPathString("")}TagsForContentAtPath(C){return this.TagsAtStartOfFlowContainerWithPathString(C)}TagsAtStartOfFlowContainerWithPathString(C){let E=new i.Path(C),x=this.ContentAtPath(E).container;if(x===null)return(0,h.throwNullException)("flowContainer");for(;;){let M=x.content[0];if(M instanceof n.Container)x=M;else break}let A=!1,W=null;for(let M of x.content){let G=(0,u.asOrNull)(M,t.ControlCommand);if(G!=null)G.commandType==t.ControlCommand.CommandType.BeginTag?A=!0:G.commandType==t.ControlCommand.CommandType.EndTag&&(A=!1);else if(A){let H=(0,u.asOrNull)(M,c.StringValue);H!==null?(W===null&&(W=[]),H.value!==null&&W.push(H.value)):this.Error("Tag contained non-text content. Only plain text is allowed when using globalTags or TagsAtContentPath. If you want to evaluate dynamic content, you need to use story.Continue().")}else break}return W}BuildStringOfHierarchy(){let C=new F.StringBuilder;return this.mainContentContainer.BuildStringOfHierarchy(C,0,this.state.currentPointer.Resolve()),C.toString()}BuildStringOfContainer(C){let E=new F.StringBuilder;return C.BuildStringOfHierarchy(E,0,this.state.currentPointer.Resolve()),E.toString()}NextContent(){if(this.state.previousPointer=this.state.currentPointer.copy(),!this.state.divertedPointer.isNull&&(this.state.currentPointer=this.state.divertedPointer.copy(),this.state.divertedPointer=g.Pointer.Null,this.VisitChangedContainersDueToDivert(),!this.state.currentPointer.isNull))return;if(!this.IncrementContentPointer()){let E=!1;this.state.callStack.CanPop(p.PushPopType.Function)?(this.state.PopCallStack(p.PushPopType.Function),this.state.inExpressionEvaluation&&this.state.PushEvaluationStack(new l.Void),E=!0):this.state.callStack.canPopThread?(this.state.callStack.PopThread(),E=!0):this.state.TryExitFunctionEvaluationFromGame(),E&&!this.state.currentPointer.isNull&&this.NextContent()}}IncrementContentPointer(){let C=!0,E=this.state.callStack.currentElement.currentPointer.copy();if(E.index++,E.container===null)return(0,h.throwNullException)("pointer.container");for(;E.index>=E.container.content.length;){C=!1;let x=(0,u.asOrNull)(E.container.parent,n.Container);if(!(x instanceof n.Container))break;let A=x.content.indexOf(E.container);if(A==-1)break;if(E=new g.Pointer(x,A),E.index++,C=!0,E.container===null)return(0,h.throwNullException)("pointer.container")}return C||(E=g.Pointer.Null),this.state.callStack.currentElement.currentPointer=E.copy(),C}TryFollowDefaultInvisibleChoice(){let C=this._state.currentChoices,E=C.filter(A=>A.isInvisibleDefault);if(E.length==0||C.length>E.length)return!1;let x=E[0];return x.targetPath===null?(0,h.throwNullException)("choice.targetPath"):x.threadAtGeneration===null?(0,h.throwNullException)("choice.threadAtGeneration"):(this.state.callStack.currentThread=x.threadAtGeneration,this._stateSnapshotAtLastNewline!==null&&(this.state.callStack.currentThread=this.state.callStack.ForkThread()),this.ChoosePath(x.targetPath,!1),!0)}NextSequenceShuffleIndex(){let C=(0,u.asOrNull)(this.state.PopEvaluationStack(),c.IntValue);if(!(C instanceof c.IntValue))return this.Error("expected number of elements in sequence for shuffle index"),0;let E=this.state.currentPointer.container;if(E===null)return(0,h.throwNullException)("seqContainer");if(C.value===null)return(0,h.throwNullException)("numElementsIntVal.value");let x=C.value,W=(0,u.asOrThrows)(this.state.PopEvaluationStack(),c.IntValue).value;if(W===null)return(0,h.throwNullException)("seqCount");let M=W/x,G=W%x,H=E.path.toString(),Q=0;for(let rt=0,_t=H.length;rt<_t;rt++)Q+=H.charCodeAt(rt)||0;let ut=Q+M+this.state.storySeed,Y=new w.PRNG(Math.floor(ut)),mt=[];for(let rt=0;rt<x;++rt)mt.push(rt);for(let rt=0;rt<=G;++rt){let _t=Y.next()%mt.length,Dt=mt[_t];if(mt.splice(_t,1),rt==G)return Dt}throw new Error("Should never reach here")}Error(C,E=!1){let x=new I.StoryException(C);throw x.useEndLineNumber=E,x}Warning(C){this.AddError(C,!0)}AddError(C,E=!1,x=!1){let A=this.currentDebugMetadata,W=E?"WARNING":"ERROR";if(A!=null){let M=x?A.endLineNumber:A.startLineNumber;C="RUNTIME "+W+": '"+A.fileName+"' line "+M+": "+C}else this.state.currentPointer.isNull?C="RUNTIME "+W+": "+C:C="RUNTIME "+W+": ("+this.state.currentPointer+"): "+C;this.state.AddError(C,E),E||this.state.ForceEnd()}Assert(C,E=null){if(C==!1)throw E==null&&(E="Story assert"),new Error(E+" "+this.currentDebugMetadata)}get currentDebugMetadata(){let C,E=this.state.currentPointer;if(!E.isNull&&E.Resolve()!==null&&(C=E.Resolve().debugMetadata,C!==null))return C;for(let x=this.state.callStack.elements.length-1;x>=0;--x)if(E=this.state.callStack.elements[x].currentPointer,!E.isNull&&E.Resolve()!==null&&(C=E.Resolve().debugMetadata,C!==null))return C;for(let x=this.state.outputStream.length-1;x>=0;--x)if(C=this.state.outputStream[x].debugMetadata,C!==null)return C;return null}get mainContentContainer(){return this._temporaryEvaluationContainer?this._temporaryEvaluationContainer:this._mainContentContainer}}o.Story=j,j.inkVersionCurrent=21,(function(L){(function(C){C[C.NoChange=0]="NoChange",C[C.ExtendedBeyondNewline=1]="ExtendedBeyondNewline",C[C.NewlineRemoved=2]="NewlineRemoved"})(L.OutputStateChange||(L.OutputStateChange={}))})(j||(o.Story=j={}))})(gi)),gi}var Ps;function Ua(){if(Ps)return wn;Ps=1,Object.defineProperty(wn,"__esModule",{value:!0}),wn.Story=void 0;const o=xi(),n=Ai(),a=ot(),e=pt(),f=Oi(),t=kt(),p=Un(),r=ea(),y=ki(),s=ia(),c=ci(),i=Wt(),l=$t(),S=Gt(),P=Z(),N=ui(),O=hi(),I=ee();class w extends t.FlowBase{get flowLevel(){return p.FlowLevel.Story}get hadError(){return this._hadError}get hadWarning(){return this._hadWarning}constructor(k,m=!1){super(null,k,null,!1,m),this._errorHandler=null,this._hadError=!1,this._hadWarning=!1,this._dontFlattenContainers=new Set,this._listDefs=new Map,this.constants=new Map,this.externals=new Map,this.countAllVisits=!1,this.ExportRuntime=(g=null)=>{var v,u;this._errorHandler=g,this.constants=new Map;for(const j of this.FindAll(n.ConstantDeclaration)()){const L=this.constants.get(j.constantName);if(L&&!L.Equals(j.expression)){const C=`CONST '${j.constantName}' has been redefined with a different value. Multiple definitions of the same CONST are valid so long as they contain the same value. Initial definition was on ${L.debugMetadata}.`;this.Error(C,j,!1)}this.constants.set(j.constantName,j.expression)}this._listDefs=new Map;for(const j of this.FindAll(y.ListDefinition)())!((v=j.identifier)===null||v===void 0)&&v.name&&this._listDefs.set((u=j.identifier)===null||u===void 0?void 0:u.name,j);this.externals=new Map,this.ResolveWeavePointNaming();const h=this.runtimeObject,b=new a.Container;b.AddContent(e.ControlCommand.EvalStart());const R=[];for(const[j,L]of this.variableDeclarations)if(L.isGlobalDeclaration){if(L.listDefinition)this._listDefs.set(j,L.listDefinition),b.AddContent(L.listDefinition.runtimeObject),R.push(L.listDefinition.runtimeListDefinition);else{if(!L.expression)throw new Error;L.expression.GenerateIntoContainer(b)}const C=new S.VariableAssignment(j,!0);C.isGlobal=!0,b.AddContent(C)}b.AddContent(e.ControlCommand.EvalEnd()),b.AddContent(e.ControlCommand.End()),this.variableDeclarations.size>0&&(b.name="global decl",h.AddToNamedContentOnly(b)),h.AddContent(e.ControlCommand.Done());const V=new c.Story(h,R);return this.runtimeObject=V,this.hadError||(this.FlattenContainersIn(h),this.ResolveReferences(this),this.hadError)?null:(V.ResetState(),V)},this.ResolveList=g=>{let v=this._listDefs.get(g);return v||null},this.ResolveListItem=(g,v,u=null)=>{let h=null;if(g)return(h=this._listDefs.get(g))?h.ItemNamed(v):null;{let b=null,R=null;for(const[,V]of this._listDefs.entries()){const j=V.ItemNamed(v);j&&(b?this.Error(`Ambiguous item name '${v}' found in multiple sets, including ${R.identifier} and ${V.identifier}`,u,!1):(b=j,R=V))}return b}},this.FlattenContainersIn=g=>{const v=new Set;if(g.content)for(const u of g.content){const h=(0,P.asOrNull)(u,a.Container);h&&v.add(h)}if(g.namedContent)for(const[,u]of g.namedContent){const h=(0,P.asOrNull)(u,a.Container);h&&v.add(h)}for(const u of v)this.TryFlattenContainer(u),this.FlattenContainersIn(u)},this.TryFlattenContainer=g=>{if(g.namedContent&&g.namedContent.size>0||g.hasValidName||this._dontFlattenContainers.has(g))return;const v=(0,P.asOrNull)(g.parent,a.Container);if(v){let u=v.content.indexOf(g);v.content.splice(u,1);const h=g.ownDebugMetadata;if(g.content)for(const b of g.content)b.parent=null,h!==null&&b.ownDebugMetadata===null&&(b.debugMetadata=h),v.InsertContent(b,u),u+=1}},this.Error=(g,v,u)=>{let h=u?f.ErrorType.Warning:f.ErrorType.Error,b="";if(v instanceof o.AuthorWarning?(b+="TODO: ",h=f.ErrorType.Author):u?b+="WARNING: ":b+="ERROR: ",v&&v.debugMetadata!==null&&v.debugMetadata.startLineNumber>=1&&(v.debugMetadata.fileName!=null&&(b+=`'${v.debugMetadata.fileName}' `),b+=`line ${v.debugMetadata.startLineNumber}: `),b+=g,g=b,this._errorHandler!==null)this._errorHandler(g,h);else throw new Error(g);this._hadError=h===f.ErrorType.Error,this._hadWarning=h===f.ErrorType.Warning},this.ResetError=()=>{this._hadError=!1,this._hadWarning=!1},this.IsExternal=g=>this.externals.has(g),this.AddExternal=g=>{this.externals.has(g.name)?this.Error(`Duplicate EXTERNAL definition of '${g.name}'`,g,!1):g.name&&this.externals.set(g.name,g)},this.DontFlattenContainer=g=>{this._dontFlattenContainers.add(g)},this.NameConflictError=(g,v,u,h)=>{g.Error(`${h} '${v}': name has already been used for a ${u.typeName.toLowerCase()} on ${u.debugMetadata}`)},this.CheckForNamingCollisions=(g,v,u,h="")=>{var b;const R=h||g.typeName;if(w.IsReservedKeyword(v==null?void 0:v.name)){g.Error(`'${v}' cannot be used for the name of a ${R.toLowerCase()} because it's a reserved keyword`);return}else if(O.FunctionCall.IsBuiltIn((v==null?void 0:v.name)||"")){g.Error(`'${v}' cannot be used for the name of a ${R.toLowerCase()} because it's a built in function`);return}const V=this.ContentWithNameAtLevel((v==null?void 0:v.name)||"",p.FlowLevel.Knot),j=(0,P.asOrNull)(V,t.FlowBase);if(j&&(j!==g||u===i.SymbolType.Arg)){this.NameConflictError(g,(v==null?void 0:v.name)||"",j,R);return}if(u<i.SymbolType.List)return;for(const[x,A]of this._listDefs)if((v==null?void 0:v.name)===x&&g!==A&&A.variableAssignment!==g&&this.NameConflictError(g,v==null?void 0:v.name,A,R),!(g instanceof s.ListElementDefinition))for(const W of A.itemDefinitions)(v==null?void 0:v.name)===W.name&&this.NameConflictError(g,(v==null?void 0:v.name)||"",W,R);if(u<=i.SymbolType.Var)return;const L=(v==null?void 0:v.name)&&this.variableDeclarations.get(v==null?void 0:v.name)||null;if(L&&L!==g&&L.isGlobalDeclaration&&L.listDefinition==null&&this.NameConflictError(g,(v==null?void 0:v.name)||"",L,R),u<i.SymbolType.SubFlowAndWeave)return;const E=new I.Path(v).ResolveFromContext(g);if(E&&E!==g){this.NameConflictError(g,(v==null?void 0:v.name)||"",E,R);return}if(!(u<i.SymbolType.Arg)&&u!==i.SymbolType.Arg){let x=(0,P.asOrNull)(g,t.FlowBase);if(x||(x=(0,N.ClosestFlowBase)(g)),x&&x.hasParameters&&x.args){for(const A of x.args)if(((b=A.identifier)===null||b===void 0?void 0:b.name)===(v==null?void 0:v.name)){g.Error(`${R} '${v}': name has already been used for a argument to ${x.identifier} on ${x.debugMetadata}`);return}}}}}get typeName(){return"Story"}PreProcessTopLevelObjects(k){super.PreProcessTopLevelObjects(k);const m=[];for(let g of k)if(g instanceof r.IncludedFile){const v=g,u=k.indexOf(g);if(k.splice(u,1),v.includedStory){const h=[],b=v.includedStory;if(b.content!=null){for(const R of b.content)R instanceof t.FlowBase?m.push(R):h.push(R);h.push(new l.Text(`
|
|
29
|
+
`)),k.splice(u,0,...h)}}continue}k.splice(0,0,...m)}}return wn.Story=w,w.IsReservedKeyword=F=>{switch(F){case"true":case"false":case"not":case"return":case"else":case"VAR":case"CONST":case"temp":case"LIST":case"function":return!0}return!1},wn}var Vn={},Os;function Ha(){if(Os)return Vn;Os=1,Object.defineProperty(Vn,"__esModule",{value:!0}),Vn.StringExpression=void 0;const o=pt(),n=Ot(),a=$t(),e=Z();let f=class pa extends n.Expression{get isSingleString(){return!(this.content.length!==1||!(this.content[0]instanceof a.Text))}constructor(p){super(),this.GenerateIntoContainer=r=>{r.AddContent(o.ControlCommand.BeginString());for(const y of this.content)r.AddContent(y.runtimeObject);r.AddContent(o.ControlCommand.EndString())},this.toString=()=>{let r="";for(const y of this.content)r+=y;return r},this.AddContent(p)}get typeName(){return"String"}Equals(p){const r=(0,e.asOrNull)(p,pa);if(r===null||!this.isSingleString||!r.isSingleString)return!1;const y=this.toString(),s=r.toString();return y===s}};return Vn.StringExpression=f,Vn}var Bt={},xs;function Ka(){if(xs)return Bt;xs=1,Object.defineProperty(Bt,"__esModule",{value:!0}),Bt.LegacyTag=Bt.Tag=void 0;const o=et(),n=pt();let a=class extends o.ParsedObject{constructor(p,r=!1){super(),this.GenerateRuntimeObject=()=>this.isStart?n.ControlCommand.BeginTag():n.ControlCommand.EndTag(),this.toString=()=>this.isStart?"#StartTag":"#EndTag",this.isStart=p,this.inChoice=r}get typeName(){return"Tag"}};Bt.Tag=a;const e=ta();class f extends e.Wrap{constructor(p){super(p)}get typeName(){return"Tag"}}return Bt.LegacyTag=f,Bt}var Wn={},Ts;function Ja(){if(Ts)return Wn;Ts=1,Object.defineProperty(Wn,"__esModule",{value:!0}),Wn.DefaultFileHandler=void 0;let o=class{constructor(a){this.rootPath=a,this.ResolveInkFilename=()=>{throw Error("Can't resolve filename because no FileHandler was provided when instantiating the parser / compiler.")},this.LoadInkFileContents=()=>{throw Error("Can't load ink content because no FileHandler was provided when instantiating the parser / compiler.")}}};return Wn.DefaultFileHandler=o,Wn}var Ns;function Is(){if(Ns)return le;Ns=1,Object.defineProperty(le,"__esModule",{value:!0}),le.InkParser=void 0;const o=Ea(),n=xi(),a=qs(),e=Pa(),f=ai(),t=$n(),p=Ta(),r=Ii(),y=Zs(),s=Ri(),c=Ai(),i=Aa(),l=Fa(),S=zn(),P=Jn(),N=Ot(),O=Ra(),I=ka(),w=hi(),F=li(),k=Da(),m=Di(),g=Va(),v=ea(),u=Wa(),h=na(),b=La(),R=ki(),V=ia(),j=Hs(),L=et(),C=ee(),E=$s(),x=Js(),A=Ks(),W=ra(),M=sa(),G=Ua(),H=Ha(),Q=Gs(),ut=Ka(),Y=$t(),mt=zs(),rt=Ys(),_t=Kn(),Dt=Bs(),Et=Z(),Vt=Fi(),xt=Ti(),Ut=Oi(),di=Ja();let B=class Ei extends Q.StringParser{get fileHandler(){if(!this._fileHandler)throw new Error("No FileHandler defined");return this._fileHandler}set fileHandler(K){this._fileHandler=K}constructor(K,wt=null,ht=null,lt=null,bt=null){if(super(K),this.ParseStory=()=>{const d=this.StatementsAtLevel(W.StatementLevel.Top);return new G.Story(d,this._rootParser!==this)},this.SeparatedList=(d,_)=>{const T=this.Parse(d);if(T===null)return null;const D=[];D.push(T);do{const U=this.BeginRule();if(_()===null){this.FailRule(U);break}const J=this.Parse(d);if(J===null){this.FailRule(U);break}this.SucceedRule(U),D.push(J)}while(!0);return D},this.CreateDebugMetadata=(d,_)=>{const T=new l.DebugMetadata;return T.startLineNumber=((d==null?void 0:d.lineIndex)||0)+1,T.endLineNumber=_.lineIndex+1,T.startCharacterNumber=((d==null?void 0:d.characterInLineIndex)||0)+1,T.endCharacterNumber=_.characterInLineIndex+1,T.fileName=this._filename,T},this.RuleDidSucceed=(d,_,T)=>{const D=(0,Et.asOrNull)(d,L.ParsedObject);D&&(D.debugMetadata=this.CreateDebugMetadata(_,T));const U=Array.isArray(d)?d:null;if(U!==null)for(const J of U)(0,Et.asOrNull)(J,L.ParsedObject)&&(J.hasOwnDebugMetadata||(J.debugMetadata=this.CreateDebugMetadata(_,T)));const $=(0,Et.asOrNull)(d,Vt.Identifier);$!=null&&($.debugMetadata=this.CreateDebugMetadata(_,T))},this.OnStringParserError=(d,_,T=0,D=!1)=>{let $=D?"WARNING:":"ERROR:";if(this._filename!==null&&($+=` '${this._filename}'`),$+=` line ${T+1}: ${d}`,this._externalErrorHandler!==null)this._externalErrorHandler($,D?Ut.ErrorType.Warning:Ut.ErrorType.Error);else throw new Error($)},this.AuthorWarning=()=>{this.Whitespace();const d=this.Parse(this.IdentifierWithMetadata);if(d===null||d.name!=="TODO")return null;this.Whitespace(),this.ParseString(":"),this.Whitespace();const _=this.ParseUntilCharactersFromString(`
|
|
30
|
+
\r`);return _?new n.AuthorWarning(_):null},this.ExtendIdentifierCharacterRanges=d=>{const _=Ei.ListAllCharacterRanges();for(const T of _)d.AddCharacters(T.ToCharacterSet())},this._parsingChoice=!1,this.Choice=()=>{let d=!0,_=this.Interleave(this.OptionalExclude(this.Whitespace),this.String("*"));if(!_){if(_=this.Interleave(this.OptionalExclude(this.Whitespace),this.String("+")),_===null)return null;d=!1}const T=this.Parse(this.BracketedName);this.Whitespace(),T!=null&&this.Newline();const D=this.Parse(this.ChoiceCondition);if(this.Whitespace(),this._parsingChoice)throw new Error("Already parsing a choice - shouldn't have nested choices");this._parsingChoice=!0;let U=null;const $=this.Parse(this.MixedTextAndLogic);$&&(U=new s.ContentList($));let J=null,X=null;const Tt=this.ParseString("[")!==null;if(Tt){this.EndTagIfNecessary(U);const ie=this.Parse(this.MixedTextAndLogic);ie!==null&&(J=new s.ContentList(ie)),this.Expect(this.String("]"),"closing ']' for weave-style option"),this.EndTagIfNecessary(J);let re=this.Parse(this.MixedTextAndLogic);re!==null&&(X=new s.ContentList(re))}this.Whitespace(),this.EndTagIfNecessary(X??U);const fi=this.Parse(this.MultiDivert);this._parsingChoice=!1,this.Whitespace();const Wi=!U&&!X&&!J;if(Wi&&fi===null&&this.Warning("Choice is completely empty. Interpretting as a default fallback choice. Add a divert arrow to remove this warning: * ->"),!U&&Tt&&!J&&this.Warning("Blank choice - if you intended a default fallback choice, use the `* ->` syntax"),X||(X=new s.ContentList),this.EndTagIfNecessary(X),fi!==null)for(const ie of fi){const re=(0,Et.asOrNull)(ie,S.Divert);re&&re.isEmpty||X.AddContent(ie)}X.AddContent(new Y.Text(`
|
|
31
31
|
`));const Lt=new t.Choice(U,J,X);return T&&(Lt.identifier=T),Lt.indentationDepth=_.length,Lt.hasWeaveStyleInlineBrackets=Tt,Lt.condition=D,Lt.onceOnly=d,Lt.isInvisibleDefault=Wi,Lt},this.ChoiceCondition=()=>{const d=this.Interleave(this.ChoiceSingleCondition,this.ChoiceConditionsSpace);return d===null?null:d.length===1?d[0]:new j.MultipleConditionExpression(d)},this.ChoiceConditionsSpace=()=>(this.Newline(),this.Whitespace(),Q.ParseSuccess),this.ChoiceSingleCondition=()=>{if(this.ParseString("{")===null)return null;const d=this.Expect(this.Expression,"choice condition inside { }");return this.DisallowIncrement(d),this.Expect(this.String("}"),"closing '}' for choice condition"),d},this.Gather=()=>{const d=this.Parse(this.GatherDashes);if(d===null)return null;const _=Number(d),T=this.Parse(this.BracketedName),D=new F.Gather(T,_);return this.Newline(),D},this.GatherDashes=()=>{this.Whitespace();let d=0;for(;this.ParseDashNotArrow()!==null;)d+=1,this.Whitespace();return d===0?null:d},this.ParseDashNotArrow=()=>{const d=this.BeginRule();return this.ParseString("->")===null&&this.ParseSingleCharacter()==="-"?this.SucceedRule(d):this.FailRule(d)},this.BracketedName=()=>{if(this.ParseString("(")===null)return null;this.Whitespace();const d=this.Parse(this.IdentifierWithMetadata);return d===null?null:(this.Whitespace(),this.Expect(this.String(")"),"closing ')' for bracketed name"),d)},this.InnerConditionalContent=d=>{if(d===void 0){const $=this.Parse(this.ConditionExpression),J=this.Parse(()=>this.InnerConditionalContent($));return J===null?null:J}let _;const T=d!==null,D=this.Parse(this.Newline)===null;if(D&&!T)return null;if(D)_=this.InlineConditionalBranches();else{if(_=this.MultilineConditionalBranches(),_===null){if(d){let $=this.StatementsAtLevel(W.StatementLevel.InnerBlock);if($!==null){_=[new y.ConditionalSingleBranch($)];const X=this.Parse(this.SingleMultilineCondition);X&&(X.isElse||(this.ErrorWithParsedObject("Expected an '- else:' clause here rather than an extra condition",X),X.isElse=!0),_.push(X))}}if(_===null)return null}else if(_.length===1&&_[0].isElse&&d){const $=new y.ConditionalSingleBranch(null);$.isTrueBranch=!0,_.unshift($)}if(d){let $=!1;for(let J=0;J<_.length;++J){const X=_[J],Tt=J===_.length-1;X.ownExpression?(X.matchingEquality=!0,$=!0):$&&Tt?(X.matchingEquality=!0,X.isElse=!0):!Tt&&_.length>2?this.ErrorWithParsedObject("Only final branch can be an 'else'. Did you miss a ':'?",X):J===0?X.isTrueBranch=!0:X.isElse=!0}}else{for(let $=0;$<_.length;++$){const J=_[$],X=$===_.length-1;if(J.ownExpression===null)if(X)J.isElse=!0;else if(J.isElse){const Tt=_[_.length-1];Tt.isElse?this.ErrorWithParsedObject("Multiple 'else' cases. Can have a maximum of one, at the end.",Tt):this.ErrorWithParsedObject("'else' case in conditional should always be the final one",J)}else this.ErrorWithParsedObject("Branch doesn't have condition. Are you missing a ':'? ",J)}_.length===1&&_[0].ownExpression===null&&this.ErrorWithParsedObject("Condition block with no conditions",_[0])}}if(_===null)return null;for(const $ of _)$.isInline=D;return new r.Conditional(d,_)},this.InlineConditionalBranches=()=>{const d=this.Interleave(this.MixedTextAndLogic,this.Exclude(this.String("|")),null,!1);if(d===null||d.length===0)return null;const _=[];if(d.length>2)this.Error("Expected one or two alternatives separated by '|' in inline conditional");else{const T=new y.ConditionalSingleBranch(d[0]);if(T.isTrueBranch=!0,_.push(T),d.length>1){const D=new y.ConditionalSingleBranch(d[1]);D.isElse=!0,_.push(D)}}return _},this.MultilineConditionalBranches=()=>{this.MultilineWhitespace();const d=this.OneOrMore(this.SingleMultilineCondition);return d===null?null:(this.MultilineWhitespace(),d)},this.SingleMultilineCondition=()=>{if(this.Whitespace(),this.ParseString("->")!==null||this.ParseString("-")===null)return null;this.Whitespace();let d=null;const _=this.Parse(this.ElseExpression)!==null;_||(d=this.Parse(this.ConditionExpression));let T=this.StatementsAtLevel(W.StatementLevel.InnerBlock);d===null&&T===null&&(this.Error("expected content for the conditional branch following '-'"),T=[new Y.Text("")]),this.MultilineWhitespace();const D=new y.ConditionalSingleBranch(T);return D.ownExpression=d,D.isElse=_,D},this.ConditionExpression=()=>{const d=this.Parse(this.Expression);return d===null||(this.DisallowIncrement(d),this.Whitespace(),this.ParseString(":")===null)?null:d},this.ElseExpression=()=>this.ParseString("else")===null||(this.Whitespace(),this.ParseString(":")===null)?null:Q.ParseSuccess,this._nonTextPauseCharacters=null,this._nonTextEndCharacters=null,this._notTextEndCharactersChoice=null,this._notTextEndCharactersString=null,this.TrimEndWhitespace=(d,_)=>{if(d.length>0){const T=d.length-1,D=d[T];if(D instanceof Y.Text){const U=D;U.text=U.text.replace(new RegExp(/[ \t]+$/g),""),_?U.text+=" ":U.text.length===0&&(d.splice(T,1),this.TrimEndWhitespace(d,!1))}}},this.LineOfMixedTextAndLogic=()=>{this.Parse(this.Whitespace);let d=this.Parse(this.MixedTextAndLogic);if(!d||!d.length)return null;const _=d[0];return _&&_.text&&_.text.startsWith("return")&&this.Warning("Do you need a '~' before 'return'? If not, perhaps use a glue: <> (since it's lowercase) or rewrite somehow?"),d.length===0?null:(d[d.length-1]instanceof S.Divert||this.TrimEndWhitespace(d,!1),this.EndTagIfNecessary(d),d.length>0&&d[0]instanceof ut.Tag&&d[0].isStart||d.push(new Y.Text(`
|
|
32
32
|
`)),this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),d)},this.MixedTextAndLogic=()=>{this.ParseObject(this.Spaced(this.String("~")))!==null&&this.Error("You shouldn't use a '~' here - tildas are for logic that's on its own line. To do inline logic, use { curly braces } instead");let _=this.Interleave(this.Optional(this.ContentText),this.Optional(this.InlineLogicOrGlueOrStartTag));if(!this._parsingChoice){const T=this.Parse(this.MultiDivert);T!==null&&(_===null&&(_=[]),this.EndTagIfNecessary(_),this.TrimEndWhitespace(_,!0),_.push(...T))}return _||null},this.ContentText=()=>this.ContentTextAllowingEscapeChar(),this.ContentTextAllowingEscapeChar=()=>{let d=null;do{let _=this.Parse(this.ContentTextNoEscape);const T=this.ParseString("\\")!==null;if(T||_!==null){if(d===null&&(d=""),_!==null&&(d+=String(_)),T){const D=this.ParseSingleCharacter();d+=D}}else break}while(!0);return d!==null?new Y.Text(d):null},this.ContentTextNoEscape=()=>{this._nonTextPauseCharacters===null&&(this._nonTextPauseCharacters=new f.CharacterSet("-<")),this._nonTextEndCharacters===null&&(this._nonTextEndCharacters=new f.CharacterSet(`{}|
|
|
33
|
-
\r\\#`),this._notTextEndCharactersChoice=new f.CharacterSet(this._nonTextEndCharacters),this._notTextEndCharactersChoice.AddCharacters("[]"),this._notTextEndCharactersString=new f.CharacterSet(this._nonTextEndCharacters),this._notTextEndCharactersString.AddCharacters('"'));const d=()=>this.OneOf([this.ParseDivertArrow,this.ParseThreadArrow,this.EndOfLine,this.Glue]);let _=null;this.parsingStringExpression?_=this._notTextEndCharactersString:this._parsingChoice?_=this._notTextEndCharactersChoice:_=this._nonTextEndCharacters;const T=this.ParseUntil(d,this._nonTextPauseCharacters,_);return T!==null?T:null},this.MultiDivert=()=>{this.Whitespace();let d=[];const _=this.Parse(this.StartThread);if(_)return d=[_],d;const T=this.Interleave(this.ParseDivertArrowOrTunnelOnwards,this.DivertIdentifierWithArguments);if(!T)return null;d=[],this.EndTagIfNecessary(d);for(let D=0;D<T.length;++D)if(D%2===0){if(T[D]==="->->"){D===0||D===T.length-1||D===T.length-2||this.Error("Tunnel onwards '->->' must only come at the begining or the start of a divert");const J=new mt.TunnelOnwards;if(D<T.length-1){const X=(0,Et.asOrNull)(T[D+1],S.Divert);J.divertAfter=X}d.push(J);break}}else{const $=T[D];D<T.length-1&&($.isTunnel=!0),d.push($)}if(d.length===0&&T.length===1){const D=new S.Divert(null);D.isEmpty=!0,d.push(D),this._parsingChoice||this.Error("Empty diverts (->) are only valid on choices")}return d},this.StartThread=()=>{if(this.Whitespace(),this.ParseThreadArrow()===null)return null;this.Whitespace();const d=this.Expect(this.DivertIdentifierWithArguments,"target for new thread",()=>new S.Divert(null));return d.isThread=!0,d},this.DivertIdentifierWithArguments=()=>{this.Whitespace();const d=this.Parse(this.DotSeparatedDivertPathComponents);if(!d)return null;this.Whitespace();const _=this.Parse(this.ExpressionFunctionCallArguments);this.Whitespace();const T=new C.Path(d);return new S.Divert(T,_)},this.SingleDivert=()=>{const d=this.Parse(this.MultiDivert);if(!d||d.length!==1||d[0]instanceof mt.TunnelOnwards)return null;const T=d[0];return T.isTunnel?null:T},this.DotSeparatedDivertPathComponents=()=>this.Interleave(this.Spaced(this.IdentifierWithMetadata),this.Exclude(this.String("."))),this.ParseDivertArrowOrTunnelOnwards=()=>{let d=0;for(;this.ParseString("->")!==null;)d+=1;return d===0?null:d===1?"->":(d===2||this.Error("Unexpected number of arrows in divert. Should only have '->' or '->->'"),"->->")},this.ParseDivertArrow=()=>this.ParseString("->"),this.ParseThreadArrow=()=>this.ParseString("<-"),this._binaryOperators=[],this._maxBinaryOpLength=0,this.TempDeclarationOrAssignment=()=>{this.Whitespace();const d=this.ParseTempKeyword();this.Whitespace();let _=null;if(d?_=this.Expect(this.IdentifierWithMetadata,"variable name"):_=this.Parse(this.IdentifierWithMetadata),_===null)return null;this.Whitespace();const T=this.ParseString("+")!==null,D=this.ParseString("-")!==null;if(T&&D&&this.Error("Unexpected sequence '+-'"),this.ParseString("=")===null)return d&&this.Error("Expected '='"),null;const U=this.Expect(this.Expression,"value expression to be assigned");return T||D?new g.IncDecExpression(_,U,T):new rt.VariableAssignment({variableIdentifier:_,assignedExpression:U,isTemporaryNewDeclaration:d})},this.DisallowIncrement=d=>{d instanceof g.IncDecExpression&&this.Error("Can't use increment/decrement here. It can only be used on a ~ line")},this.ParseTempKeyword=()=>{const d=this.BeginRule();return this.Parse(this.Identifier)==="temp"?(this.SucceedRule(d),!0):(this.FailRule(d),!1)},this.ReturnStatement=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="return")return null;this.Whitespace();const _=this.Parse(this.Expression);return new E.ReturnType(_)},this.Expression=(d=0)=>{this.Whitespace();let _=this.ExpressionUnary();if(_===null)return null;for(this.Whitespace();;){const T=this.BeginRule(),D=this.ParseInfixOperator();if(D!==null&&D.precedence>d){const U=`right side of '${D.type}' expression`,$=this.Expect(()=>this.ExpressionInfixRight(_,D),U);if($===null)return this.FailRule(T),null;_=this.SucceedRule(T,$);continue}this.FailRule(T);break}return this.Whitespace(),_},this.ExpressionUnary=()=>{const d=this.Parse(this.ExpressionDivertTarget);if(d!==null)return d;let _=this.OneOf([this.String("-"),this.String("!")]);_===null&&(_=this.Parse(this.ExpressionNot)),this.Whitespace();let T=this.OneOf([this.ExpressionList,this.ExpressionParen,this.ExpressionFunctionCall,this.ExpressionVariableName,this.ExpressionLiteral]);if(T===null&&_!==null&&(T=this.ExpressionUnary()),T===null)return null;_!==null&&(T=Dt.UnaryExpression.WithInner(T,_)),this.Whitespace();const D=this.OneOf([this.String("++"),this.String("--")]);if(D!==null){const U=D==="++";if(!(T instanceof _t.VariableReference))this.Error(`can only increment and decrement variables, but saw '${T}'.`);else{const $=T;T=new g.IncDecExpression($.identifier,U)}}return T},this.ExpressionNot=()=>{const d=this.Identifier();return d==="not"?d:null},this.ExpressionLiteral=()=>this.OneOf([this.ExpressionFloat,this.ExpressionInt,this.ExpressionBool,this.ExpressionString]),this.ExpressionDivertTarget=()=>{this.Whitespace();const d=this.Parse(this.SingleDivert);return!d||d&&d.isThread?null:(this.Whitespace(),new P.DivertTarget(d))},this.ExpressionInt=()=>{const d=this.ParseInt();return d===null?null:new xt.NumberExpression(d,"int")},this.ExpressionFloat=()=>{const d=this.ParseFloat();return d===null?null:new xt.NumberExpression(d,"float")},this.ExpressionString=()=>{if(this.ParseString('"')===null)return null;this.parsingStringExpression=!0;let _=this.Parse(this.MixedTextAndLogic);return this.Expect(this.String('"'),"close quote for string expression"),this.parsingStringExpression=!1,_===null?_=[new Y.Text("")]:_.find(T=>T instanceof S.Divert)&&this.Error("String expressions cannot contain diverts (->)"),new
|
|
33
|
+
\r\\#`),this._notTextEndCharactersChoice=new f.CharacterSet(this._nonTextEndCharacters),this._notTextEndCharactersChoice.AddCharacters("[]"),this._notTextEndCharactersString=new f.CharacterSet(this._nonTextEndCharacters),this._notTextEndCharactersString.AddCharacters('"'));const d=()=>this.OneOf([this.ParseDivertArrow,this.ParseThreadArrow,this.EndOfLine,this.Glue]);let _=null;this.parsingStringExpression?_=this._notTextEndCharactersString:this._parsingChoice?_=this._notTextEndCharactersChoice:_=this._nonTextEndCharacters;const T=this.ParseUntil(d,this._nonTextPauseCharacters,_);return T!==null?T:null},this.MultiDivert=()=>{this.Whitespace();let d=[];const _=this.Parse(this.StartThread);if(_)return d=[_],d;const T=this.Interleave(this.ParseDivertArrowOrTunnelOnwards,this.DivertIdentifierWithArguments);if(!T)return null;d=[],this.EndTagIfNecessary(d);for(let D=0;D<T.length;++D)if(D%2===0){if(T[D]==="->->"){D===0||D===T.length-1||D===T.length-2||this.Error("Tunnel onwards '->->' must only come at the begining or the start of a divert");const J=new mt.TunnelOnwards;if(D<T.length-1){const X=(0,Et.asOrNull)(T[D+1],S.Divert);J.divertAfter=X}d.push(J);break}}else{const $=T[D];D<T.length-1&&($.isTunnel=!0),d.push($)}if(d.length===0&&T.length===1){const D=new S.Divert(null);D.isEmpty=!0,d.push(D),this._parsingChoice||this.Error("Empty diverts (->) are only valid on choices")}return d},this.StartThread=()=>{if(this.Whitespace(),this.ParseThreadArrow()===null)return null;this.Whitespace();const d=this.Expect(this.DivertIdentifierWithArguments,"target for new thread",()=>new S.Divert(null));return d.isThread=!0,d},this.DivertIdentifierWithArguments=()=>{this.Whitespace();const d=this.Parse(this.DotSeparatedDivertPathComponents);if(!d)return null;this.Whitespace();const _=this.Parse(this.ExpressionFunctionCallArguments);this.Whitespace();const T=new C.Path(d);return new S.Divert(T,_)},this.SingleDivert=()=>{const d=this.Parse(this.MultiDivert);if(!d||d.length!==1||d[0]instanceof mt.TunnelOnwards)return null;const T=d[0];return T.isTunnel?null:T},this.DotSeparatedDivertPathComponents=()=>this.Interleave(this.Spaced(this.IdentifierWithMetadata),this.Exclude(this.String("."))),this.ParseDivertArrowOrTunnelOnwards=()=>{let d=0;for(;this.ParseString("->")!==null;)d+=1;return d===0?null:d===1?"->":(d===2||this.Error("Unexpected number of arrows in divert. Should only have '->' or '->->'"),"->->")},this.ParseDivertArrow=()=>this.ParseString("->"),this.ParseThreadArrow=()=>this.ParseString("<-"),this._binaryOperators=[],this._maxBinaryOpLength=0,this.TempDeclarationOrAssignment=()=>{this.Whitespace();const d=this.ParseTempKeyword();this.Whitespace();let _=null;if(d?_=this.Expect(this.IdentifierWithMetadata,"variable name"):_=this.Parse(this.IdentifierWithMetadata),_===null)return null;this.Whitespace();const T=this.ParseString("+")!==null,D=this.ParseString("-")!==null;if(T&&D&&this.Error("Unexpected sequence '+-'"),this.ParseString("=")===null)return d&&this.Error("Expected '='"),null;const U=this.Expect(this.Expression,"value expression to be assigned");return T||D?new g.IncDecExpression(_,U,T):new rt.VariableAssignment({variableIdentifier:_,assignedExpression:U,isTemporaryNewDeclaration:d})},this.DisallowIncrement=d=>{d instanceof g.IncDecExpression&&this.Error("Can't use increment/decrement here. It can only be used on a ~ line")},this.ParseTempKeyword=()=>{const d=this.BeginRule();return this.Parse(this.Identifier)==="temp"?(this.SucceedRule(d),!0):(this.FailRule(d),!1)},this.ReturnStatement=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="return")return null;this.Whitespace();const _=this.Parse(this.Expression);return new E.ReturnType(_)},this.Expression=(d=0)=>{this.Whitespace();let _=this.ExpressionUnary();if(_===null)return null;for(this.Whitespace();;){const T=this.BeginRule(),D=this.ParseInfixOperator();if(D!==null&&D.precedence>d){const U=`right side of '${D.type}' expression`,$=this.Expect(()=>this.ExpressionInfixRight(_,D),U);if($===null)return this.FailRule(T),null;_=this.SucceedRule(T,$);continue}this.FailRule(T);break}return this.Whitespace(),_},this.ExpressionUnary=()=>{const d=this.Parse(this.ExpressionDivertTarget);if(d!==null)return d;let _=this.OneOf([this.String("-"),this.String("!")]);_===null&&(_=this.Parse(this.ExpressionNot)),this.Whitespace();let T=this.OneOf([this.ExpressionList,this.ExpressionParen,this.ExpressionFunctionCall,this.ExpressionVariableName,this.ExpressionLiteral]);if(T===null&&_!==null&&(T=this.ExpressionUnary()),T===null)return null;_!==null&&(T=Dt.UnaryExpression.WithInner(T,_)),this.Whitespace();const D=this.OneOf([this.String("++"),this.String("--")]);if(D!==null){const U=D==="++";if(!(T instanceof _t.VariableReference))this.Error(`can only increment and decrement variables, but saw '${T}'.`);else{const $=T;T=new g.IncDecExpression($.identifier,U)}}return T},this.ExpressionNot=()=>{const d=this.Identifier();return d==="not"?d:null},this.ExpressionLiteral=()=>this.OneOf([this.ExpressionFloat,this.ExpressionInt,this.ExpressionBool,this.ExpressionString]),this.ExpressionDivertTarget=()=>{this.Whitespace();const d=this.Parse(this.SingleDivert);return!d||d&&d.isThread?null:(this.Whitespace(),new P.DivertTarget(d))},this.ExpressionInt=()=>{const d=this.ParseInt();return d===null?null:new xt.NumberExpression(d,"int")},this.ExpressionFloat=()=>{const d=this.ParseFloat();return d===null?null:new xt.NumberExpression(d,"float")},this.ExpressionString=()=>{if(this.ParseString('"')===null)return null;this.parsingStringExpression=!0;let _=this.Parse(this.MixedTextAndLogic);return this.Expect(this.String('"'),"close quote for string expression"),this.parsingStringExpression=!1,_===null?_=[new Y.Text("")]:_.find(T=>T instanceof S.Divert)&&this.Error("String expressions cannot contain diverts (->)"),new H.StringExpression(_)},this.ExpressionBool=()=>{const d=this.Parse(this.Identifier);return d==="true"?new xt.NumberExpression(!0,"bool"):d==="false"?new xt.NumberExpression(!1,"bool"):null},this.ExpressionFunctionCall=()=>{const d=this.Parse(this.IdentifierWithMetadata);if(d===null)return null;this.Whitespace();const _=this.Parse(this.ExpressionFunctionCallArguments);return _===null?null:new w.FunctionCall(d,_)},this.ExpressionFunctionCallArguments=()=>{if(this.ParseString("(")===null)return null;const d=this.Exclude(this.String(","));let _=this.Interleave(this.Expression,d);return _===null&&(_=[]),this.Whitespace(),this.Expect(this.String(")"),"closing ')' for function call"),_},this.ExpressionVariableName=()=>{const d=this.Interleave(this.IdentifierWithMetadata,this.Exclude(this.Spaced(this.String("."))));return d===null||G.Story.IsReservedKeyword(d[0].name)?null:new _t.VariableReference(d)},this.ExpressionParen=()=>{if(this.ParseString("(")===null)return null;const d=this.Parse(this.Expression);return d===null?null:(this.Whitespace(),this.Expect(this.String(")"),"closing parenthesis ')' for expression"),d)},this.ExpressionInfixRight=(d,_)=>{if(!d)return null;this.Whitespace();const T=this.Parse(()=>this.Expression(_.precedence));return T?new a.BinaryExpression(d,T,_.type):null},this.ParseInfixOperator=()=>{for(const d of this._binaryOperators){const _=this.BeginRule();if(this.ParseString(d.type)!==null){if(d.requireWhitespace&&this.Whitespace()===null){this.FailRule(_);continue}return this.SucceedRule(_,d)}this.FailRule(_)}return null},this.ExpressionList=()=>{if(this.Whitespace(),this.ParseString("(")===null)return null;this.Whitespace();const d=this.SeparatedList(this.ListMember,this.Spaced(this.String(",")));return this.Whitespace(),this.ParseString(")")===null?null:new b.List(d)},this.ListMember=()=>{this.Whitespace();let d=this.Parse(this.IdentifierWithMetadata);if(d===null)return null;if(this.ParseString(".")!==null){const T=this.Expect(this.IdentifierWithMetadata,`element name within the set ${d}`);d.name+=`.${T==null?void 0:T.name}`}return this.Whitespace(),d},this.RegisterExpressionOperators=()=>{this.RegisterBinaryOperator("&&",1),this.RegisterBinaryOperator("||",1),this.RegisterBinaryOperator("and",1,!0),this.RegisterBinaryOperator("or",1,!0),this.RegisterBinaryOperator("==",2),this.RegisterBinaryOperator(">=",2),this.RegisterBinaryOperator("<=",2),this.RegisterBinaryOperator("<",2),this.RegisterBinaryOperator(">",2),this.RegisterBinaryOperator("!=",2),this.RegisterBinaryOperator("?",3),this.RegisterBinaryOperator("has",3,!0),this.RegisterBinaryOperator("!?",3),this.RegisterBinaryOperator("hasnt",3,!0),this.RegisterBinaryOperator("^",3),this.RegisterBinaryOperator("+",4),this.RegisterBinaryOperator("-",5),this.RegisterBinaryOperator("*",6),this.RegisterBinaryOperator("/",7),this.RegisterBinaryOperator("%",8),this.RegisterBinaryOperator("mod",8,!0)},this.RegisterBinaryOperator=(d,_,T=!1)=>{const D=new u.InfixOperator(d,_,T);this._binaryOperators.push(D),this._maxBinaryOpLength=Math.max(this._maxBinaryOpLength,d.length)},this._openFilenames=[],this.IncludeStatement=()=>{if(this.Whitespace(),this.ParseString("INCLUDE")===null)return null;this.Whitespace();let d=this.Expect(()=>this.ParseUntilCharactersFromString(`
|
|
34
34
|
\r`),"filename for include statement");d=d.replace(new RegExp(/[ \t]+$/g),"");const _=this.fileHandler.ResolveInkFilename(d,this._filename);if(this.FilenameIsAlreadyOpen(_))return this.Error(`Recursive INCLUDE detected: '${_}' is already open.`),this.ParseUntilCharactersFromString(`\r
|
|
35
35
|
`),new v.IncludedFile(null);this.AddOpenFilename(_);let T=null,D="";try{D=this._rootParser.fileHandler.LoadInkFileContents(_,this._filename)}catch(U){this.Error(`Failed to load: '${d}'.
|
|
36
36
|
Error:${U}`)}return D!=null&&(T=new Ei(D,d,this._externalErrorHandler,this._rootParser,this.fileHandler).ParseStory()),this.RemoveOpenFilename(_),new v.IncludedFile(T)},this.FilenameIsAlreadyOpen=d=>this._rootParser._openFilenames.includes(d),this.AddOpenFilename=d=>{this._rootParser._openFilenames.push(d)},this.RemoveOpenFilename=d=>{this._rootParser._openFilenames.splice(this._rootParser._openFilenames.indexOf(d),1)},this.KnotDefinition=()=>{const d=this.Parse(this.KnotDeclaration);if(d===null)return null;this.Expect(this.EndOfLine,"end of line after knot name definition",this.SkipToNextLine);const _=()=>this.StatementsAtLevel(W.StatementLevel.Knot),T=this.Expect(_,"at least one line within the knot",this.KnotStitchNoContentRecoveryRule);return new h.Knot(d.name,T,d.args,d.isFunction)},this.KnotDeclaration=()=>{if(this.Whitespace(),this.KnotTitleEquals()===null)return null;this.Whitespace();const d=this.Parse(this.IdentifierWithMetadata);let _;const T=(d==null?void 0:d.name)==="function";T?(this.Expect(this.Whitespace,"whitespace after the 'function' keyword"),_=this.Parse(this.IdentifierWithMetadata)):_=d,_===null&&(this.Error(`Expected the name of the ${T?"function":"knot"}`),_=new Vt.Identifier("")),this.Whitespace();const D=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),this.Parse(this.KnotTitleEquals),new I.FlowDecl(_,D,T)},this.KnotTitleEquals=()=>{const d=this.ParseCharactersFromString("=");return d===null||d.length<=1?null:d},this.StitchDefinition=()=>{const d=this.Parse(this.StitchDeclaration);if(d===null)return null;this.Expect(this.EndOfLine,"end of line after stitch name",this.SkipToNextLine);const _=()=>this.StatementsAtLevel(W.StatementLevel.Stitch),T=this.Expect(_,"at least one line within the stitch",this.KnotStitchNoContentRecoveryRule);return new M.Stitch(d.name,T,d.args,d.isFunction)},this.StitchDeclaration=()=>{if(this.Whitespace(),this.ParseString("=")===null||this.ParseString("=")!==null)return null;this.Whitespace();const d=this.ParseString("function")!==null;d&&this.Whitespace();const _=this.Parse(this.IdentifierWithMetadata);if(_===null)return null;this.Whitespace();const T=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),new I.FlowDecl(_,T,d)},this.KnotStitchNoContentRecoveryRule=()=>(this.ParseUntil(this.KnotDeclaration,new f.CharacterSet("="),null),[new Y.Text("<ERROR IN FLOW>")]),this.BracketedKnotDeclArguments=()=>{if(this.ParseString("(")===null)return null;let d=this.Interleave(this.Spaced(this.FlowDeclArgument),this.Exclude(this.String(",")));return this.Expect(this.String(")"),"closing ')' for parameter list"),d===null&&(d=[]),d},this.FlowDeclArgument=()=>{const d=this.Parse(this.IdentifierWithMetadata);this.Whitespace();const _=this.ParseDivertArrow();this.Whitespace();const T=this.Parse(this.IdentifierWithMetadata);if(d==null&&T===null)return null;const D=new o.Argument;return _!==null&&(D.isDivertTarget=!0),d!==null&&d.name==="ref"?(T===null&&this.Error("Expected an parameter name after 'ref'"),D.identifier=T,D.isByReference=!0):(D.isDivertTarget?D.identifier=T:D.identifier=d,D.identifier===null&&this.Error("Expected an parameter name"),D.isByReference=!1),D},this.ExternalDeclaration=()=>{this.Whitespace();const d=this.Parse(this.IdentifierWithMetadata);if(d===null||d.name!="EXTERNAL")return null;this.Whitespace();const _=this.Expect(this.IdentifierWithMetadata,"name of external function")||new Vt.Identifier("");this.Whitespace();let T=this.Expect(this.BracketedKnotDeclArguments,`declaration of arguments for EXTERNAL, even if empty, i.e. 'EXTERNAL ${_}()'`);T===null&&(T=[]);const D=T.map(U=>{var $;return($=U.identifier)===null||$===void 0?void 0:$.name}).filter(Et.filterUndef);return new O.ExternalDeclaration(_,D)},this._identifierCharSet=null,this.LogicLine=()=>{if(this.Whitespace(),this.ParseString("~")===null)return null;this.Whitespace();const d=()=>this.OneOf([this.ReturnStatement,this.TempDeclarationOrAssignment,this.Expression]);let _=this.Expect(d,"expression after '~'",this.SkipToNextLine);if(_===null)return new s.ContentList;_ instanceof N.Expression&&!(_ instanceof w.FunctionCall||_ instanceof g.IncDecExpression)&&this.Error(`Logic following a '~' can't be that type of expression. It can only be something like:
|
|
@@ -38,8 +38,8 @@ Error:${U}`)}return D!=null&&(T=new Ei(D,d,this._externalErrorHandler,this._root
|
|
|
38
38
|
~ var x = blah
|
|
39
39
|
~ x++
|
|
40
40
|
~ myFunction()`);const T=(0,Et.asOrNull)(_,w.FunctionCall);return T&&(T.shouldPopReturnedValue=!0),_.Find(w.FunctionCall)()!==null&&(_=new s.ContentList(_,new Y.Text(`
|
|
41
|
-
`))),this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),_},this.VariableDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="VAR")return null;this.Whitespace();const _=this.Expect(this.IdentifierWithMetadata,"variable name");this.Whitespace(),this.Expect(this.String("="),"the '=' for an assignment of a value, e.g. '= 5' (initial values are mandatory)"),this.Whitespace();const D=this.Expect(this.Expression,"initial value for ");return D?(D instanceof xt.NumberExpression||D instanceof
|
|
41
|
+
`))),this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),_},this.VariableDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="VAR")return null;this.Whitespace();const _=this.Expect(this.IdentifierWithMetadata,"variable name");this.Whitespace(),this.Expect(this.String("="),"the '=' for an assignment of a value, e.g. '= 5' (initial values are mandatory)"),this.Whitespace();const D=this.Expect(this.Expression,"initial value for ");return D?(D instanceof xt.NumberExpression||D instanceof H.StringExpression||D instanceof P.DivertTarget||D instanceof _t.VariableReference||D instanceof b.List||this.Error("initial value for a variable must be a number, constant, list or divert target"),this.Parse(this.ListElementDefinitionSeparator)!==null?this.Error("Unexpected ','. If you're trying to declare a new list, use the LIST keyword, not VAR"):D instanceof H.StringExpression&&(D.isSingleString||this.Error("Constant strings cannot contain any logic.")),new rt.VariableAssignment({assignedExpression:D,isGlobalDeclaration:!0,variableIdentifier:_})):null},this.ListDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!="LIST")return null;this.Whitespace();const _=this.Expect(this.IdentifierWithMetadata,"list name");this.Whitespace(),this.Expect(this.String("="),"the '=' for an assignment of the list definition"),this.Whitespace();const T=this.Expect(this.ListDefinition,"list item names");return T?(T.identifier=new Vt.Identifier(_.name),new rt.VariableAssignment({variableIdentifier:_,listDef:T})):null},this.ListDefinition=()=>{this.AnyWhitespace();const d=this.SeparatedList(this.ListElementDefinition,this.ListElementDefinitionSeparator);return d===null?null:new R.ListDefinition(d)},this.ListElementDefinitionSeparator=()=>(this.AnyWhitespace(),this.ParseString(",")===null?null:(this.AnyWhitespace(),",")),this.ListElementDefinition=()=>{const d=this.ParseString("(")!==null;let _=d;this.Whitespace();const T=this.Parse(this.IdentifierWithMetadata);if(T===null)return null;this.Whitespace(),d&&this.ParseString(")")!=null&&(_=!1,this.Whitespace());let D=null;if(this.ParseString("=")!==null){this.Whitespace();const U=this.Expect(this.ExpressionInt,"value to be assigned to list item");U!==null&&(D=U.value),_&&(this.Whitespace(),this.ParseString(")")!==null&&(_=!1))}return _&&this.Error("Expected closing ')'"),new V.ListElementDefinition(T,d,D)},this.ConstDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="CONST")return null;this.Whitespace();const _=this.Expect(this.IdentifierWithMetadata,"constant name");this.Whitespace(),this.Expect(this.String("="),"the '=' for an assignment of a value, e.g. '= 5' (initial values are mandatory)"),this.Whitespace();const T=this.Expect(this.Expression,"initial value for ");return T instanceof xt.NumberExpression||T instanceof P.DivertTarget||T instanceof H.StringExpression?T instanceof H.StringExpression&&(T.isSingleString||this.Error("Constant strings cannot contain any logic.")):this.Error("initial value for a constant must be a number or divert target"),new c.ConstantDeclaration(_,T)},this.InlineLogicOrGlueOrStartTag=()=>this.OneOf([this.InlineLogic,this.Glue,this.StartTag]),this.Glue=()=>this.ParseString("<>")!==null?new k.Glue(new m.Glue):null,this.InlineLogic=()=>{if(this.ParseString("{")===null)return null;let d=this.parsingStringExpression,_=this.tagActive;this.Whitespace();const T=this.Expect(this.InnerLogic,"some kind of logic, conditional or sequence within braces: { ... }");if(T===null)return this.parsingStringExpression=d,null;this.DisallowIncrement(T);let D=(0,Et.asOrNull)(T,s.ContentList);return D||(D=new s.ContentList(T)),this.Whitespace(),this.Expect(this.String("}"),"closing brace '}' for inline logic"),this.parsingStringExpression=d,_||this.EndTagIfNecessary(D),D},this.InnerLogic=()=>{this.Whitespace();const d=this.ParseObject(this.SequenceTypeAnnotation);if(d!==null){const D=this.Expect(this.InnerSequenceObjects,"sequence elements (for cycle/stoping etc)");return D===null?null:new x.Sequence(D,d)}const _=this.Parse(this.ConditionExpression);if(_)return this.Expect(()=>this.InnerConditionalContent(_),"conditional content following query");const T=[this.InnerConditionalContent,this.InnerSequence,this.InnerExpression];for(const D of T){const U=this.BeginRule(),$=this.ParseObject(D);if($)if(this.Peek(this.Spaced(this.String("}")))===null)this.FailRule(U);else return this.SucceedRule(U,$);else this.FailRule(U)}return null},this.InnerExpression=()=>{const d=this.Parse(this.Expression);return d&&(d.outputWhenComplete=!0),d},this.IdentifierWithMetadata=()=>{const d=this.Identifier();return d===null?null:new Vt.Identifier(d)},this.Identifier=()=>{const d=this.ParseCharactersFromCharSet(this.identifierCharSet);if(d===null)return null;let _=!0;for(let T of d)if(!(T>="0"&&T<="9")){_=!1;break}return _?null:d},this._sequenceTypeSymbols=new f.CharacterSet("!&~$"),this.InnerSequence=()=>{this.Whitespace();let d=A.SequenceType.Stopping;const _=this.Parse(this.SequenceTypeAnnotation);_!==null&&(d=_);const T=this.Parse(this.InnerSequenceObjects);return T===null||T.length<=1?null:new x.Sequence(T,d)},this.SequenceTypeAnnotation=()=>{let d=this.Parse(this.SequenceTypeSymbolAnnotation);if(d===null&&(d=this.Parse(this.SequenceTypeWordAnnotation)),d===null)return null;switch(d){case A.SequenceType.Once:case A.SequenceType.Cycle:case A.SequenceType.Stopping:case A.SequenceType.Shuffle:case A.SequenceType.Shuffle|A.SequenceType.Stopping:case A.SequenceType.Shuffle|A.SequenceType.Once:break;default:return this.Error(`Sequence type combination not supported: ${d}`),A.SequenceType.Stopping}return d},this.SequenceTypeSymbolAnnotation=()=>{this._sequenceTypeSymbols===null&&(this._sequenceTypeSymbols=new f.CharacterSet("!&~$ "));let d=0;const _=this.ParseCharactersFromCharSet(this._sequenceTypeSymbols);if(_===null)return null;for(const T of _)switch(T){case"!":d|=A.SequenceType.Once;break;case"&":d|=A.SequenceType.Cycle;break;case"~":d|=A.SequenceType.Shuffle;break;case"$":d|=A.SequenceType.Stopping;break}return d===0?null:d},this.SequenceTypeWordAnnotation=()=>{const d=this.Interleave(this.SequenceTypeSingleWord,this.Exclude(this.Whitespace));if(d===null||d.length===0||this.ParseString(":")===null)return null;let _=0;for(const T of d)_|=T;return _},this.SequenceTypeSingleWord=()=>{let d=null;const _=this.Parse(this.IdentifierWithMetadata);if(_!==null)switch(_.name){case"once":d=A.SequenceType.Once;break;case"cycle":d=A.SequenceType.Cycle;break;case"shuffle":d=A.SequenceType.Shuffle;break;case"stopping":d=A.SequenceType.Stopping;break}return d===null?null:d},this.InnerSequenceObjects=()=>{const d=this.Parse(this.Newline)!==null;let _=null;return d?_=this.Parse(this.InnerMultilineSequenceObjects):_=this.Parse(this.InnerInlineSequenceObjects),_},this.InnerInlineSequenceObjects=()=>{const d=this.Interleave(this.Optional(this.MixedTextAndLogic),this.String("|"),null,!1);if(d===null)return null;const _=[];let T=!1;for(const D of d)if(D==="|")T||_.push(new s.ContentList),T=!1;else{const U=D;U===null?this.Error(`Expected content, but got ${D} (this is an ink compiler bug!)`):_.push(new s.ContentList(U)),T=!0}return T||_.push(new s.ContentList),_},this.InnerMultilineSequenceObjects=()=>{this.MultilineWhitespace();const d=this.OneOrMore(this.SingleMultilineSequenceElement);return d===null?null:d},this.SingleMultilineSequenceElement=()=>{if(this.Whitespace(),this.ParseString("->")!==null||this.ParseString("-")===null)return null;this.Whitespace();const d=this.StatementsAtLevel(W.StatementLevel.InnerBlock);return d===null?this.MultilineWhitespace():d.unshift(new Y.Text(`
|
|
42
42
|
`)),new s.ContentList(d)},this._statementRulesAtLevel=[],this._statementBreakRulesAtLevel=[],this.StatementsAtLevel=d=>(d===W.StatementLevel.InnerBlock&&this.Parse(this.GatherDashes)!==null&&this.Error("You can't use a gather (the dashes) within the { curly braces } context. For multi-line sequences and conditions, you should only use one dash."),this.Interleave(this.Optional(this.MultilineWhitespace),()=>this.StatementAtLevel(d),()=>this.StatementsBreakForLevel(d))),this.StatementAtLevel=d=>{const _=this._statementRulesAtLevel[d],T=this.OneOf(_);return d===W.StatementLevel.Top&&T instanceof E.ReturnType&&this.Error("should not have return statement outside of a knot"),T},this.StatementsBreakForLevel=d=>{this.Whitespace();const _=this._statementBreakRulesAtLevel[d],T=this.OneOf(_);return T===null?null:T},this.GenerateStatementLevelRules=()=>{const d=Object.values(W.StatementLevel);this._statementRulesAtLevel="f".repeat(d.length).split("f").map(()=>[]),this._statementBreakRulesAtLevel="f".repeat(d.length).split("f").map(()=>[]);for(const _ of d){const T=[],D=[];T.push(this.Line(this.MultiDivert)),_>=W.StatementLevel.Top&&T.push(this.KnotDefinition),T.push(this.Line(this.Choice)),T.push(this.Line(this.AuthorWarning)),_>W.StatementLevel.InnerBlock&&T.push(this.Gather),_>=W.StatementLevel.Knot&&T.push(this.StitchDefinition),T.push(this.Line(this.ListDeclaration)),T.push(this.Line(this.VariableDeclaration)),T.push(this.Line(this.ConstDeclaration)),T.push(this.Line(this.ExternalDeclaration)),T.push(this.Line(this.IncludeStatement)),T.push(this.LogicLine),T.push(this.LineOfMixedTextAndLogic),_<=W.StatementLevel.Knot&&D.push(this.KnotDeclaration),_<=W.StatementLevel.Stitch&&D.push(this.StitchDeclaration),_<=W.StatementLevel.InnerBlock&&(D.push(this.ParseDashNotArrow),D.push(this.String("}"))),this._statementRulesAtLevel[_]=T,this._statementBreakRulesAtLevel[_]=D}},this.SkipToNextLine=()=>(this.ParseUntilCharactersFromString(`
|
|
43
|
-
\r`),this.ParseNewline(),Q.ParseSuccess),this.Line=d=>()=>{const _=this.ParseObject(d);return _===null?null:(this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),_)},this.StartTag=()=>{if(this.Whitespace(),this.ParseString("#")===null)return null;this.parsingStringExpression&&this.Error("Tags aren't allowed inside of strings. Please use \\# if you want a hash symbol.");let d=null;if(this.tagActive){let _=new s.ContentList;_.AddContent(new ut.Tag(!1)),_.AddContent(new ut.Tag(!0)),d=_}else d=new ut.Tag(!0);return this.tagActive=!0,this.Whitespace(),d},this._inlineWhitespaceChars=new f.CharacterSet(" "),this.EndOfLine=()=>this.OneOf([this.Newline,this.EndOfFile]),this.Newline=()=>(this.Whitespace(),this.ParseNewline()!==null?Q.ParseSuccess:null),this.EndOfFile=()=>(this.Whitespace(),this.endOfInput?Q.ParseSuccess:null),this.MultilineWhitespace=()=>{let d=this.OneOrMore(this.Newline);return d===null?null:d.length>=1?Q.ParseSuccess:null},this.Whitespace=()=>this.ParseCharactersFromCharSet(this._inlineWhitespaceChars)!==null?Q.ParseSuccess:null,this.Spaced=d=>()=>{this.Whitespace();const _=this.ParseObject(d);return _===null?null:(this.Whitespace(),_)},this.AnyWhitespace=()=>{let d=!1;for(;this.OneOf([this.Whitespace,this.MultilineWhitespace])!==null;)d=!0;return d?Q.ParseSuccess:null},this.MultiSpaced=d=>()=>{this.AnyWhitespace();const _=this.ParseObject(d);return _===null?null:(this.AnyWhitespace(),_)},this._filename=null,this._externalErrorHandler=null,this._fileHandler=null,this._filename=wt,this.RegisterExpressionOperators(),this.GenerateStatementLevelRules(),this.errorHandler=this.OnStringParserError,this._externalErrorHandler=ht,bt===null?this._fileHandler=new di.DefaultFileHandler:this._fileHandler=bt,lt===null){if(this._rootParser=this,this._openFilenames=[],this._filename!==null){const d=this.fileHandler.ResolveInkFilename(this._filename);this._openFilenames.push(d)}}else this._rootParser=lt}PreProcessInputString(
|
|
44
|
-
`||w=="\r"?I=!0:I&&(O++,I=!1);s+=O}const c=r.FindAll(e.Knot)(),i=r.FindAll(f.Stitch)(),l=r.FindAll(o.Choice)(),S=r.FindAll(a.Gather)(N=>N.debugMetadata!=null),P=r.FindAll(n.Divert)();return{words:s,knots:c.length,functions:c.filter(N=>N.isFunction).length,stitches:i.length,gathers:S.length,diverts:P.length-1,choices:l.length}}return
|
|
43
|
+
\r`),this.ParseNewline(),Q.ParseSuccess),this.Line=d=>()=>{const _=this.ParseObject(d);return _===null?null:(this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),_)},this.StartTag=()=>{if(this.Whitespace(),this.ParseString("#")===null)return null;this.parsingStringExpression&&this.Error("Tags aren't allowed inside of strings. Please use \\# if you want a hash symbol.");let d=null;if(this.tagActive){let _=new s.ContentList;_.AddContent(new ut.Tag(!1)),_.AddContent(new ut.Tag(!0)),d=_}else d=new ut.Tag(!0);return this.tagActive=!0,this.Whitespace(),d},this._inlineWhitespaceChars=new f.CharacterSet(" "),this.EndOfLine=()=>this.OneOf([this.Newline,this.EndOfFile]),this.Newline=()=>(this.Whitespace(),this.ParseNewline()!==null?Q.ParseSuccess:null),this.EndOfFile=()=>(this.Whitespace(),this.endOfInput?Q.ParseSuccess:null),this.MultilineWhitespace=()=>{let d=this.OneOrMore(this.Newline);return d===null?null:d.length>=1?Q.ParseSuccess:null},this.Whitespace=()=>this.ParseCharactersFromCharSet(this._inlineWhitespaceChars)!==null?Q.ParseSuccess:null,this.Spaced=d=>()=>{this.Whitespace();const _=this.ParseObject(d);return _===null?null:(this.Whitespace(),_)},this.AnyWhitespace=()=>{let d=!1;for(;this.OneOf([this.Whitespace,this.MultilineWhitespace])!==null;)d=!0;return d?Q.ParseSuccess:null},this.MultiSpaced=d=>()=>{this.AnyWhitespace();const _=this.ParseObject(d);return _===null?null:(this.AnyWhitespace(),_)},this._filename=null,this._externalErrorHandler=null,this._fileHandler=null,this._filename=wt,this.RegisterExpressionOperators(),this.GenerateStatementLevelRules(),this.errorHandler=this.OnStringParserError,this._externalErrorHandler=ht,bt===null?this._fileHandler=new di.DefaultFileHandler:this._fileHandler=bt,lt===null){if(this._rootParser=this,this._openFilenames=[],this._filename!==null){const d=this.fileHandler.ResolveInkFilename(this._filename);this._openFilenames.push(d)}}else this._rootParser=lt}PreProcessInputString(K){return new p.CommentEliminator(K).Process()}get parsingStringExpression(){return this.GetFlag(Number(i.CustomFlags.ParsingString))}set parsingStringExpression(K){this.SetFlag(Number(i.CustomFlags.ParsingString),K)}get tagActive(){return this.GetFlag(Number(i.CustomFlags.TagActive))}set tagActive(K){this.SetFlag(Number(i.CustomFlags.TagActive),K)}get identifierCharSet(){return this._identifierCharSet===null&&((this._identifierCharSet=new f.CharacterSet).AddRange("A","Z").AddRange("a","z").AddRange("0","9").Add("_"),this.ExtendIdentifierCharacterRanges(this._identifierCharSet)),this._identifierCharSet}EndTagIfNecessary(K){this.tagActive&&(K!=null&&(K instanceof s.ContentList?K.AddContent(new ut.Tag(!1)):K.push(new ut.Tag(!1))),this.tagActive=!1)}};return le.InkParser=B,B.LatinBasic=e.CharacterRange.Define("A","z",new f.CharacterSet().AddRange("[","`")),B.LatinExtendedA=e.CharacterRange.Define("Ā","ſ"),B.LatinExtendedB=e.CharacterRange.Define("ƀ","ɏ"),B.Greek=e.CharacterRange.Define("Ͱ","Ͽ",new f.CharacterSet().AddRange("","΅").AddCharacters("ʹ͵·")),B.Cyrillic=e.CharacterRange.Define("Ѐ","ӿ",new f.CharacterSet().AddRange("҂","҉")),B.Armenian=e.CharacterRange.Define("","֏",new f.CharacterSet().AddCharacters("").AddRange("","ՠ").AddRange("ֈ","֎")),B.Hebrew=e.CharacterRange.Define("","",new f.CharacterSet),B.Arabic=e.CharacterRange.Define("","ۿ",new f.CharacterSet),B.Korean=e.CharacterRange.Define("가","",new f.CharacterSet),B.Latin1Supplement=e.CharacterRange.Define("","ÿ",new f.CharacterSet),B.Chinese=e.CharacterRange.Define("一","鿿",new f.CharacterSet),B.ListAllCharacterRanges=()=>[B.LatinBasic,B.LatinExtendedA,B.LatinExtendedB,B.Arabic,B.Armenian,B.Cyrillic,B.Greek,B.Hebrew,B.Korean,B.Latin1Supplement,B.Chinese],le}var Ln={},As;function za(){if(As)return Ln;As=1,Object.defineProperty(Ln,"__esModule",{value:!0}),Ln.GenerateStoryStats=void 0;const o=$n(),n=zn(),a=li(),e=na(),f=sa(),t=$t();function p(r){let y=r.FindAll(t.Text)(),s=0;for(const N of y){let O=0,I=!0;for(const w of N.text)w==" "||w==" "||w==`
|
|
44
|
+
`||w=="\r"?I=!0:I&&(O++,I=!1);s+=O}const c=r.FindAll(e.Knot)(),i=r.FindAll(f.Stitch)(),l=r.FindAll(o.Choice)(),S=r.FindAll(a.Gather)(N=>N.debugMetadata!=null),P=r.FindAll(n.Divert)();return{words:s,knots:c.length,functions:c.filter(N=>N.isFunction).length,stitches:i.length,gathers:S.length,diverts:P.length-1,choices:l.length}}return Ln.GenerateStoryStats=p,Ln}var jn={},Fs;function Xa(){if(Fs)return jn;Fs=1,Object.defineProperty(jn,"__esModule",{value:!0}),jn.JsonFileHandler=void 0;let o=class{constructor(a){this.fileHierarchy=a,this.ResolveInkFilename=e=>{if(Object.keys(this.fileHierarchy).includes(e))return e;throw new Error(`Cannot locate ${e}. Are you trying a relative import ? This is not yet implemented.`)},this.LoadInkFileContents=e=>{if(Object.keys(this.fileHierarchy).includes(e))return this.fileHierarchy[e];throw new Error(`Cannot open ${e}.`)}}};return jn.JsonFileHandler=o,jn}var Rs;function Ya(){return Rs||(Rs=1,(function(o){Object.defineProperty(o,"__esModule",{value:!0}),o.Compiler=o.Story=o.InkList=o.JsonFileHandler=o.StatementLevel=o.InkParser=o.CompilerOptions=void 0;const n=vi(),a=_a(),e=Oi(),f=Is(),t=it(),p=Z(),r=za();var y=vi();Object.defineProperty(o,"CompilerOptions",{enumerable:!0,get:function(){return y.CompilerOptions}});var s=Is();Object.defineProperty(o,"InkParser",{enumerable:!0,get:function(){return s.InkParser}});var c=ra();Object.defineProperty(o,"StatementLevel",{enumerable:!0,get:function(){return c.StatementLevel}});var i=Xa();Object.defineProperty(o,"JsonFileHandler",{enumerable:!0,get:function(){return i.JsonFileHandler}});var l=ci();Object.defineProperty(o,"InkList",{enumerable:!0,get:function(){return l.InkList}}),Object.defineProperty(o,"Story",{enumerable:!0,get:function(){return l.Story}});class S{get errors(){return this._errors}get warnings(){return this._warnings}get authorMessages(){return this._authorMessages}get inputString(){return this._inputString}get options(){return this._options}get parsedStory(){if(!this._parsedStory)throw new Error;return this._parsedStory}get runtimeStory(){if(!this._runtimeStory)throw new Error("Compilation failed.");return this._runtimeStory}get parser(){if(!this._parser)throw new Error;return this._parser}get debugSourceRanges(){return this._debugSourceRanges}constructor(N,O=null){this._errors=[],this._warnings=[],this._authorMessages=[],this._parsedStory=null,this._runtimeStory=null,this._parser=null,this._debugSourceRanges=[],this.Compile=()=>(this._parser=new f.InkParser(this.inputString,this.options.sourceFilename||null,this.OnError,null,this.options.fileHandler),this._parsedStory=this.parser.ParseStory(),this.errors.length===0?(this.parsedStory.countAllVisits=this.options.countAllVisits,this._runtimeStory=this.parsedStory.ExportRuntime(this.OnError)):this._runtimeStory=null,this.runtimeStory),this.RetrieveDebugSourceForLatestContent=()=>{var I;for(const w of this.runtimeStory.state.outputStream){const F=(0,p.asOrNull)(w,t.StringValue);if(F!==null){const k=new a.DebugSourceRange(((I=F.value)===null||I===void 0?void 0:I.length)||0,F.debugMetadata,F.value||"unknown");this.debugSourceRanges.push(k)}}},this.GenerateStats=()=>this._parsedStory===null?null:(0,r.GenerateStoryStats)(this._parsedStory),this.DebugMetadataForContentAtOffset=I=>{let w=0,F=null;for(const k of this.debugSourceRanges){if(k.debugMetadata!==null&&(F=k.debugMetadata),I>=w&&I<w+k.length)return F;w+=k.length}return null},this.OnError=(I,w)=>{switch(w){case e.ErrorType.Author:this._authorMessages.push(I);break;case e.ErrorType.Warning:this._warnings.push(I);break;case e.ErrorType.Error:this._errors.push(I);break}this.options.errorHandler!==null&&this.options.errorHandler(I,w)},this._inputString=N,this._options=O||new n.CompilerOptions}}o.Compiler=S})(pi)),pi}var Za=Ya(),Qa=vi();class to{constructor(n){z(this,"handler");z(this,"resolve");z(this,"ResolveInkFilename",n=>this.resolve(n));z(this,"LoadInkFileContents",n=>this.handler.loadFile(n));this.handler=n,this.resolve=n instanceof Ds?a=>n.resolveFilename(a):a=>a}}function eo(o){const n=o.trim();return n.startsWith("{")&&n.endsWith("}")}function no(o,n){let a;if(o instanceof Li.Story)a=o;else if(typeof o=="string")if(eo(o))a=new Li.Story(o);else{const e=(n==null?void 0:n.errorHandler)||null,f=n!=null&&n.fileHandler?new to(n.fileHandler):null,t=new Qa.CompilerOptions(null,[],!1,e,f);a=new Za.Compiler(o,t).Compile()}else throw new Error("Invalid source type: expected string or Story");return new Ls(a,(n==null?void 0:n.title)||"Ink Story",n)}exports.BaseFileHandler=Ds;exports.CHOICE_SEPARATOR=ks;exports.Choice=Vs;exports.ChoiceParser=qn;exports.ExternalFunctions=ni;exports.InkStory=Ls;exports.Parser=ei;exports.Patches=ti;exports.Tags=Yt;exports.choicesStore=Ci;exports.contentsStore=Mn;exports.createInkStory=no;exports.createSelectors=ii;exports.variablesStore=Ws;
|
|
45
45
|
//# sourceMappingURL=index.cjs.map
|