!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define("inkjs",["exports"],e):e(t.inkjs=t.inkjs||{})}(this,function(t){"use strict";var e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},n=function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")},a=function(){function t(t,e){for(var n=0;n0?this.components[0]:null}},{key:"tail",get:function(){return this.components.length>=2?new t(this.components.slice(1,this.components.length)):t.self}},{key:"length",get:function(){return this.components.length}},{key:"lastComponent",get:function(){return this.components.length>0?this.components[this.components.length-1]:null}},{key:"containsNamedComponent",get:function(){for(var t=0,e=this.components.length;t=0}},{key:"isParent",get:function(){return this.name==u.parentId}}],[{key:"ToParent",val ue:function(){return new t(u.parentId)}}]),t}();u.parentId="^",u.Component=l;var h=function(){function t(){n(this,t),this.parent=null,this._path=null}return a(t,[{key:"ResolvePath",value:function(t){if(t.isRelative){var e=this;return e instanceof T==!1&&(null==this.parent&&console.warn("Can't resolve relative path because we don't have a parent"),"Container"!==(e=this.parent).constructor.name&&console.warn("Expected parent to be a container"),t=t.tail),e.ContentAtPath(t)}return this.rootContentContainer.ContentAtPath(t)}},{key:"ConvertPathToRelative",value:function(t){for(var e=this.path,n=Math.min(t.components.length,e.components.length),i=-1,a=0;at.maxItem.Value)}},{key:"GreaterThanOrEquals",value:function(t){return 0!=this.Count&&(0==t.Count||this.minItem.Value>=t.minItem.Value&&this.maxItem.Value>=t.maxItem.Value)}},{key:"LessThan",value:function(t){return 0!=t.Count&&(0==this.Count||this.maxItem.Value0?new t(this.maxItem):new t}},{key:"MinAsList",value:function(){return this.Count>0?new t(this.minItem):new t}},{key:"Equals",value:function(e){var n=e;if(n instanceof t==!1)return!1;if(n.Count!=this.Count)return!1;var i=!0;return this.forEach(function(t){n.ContainsKey(t.Key)||(i=!1)}),i}},{key:"toString",value:function(){var t=[];this.forEach(function(e){t.push(e)}),t=t.sort(function(t,e){return t.Value===e.Value?0:t.Value>e.Value?1:-1});for(var e=new c,n=0;n0&&e.Append(", ");var i=t[n].Key;e.Append(i.itemName)}return e.toString()}},{key:"valueOf",value:function(){return NaN}},{key:"Count",get:function(){return Object.keys(this._values).length}},{key:"originOfMaxItem",get:function(){if(null==this.origins)return null;var t=this.maxItem.Key.originName,e=null;return this.origins.every(function(n){return n.name!=t||(e=n,!1)}),e}},{key:"originNames",get:function(){var t=this;return this.Count>0&&(null==this._originNames&&this.Count>0?this._originNames =[]:this._originNames.length=0,this.forEach(function(e){t._originNames.push(e.Key.originName)})),this._originNames}},{key:"maxItem",get:function(){var t={Key:null,Value:null};return this.forEach(function(e){(null===t.Key||e.Value>t.Value)&&(t=e)}),t}},{key:"minItem",get:function(){var t={Key:null,Value:null};return this.forEach(function(e){(null===t.Key||e.Value0}},{key:"isNewline",get:function(){return this._isNewline}},{key:"isInlineWhitespace",get:function(){return this._isInlineWhitespace}},{key:"isNonWhitespace",get:function(){return!this.isNewline&&!this.isInlineWhitespace}}]),e}(p),k=function(t){function e(t){n(this,e);var i=s(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t));return i._valueType=d.DivertTarget,i}return o(e,t),a(e,[{key:"Cast",value:function(t){if(t==this.valueType)return this;throw"Unexpected type cast of Value to new ValueType"}},{key:"toString",value:function(){return"DivertTargetValue("+this.targetPath+")"}},{key:"targetPath",get:function(){return this.value},set:function(t){th is.value=t}},{key:"isTruthy",get:function(){throw"Shouldn't be checking the truthiness of a divert target"}}]),e}(p),C=function(t){function e(t,i){n(this,e);var a=s(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t));return a._valueType=d.VariablePointer,a.contextIndex=void 0!==i?i:-1,a}return o(e,t),a(e,[{key:"Cast",value:function(t){if(t==this.valueType)return this;throw"Unexpected type cast of Value to new ValueType"}},{key:"toString",value:function(){return"VariablePointerValue("+this.variableName+")"}},{key:"Copy",value:function(){return new e(this.variableName,this.contextIndex)}},{key:"variableName",get:function(){return this.value},set:function(t){this.value=t}},{key:"isTruthy",get:function(){throw"Shouldn't be checking the truthiness of a variable pointer"}}]),e}(p),S=function(t){function e(t,i){n(this,e);var a=s(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,null));return a._valueType=d.List,a.value=t instanceof v?new v(t):void 0!==t&&void 0!==i?new v({Key:t,Value:i}):new v,a}return o(e,t),a(e,[{key:"Cast",value:function(t){if(t==d.Int){e=this.value.maxItem;return new y(e.Key.isNull?0:e.Value)}if(t==d.Float){e=this.value.maxItem;return new m(e.Key.isNull?0:parseFloat(e.Value))}if(t==d.String){var e=value.maxItem;return new g(e.Key.isNull?"":e.Key.toString())}if(t==this.valueType)return this;throw"Unexpected type cast of Value to new ValueType"}},{key:"valueType",get:function(){return d.List}},{key:"isTruthy",get:function(){var t=!1;return this.value.forEach(function(e){0!=e.Value&&(t=!0)}),t}}]),a(e,null,[{key:"RetainListOriginsForAssignment",value:function(t,n){var i=t,a=n;i instanceof e&&a instanceof e&&0==a.value.Count&&a.value.SetInitialOriginNames(i.value.originNames)}}]),e}(p),b=function(t){function e(t){n(this,e);var i=s(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t));return i.message=t,i.name="StoryException",i}return o(e,t),e}(Error),T=function(t){function e(){n(this,e);var t=s(this,(e.__proto__||Object.getPrototypeOf(e)).call(this));return t.name="",t._content=[],t. namedContent={},t.visitsShouldBeCounted=!1,t.turnIndexShouldBeCounted=!1,t.countingAtStartOnly=!1,t.CountFlags={Visits:1,Turns:2,CountStartOnly:4},t._pathToFirstLeafContent=null,t}return o(e,t),a(e,[{key:"AddContent",value:function(t){var e=this;if(t instanceof Array)t.forEach(function(t){e.AddContent(t)});else{if(this._content.push(t),t.parent)throw"content is already in "+t.parent;t.parent=this,this.TryAddNamedContent(t)}}},{key:"TryAddNamedContent",value:function(t){t.hasValidName&&t.name&&this.AddToNamedContentOnly(t)}},{key:"AddToNamedContentOnly",value:function(t){t instanceof h==!1&&console.warn("Can only add Runtime.Objects to a Runtime.Container"),t.parent=this,this.namedContent[t.name]=t}},{key:"ContentAtPath",value:function(t,n){n=void 0!==n?n:t.components.length;for(var i=this,a=this,r=0;r=0&&t.index=0||(s[u]=this.namedContent[u]);if(Object.keys(s).length>0){a(),t.AppendLine("-- named: --");for(var u in s){s[u]instanceof e||console.warn("Can only print out named Containers");var l=s[u];l.BuildStringOfHierarchy(t,n,i),t.Append("\n")}}n--,a(),t.Append("]")}},{key:"hasValidName",get:function(){return null!=this.name&&this.name.length>0}},{key:"content",get:function(){return this._content},set:function(t){this.AddContent(t)}},{key:"namedOnlyContent",get:function(){var t={};for(var e in this.namedContent)t[e]=this.namedContent[e];return this.content.forEach(function(e){var n=e;n.name&&n.hasValidName&&delete t[n.name]}),0==Object.keys(t).length&&(t=null),t},set:function(t){var e=this.namedOnlyContent;if(null!=e)for(var n in e)delete this.namedCo ntent[n];if(null!=t)for(var n in t){var i=t[n];i.name&&void 0!==i.hasValidName&&this.AddToNamedContentOnly(i)}}},{key:"countFlags",get:function(){var t=0;return this.visitsShouldBeCounted&&(t|=this.CountFlags.Visits),this.turnIndexShouldBeCounted&&(t|=this.CountFlags.Turns),this.countingAtStartOnly&&(t|=this.CountFlags.CountStartOnly),t==this.CountFlags.CountStartOnly&&(t=0),t},set:function(t){var e=t;(e&this.CountFlags.Visits)>0&&(this.visitsShouldBeCounted=!0),(e&this.CountFlags.Turns)>0&&(this.turnIndexShouldBeCounted=!0),(e&this.CountFlags.CountStartOnly)>0&&(this.countingAtStartOnly=!0)}},{key:"pathToFirstLeafContent",get:function(){return null==this._pathToFirstLeafContent&&(this._pathToFirstLeafContent=this.path.PathByAppendingPath(this.internalPathToFirstLeafContent)),this._pathToFirstLeafContent}},{key:"internalPathToFirstLeafContent",get:function(){for(var t=new Path,n=this;n instanceof e;)n.content.length>0&&(t.components.push(new Path.Component(0)),n=n.content[0]);return t}}]),e}(h),_=function(t) {function e(t){n(this,e);var i=s(this,(e.__proto__||Object.getPrototypeOf(e)).call(this));return i.glueType=t,i}return o(e,t),a(e,[{key:"toString",value:function(){switch(this.glueType){case O.Bidirectional:return"BidirGlue";case O.Left:return"LeftGlue";case O.Right:return"RightGlue"}return"UnexpectedGlueType"}},{key:"isLeft",get:function(){return this.glueType==O.Left}},{key:"isBi",get:function(){return this.glueType==O.Bidirectional}},{key:"isRight",get:function(){return this.glueType==O.Right}}]),e}(h),O={Bidirectional:0,Left:1,Right:2},E=function(t){function e(t){n(this,e);var i=s(this,(e.__proto__||Object.getPrototypeOf(e)).call(this));return i._commandType=void 0!==t?t:w.NotSet,i}return o(e,t),a(e,[{key:"copy",value:function(){return new e(this.commandType)}},{key:"toString",value:function(){return this.commandType.toString()}},{key:"commandType",get:function(){return this._commandType}}],[{key:"EvalStart",value:function(){return new e(w.EvalStart)}},{key:"EvalOutput",value:function(){return new e(w.Ev alOutput)}},{key:"EvalEnd",value:function(){return new e(w.EvalEnd)}},{key:"Duplicate",value:function(){return new e(w.Duplicate)}},{key:"PopEvaluatedValue",value:function(){return new e(w.PopEvaluatedValue)}},{key:"PopFunction",value:function(){return new e(w.PopFunction)}},{key:"PopTunnel",value:function(){return new e(w.PopTunnel)}},{key:"BeginString",value:function(){return new e(w.BeginString)}},{key:"EndString",value:function(){return new e(w.EndString)}},{key:"NoOp",value:function(){return new e(w.NoOp)}},{key:"ChoiceCount",value:function(){return new e(w.ChoiceCount)}},{key:"TurnsSince",value:function(){return new e(w.TurnsSince)}},{key:"ReadCount",value:function(){return new e(w.ReadCount)}},{key:"Random",value:function(){return new e(w.Random)}},{key:"SeedRandom",value:function(){return new e(w.SeedRandom)}},{key:"VisitIndex",value:function(){return new e(w.VisitIndex)}},{key:"SequenceShuffleIndex",value:function(){return new e(w.SequenceShuffleIndex)}},{key:"StartThread",value:function(){return ne w e(w.StartThread)}},{key:"Done",value:function(){return new e(w.Done)}},{key:"End",value:function(){return new e(w.End)}},{key:"ListFromInt",value:function(){return new e(w.ListFromInt)}},{key:"ListRange",value:function(){return new e(w.ListRange)}}]),e}(h),w={NotSet:-1,EvalStart:0,EvalOutput:1,EvalEnd:2,Duplicate:3,PopEvaluatedValue:4,PopFunction:5,PopTunnel:6,BeginString:7,EndString:8,NoOp:9,ChoiceCount:10,TurnsSince:11,Random:12,SeedRandom:13,VisitIndex:14,SequenceShuffleIndex:15,StartThread:16,Done:17,End:18,ListFromInt:19,ListRange:20,ReadCount:21};w.TOTAL_VALUES=Object.keys(w).length-1,E.CommandType=w;var x={Tunnel:0,Function:1},I=function(t){function e(t){n(this,e);var i=s(this,(e.__proto__||Object.getPrototypeOf(e)).call(this));return i._targetPath,i._targetContent,i.variableDivertName,i.pushesToStack,i.stackPushType,i.isExternal,i.isConditional,i.externalArgs,i.pushesToStack=!1,t&&(i.pushesToStack=!0,i.stackPushType=t),i}return o(e,t),a(e,[{key:"Equals",value:function(t){var n=t;return n instanceof e&&this.hasVariableTarget==n.hasVariableTarget&&(this.hasVariableTarget?this.variableDivertName==n.variableDivertName:this.targetPath.Equals(n.targetPath))}},{key:"toString",value:function(){if(this.hasVariableTarget)return"Divert(variable: "+this.variableDivertName+")";if(null==this.targetPath)return"Divert(null)";var t=new c,e=this.targetPath.toString();return t.Append("Divert"),this.pushesToStack&&(this.stackPushType==x.Function?t.Append(" function"):t.Append(" tunnel")),t.Append(" ("),t.Append(e),t.Append(")"),t.toString()}},{key:"targetPath",get:function(){if(null!=this._targetPath&&this._targetPath.isRelative){var t=this.targetContent;t&&(this._targetPath=t.path)}return this._targetPath},set:function(t){this._targetPath=t,this._targetContent=null}},{key:"targetContent",get:function(){return null==this._targetContent&&(this._targetContent=this.ResolvePath(this._targetPath)),this._targetContent}},{key:"targetPathString",get:function(){return null==this.targetPath?null:this.CompactPathString(this.targetP ath)},set:function(t){this.targetPath=null==t?null:new u(t)}},{key:"hasVariableTarget",get:function(){return null!=this.variableDivertName}}]),e}(h),P=function(t){function e(t){n(this,e);var i=s(this,(e.__proto__||Object.getPrototypeOf(e)).call(this));return i._pathOnChoice,i.hasCondition,i.hasStartContent,i.hasChoiceOnlyContent,i.onceOnly,i.isInvisibleDefault,i.onceOnly=!!t,i}return o(e,t),a(e,[{key:"toString",value:function(){var t=this.pathOnChoice.toString();return"Choice: -> "+t}},{key:"pathOnChoice",get:function(){if(null!=this._pathOnChoice&&this._pathOnChoice.isRelative){var t=this.choiceTarget;t&&(this._pathOnChoice=t.path)}return this._pathOnChoice},set:function(t){this._pathOnChoice=t}},{key:"choiceTarget",get:function(){return this.ResolvePath(this._pathOnChoice)}},{key:"pathStringOnChoice",get:function(){return this.CompactPathString(this.pathOnChoice)},set:function(t){this.pathOnChoice=new u(t)}},{key:"flags",get:function(){var t=0;return this.hasCondition&&(t|=1),this.hasStartContent&&(t|=2),t his.hasChoiceOnlyContent&&(t|=4),this.isInvisibleDefault&&(t|=8),this.onceOnly&&(t|=16),t},set:function(t){this.hasCondition=(1&t)>0,this.hasStartContent=(2&t)>0,this.hasChoiceOnlyContent=(4&t)>0,this.isInvisibleDefault=(8&t)>0,this.onceOnly=(16&t)>0}}]),e}(h),A=function(t){function e(t){n(this,e);var i=s(this,(e.__proto__||Object.getPrototypeOf(e)).call(this));return i.name=t,i.pathForCount,i}return o(e,t),a(e,[{key:"toString",value:function(){return null!=this.name?"var("+this.name+")":"read_count("+this.pathStringForCount+")"}},{key:"containerForCount",get:function(){return this.ResolvePath(this.pathForCount)}},{key:"pathStringForCount",get:function(){return null==this.pathForCount?null:this.CompactPathString(this.pathForCount)},set:function(t){this.pathForCount=null==t?null:new u(t)}}]),e}(h),V=function(t){function e(t,i){n(this,e);var a=s(this,(e.__proto__||Object.getPrototypeOf(e)).call(this));return a._variableName=t||null,a._isNewDeclaration=!!i,a.isGlobal,a}return o(e,t),a(e,[{key:"toString",value:f unction(){return"VarAssign to "+this.variableName}},{key:"variableName",get:function(){return this._variableName}},{key:"isNewDeclaration",get:function(){return this._isNewDeclaration}}]),e}(h),N=function(t){function e(){return n(this,e),s(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return o(e,t),e}(h),F=function(t){function e(t){n(this,e);var i=s(this,(e.__proto__||Object.getPrototypeOf(e)).call(this));return i.name=t,i._numberOfParameters,i._prototype,i._isPrototype,i._operationFuncs=null,e.GenerateNativeFunctionsIfNecessary(),i}return o(e,t),a(e,[{key:"Call",value:function(t){if(this._prototype)return this._prototype.Call(t);if(this.numberOfParameters!=t.length)throw"Unexpected number of parameters";var e=!1;if(t.forEach(function(t){if(t instanceof N)throw new b("Attempting to perform operation on a void value. Did you forget to 'return' a value from a function you called here?");t instanceof S&&(e=!0)}),2==t.length&&e)return this.CallBinaryListOperation(t);var n=this.CoerceValuesT oSingleType(t),i=n[0].valueType;return i==d.Int?this.CallType(n):i==d.Float?this.CallType(n):i==d.String?this.CallType(n):i==d.DivertTarget?this.CallType(n):i==d.List?this.CallType(n):null}},{key:"CallType",value:function(t){var e=t[0],n=e.valueType,i=e,a=t.length;if(2==a||1==a){var r=this._operationFuncs[n];if(!r)throw new b("Cannot perform operation '"+this.name+"' on "+n);if(2==a){var o=t[1],s=(u=r)(i.value,o.value);return p.Create(s)}var u=r,s=u(i.value);return p.Create(s)}throw"Unexpected number of parameters to NativeFunctionCall: "+t.length}},{key:"CallBinaryListOperation",value:function(t){if(("+"==this.name||"-"==this.name)&&t[0]instanceof S&&t[1]instanceof y)return this.CallListIncrementOperation(t);var e=t[0],n=t[1];if(!("&&"!=this.name&&"||"!=this.name||e.valueType==d.List&&n.valueType==d.List)){var i=(0,this._operationFuncs[d.Int])(e.isTruthy?1:0,n.isTruthy?1:0);return new y(i)}if(e.valueType==d.List&&n.valueType==d.List)return this.CallType([e,n]);throw new b("Can not call use '"+this.name+"' o peration on "+e.valueType+" and "+n.valueType)}},{key:"CallListIncrementOperation",value:function(t){var e=this,n=t[0],i=t[1],a=new v;return n.value.forEach(function(t){var r=t.Key,o=t.Value,s=(0,e._operationFuncs[d.Int])(o,i.value),u=null;if(n.value.origins.forEach(function(t){if(t.name==r.originName)return u=t,!1}),null!=u){var l=u.TryGetItemWithValue(s);l.exists&&a.Add(l.item,s)}}),new S(a)}},{key:"CoerceValuesToSingleType",value:function(t){var e=d.Int,n=null;t.forEach(function(t){var i=t;i.valueType>e&&(e=i.valueType),i.valueType==d.List&&(n=i)});var i=[];return e==d.List?t.forEach(function(t){if(t.valueType==d.List)i.push(t);else{if(t.valueType!=d.Int)throw new b("Cannot mix Lists and "+t.valueType+" values in this operation");var e=parseInt(t.valueObject),a=n.value.originOfMaxItem,r=a.TryGetItemWithValue(e);if(!r.exists)throw new b("Could not find List item with the value "+e+" in "+a.name);var o=new S(r.item,e);i.push(o)}}):t.forEach(function(t){var n=t.Cast(e);i.push(n)}),i}},{key:"AddOpFuncForType" ,value:function(t,e){null==this._operationFuncs&&(this._operationFuncs={}),this._operationFuncs[t]=e}},{key:"toString",value:function(){return"Native '"+this.name+"'"}},{key:"name",get:function(){return this._name},set:function(t){this._name=t,this._isPrototype||(this._prototype=e._nativeFunctions[this._name])}},{key:"numberOfParameters",get:function(){return this._prototype?this._prototype.numberOfParameters:this._numberOfParameters},set:function(t){this._numberOfParameters=t}}],[{key:"internalConstructor",value:function(t,n){var i=new e(t);return i._isPrototype=!0,i.numberOfParameters=n,i}},{key:"CallWithName",value:function(t){return new e(t)}},{key:"CallExistsWithName",value:function(t){return this.GenerateNativeFunctionsIfNecessary(),this._nativeFunctions[t]}},{key:"GenerateNativeFunctionsIfNecessary",value:function(){if(null==this._nativeFunctions){this._nativeFunctions={},this.AddIntBinaryOp(this.Add,function(t,e){return t+e}),this.AddIntBinaryOp(this.Subtract,function(t,e){return t-e}),this.AddIntBin aryOp(this.Multiply,function(t,e){return t*e}),this.AddIntBinaryOp(this.Divide,function(t,e){return parseInt(t/e)}),this.AddIntBinaryOp(this.Mod,function(t,e){return t%e}),this.AddIntUnaryOp(this.Negate,function(t){return-t}),this.AddIntBinaryOp(this.Equal,function(t,e){return t==e?1:0}),this.AddIntBinaryOp(this.Greater,function(t,e){return t>e?1:0}),this.AddIntBinaryOp(this.Less,function(t,e){return t=e?1:0}),this.AddIntBinaryOp(this.LessThanOrEquals,function(t,e){return t<=e?1:0}),this.AddIntBinaryOp(this.NotEquals,function(t,e){return t!=e?1:0}),this.AddIntUnaryOp(this.Not,function(t){return 0==t?1:0}),this.AddIntBinaryOp(this.And,function(t,e){return 0!=t&&0!=e?1:0}),this.AddIntBinaryOp(this.Or,function(t,e){return 0!=t||0!=e?1:0}),this.AddIntBinaryOp(this.Max,function(t,e){return Math.max(t,e)}),this.AddIntBinaryOp(this.Min,function(t,e){return Math.min(t,e)}),this.AddFloatBinaryOp(this.Add,function(t,e){return t+e}),this.AddFl oatBinaryOp(this.Subtract,function(t,e){return t-e}),this.AddFloatBinaryOp(this.Multiply,function(t,e){return t*e}),this.AddFloatBinaryOp(this.Divide,function(t,e){return t/e}),this.AddFloatBinaryOp(this.Mod,function(t,e){return t%e}),this.AddFloatUnaryOp(this.Negate,function(t){return-t}),this.AddFloatBinaryOp(this.Equal,function(t,e){return t==e?1:0}),this.AddFloatBinaryOp(this.Greater,function(t,e){return t>e?1:0}),this.AddFloatBinaryOp(this.Less,function(t,e){return t=e?1:0}),this.AddFloatBinaryOp(this.LessThanOrEquals,function(t,e){return t<=e?1:0}),this.AddFloatBinaryOp(this.NotEquals,function(t,e){return t!=e?1:0}),this.AddFloatUnaryOp(this.Not,function(t){return 0==t?1:0}),this.AddFloatBinaryOp(this.And,function(t,e){return 0!=t&&0!=e?1:0}),this.AddFloatBinaryOp(this.Or,function(t,e){return 0!=t||0!=e?1:0}),this.AddFloatBinaryOp(this.Max,function(t,e){return Math.max(t,e)}),this.AddFloatBinaryOp(this.Min,function(t,e){retu rn Math.min(t,e)}),this.AddStringBinaryOp(this.Add,function(t,e){return t+e}),this.AddStringBinaryOp(this.Equal,function(t,e){return t===e?1:0}),this.AddStringBinaryOp(this.NotEquals,function(t,e){return t!==e?1:0}),this.AddListBinaryOp(this.Add,function(t,e){return t.Union(e)}),this.AddListBinaryOp(this.Subtract,function(t,e){return t.Without(e)}),this.AddListBinaryOp(this.Has,function(t,e){return t.Contains(e)?1:0}),this.AddListBinaryOp(this.Hasnt,function(t,e){return t.Contains(e)?0:1}),this.AddListBinaryOp(this.Intersect,function(t,e){return t.Intersect(e)}),this.AddListBinaryOp(this.Equal,function(t,e){return t.Equals(e)?1:0}),this.AddListBinaryOp(this.Greater,function(t,e){return t.GreaterThan(e)?1:0}),this.AddListBinaryOp(this.Less,function(t,e){return t.LessThan(e)?1:0}),this.AddListBinaryOp(this.GreaterThanOrEquals,function(t,e){return t.GreaterThanOrEquals(e)?1:0}),this.AddListBinaryOp(this.LessThanOrEquals,function(t,e){return t.LessThanOrEquals(e)?1:0}),this.AddListBinaryOp(this.NotEquals,functio n(t,e){return t.Equals(e)?0:1}),this.AddListBinaryOp(this.And,function(t,e){return t.Count>0&&e.Count>0?1:0}),this.AddListBinaryOp(this.Or,function(t,e){return t.Count>0||e.Count>0?1:0}),this.AddListUnaryOp(this.Not,function(t){return 0==t.Count?1:0}),this.AddListUnaryOp(this.Invert,function(t){return t.inverse}),this.AddListUnaryOp(this.All,function(t){return t.all}),this.AddListUnaryOp(this.ListMin,function(t){return t.MinAsList()}),this.AddListUnaryOp(this.ListMax,function(t){return t.MaxAsList()}),this.AddListUnaryOp(this.Count,function(t){return t.Count}),this.AddListUnaryOp(this.ValueOfList,function(t){return t.maxItem.Value});this.AddOpToNativeFunc(this.Equal,2,d.DivertTarget,function(t,e){return t.Equals(e)?1:0})}}},{key:"AddOpToNativeFunc",value:function(t,n,i,a){var r=this._nativeFunctions[t];r||(r=e.internalConstructor(t,n),this._nativeFunctions[t]=r),r.AddOpFuncForType(i,a)}},{key:"AddIntBinaryOp",value:function(t,e){this.AddOpToNativeFunc(t,2,d.Int,e)}},{key:"AddIntUnaryOp",value:function(t,e){t his.AddOpToNativeFunc(t,1,d.Int,e)}},{key:"AddFloatBinaryOp",value:function(t,e){this.AddOpToNativeFunc(t,2,d.Float,e)}},{key:"AddFloatUnaryOp",value:function(t,e){this.AddOpToNativeFunc(t,1,d.Float,e)}},{key:"AddStringBinaryOp",value:function(t,e){this.AddOpToNativeFunc(t,2,d.String,e)}},{key:"AddListBinaryOp",value:function(t,e){this.AddOpToNativeFunc(t,2,d.List,e)}},{key:"AddListUnaryOp",value:function(t,e){this.AddOpToNativeFunc(t,1,d.List,e)}}]),e}(h);F.Add="+",F.Subtract="-",F.Divide="/",F.Multiply="*",F.Mod="%",F.Negate="_",F.Equal="==",F.Greater=">",F.Less="<",F.GreaterThanOrEquals=">=",F.LessThanOrEquals="<=",F.NotEquals="!=",F.Not="!",F.And="&&",F.Or="||",F.Min="MIN",F.Max="MAX",F.Has="?",F.Hasnt="!?",F.Intersect="^",F.ListMin="LIST_MIN",F.ListMax="LIST_MAX",F.All="LIST_ALL",F.Count="LIST_COUNT",F.ValueOfList="LIST_VALUE",F.Invert="LIST_INVERT",F._nativeFunctions=null;var L=function(t){function e(t){n(this,e);var i=s(this,(e.__proto__||Object.getPrototypeOf(e)).call(this));return i._text=t.toString ()||"",i}return o(e,t),a(e,[{key:"toString",value:function(){return"# "+this._text}},{key:"text",get:function(){return this._text}}]),e}(h),j=function(){function t(e){n(this,t),this.text,this.index,this.choicePoint,this.threadAtGeneration,this._originalThreadIndex,this._originalChoicePath,e&&(this.choicePoint=e)}return a(t,[{key:"pathStringOnChoice",get:function(){return this.choicePoint.pathStringOnChoice}},{key:"sourcePath",get:function(){return this.choicePoint.path.componentsString}}]),t}(),R=function(){function t(e,i){n(this,t),this._name=e||"",this._items=null,this._rawListItemsKeys=null,this._itemNameToValues=i||{}}return a(t,[{key:"forEachItems",value:function(t){for(var e in this._rawListItemsKeys)t({Key:this._rawListItemsKeys[e],Value:this._items[e]})}},{key:"ValueForItem",value:function(t){var e=this._itemNameToValues[t.itemName];return void 0!==e?e:0}},{key:"ContainsItem",value:function(t){return t.originName==this.name&&t.itemName in this._itemNameToValues}},{key:"ContainsItemWithName",value:fun ction(t){return void 0!==this._itemNameToValues[t]}},{key:"TryGetItemWithValue",value:function(t,e){for(var n in this._itemNameToValues)if(this._itemNameToValues[n]==t)return e=new f(this.name,n),{item:e,exists:!0};return e=f.Null,{item:e,exists:!1}}},{key:"TryGetValueForItem",value:function(t,e){return intVal=this._itemNameToValues[t.itemName],intVal}},{key:"ListRange",value:function(t,e){var n=new v;for(var i in this._itemNameToValues)if(this._itemNameToValues[i]>=t&&this._itemNameToValues[i]<=e){var a=new f(this.name,i);n.Add(a,this._itemNameToValues[i])}return new S(n)}},{key:"name",get:function(){return this._name}},{key:"items",get:function(){if(null==this._items){this._items={},this._rawListItemsKeys={};for(var t in this._itemNameToValues){var e=new f(this.name,t);this._rawListItemsKeys[e]=e,this._items[e]=this._itemNameToValues[t]}}return this._items.forEach=this.forEachItems.bind(this),this._items}}]),t}(),D=function(){function t(e){var i=this;n(this,t),this._lists={},e.forEach(function(t){i._lists[ t.name]=t})}return a(t,[{key:"TryGetDefinition",value:function(t,e){return t in this._lists?this._lists[t]:e}},{key:"FindSingleItemListWithName",value:function(t){var e=f.Null,n=null,i=t.split(".");if(2==i.length)e=new f(i[0],i[1]),n=this.TryGetDefinition(e.originName,n);else for(var a in this._lists){var r=this._lists[a];if(e=new f(a,t),r.ContainsItem(e)){n=r;break}}if(null!=n){var o=n.ValueForItem(e);return new S(e,o)}return null}},{key:"lists",get:function(){var t=[];for(var e in this._lists)t.push(this._lists[e]);return t}}]),t}(),B=function(){function t(){n(this,t)}return a(t,null,[{key:"ListToJArray",value:function(t){var e=this,n=[];return t.forEach(function(t){n.push(e.RuntimeObjectToJToken(t))}),n}},{key:"JArrayToRuntimeObjList",value:function(t,e){var n=t.length;e&&n--;for(var i=[],a=0;a"==n)return new _(O.Bidirectional);if("G<"==n)return new _(O.Left);if("G>"==n)return new _(O.Right);for(var a=0;a->"==n)return E.PopTunnel();if("~ret"==n)return E.PopFunction();if("void"==n)return new N}if("object"===(void 0===t?"undefined":e(t))&&t instanceof Array==!1){var r,o=t;if(o["^->"])return r=o["^->"],new k(new u(r.toString()));if(o ["^var"]){r=o["^var"];var s=new C(r.toString());return o.ci&&(r=o.ci,s.contextIndex=parseInt(r)),s}var l=!1,h=!1,c=x.Function,d=!1;if((r=o["->"])?l=!0:(r=o["f()"])?(l=!0,h=!0,c=x.Function):(r=o["->t->"])?(l=!0,h=!0,c=x.Tunnel):(r=o["x()"])&&(l=!0,d=!0,h=!1,c=x.Function),l){var y=new I;y.pushesToStack=h,y.stackPushType=c,y.isExternal=d;var m=r.toString();return(r=o.var)?y.variableDivertName=m:y.targetPathString=m,y.isConditional=!!o.c,d&&(r=o.exArgs)&&(y.externalArgs=parseInt(r)),y}if(r=o["*"]){var b=new P;return b.pathStringOnChoice=r.toString(),(r=o.flg)&&(b.flags=parseInt(r)),b}if(r=o["VAR?"])return new A(r.toString());if(r=o["CNT?"]){var T=new A;return T.pathStringForCount=r.toString(),T}var w=!1,j=!1;if((r=o["VAR="])?(w=!0,j=!0):(r=o["temp="])&&(w=!0,j=!1),w){var R=r.toString(),D=!o.re,B=new V(R,D);return B.isGlobal=j,B}if(void 0!==o["#"])return r=o["#"],new L(r.toString());if(r=o.list){var J=r,M=new v;if(r=o.origins){var W=r;M.SetInitialOriginNames(W)}for(var q in J){var K=J[q],U=new f(q),H=parseInt(K); M.Add(U,H)}return new S(M)}if(null!=o.originalChoicePath)return this.JObjectToChoice(o)}if(t instanceof Array)return this.JArrayToContainer(t);if(null==t)return null;throw"Failed to convert token to runtime object: "+JSON.stringify(t)}},{key:"RuntimeObjectToJToken",value:function(t){var e=t;if(e instanceof T)return this.ContainerToJArray(e);var n=t;if(n instanceof I){var i="->";n.isExternal?i="x()":n.pushesToStack&&(n.stackPushType==x.Function?i="f()":n.stackPushType==x.Tunnel&&(i="->t->"));var a;return a=n.hasVariableTarget?n.variableDivertName:n.targetPathString,(O={})[i]=a,n.hasVariableTarget&&(O.var=!0),n.isConditional&&(O.c=!0),n.externalArgs>0&&(O.exArgs=n.externalArgs),O}var r=t;if(r instanceof P)return(O={})["*"]=r.pathStringOnChoice,O.flg=r.flags,O;var o=t;if(o instanceof y)return o.value;var s=t;if(s instanceof m)return s.value;var u=t;if(u instanceof g)return u.isNewline?"\n":"^"+u.value;var l=t;if(l instanceof S)return this.InkListToJObject(l);var h=t;if(h instanceof k)return{"^->":h.value.compon entsString};var c=t;if(c instanceof C)return{"^var":c.value,ci:c.contextIndex};var f=t;if(f instanceof _)return f.isBi?"<>":f.isLeft?"G<":"G>";var v=t;if(v instanceof E)return G[parseInt(v.commandType)];var d=t;if(d instanceof F){var p=d.name;return"^"==p&&(p="L^"),p}var b=t;if(b instanceof A){var O={},w=b.pathStringForCount;return null!=w?O["CNT?"]=w:O["VAR?"]=b.name,O}var R=t;if(R instanceof V)return(O={})[R.isGlobal?"VAR=":"temp="]=R.variableName,R.isNewDeclaration||(O.re=!0),O;if(t instanceof N)return"void";var D=t;if(D instanceof L)return(O={})["#"]=D.text,O;var B=t;if(B instanceof j)return this.ChoiceToJObject(B);throw"Failed to convert runtime object to Json token: "+t}},{key:"ContainerToJArray",value:function(t){var e=this.ListToJArray(t.content),n=t.namedOnlyContent,i=t.countFlags;if(null!=n&&n.length>0||i>0||null!=t.name){var a;if(null!=n){a=this.DictionaryRuntimeObjsToJObject(n);for(var r in a){var o=a[r];if(null!=o){var s=o[o.length-1];null!=s&&(delete s["#n"],0==Object.keys(s).length&&(o[o.lengt h-1]=null))}}}else a={};i>0&&(a["#f"]=i),null!=t.name&&(a["#n"]=t.name),e.push(a)}else e.push(null);return e}},{key:"JArrayToContainer",value:function(t){var e=new T;e.content=this.JArrayToRuntimeObjList(t,!0);var n=t[t.length-1];if(null!=n){var i={};for(var a in n)if("#f"==a)e.countFlags=parseInt(n[a]);else if("#n"==a)e.name=n[a].toString();else{var r=this.JTokenToRuntimeObject(n[a]),o=r;o instanceof T&&(o.name=a),i[a]=r}e.namedOnlyContent=i}return e}},{key:"JObjectToChoice",value:function(t){var e=new j;return e.text=t.text.toString(),e.index=parseInt(t.index),e.originalChoicePath=t.originalChoicePath.toString(),e.originalThreadIndex=parseInt(t.originalThreadIndex),e}},{key:"ChoiceToJObject",value:function(t){var e={};return e.text=t.text,e.index=t.index,e.originalChoicePath=t.originalChoicePath,e.originalThreadIndex=t.originalThreadIndex,e}},{key:"InkListToJObject",value:function(t){var e=t.value,n={},i={};return e.forEach(function(t){var e=t.Key,n=t.Value;i[e.toString()]=n}),n.list=i,0==e.Count&&null!=e. originNames&&e.originNames.length>0&&(n.origins=e.originNames),n}},{key:"ListDefinitionsToJToken",value:function(t){var e={};return t.lists.forEach(function(t){var n={};t.items.forEach(function(t){var e=t.Key,i=t.Value;n[e.itemName]=i}),e[t.name]=n}),e}},{key:"JTokenToListDefinitions",value:function(t){var e=t,n=[];for(var i in e){var a=i.toString(),r=e[i],o={};for(var s in r){var u=r[s];o[s]=parseInt(u)}var l=new R(a,o);n.push(l)}return new D(n)}}]),t}(),G=[];G[E.CommandType.EvalStart]="ev",G[E.CommandType.EvalOutput]="out",G[E.CommandType.EvalEnd]="/ev",G[E.CommandType.Duplicate]="du",G[E.CommandType.PopEvaluatedValue]="pop",G[E.CommandType.PopFunction]="~ret",G[E.CommandType.PopTunnel]="->->",G[E.CommandType.BeginString]="str",G[E.CommandType.EndString]="/str",G[E.CommandType.NoOp]="nop",G[E.CommandType.ChoiceCount]="choiceCnt",G[E.CommandType.TurnsSince]="turns",G[E.CommandType.ReadCount]="readc",G[E.CommandType.Random]="rnd",G[E.CommandType.SeedRandom]="srnd",G[E.CommandType.VisitIndex]="visit",G[E.Comm andType.SequenceShuffleIndex]="seq",G[E.CommandType.StartThread]="thread",G[E.CommandType.Done]="done",G[E.CommandType.End]="end",G[E.CommandType.ListFromInt]="listInt",G[E.CommandType.ListRange]="range";for(var J=0;J1}},{key:"canPopThread",get:function(){return this._threads.length>1}}]),t}(),K=function(){function t(e,i){n(this,t),this._globalVariables={},this._callStack=e,this._listDefsOrigin=i,this._batchObservingVariableChanges=null,this._changedVariables=null,this.variableChangedEvent=null,this.variableChangedEventCallbacks=[];try{return new Proxy(this,{get:function(t,e){return e in t?t[e]:t.$(e)},set:function(t,e,n){return e in t?t[e]=n:t.$(e,n),!0}})}catch(t){}}return a(t,[{key:"ObserveVariableChange",value:function(t){var e=this;null==this.variableChangedEvent&&(this.variableChangedEvent=function(t,n){e.variableChangedEventCallbacks.forEach(function(e){e(t,n)})}),this.variableChangedEventCallbacks.push(t)}},{key:"CopyFrom",value:function(t){this._globalVariables=r({},t._globalVariables),this.variableChangedEvent=t.variableChangedEvent,t.batchObservingVariableChanges!=this.batchObservingVariableChanges&&(t.batc hObservingVariableChanges?(this._batchObservingVariableChanges=!0,this._changedVariables=t._changedVariables):(this._batchObservingVariableChanges=!1,this._changedVariables=null))}},{key:"GetVariableWithName",value:function(t,e){void 0===e&&(e=-1);var n=this.GetRawVariableWithName(t,e),i=n;return i instanceof C&&(n=this.ValueAtVariablePointer(i)),n}},{key:"GetRawVariableWithName",value:function(t,e){var n=null;if(0==e||-1==e){if(n=this._globalVariables[t])return n;var i=this._listDefsOrigin.FindSingleItemListWithName(t);if(i)return i}if(null==(n=this._callStack.GetTemporaryVariableWithName(t,e)))throw"RUNTIME ERROR: Variable '"+t+"' could not be found in context '"+e+"'. This shouldn't be possible so is a bug in the ink engine. Please try to construct a minimal story that reproduces the problem and report to inkle, thank you!";return n}},{key:"ValueAtVariablePointer",value:function(t){return this.GetVariableWithName(t.variableName,t.contextIndex)}},{key:"Assign",value:function(t,e){var n=t.variableName,i=-1, a=!1;if(a=t.isNewDeclaration?t.isGlobal:!!this._globalVariables[n],t.isNewDeclaration){var r=e;r instanceof C&&(e=this.ResolveVariablePointer(r))}else{var o=null;do{(o=this.GetRawVariableWithName(n,i))instanceof C&&(n=o.variableName,a=0==(i=o.contextIndex))}while(o instanceof C)}a?this.SetGlobal(n,e):this._callStack.SetTemporaryVariable(n,e,t.isNewDeclaration,i)}},{key:"RetainListOriginsForAssignment",value:function(t,e){var n=t,i=e;n instanceof S&&i instanceof S&&0==i.value.Count&&i.value.SetInitialOriginNames(n.value.originNames)}},{key:"SetGlobal",value:function(t,e){var n=null;n=this._globalVariables[t],S.RetainListOriginsForAssignment(n,e),this._globalVariables[t]=e,null!=this.variableChangedEvent&&e!==n&&(this.batchObservingVariableChanges?this._changedVariables.push(t):this.variableChangedEvent(t,e))}},{key:"ResolveVariablePointer",value:function(t){var e=t.contextIndex;-1==e&&(e=this.GetContextIndexOfVariableNamed(t.variableName));var n=this.GetRawVariableWithName(t.variableName,e);return n instanceo f C?n:new C(t.variableName,e)}},{key:"GetContextIndexOfVariableNamed",value:function(t){return this._globalVariables[t]?0:this._callStack.currentElementIndex}},{key:"$",value:function(t,e){if(void 0===e){var n=this._globalVariables[t];return void 0!==n?n.valueObject:null}if(void 0===this._globalVariables[t])throw new b("Variable '"+t+"' doesn't exist, so can't be set.");var i=p.Create(e);if(null==i)throw new b(null==e?"Cannot pass null to VariableState":"Invalid value passed to VariableState: "+e.toString());this.SetGlobal(t,i)}},{key:"callStack",get:function(){return this._callStack},set:function(t){this._callStack=t}},{key:"batchObservingVariableChanges",get:function(){return this._batchObservingVariableChanges},set:function(t){var e=this;t=!!t,this._batchObservingVariableChanges=t,t?this._changedVariables=[]:(null!=this._changedVariables&&this._changedVariables.forEach(function(t){var n=e._globalVariables[t];e.variableChangedEvent(t,n)}),this._changedVariables=null)}},{key:"jsonToken",get:function(){retur n B.DictionaryRuntimeObjsToJObject(this._globalVariables)},set:function(t){this._globalVariables=B.JObjectToDictionaryRuntimeObjs(t)}}]),t}(),U=function(){function t(e){n(this,t),this._seed=e%2147483647,this._seed<=0&&(this._seed+=2147483646)}return a(t,[{key:"next",value:function(){return this._seed=16807*this._seed%2147483647}},{key:"nextFloat",value:function(){return(this.next()-1)/2147483646}}]),t}(),H=function(){function t(e){n(this,t),this.story=e,this._outputStream=[],this._outputStreamTextDirty=!0,this._outputStreamTagsDirty=!0,this.OutputStreamDirty(),this._evaluationStack=[],this.callStack=new q(e.rootContentContainer),this._variablesState=new K(this.callStack,e.listDefinitions),this._visitCounts={},this._turnIndices={},this._currentTurnIndex=-1,this.divertedTargetObject=null;var i=(new Date).getTime();this.storySeed=new U(i).next()%100,this.previousRandom=0,this._currentChoices=[],this._currentText=null,this._currentTags=null,this._currentErrors=null,this.didSafeExit=!1,this._isExternalFunctionEva luation=!1,this._originalCallstack=null,this._originalEvaluationStackHeight=0,this.GoToStart()}return a(t,[{key:"MatchRightGlueForLeftGlue",value:function(t){if(!t.isLeft)return null;for(var e=this._outputStream.length-1;e>=0;e--){var n=this._outputStream[e],i=n;if(i instanceof _&&i.isRight&&i.parent==t.parent)return i;if(n instanceof E)break}return null}},{key:"GoToStart",value:function(){this.callStack.currentElement.currentContainer=this.story.mainContentContainer,this.callStack.currentElement.currentContentIndex=0}},{key:"ResetErrors",value:function(){this._currentErrors=null}},{key:"ResetOutput",value:function(){this._outputStream.length=0,this.OutputStreamDirty()}},{key:"PushEvaluationStack",value:function(t){var e=this,n=t;if(n instanceof S){var i=n.value,a=i.originNames;if(null!=a){var r=[];a.forEach(function(t){var n=null;n=e.story.listDefinitions.TryGetDefinition(t,n),r.indexOf(n)<0&&r.push(n)}),i.origins=r}}this.evaluationStack.push(t)}},{key:"PopEvaluationStack",value:function(t){if(t){if(t>this. evaluationStack.length)throw"trying to pop too many objects";return this.evaluationStack.splice(this.evaluationStack.length-t,t)}return this.evaluationStack.pop()}},{key:"PeekEvaluationStack",value:function(){return this.evaluationStack[this.evaluationStack.length-1]}},{key:"PushToOutputStream",value:function(t){var e=this,n=t;if(n instanceof g){var i=this.TrySplittingHeadTailWhitespace(n);if(null!=i)return void i.forEach(function(t){e.PushToOutputStreamIndividual(t)})}this.PushToOutputStreamIndividual(t),this.OutputStreamDirty()}},{key:"TrySplittingHeadTailWhitespace",value:function(t){for(var e=t.value,n=-1,i=-1,a=0;a0){var c=e.substring(0,n);u.push(c)}u.push(new g("\n")),l=i+1}if(-1!=r&&(h=o),h>l){var f=e.substring(l,h-l);u.push(new g(f))}if(-1!= r&&o>i&&(u.push(new g("\n")),r=0;){var r=this._outputStream[a],o=r,s=r;if(r instanceof E||o instanceof g&&o.isNonWhitespace){if(i=!0,null==t)break}else{if(t&&s instanceof _&&s==t){n=a;break}o instanceof g&&o.isNewline&&!i&&(e=a)}a--}if(e>=0)for(a=e;a-1)for(a=n;a=0;t--){var e=this._outputStream[t];if(e instanceof _)this._outputStream.splice(t,1);else if(e instanceof E)break}this.OutputStreamDirty()}},{key:"ForceEnd",value:function(){for(;this.callStack.canPopThread;)this.callStack.PopThread();for(;this.callStack.canPop;)this.callStack.Pop();this._currentChoices.length=0,this.currentContentObject=null,this.previousContentObject=null,this.didSafeExit=!0}},{key:"SetChosenPath",value:function(t){this. _currentChoices.length=0,this.currentPath=t,this._currentTurnIndex++}},{key:"StartExternalFunctionEvaluation",value:function(t,e){this._originalCallstack=this.callStack,this._originalEvaluationStackHeight=this.evaluationStack.length,this.callStack=new q(t),this.callStack.currentElement.type=x.Function,this._variablesState.callStack=this.callStack,this._isExternalFunctionEvaluation=!0,this.PassArgumentsToEvaluationStack(e)}},{key:"PassArgumentsToEvaluationStack",value:function(t){if(null!=t)for(var e=0;ethis._originalEvaluationStackHeight;){var e=this.PopEvaluationStack();null==t&&(t=e)}if(this.callStack=this._originalCallstack,this._originalCallstack=null,this._originalEvaluationStackHeight=0,this._variablesState.callStack=this.callStack,t){if(t instanceof N)return null;var n=t;return n.valueType==d.DivertTarget?n.valueObject.toString():n.valueObject}return null}},{key:"AddError",value:function(t){null==this._currentErrors&&(this._currentErrors=[]),this._currentErrors.push(t)}},{key:"OutputStreamDirty",value:function(){this._outputStreamTextDirty=!0,this._outputStreamTagsDirty=!0}},{key:"VisitCountAtPathString",value:function(t){var e;return(e=this.visitCounts[t])?e:0}},{key:"Copy",value:function(){var e=new t(this.story);e.outputStream.push.apply(e.outputStream,this._outputStream),this.OutputStreamDirty(),e._currentChoices.push.apply(e._currentChoices,this._currentChoices),this.hasError&&(e.currentErrors=[],e.currentErrors.push.apply(e.currentErrors,thi s.currentErrors)),e.callStack=new q(this.callStack),this._originalCallstack&&(e._originalCallstack=new q(this._originalCallstack)),e._variablesState=new K(e.callStack,this.story.listDefinitions),e.variablesState.CopyFrom(this.variablesState),e.evaluationStack.push.apply(e.evaluationStack,this.evaluationStack),e._originalEvaluationStackHeight=this._originalEvaluationStackHeight,null!=this.divertedTargetObject&&(e.divertedTargetObject=this.divertedTargetObject),e.previousContentObject=this.previousContentObject,e._isExternalFunctionEvaluation=this._isExternalFunctionEvaluation,e._visitCounts={};for(var n in this._visitCounts)e._visitCounts[n]=this._visitCounts[n];e._turnIndices={};for(var n in this._turnIndices)e._turnIndices[n]=this._turnIndices[n];return e._currentTurnIndex=this.currentTurnIndex,e.storySeed=this.storySeed,e.previousRandom=this.previousRandom,e.didSafeExit=this.didSafeExit,e}},{key:"toJson",value:function(t){return JSON.stringify(this.jsonToken,null,t?2:0)}},{key:"LoadJson",value:function(t){ this.jsonToken=JSON.parse(t)}},{key:"currentChoices",get:function(){return this.canContinue?[]:this._currentChoices}},{key:"generatedChoices",get:function(){return this._currentChoices}},{key:"currentErrors",get:function(){return this._currentErrors}},{key:"visitCounts",get:function(){return this._visitCounts}},{key:"turnIndices",get:function(){return this._turnIndices}},{key:"currentTurnIndex",get:function(){return this._currentTurnIndex}},{key:"variablesState",get:function(){return this._variablesState}},{key:"currentContentObject",get:function(){return this.callStack.currentElement.currentObject},set:function(t){this.callStack.currentElement.currentObject=t}},{key:"canContinue",get:function(){return null!=this.currentContentObject&&!this.hasError}},{key:"hasError",get:function(){return null!=this.currentErrors&&this.currentErrors.length>0}},{key:"inExpressionEvaluation",get:function(){return this.callStack.currentElement.inExpressionEvaluation},set:function(t){this.callStack.currentElement.inExpressionEva luation=t}},{key:"evaluationStack",get:function(){return this._evaluationStack}},{key:"outputStreamEndsInNewline",get:function(){if(this._outputStream.length>0)for(var t=this._outputStream.length-1;t>=0&&!(this._outputStream[t]instanceof E);t--){var e=this._outputStream[t];if(e instanceof g){if(e.isNewline)return!0;if(e.isNonWhitespace)break}}return!1}},{key:"outputStreamContainsContent",get:function(){for(var t=0;t=0;t--){var e=this._outputStream[t];if(e instanceof _)return t;if(e instanceof E)break}return-1}},{key:"currentRightGlue",get:function(){for(var t=this._outputStream.length-1;t>=0;t--){var e=this._outputStream[t],n=e;if(n instanceof _&&n.isRight)return n;if(e instanceof E)break}return null}},{key:"inStringEvaluation",get:function(){for(var t=this._outputStream.length-1;t>=0;t--){var e=this._outputStream[t];if(e instanceof E&&e.comman dType==E.CommandType.BeginString)return!0}return!1}},{key:"currentText",get:function(){if(this._outputStreamTextDirty){var t=new c;this._outputStream.forEach(function(e){var n=e;n instanceof g&&t.Append(n.value)}),this._currentText=t.toString(),this._outputStreamTextDirty=!1}return this._currentText}},{key:"currentTags",get:function(){var t=this;return this._outputStreamTagsDirty&&(this._currentTags=[],this._outputStream.forEach(function(e){var n=e;n instanceof L&&t._currentTags.push(n.text)}),this._outputStreamTagsDirty=!1),this._currentTags}},{key:"outputStream",get:function(){return this._outputStream}},{key:"currentPath",get:function(){return null==this.currentContentObject?null:this.currentContentObject.path},set:function(t){this.currentContentObject=null!=t?this.story.ContentAtPath(t):null}},{key:"currentContainer",get:function(){return this.callStack.currentElement.currentContainer}},{key:"previousContentObject",get:function(){return this.callStack.currentThread.previousContentObject},set:function(t){ this.callStack.currentThread.previousContentObject=t}},{key:"callstackDepth",get:function(){return this.callStack.depth}},{key:"jsonToken",get:function(){var e=this,n={},i=null;return this._currentChoices.forEach(function(t){t.originalChoicePath=t.choicePoint.path.componentsString,t.originalThreadIndex=t.threadAtGeneration.threadIndex,null==e.callStack.ThreadWithIndex(t.originalThreadIndex)&&(null==i&&(i={}),i[t.originalThreadIndex.toString()]=t.threadAtGeneration.jsonToken)}),null!=this.choiceThreads&&(n.choiceThreads=this.choiceThreads),n.callstackThreads=this.callStack.GetJsonToken(),n.variablesState=this.variablesState.jsonToken,n.evalStack=B.ListToJArray(this.evaluationStack),n.outputStream=B.ListToJArray(this._outputStream),n.currentChoices=B.ListToJArray(this._currentChoices),null!=this.divertedTargetObject&&(n.currentDivertTarget=this.divertedTargetObject.path.componentsString),n.visitCounts=B.IntDictionaryToJObject(this.visitCounts),n.turnIndices=B.IntDictionaryToJObject(this.turnIndices),n.turnIdx= this.currentTurnIndex,n.storySeed=this.storySeed,n.inkSaveVersion=t.kInkSaveStateVersion,n.inkFormatVersion=this.story.inkVersionCurrent,n},set:function(e){var n=this,i=e,a=i.inkSaveVersion;if(null==a)throw new b("ink save format incorrect, can't load.");if(parseInt(a)-9007199254740992&&t<9007199254740992&&Math.floor(t)===t});var X=function(t){function i(t,e){n(this,i);var a=s(this,(i.__proto__||Object.getPrototypeOf(i)).call(this));if(e=e||null,a.inkVersionCurrent=17,a.inkVersionMinimumCompatible=16,a._variableObservers=null,a._externals={},a._prevContainerSet=null,a._listDefinitions=null,t instanceof T)a._mainContentContainer=t,null!=e&&(a._listDefinitions=new D(e));else{var r="string"==typeof t?JSON.parse(t):t,o=r.inkVersion;if(null==o)throw"ink version n umber not found. Are you sure it's a valid .ink.json file?";var u=parseInt(o);if(u>a.inkVersionCurrent)throw"Version of ink used to build story was newer than the current verison of the engine";if(u=n&&"\n"==e[n-1]){this.RestoreStateSnapshot(t);break}t=null}}this.state.outputStreamEndsInNewline&&(this.canContinue?null==t&&(t=this.StateSnapshot()):t=null)}}while(this.canContinue);null!=t&&this.RestoreStateSnapshot(t),this.canContinue||(this.state.callStack.canPopThread&&this.Error("Thread available to pop, threads should always be flat by the end of evaluation?"),0!=this.state.generatedChoices.length||this.state.didSafeExit||null!=this._temporaryEvaluationContainer||(this.state.callStack.CanPop(x.Tunnel)?this.Error("unexpectedly reached end of content. Do you need a '->->' to return from a tunnel?"):this.state.callStack.CanPop(x.Function)?this.Error("unexpectedly reached end of content. Do you need a '~ return'?"):this.state.callStack.canPop?this.Error("unexpectedly reached end of content for unkno wn reason. Please debug compiler!"):this.Error("ran out of content. Do you need a '-> DONE' or '-> END'?")))}catch(t){throw t}finally{this.state.didSafeExit=!1,this._state.variablesState.batchObservingVariableChanges=!1}return this.currentText}},{key:"ContinueMaximally",value:function(){for(var t=new c;this.canContinue;)t.Append(this.Continue());return t.toString()}},{key:"ContentAtPath",value:function(t){return this.mainContentContainer.ContentAtPath(t)}},{key:"StateSnapshot",value:function(){return this.state.Copy()}},{key:"RestoreStateSnapshot",value:function(t){this._state=t}},{key:"Step",value:function(){var t=!0,e=this.state.currentContentObject;if(null!=e){for(var n=e;n instanceof T&&(this.VisitContainer(n,!0),0!=n.content.length);)e=n.content[0],this.state.callStack.currentElement.currentContentIndex=0,this.state.callStack.currentElement.currentContainer=n,n=e;n=this.state.callStack.currentElement.currentContainer;var i=this.PerformLogicAndFlowControl(e);if(null!=this.state.currentContentObject){i&&( t=!1);var a=e;if(a instanceof P){var r=this.ProcessChoice(a);r&&this.state.generatedChoices.push(r),e=null,t=!1}if(e instanceof T&&(t=!1),t){var o=e;if(o instanceof C&&-1==o.contextIndex){var s=this.state.callStack.ContextForVariableNamed(o.variableName);e=new C(o.variableName,s)}this.state.inExpressionEvaluation?this.state.PushEvaluationStack(e):this.state.PushToOutputStream(e)}this.NextContent();var u=e;u instanceof E&&u.commandType==E.CommandType.StartThread&&this.state.callStack.PushThread()}}}},{key:"VisitContainer",value:function(t,e){t.countingAtStartOnly&&!e||(t.visitsShouldBeCounted&&this.IncrementVisitCountForContainer(t),t.turnIndexShouldBeCounted&&this.RecordTurnIndexVisitToContainer(t))}},{key:"VisitChangedContainersDueToDivert",value:function(){var t=this.state.previousContentObject,e=this.state.currentContentObject;if(e){if(this._prevContainerSet=[],t)for(var n=t instanceof T?t:t.parent;n instanceof T;)this._prevContainerSet.push(n),n=n.parent;for(var i=e,a=i.parent;a instanceof T&&this._prevC ontainerSet.indexOf(a)<0;){var r=a.content.length>0&&i==a.content[0];this.VisitContainer(a,r),i=a,a=a.parent}}}},{key:"ProcessChoice",value:function(t){var e=!0;if(t.hasCondition){var n=this.state.PopEvaluationStack();this.IsTruthy(n)||(e=!1)}var i="",a="";t.hasChoiceOnlyContent&&(a=this.state.PopEvaluationStack().value),t.hasStartContent&&(i=this.state.PopEvaluationStack().value),t.onceOnly&&this.VisitCountForContainer(t.choiceTarget)>0&&(e=!1);var r=new j(t);return r.threadAtGeneration=this.state.callStack.currentThread.Copy(),e?(r.text=i+a,r):null}},{key:"IsTruthy",value:function(t){if(t instanceof p){var e=t;if(e instanceof k){var n=e;return this.Error("Shouldn't use a divert target (to "+n.targetPath+") as a conditional value. Did you intend a function call 'likeThis()' or a read count check 'likeThis'? (no arrows)"),!1}return e.isTruthy}return!1}},{key:"PerformLogicAndFlowControl",value:function(t){if(null==t)return!1;if(t instanceof I){var e=t;if(e.isConditional){var n=this.state.PopEvaluationStack(); if(!this.IsTruthy(n))return!0}if(e.hasVariableTarget){var i=e.variableDivertName,a=this.state.variablesState.GetVariableWithName(i);if(!(a instanceof k)){var r=a,o="Tried to divert to a target from a variable, but the variable ("+i+") didn't contain a divert target, it ";r instanceof y&&0==r.value?o+="was empty/null (the value 0).":o+="contained '"+a+"'.",this.Error(o)}var s=a;this.state.divertedTargetObject=this.ContentAtPath(s.targetPath)}else{if(e.isExternal)return this.CallExternalFunction(e.targetPathString,e.externalArgs),!0;this.state.divertedTargetObject=e.targetContent}return e.pushesToStack&&this.state.callStack.Push(e.stackPushType),null!=this.state.divertedTargetObject||e.isExternal||(e&&null!=e.debugMetadata.sourceName?this.Error("Divert target doesn't exist: "+e.debugMetadata.sourceName):this.Error("Divert resolution failed: "+e)),!0}if(t instanceof E){var u=t;switch(u.commandType){case E.CommandType.EvalStart:this.state.inExpressionEvaluation&&console.warn("Already in expression evaluation?"), this.state.inExpressionEvaluation=!0;break;case E.CommandType.EvalEnd:this.state.inExpressionEvaluation||console.warn("Not in expression evaluation mode"),this.state.inExpressionEvaluation=!1;break;case E.CommandType.EvalOutput:if(this.state.evaluationStack.length>0){var l=this.state.PopEvaluationStack();if(null!=l&&!(l instanceof N)){var h=new g(l.toString());this.state.PushToOutputStream(h)}}break;case E.CommandType.NoOp:break;case E.CommandType.Duplicate:this.state.PushEvaluationStack(this.state.PeekEvaluationStack());break;case E.CommandType.PopEvaluatedValue:this.state.PopEvaluationStack();break;case E.CommandType.PopFunction:case E.CommandType.PopTunnel:var f=u.commandType==E.CommandType.PopFunction?x.Function:x.Tunnel,v=null;if(f==x.Tunnel){var d=this.state.PopEvaluationStack();if((v=d)instanceof k==!1){if(d instanceof N==!1)throw"Expected void if ->-> doesn't override target";v=null}}if(this.state.TryExitExternalFunctionEvaluation())break;if(this.state.callStack.currentElement.type==f&&this.state.cal lStack.canPop)this.state.callStack.Pop(),v&&(this.state.divertedTargetObject=this.ContentAtPath(v.targetPath));else{var p={};p[x.Function]="function return statement (~ return)",p[x.Tunnel]="tunnel onwards statement (->->)";var m=p[this.state.callStack.currentElement.type];this.state.callStack.canPop||(m="end of flow (-> END or choice)");var C="Found "+p[f]+", when expected "+m;this.Error(C)}break;case E.CommandType.BeginString:this.state.PushToOutputStream(u),this.state.inExpressionEvaluation||console.warn("Expected to be in an expression when evaluating a string"),this.state.inExpressionEvaluation=!1;break;case E.CommandType.EndString:for(var T=[],_=0,O=this.state.outputStream.length-1;O>=0;--O){var w=this.state.outputStream[O];_++;var P=w;if(P instanceof E&&P.commandType==E.CommandType.BeginString)break;w instanceof g&&T.push(w)}this.state.outputStream.splice(this.state.outputStream.length-_,_),T=T.reverse();var L=new c;T.forEach(function(t){L.Append(t.toString())}),this.state.inExpressionEvaluation=!0,th is.state.PushEvaluationStack(new g(L.toString()));break;case E.CommandType.ChoiceCount:var j=this.state.generatedChoices.length;this.state.PushEvaluationStack(new y(j));break;case E.CommandType.TurnsSince:case E.CommandType.ReadCount:if(!((s=this.state.PopEvaluationStack())instanceof k)){var R="";s instanceof y&&(R=". Did you accidentally pass a read count ('knot_name') instead of a target ('-> knot_name')?"),this.Error("TURNS_SINCE / READ_COUNT expected a divert target (knot, stitch, label name), but saw "+s+R);break}var D,B=s,G=this.ContentAtPath(B.targetPath);D=u.commandType==E.CommandType.TurnsSince?this.TurnsSinceForContainer(G):this.VisitCountForContainer(G),this.state.PushEvaluationStack(new y(D));break;case E.CommandType.Random:var J=this.state.PopEvaluationStack(),M=this.state.PopEvaluationStack();null!=M&&M instanceof y!=!1||this.Error("Invalid value for minimum parameter of RANDOM(min, max)"),null!=J&&M instanceof y!=!1||this.Error("Invalid value for maximum parameter of RANDOM(min, max)");var W=J .value-M.value+1;W<=0&&this.Error("RANDOM was called with minimum as "+M.value+" and maximum as "+J.value+". The maximum must be larger");var q=this.state.storySeed+this.state.previousRandom,K=new U(q).next(),H=K%W+M.value;this.state.PushEvaluationStack(new y(H)),this.state.previousRandom=K;break;case E.CommandType.SeedRandom:var X=this.state.PopEvaluationStack();null!=X&&X instanceof y!=!1||this.Error("Invalid value passed to SEED_RANDOM"),this.state.storySeed=X.value,this.state.previousRandom=0,this.state.PushEvaluationStack(new N);break;case E.CommandType.VisitIndex:vt=this.VisitCountForContainer(this.state.currentContainer)-1;this.state.PushEvaluationStack(new y(vt));break;case E.CommandType.SequenceShuffleIndex:var $=this.NextSequenceShuffleIndex();this.state.PushEvaluationStack(new y($));break;case E.CommandType.StartThread:break;case E.CommandType.Done:this.state.callStack.canPopThread?this.state.callStack.PopThread():(this.state.didSafeExit=!0,this.state.currentContentObject=null);break;case E.Comman dType.End:this.state.ForceEnd();break;case E.CommandType.ListFromInt:var z,Q=parseInt(this.state.PopEvaluationStack()),Y=this.state.PopEvaluationStack().toString(),Z=null;if(!(z=this.listDefinitions.TryGetDefinition(Y,z)))throw new b("Failed to find LIST called "+Y.value);var tt=z.TryGetItemWithValue(Q.value);tt.exists&&(Z=new S(tt.item,Q.value)),null==Z&&(Z=new S),this.state.PushEvaluationStack(Z);break;case E.CommandType.ListRange:var et=this.state.PopEvaluationStack(),nt=this.state.PopEvaluationStack(),it=this.state.PopEvaluationStack();if(it instanceof S==!1||null==it||null==nt||null==et)throw new b("Expected list, minimum and maximum for LIST_RANGE");var at=function(t){var e=t;if(e instanceof S)return parseInt(e.value.maxItem.Value);var n=t;return n instanceof y?n.value:-1},rt=at(nt),ot=at(et);if(-1==rt)throw new b("Invalid min range bound passed to LIST_VALUE(): "+nt);if(-1==ot)throw new b("Invalid max range bound passed to LIST_VALUE(): "+et);var st=new S,ut=it.value.origins;null!=ut&&ut.forEach(funct ion(t){t.ListRange(rt,ot).value.forEach(function(t){st.value.Add(t.Key,t.Value)})}),this.state.PushEvaluationStack(st);break;default:this.Error("unhandled ControlCommand: "+u)}return!0}if(t instanceof V){var lt=t,ht=this.state.PopEvaluationStack();return this.state.variablesState.Assign(lt,ht),!0}if(t instanceof A){var ct=t,ft=null;if(null!=ct.pathForCount){var G=ct.containerForCount,vt=this.VisitCountForContainer(G);ft=new y(vt)}else null==(ft=this.state.variablesState.GetVariableWithName(ct.name))&&(this.Error("Uninitialised variable: "+ct.name),ft=new y(0));return this.state.PushEvaluationStack(ft),!0}if(t instanceof F){var dt=t,pt=this.state.PopEvaluationStack(dt.numberOfParameters),st=dt.Call(pt);return this.state.PushEvaluationStack(st),!0}return!1}},{key:"ChoosePathString",value:function(t,e){e=e||[],this.state.PassArgumentsToEvaluationStack(e),this.ChoosePath(new u(t))}},{key:"ChoosePath",value:function(t){this.state.SetChosenPath(t),this.VisitChangedContainersDueToDivert()}},{key:"ChooseChoiceIndex" ,value:function(t){t=t;var e=this.currentChoices;(t<0||t>e.length)&&console.warn("choice out of range");var n=e[t];this.state.callStack.currentThread=n.threadAtGeneration,this.ChoosePath(n.choicePoint.choiceTarget.path)}},{key:"HasFunction",value:function(t){try{return this.ContentAtPath(new u(t))instanceof T}catch(t){return!1}}},{key:"EvaluateFunction",value:function(t,e,n){if(n=!!n,null==t)throw"Function is null";if(""==t||""==t.trim())throw"Function is empty or white space.";var i=null;try{i=this.ContentAtPath(new u(t))}catch(e){throw e.message.indexOf("not found")>=0?"Function doesn't exist: '"+t+"'":e}this.state.StartExternalFunctionEvaluation(i,e);for(var a=new c;this.canContinue;)a.Append(this.Continue());var r=a.toString(),o=this.state.CompleteExternalFunctionEvaluation();return n?{returned:o,output:r}:o}},{key:"EvaluateExpression",value:function(t){var e=this.state.callStack.elements.length;this.state.callStack.Push(x.Tunnel),this._temporaryEvaluationContainer=t,this.state.GoToStart();var n=this.sta te.evaluationStack.length;return this.Continue(),this._temporaryEvaluationContainer=null,this.state.callStack.elements.length>e&&this.state.callStack.Pop(),this.state.evaluationStack.length>n?this.state.PopEvaluationStack():null}},{key:"CallExternalFunction",value:function(t,n){var i=this._externals[t],a=null;if(!(void 0!==i)){if(this.allowExternalFunctionFallbacks)return(a=this.ContentAtPath(new u(t)))instanceof T||console.warn("Trying to call EXTERNAL function '"+t+"' which has not been bound, and fallback ink function could not be found."),this.state.callStack.Push(x.Function),void(this.state.divertedTargetObject=a);console.warn("Trying to call EXTERNAL function '"+t+"' which has not been bound (and ink fallbacks disabled).")}for(var r=[],o=0;o1?"s":"",s+=": '",s+=e.join("', '"),s+="' ",s+=this.allowExternalFunctionFallbacks?", and no fallback ink function found.":" (ink fallbacks disabled)",this.Error(s)}}}},{key:"ObserveVariable",value:function(t,e){null==this._variableObservers&&(this._variableObservers={}),this._variableObservers[t]?this._variableObservers[t].push(e):this._variableObservers[t]=[e]}},{key:"ObserveVariables",value:function(t,e){for(var n=0,i=t.length;n=e.currentContainer.content.length;){t=!1;var n=e.currentContainer.parent;if(n instanceof T==!1)break;var i=n.cont ent.indexOf(e.currentContainer);if(-1==i)break;e.currentContainer=n,e.currentContentIndex=i+1,t=!0}return t||(e.currentContainer=null),t}},{key:"TryFollowDefaultInvisibleChoice",value:function(){var t=this._state.currentChoices,e=t.filter(function(t){return t.choicePoint.isInvisibleDefault});if(0==e.length||t.length>e.length)return!1;var n=e[0];return this.ChoosePath(n.choicePoint.choiceTarget.path),!0}},{key:"VisitCountForContainer",value:function(t){if(!t.visitsShouldBeCounted)return console.warn("Read count for target ("+t.name+" - on "+t.debugMetadata+") unknown. The story may need to be compiled with countAllVisits flag (-c)."),0;var e=0,n=t.path.toString();return e=this.state.visitCounts[n]||e}},{key:"IncrementVisitCountForContainer",value:function(t){var e=0,n=t.path.toString();this.state.visitCounts[n]&&(e=this.state.visitCounts[n]),e++,this.state.visitCounts[n]=e}},{key:"RecordTurnIndexVisitToContainer",value:function(t){var e=t.path.toString();this.state.turnIndices[e]=this.state.currentTurnIndex}} ,{key:"TurnsSinceForContainer",value:function(t){t.turnIndexShouldBeCounted||this.Error("TURNS_SINCE() for target ("+t.name+" - on "+t.debugMetadata+") unknown. The story may need to be compiled with countAllVisits flag (-c).");var e=t.path.toString(),n=this.state.turnIndices[e];return void 0!==n?this.state.currentTurnIndex-n:-1}},{key:"NextSequenceShuffleIndex",value:function(){var t=this.state.PopEvaluationStack();if(!(t instanceof y))return this.Error("expected number of elements in sequence for shuffle index"),0;for(var e=this.state.currentContainer,n=t.value,i=this.state.PopEvaluationStack().value,a=i/n,r=i%n,o=e.path.toString(),s=0,u=0,l=o.length;u