route-engine-js 1.11.0 → 1.12.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/README.md +1 -0
- package/dist/RouteEngine.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -6,6 +6,7 @@ A Visual Novel engine built in JavaScript
|
|
|
6
6
|
|
|
7
7
|
- [Concepts](docs/Concepts.md) - Core architecture and data flow
|
|
8
8
|
- [API Reference](docs/RouteEngine.md) - Engine methods and actions
|
|
9
|
+
- [Computed Variables](docs/ComputedVariables.md) - Locked interface for derived read-only variables
|
|
9
10
|
|
|
10
11
|
## Community
|
|
11
12
|
|
package/dist/RouteEngine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var Ro=Object.defineProperty;var Lo=(e,t)=>{for(var n in t)Ro(e,n,{get:t[n],enumerable:!0})};var Dn=Symbol.for("immer-nothing"),On=Symbol.for("immer-draftable"),X=Symbol.for("immer-state");function ee(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var Ce=Object.getPrototypeOf;function ue(e){return!!e&&!!e[X]}function ge(e){return e?Vn(e)||Array.isArray(e)||!!e[On]||!!e.constructor?.[On]||et(e)||tt(e):!1}var $o=Object.prototype.constructor.toString();function Vn(e){if(!e||typeof e!="object")return!1;let t=Ce(e);if(t===null)return!0;let n=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return n===Object?!0:typeof n=="function"&&Function.toString.call(n)===$o}function Ge(e,t){Ze(e)===0?Reflect.ownKeys(e).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function Ze(e){let t=e[X];return t?t.type_:Array.isArray(e)?1:et(e)?2:tt(e)?3:0}function vt(e,t){return Ze(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function jn(e,t,n){let r=Ze(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function Oo(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function et(e){return e instanceof Map}function tt(e){return e instanceof Set}function he(e){return e.copy_||e.base_}function St(e,t){if(et(e))return new Map(e);if(tt(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let n=Vn(e);if(t===!0||t==="class_only"&&!n){let r=Object.getOwnPropertyDescriptors(e);delete r[X];let o=Reflect.ownKeys(r);for(let i=0;i<o.length;i++){let s=o[i],l=r[s];l.writable===!1&&(l.writable=!0,l.configurable=!0),(l.get||l.set)&&(r[s]={configurable:!0,writable:!0,enumerable:l.enumerable,value:e[s]})}return Object.create(Ce(e),r)}else{let r=Ce(e);if(r!==null&&n)return{...e};let o=Object.create(r);return Object.assign(o,e)}}function $t(e,t=!1){return nt(e)||ue(e)||!ge(e)||(Ze(e)>1&&(e.set=e.add=e.clear=e.delete=ko),Object.freeze(e),t&&Object.entries(e).forEach(([n,r])=>$t(r,!0))),e}function ko(){ee(2)}function nt(e){return Object.isFrozen(e)}var Po={};function me(e){let t=Po[e];return t||ee(0,e),t}var Te;function Mn(){return Te}function To(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function kn(e,t){t&&(me("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Ct(e){_t(e),e.drafts_.forEach(No),e.drafts_=null}function _t(e){e===Te&&(Te=e.parent_)}function Pn(e){return Te=To(Te,e)}function No(e){let t=e[X];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function Tn(e,t){t.unfinalizedDrafts_=t.drafts_.length;let n=t.drafts_[0];return e!==void 0&&e!==n?(n[X].modified_&&(Ct(t),ee(4)),ge(e)&&(e=Xe(t,e),t.parent_||Qe(t,e)),t.patches_&&me("Patches").generateReplacementPatches_(n[X].base_,e,t.patches_,t.inversePatches_)):e=Xe(t,n,[]),Ct(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Dn?e:void 0}function Xe(e,t,n){if(nt(t))return t;let r=t[X];if(!r)return Ge(t,(o,i)=>Nn(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Qe(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;let o=r.copy_,i=o,s=!1;r.type_===3&&(i=new Set(o),o.clear(),s=!0),Ge(i,(l,c)=>Nn(e,r,o,l,c,n,s)),Qe(e,o,!1),n&&e.patches_&&me("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function Nn(e,t,n,r,o,i,s){if(ue(o)){let l=i&&t&&t.type_!==3&&!vt(t.assigned_,r)?i.concat(r):void 0,c=Xe(e,o,l);if(jn(n,r,c),ue(c))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if(ge(o)&&!nt(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Xe(e,o),(!t||!t.scope_.parent_)&&typeof r!="symbol"&&Object.prototype.propertyIsEnumerable.call(n,r)&&Qe(e,o)}}function Qe(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&$t(t,n)}function Do(e,t){let n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:Mn(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=r,i=Ot;n&&(o=[r],i=Ne);let{revoke:s,proxy:l}=Proxy.revocable(o,i);return r.draft_=l,r.revoke_=s,l}var Ot={get(e,t){if(t===X)return e;let n=he(e);if(!vt(n,t))return Vo(e,n,t);let r=n[t];return e.finalized_||!ge(r)?r:r===xt(e.base_,t)?(Et(e),e.copy_[t]=Lt(r,e)):r},has(e,t){return t in he(e)},ownKeys(e){return Reflect.ownKeys(he(e))},set(e,t,n){let r=Un(he(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){let o=xt(he(e),t),i=o?.[X];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(Oo(n,o)&&(n!==void 0||vt(e.base_,t)))return!0;Et(e),Rt(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return xt(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,Et(e),Rt(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let n=he(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){ee(11)},getPrototypeOf(e){return Ce(e.base_)},setPrototypeOf(){ee(12)}},Ne={};Ge(Ot,(e,t)=>{Ne[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});Ne.deleteProperty=function(e,t){return Ne.set.call(this,e,t,void 0)};Ne.set=function(e,t,n){return Ot.set.call(this,e[0],t,n,e[0])};function xt(e,t){let n=e[X];return(n?he(n):e)[t]}function Vo(e,t,n){let r=Un(t,n);return r?"value"in r?r.value:r.get?.call(e.draft_):void 0}function Un(e,t){if(!(t in e))return;let n=Ce(e);for(;n;){let r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=Ce(n)}}function Rt(e){e.modified_||(e.modified_=!0,e.parent_&&Rt(e.parent_))}function Et(e){e.copy_||(e.copy_=St(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var jo=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){let i=n;n=t;let s=this;return function(c=i,...a){return s.produce(c,u=>n.call(this,u,...a))}}typeof n!="function"&&ee(6),r!==void 0&&typeof r!="function"&&ee(7);let o;if(ge(t)){let i=Pn(this),s=Lt(t,void 0),l=!0;try{o=n(s),l=!1}finally{l?Ct(i):_t(i)}return kn(i,r),Tn(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===Dn&&(o=void 0),this.autoFreeze_&&$t(o,!0),r){let i=[],s=[];me("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else ee(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,c=>t(c,...l));let r,o;return[this.produce(t,n,(s,l)=>{r=s,o=l}),r,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){ge(e)||ee(8),ue(e)&&(e=kt(e));let t=Pn(this),n=Lt(e,void 0);return n[X].isManual_=!0,_t(t),n}finishDraft(e,t){let n=e&&e[X];(!n||!n.isManual_)&&ee(9);let{scope_:r}=n;return kn(r,t),Tn(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){let o=t[n];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}n>-1&&(t=t.slice(n+1));let r=me("Patches").applyPatches_;return ue(e)?r(e,t):this.produce(e,o=>r(o,t))}};function Lt(e,t){let n=et(e)?me("MapSet").proxyMap_(e,t):tt(e)?me("MapSet").proxySet_(e,t):Do(e,t);return(t?t.scope_:Mn()).drafts_.push(n),n}function kt(e){return ue(e)||ee(10,e),Bn(e)}function Bn(e){if(!ge(e)||nt(e))return e;let t=e[X],n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=St(e,t.scope_.immer_.useStrictShallowCopy_)}else n=St(e,!0);return Ge(n,(r,o)=>{jn(n,r,Bn(o))}),t&&(t.finalized_=!1),n}var Q=new jo,Pt=Q.produce,ol=Q.produceWithPatches.bind(Q),il=Q.setAutoFreeze.bind(Q),sl=Q.setUseStrictShallowCopy.bind(Q),al=Q.applyPatches.bind(Q),cl=Q.createDraft.bind(Q),ll=Q.finishDraft.bind(Q);var p={LITERAL:0,VARIABLE:1,INTERPOLATION:2,FUNCTION:3,BINARY:4,UNARY:5,CONDITIONAL:6,LOOP:7,OBJECT:8,ARRAY:9,PARTIAL:10,PATH_REFERENCE:11},R={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},_e={NOT:0};var w=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},K=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var Tt=e=>{if(!e||e.trim()==="")throw new w("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let n=e.includes("===")?"==":"!=";throw new w(`Invalid comparison operator '${e.includes("===")?"===":"!=="}' - did you mean '${n}'? (got: '${e}')`)}let t=["<",">","<=",">=","==","!="];for(let n of t)if(e.trim().endsWith(n))throw new w(`Incomplete comparison expression - missing right operand (got: '${e}')`)},Fn=e=>{if(e.trim().endsWith(" in"))throw new w(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new w(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,n]=e.split(" in ");if(!n||n.trim()==="")throw new w(`Missing iterable expression after 'in' (got: '$for ${e}')`);let r=t.includes(",")?t.split(",").map(o=>o.trim()):[t.trim()];for(let o of r){if(!o)throw new w(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new w(`Invalid loop syntax (got: '$for ${e}')`)}};var zn=(e,t,n=!1)=>{if(t===null)return new K(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new K(`Cannot iterate over undefined value at '$for ${e}'`);let r=typeof t;return n?new K(`Cannot iterate over non-array value in loop '${e}' - got ${r} instead`):new K(`Cannot iterate over non-array value (got: ${r}) at '$for ${e}'`)},Wn=(e,t)=>{let n=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new K(`Unknown function '${e}' (${n})`)};var Mo=(e,t,n={})=>{let r={},o={};n&&typeof n=="object"&&(n.functions!==void 0||n.partials!==void 0?(r=n.functions||{},o=n.partials||{}):typeof n=="object"&&(r=n));let s=L(e,{functions:r,partials:o},t,{});return s===void 0?{}:s},L=(e,t,n,r)=>{let o=t.functions||t;if(e.var&&!e.type)return B(e.var,n,r);if(e.type===p.LITERAL)return e.value;if(e.type===p.VARIABLE)return B(e.path,n,r);if(e.type===p.INTERPOLATION)return Bo(e.parts,t,n,r);switch(e.type){case p.FUNCTION:return qn(e,t,n,r);case p.BINARY:return Hn(e,t,n,r);case p.UNARY:return Jn(e,t,n,r);case p.CONDITIONAL:return zo(e,t,n,r);case p.LOOP:return Jo(e,t,n,r);case p.OBJECT:return Go(e,t,n,r);case p.ARRAY:return Xo(e,t,n,r);case p.PARTIAL:return Qo(e,t,n,r);case p.PATH_REFERENCE:return Zo(e,t,n,r);default:throw new Error(`Unknown node type: ${e.type}`)}},Yn=new Map,Uo=e=>{let t=[],n="",r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(i==="[")n&&(t.push({type:"property",value:n}),n=""),r=!0;else if(i==="]"){if(r&&n){let s=n.trim();if(/^\d+$/.test(s))t.push({type:"index",value:parseInt(s,10)});else if(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'")){let l=s.slice(1,-1);t.push({type:"property",value:l})}else t.push({type:"property",value:s});n=""}r=!1}else n+=i}return n&&t.push({type:"property",value:n}),t},B=(e,t,n)=>{if(!e)return;if(e in n)return n[e];let r=Yn.get(e);if(!r){let i=[],s="",l=0;for(let c=0;c<e.length;c++){let a=e[c];a==="["?(l++,s+=a):a==="]"?(l--,s+=a):a==="."&&l===0?s&&(i.push(s),s=""):s+=a}s&&i.push(s),r=[];for(let c of i){let a=Uo(c.trim());r.push(...a)}Yn.set(e,r)}let o=t;for(let i=0;i<r.length;i++){let s=r[i];if(s.type==="property"&&s.value in n){o=n[s.value];continue}if(o==null)return;(s.type==="property"||s.type==="index")&&(o=o[s.value])}return o},Bo=(e,t,n,r)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=L(i,t,n,r);o.push(s!=null?String(s):"")}return o.join("")},qn=(e,t,n,r)=>{let o=t.functions||t,i=o[e.name];if(!i)throw Wn(e.name,o);let s=e.args.map(l=>L(l,t,n,r));return i(...s)},fe=(e,t,n,r)=>{if(e.var&&!e.type)return B(e.var,n,r);switch(e.type){case p.VARIABLE:return B(e.path,n,r);case p.LITERAL:return e.value;case p.BINARY:return Hn(e,t,n,r);case p.UNARY:return Jn(e,t,n,r);case p.FUNCTION:return qn(e,t,n,r);default:return L(e,t,n,r)}},Hn=(e,t,n,r)=>{if(e.op===R.AND||e.op===R.OR){let s=fe(e.left,t,n,r),l=fe(e.right,t,n,r);switch(e.op){case R.AND:return s&&l;case R.OR:return s||l}}let o=L(e.left,t,n,r),i=L(e.right,t,n,r);switch(e.op){case R.EQ:return o==i;case R.NEQ:return o!=i;case R.GT:return o>i;case R.LT:return o<i;case R.GTE:return o>=i;case R.LTE:return o<=i;case R.IN:return Array.isArray(i)?i.includes(o):!1;case R.ADD:if(typeof o!="number"||typeof i!="number")throw new K(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case R.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new K(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},Jn=(e,t,n,r)=>{let o=e.op===_e.NOT?fe(e.operand,t,n,r):L(e.operand,t,n,r);if(e.op===_e.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},Fo=(e,t,n,r)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===p.VARIABLE)if(B(o.path,n,r)){let s=e.bodies[0];if(s.type===p.OBJECT&&s.properties.length<=5){let l={};for(let c of s.properties){let a=c.parsedKey?L(c.parsedKey,t,n,r):c.key,u=c.value;if(u.type===p.LITERAL)l[a]=u.value;else if(u.type===p.VARIABLE)l[a]=B(u.path,n,r);else if(u.type===p.INTERPOLATION){let f=[];for(let d of u.parts)if(typeof d=="string")f.push(d);else if(d.type===p.VARIABLE){let h=B(d.path,n,r);f.push(h!=null?String(h):"")}else{let h=L(d,t,n,r);f.push(h!=null?String(h):"")}l[a]=f.join("")}else l[a]=L(u,t,n,r)}return l}}else{let s=e.bodies[1];if(s.type===p.OBJECT&&s.properties.length<=5){let l={};for(let c of s.properties){let a=c.parsedKey?L(c.parsedKey,t,n,r):c.key,u=c.value;if(u.type===p.LITERAL)l[a]=u.value;else if(u.type===p.VARIABLE)l[a]=B(u.path,n,r);else if(u.type===p.INTERPOLATION){let f=[];for(let d of u.parts)if(typeof d=="string")f.push(d);else if(d.type===p.VARIABLE){let h=B(d.path,n,r);f.push(h!=null?String(h):"")}else{let h=L(d,t,n,r);f.push(h!=null?String(h):"")}l[a]=f.join("")}else l[a]=L(u,t,n,r)}return l}}}return null},zo=(e,t,n,r)=>{let o=Fo(e,t,n,r);if(o!==null)return o;for(let i=0;i<e.conditions.length;i++){let s=e.conditions[i];if(s===null||fe(s,t,n,r))return L(e.bodies[i],t,n,r)}return Kn},Wo=(e,t)=>{let n=e.body,r=e.itemVar;if(n.type===p.CONDITIONAL&&n.conditions.length===1&&n.conditions[0].type===p.VARIABLE){let o=n.conditions[0].path,i=n.bodies[0];if(o.startsWith(r+".")){let s=o.substring(r.length+1);if(i.type===p.OBJECT&&i.properties.length<=5){for(let c of i.properties)if(c.parsedKey)return null;let l=[];for(let c=0;c<t.length;c++){let a=t[c];if(a[s]){let u={};for(let f of i.properties){let d=f.key,h=f.value;if(h.type===p.LITERAL)u[d]=h.value;else if(h.type===p.VARIABLE){let g=h.path;if(g===r)u[d]=a;else if(g.startsWith(r+".")){let y=g.substring(r.length+1);u[d]=a[y]}else return null}else if(h.type===p.INTERPOLATION){let g=[],y=!0;for(let I of h.parts)if(typeof I=="string")g.push(I);else if(I.type===p.VARIABLE){let b=I.path;if(b===r)g.push(a!=null?String(a):"");else if(b.startsWith(r+".")){let m=b.substring(r.length+1),E=a[m];g.push(E!=null?String(E):"")}else{y=!1;break}}else{y=!1;break}if(!y)return null;u[d]=g.join("")}else return null}l.push(u)}}return l}}}return null},Yo=(e,t)=>{let n=e.body,r=e.itemVar,o=Wo(e,t);if(o!==null)return o;if(n.type===p.OBJECT&&n.properties.length<=5&&!n.whenCondition){for(let l of n.properties)if(l.parsedKey)return null;let i=[],s=!0;for(let l of n.properties){let c=l.key,a=l.value;if(a.type===p.LITERAL)i.push({key:c,type:"literal",value:a.value});else if(a.type===p.VARIABLE){let u=a.path;if(u===r)i.push({key:c,type:"item"});else if(u.startsWith(r+".")){let f=u.substring(r.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:c,type:"prop",prop:f});else{s=!1;break}}else{s=!1;break}}else if(a.type===p.INTERPOLATION&&a.parts.length===1){let u=a.parts[0];if(u.type===p.VARIABLE){let f=u.path;if(f===r)i.push({key:c,type:"item_string"});else if(f.startsWith(r+".")){let d=f.substring(r.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:c,type:"prop_string",prop:d});else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}if(s){let l=new Array(t.length);if(i.length===3&&i[0].type==="prop"&&i[0].key==="id"&&i[1].type==="prop_string"&&i[1].key==="title"&&i[2].type==="prop"&&i[2].key==="completed")for(let c=0;c<t.length;c++){let a=t[c];l[c]={id:a.id,title:a.title!=null?String(a.title):"",completed:a.completed}}else for(let c=0;c<t.length;c++){let a=t[c],u={};for(let f of i)if(f.type==="literal")u[f.key]=f.value;else if(f.type==="item")u[f.key]=a;else if(f.type==="prop")u[f.key]=a[f.prop];else if(f.type==="item_string")u[f.key]=a!=null?String(a):"";else if(f.type==="prop_string"){let d=a[f.prop];u[f.key]=d!=null?String(d):""}l[c]=u}return l}}return null},qo=(e,t,n,r,o)=>{let i=[],s=e.body;if(s.type===p.OBJECT&&s.fast!==!1){let l=e.itemVar,c=e.indexVar;for(let a=0;a<o.length;a++){let u=o[a],f={},d={...r,[l]:u,...c&&{[c]:a}};d.__paths__||(d.__paths__=r.__paths__||{});let h=e.iterable.path||"";if(r&&r.__paths__&&h){let g=h.split("."),y=g[0];y in r.__paths__&&(h=r.__paths__[y],g.length>1&&(h+="."+g.slice(1).join(".")))}d.__paths__={...d.__paths__,[l]:`${h}[${a}]`,...c&&{[c]:a}};for(let g of s.properties){let y=g.parsedKey?L(g.parsedKey,t,n,d):g.key,I=g.value;if(I.type===p.LITERAL)f[y]=I.value;else if(I.type===p.VARIABLE){let b=I.path;if(b===l)f[y]=u;else if(b===c)f[y]=a;else if(b.startsWith(l+".")){let m=b.substring(l.length+1);!m.includes(".")&&!m.includes("[")?f[y]=u[m]:f[y]=B(b,n,{...r,[l]:u,...c&&{[c]:a}})}else f[y]=B(b,n,{...r,[l]:u,...c&&{[c]:a}})}else if(I.type===p.INTERPOLATION){let b=[];for(let m of I.parts)if(typeof m=="string")b.push(m);else if(m.type===p.VARIABLE){let E=m.path,S;if(E===l)S=u;else if(E===c)S=a;else if(E.startsWith(l+".")){let $=E.substring(l.length+1);!$.includes(".")&&!$.includes("[")?S=u[$]:S=B(E,n,{...r,[l]:u,...c&&{[c]:a}})}else S=B(E,n,{...r,[l]:u,...c&&{[c]:a}});b.push(S!=null?String(S):"")}else{let E={...r,[l]:u,...c&&{[c]:a}},S=L(m,t,n,E);b.push(S!=null?String(S):"")}f[y]=b.join("")}else{let b={...r,[l]:u,...c&&{[c]:a}};f[y]=L(I,t,n,b)}}i.push(f)}return i}return null},Ho=(e,t,n)=>{let r=e.body;if(r.type===p.OBJECT&&r.properties.length===1&&r.properties[0].key==="$if item.visible"){let i=r.properties[0].value;if(i.type===p.CONDITIONAL&&i.conditions.length===1&&i.conditions[0].type===p.VARIABLE&&i.conditions[0].path==="item.visible"){let s=i.bodies[0];if(s.type===p.OBJECT&&s.properties.length===2){let l=s.properties[0],c=s.properties[1];if(l.key==="id"&&l.value.type===p.VARIABLE&&l.value.path==="item.id"&&c.key==="$if item.highlighted"&&c.value.type===p.CONDITIONAL){let a=[];for(let u=0;u<t.length;u++){let f=t[u];if(f.visible){let d={id:f.id};f.highlighted?(d.highlight=!0,d.message=`This item is highlighted: ${f.name}`):(d.highlight=!1,d.message=f.name),a.push(d)}}return a}}}}return null},Jo=(e,t,n,r)=>{let o=L(e.iterable,t,n,r);if(!Array.isArray(o)){let a,u=!1;if(e.iterable.type===p.FUNCTION){u=!0;let d=e.iterable.args.map(h=>h.type===p.LITERAL?typeof h.value=="string"?`'${h.value}'`:String(h.value):h.type===p.VARIABLE?h.path:h.type===p.FUNCTION?`${h.name}(...)`:"?").join(", ");a=`${e.iterable.name}(${d})`}else a=e.iterable.path||"undefined";let f=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${a}`;throw zn(f,o,u)}if(!e.indexVar){let a=Ho(e,o,e.itemVar);if(a!==null)return a}if(!e.indexVar){let a=Yo(e,o);if(a!==null)return a}let i=qo(e,t,n,r,o);if(i!==null)return i;let s=[],l=e.iterable.path||"";if(r&&r.__paths__&&l){let a=l.split("."),u=a[0];u in r.__paths__&&(l=r.__paths__[u],a.length>1&&(l+="."+a.slice(1).join(".")))}let c=!1;e.body.type===p.ARRAY&&(e.body.items.length<=1?c=!1:c=e.body._shouldPreserveArray??=e.body.items.some(a=>a.type===p.OBJECT&&a.properties.some(u=>u.key.startsWith("$if ")||u.key.startsWith("$when "))));for(let a=0;a<o.length;a++){let u=e.indexVar?{...r,[e.itemVar]:o[a],[e.indexVar]:a}:{...r,[e.itemVar]:o[a]};u.__paths__||(u.__paths__=r.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${l}[${a}]`},e.indexVar&&(u.__paths__[e.indexVar]=a);let f=L(e.body,t,n,u);if(Array.isArray(f)&&f.length===1&&!c){let d=f[0];s.push(d===void 0?{}:d)}else s.push(f===void 0?{}:f)}return s},Ko=(e,t,n,r)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?L(o.parsedKey,t,n,r):o.key,s=o.value;if(s.type===p.OBJECT&&s.properties.length<=10&&!s.whenCondition){let l={},c={},a=!0;for(let u of s.properties){let f=u.parsedKey?L(u.parsedKey,t,n,r):u.key,d=u.value;if(d.type===p.LITERAL)c[f]=d.value;else if(d.type===p.VARIABLE)c[f]=B(d.path,n,r);else if(d.type===p.INTERPOLATION){let h=[];for(let g of d.parts)if(typeof g=="string")h.push(g);else if(g.type===p.VARIABLE){let y=B(g.path,n,r);h.push(y!=null?String(y):"")}else{a=!1;break}if(!a)break;c[f]=h.join("")}else if(d.type===p.OBJECT&&d.properties.length<=5){let h={};for(let g of d.properties){let y=g.key,I=g.value;if(I.type===p.LITERAL)h[y]=I.value;else if(I.type===p.VARIABLE)h[y]=B(I.path,n,r);else if(I.type===p.INTERPOLATION){let b=[];for(let m of I.parts)if(typeof m=="string")b.push(m);else if(m.type===p.VARIABLE){let E=B(m.path,n,r);b.push(E!=null?String(E):"")}else{a=!1;break}if(!a)break;h[y]=b.join("")}else{a=!1;break}}if(!a)break;c[f]=h}else{a=!1;break}}if(a)return l[i]=c,l}}return null},Go=(e,t,n,r)=>{let o=t.functions||t;if(e.whenCondition&&!fe(e.whenCondition,o,n,r))return;let i=Ko(e,t,n,r);if(i!==null)return i;if(e.fast){let a={};for(let u of e.properties){let f=u.parsedKey?L(u.parsedKey,t,n,r):u.key,d=u.value;if(d.type===p.LITERAL)a[f]=d.value;else if(d.type===p.VARIABLE)a[f]=B(d.path,n,r);else if(d.type===p.INTERPOLATION){let h=[];for(let g of d.parts)if(typeof g=="string")h.push(g);else if(g.type===p.VARIABLE){let y=B(g.path,n,r);h.push(y!=null?String(y):"")}else{let y=L(g,t,n,r);h.push(y!=null?String(y):"")}a[f]=h.join("")}else a[f]=L(d,t,n,r)}return a}let s={},l=null,c=!1;for(let a of e.properties)if(!a.key.startsWith("$if ")&&!a.key.match(/^\$if\s+\w+.*:?$/)&&!a.key.startsWith("$elif")&&!a.key.startsWith("$else")&&!a.key.startsWith("$for ")){c=!0;break}for(let a of e.properties)if(a.key.startsWith("$if ")||a.key.match(/^\$if\s+\w+.*:?$/)){let u=L(a.value,t,n,r);if(!c&&u!==null&&u!==void 0)return Array.isArray(u)&&u.length===1?u[0]:u;typeof u=="object"&&u!==null&&!Array.isArray(u)&&Object.assign(s,u)}else if(a.key.startsWith("$for ")){if(e.properties.length===1)return L(a.value,t,n,r)}else{let u=a.value;if(u&&u.type===p.OBJECT&&u.properties){let f=u.properties.find(d=>d.key.startsWith("$for "));if(f){let d=L(f.value,t,n,r);d!==void 0&&(s[a.key]=d)}else{let d=L(a.value,t,n,r);d!==void 0&&(s[a.key]=d)}}else{let f=a.parsedKey?L(a.parsedKey,t,n,r):a.key,d=L(a.value,t,n,r);d!==void 0&&(s[f]=d)}}return s},Kn={},Xo=(e,t,n,r)=>{let o=[];for(let i of e.items)if(i.type===p.LOOP){let s=L(i,t,n,r);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=L(i,t,n,r);s!==Kn&&s!==void 0&&o.push(s)}return o},Qo=(e,t,n,r)=>{let{name:o,data:i,whenCondition:s}=e,l=t.partials||{},c=t.functions||t;if(s&&!fe(s,c,n,r))return;if(!l[o])throw new K(`Partial '${o}' is not defined`);let a=r._partialStack||[];if(a.includes(o))throw new K(`Circular partial reference detected: ${o}`);let u=l[o],f=n,d={...r,_partialStack:[...a,o]};if(r){f={...n};for(let h of Object.keys(r))h.startsWith("_")||(f[h]=r[h])}if(i){let h=L(i,t,n,r);f={...f,...h}}return L(u,t,f,d)},Zo=(e,t,n,r)=>{let{path:o}=e,i=o.split("."),s=i[0],l=i.slice(1);if(!r||!(s in r))throw new K(`Path reference '#{${o}}' refers to '${s}' which is not a loop variable in the current scope`);if(r.__paths__||(r.__paths__={}),!(s in r.__paths__))throw new K(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let c=r.__paths__[s];if(typeof c=="number"){if(l.length>0)throw new K(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(c)}return l.length>0&&(c+="."+l.join(".")),c};var Nt=Mo;var ei=/\$\{([^}]*)\}/g,ti=/#\{([^}]*)\}/g,Xn=(e,t={})=>{let n=e.match(/^(\w+)\((.*)\)$/);if(!n)return{isFunction:!1};let[,r,o]=n,i=ni(o,t);return{isFunction:!0,type:p.FUNCTION,name:r,args:i}},ni=(e,t={})=>e.trim()?ri(e).map(r=>oi(r.trim(),t)):[],ri=e=>{let t=[],n="",r=0,o=!1,i="";for(let s=0;s<e.length;s++){let l=e[s],c=s>0?e[s-1]:"";!o&&(l==='"'||l==="'")?(o=!0,i=l,n+=l):o&&l===i&&c!=="\\"?(o=!1,i="",n+=l):!o&&l==="("?(r++,n+=l):!o&&l===")"?(r--,n+=l):!o&&l===","&&r===0?(t.push(n),n=""):n+=l}return n&&t.push(n),t},oi=(e,t={})=>{if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:p.LITERAL,value:e.slice(1,-1)};if(/^-?\d+(\.\d+)?$/.test(e))return{type:p.LITERAL,value:parseFloat(e)};if(e==="true")return{type:p.LITERAL,value:!0};if(e==="false")return{type:p.LITERAL,value:!1};if(e==="null")return{type:p.LITERAL,value:null};let n=Xn(e,t);if(n.isFunction)return{type:n.type,name:n.name,args:n.args};let r=e.trim(),o=[{op:" + ",type:"ADD"},{op:" - ",type:"SUBTRACT"}],i=-1,s=null;for(let{op:l,type:c}of o){let a=0;for(;a<r.length;){let u=ye(r.substring(a),l);if(u===-1)break;let f=a+u;f>i&&(i=f,s={op:l,type:c}),a=f+l.length}}if(i!==-1)try{return W(r,t)}catch{return{type:p.VARIABLE,path:r}}return{type:p.VARIABLE,path:r}},Qn=/^\w+\(.*\)$/,ii=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,si=e=>{if(!(!e||e.trim()===""||Qn.test(e))&&ii.test(e))throw e.includes("?")&&e.includes(":")?new w(`Complex expressions not supported in variable replacements - consider calculating the value in your data instead. Offending expression: "${e}"`):e.includes("||")||e.includes("&&")||e.includes("??")?new w(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new w(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},Gn=e=>{let t=e.trim();if(Qn.test(t))throw new w(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new w(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new w(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new w(`Logical operators not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("?")&&t.includes(":"))throw new w(`Complex expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);return{type:p.PATH_REFERENCE,path:t}},De=(e,t={})=>{let n=e.trim();si(n);let r=Xn(n,t);if(r.isFunction)return{type:r.type,name:r.name,args:r.args};if(n.includes("[")&&!/[\s+\-*/%|&?:]/.test(n)){let o=0;for(let i of n)i==="["?o++:i==="]"&&o--;if(o!==0)throw new Error("Invalid array index syntax")}return{type:p.VARIABLE,path:n}},Dt=(e,t={})=>{let n=e,r=[];(e.includes("\\${")||e.includes("\\#{"))&&(n=e.replace(/\\\\(\$\{[^}]*\})/g,"\\DOUBLE_ESC_VAR$1"),n=n.replace(/\\\\(#\{[^}]*\})/g,"\\DOUBLE_ESC_PATH$1"),n=n.replace(/\\(\$\{[^}]*\})/g,(a,u)=>{let f=`__ESCAPED_${r.length}__`;return r.push(u),f}),n=n.replace(/\\(#\{[^}]*\})/g,(a,u)=>{let f=`__ESCAPED_${r.length}__`;return r.push(u),f}),n=n.replace(/\\DOUBLE_ESC_VAR/g,"\\"),n=n.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...n.matchAll(ei)],i=[...n.matchAll(ti)],s=[...o.map(a=>({match:a,type:"variable"})),...i.map(a=>({match:a,type:"pathref"}))].sort((a,u)=>a.match.index-u.match.index);if(s.length===0){let a=n;for(let u=0;u<r.length;u++)a=a.replace(`__ESCAPED_${u}__`,r[u]);return{type:p.LITERAL,value:a}}if(s.length===1&&s[0].match[0]===n&&r.length===0){let{match:a,type:u}=s[0];try{return u==="variable"?De(a[1],t):Gn(a[1])}catch(f){if(f.message==="Invalid array index syntax")return{type:p.LITERAL,value:n};throw f}}let l=[],c=0;for(let{match:a,type:u}of s){let[f,d]=a,h=a.index;if(h>c){let g=n.substring(c,h);for(let y=0;y<r.length;y++)g=g.replace(`__ESCAPED_${y}__`,r[y]);g&&l.push(g)}try{let g;u==="variable"?g=De(d.trim(),t):g=Gn(d.trim()),l.push(g)}catch(g){if(g.message==="Invalid array index syntax")l.push(f);else throw g}c=h+f.length}if(c<n.length){let a=n.substring(c);for(let u=0;u<r.length;u++)a=a.replace(`__ESCAPED_${u}__`,r[u]);a&&l.push(a)}return{type:p.INTERPOLATION,parts:l}};var Mt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),tr=e=>Object.keys(e),J=e=>e.join("."),de=(e,t,n)=>{let r=tr(e).filter(o=>!t.has(o));if(r.length>0)throw new w(`Unexpected key '${r[0]}' in condition JSON at '${J(n)}'`)},pe=(e,t)=>typeof e=="string"?Dt(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?ci(e,t):li(e,t):{type:p.LITERAL,value:e},ai=e=>{let{$each:t,...n}=e;if(typeof t!="string")throw new w("$each value must be a non-empty string");let r=t.trim();if(r==="")throw new w("$each value must be a non-empty string");if(Object.keys(n).length===0)throw new w("Empty $each body not allowed");if(n.$partial!==void 0)throw new w("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${r}`]:n}},ci=(e,t)=>{let n=[],r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(typeof i=="object"&&i!==null&&!Array.isArray(i)){if(i.$each!==void 0)try{let c=ai(i),a=Object.keys(c);if(a.length===1&&/^\$for(?::\w+)?\s/.test(a[0])){let u=er(a[0],c[a[0]],t,!0);n.push(u),r=!0;continue}}catch(c){throw c instanceof w?c:new w(c.message)}let l=Object.keys(i);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let c=er(l[0],i[l[0]],t);n.push(c),r=!0;continue}}let s=pe(i,t);n.push(s),(s.type===p.FUNCTION||s.type===p.CONDITIONAL||s.type===p.LOOP||s.type===p.PARTIAL||s.type===p.OBJECT&&!s.fast||s.type===p.ARRAY&&!s.fast)&&(r=!0)}return{type:p.ARRAY,items:n,fast:!r}},li=(e,t)=>{let n=[],r=!1,o=null,i=Object.entries(e),s=0;if(e.$partial!==void 0){if(typeof e.$partial!="string")throw new w("$partial value must be a string");if(e.$partial.trim()==="")throw new w("$partial value cannot be an empty string");let c=["$if","$elif","$else","$for"],a=[];for(let[b]of i)for(let m of c)if(b===m||b.startsWith(m+" ")||b.startsWith(m+"#")){a.push(m);break}if(a.length>0)throw new w(`Cannot use $partial with ${a.join(", ")} at the same level. Wrap $partial in a parent object if you need conditionals.`);let{$partial:u,$when:f,...d}=e,h={},g=!1;for(let[b,m]of Object.entries(d)){let E=b;(b.startsWith("\\$")||b.startsWith("$$"))&&(E=b.slice(1)),h[E]=m,g=!0}let y=null;if(g&&(y=pe(h,t),y.type===p.OBJECT)){let b=!1;for(let m of y.properties)if(m.value.type===p.VARIABLE||m.value.type===p.INTERPOLATION||m.value.type===p.FUNCTION||m.value.type===p.CONDITIONAL||m.value.type===p.OBJECT&&!m.value.fast||m.value.type===p.ARRAY&&!m.value.fast){b=!0;break}b&&(y.fast=!1)}let I={type:p.PARTIAL,name:u,data:y};return f!==void 0&&(I.whenCondition=Zn(f,t)),I}for(let[c,a]of i)if(c==="$when"){if(o!==null)throw new w("Multiple '$when' directives on the same object are not allowed");if(a==null)throw new w("Missing condition expression after '$when'");o=Zn(a,t),r=!0}else if(c.startsWith("$when#")||c.startsWith("$when "))throw new w("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<i.length;){let[c,a]=i[s];if(c==="$when"){s++;continue}if(c==="$each")throw new w("$each can only be used inside arrays");if(c.startsWith("$if ")||c.match(/^\$if#\w+\s/)||c.match(/^\$if\s+\w+.*:$/)){let u=ui(i,s,t);n.push({key:c,value:u.node}),r=!0,s=u.nextIndex}else if(/^\$for(?::\w+)?\s/.test(c)){let u=c.match(/^\$for(?::(\w+))?\s/)?.[1]||"",f=u?`:${u}`:"";throw new w(`$for loops must be inside arrays - use '- $for${f} item in items:' instead of '$for${f} item in items:'. For cleaner object generation syntax, consider using $each.`)}else{if(c.startsWith("$elif ")||c.startsWith("$else"))throw new w(`'${c.split(" ")[0]}' without matching '$if'`);if(c==="$if"||c==="$if:")throw new w("Missing condition expression after '$if'");{let u=pe(a,t);(u.type===p.FUNCTION||u.type===p.CONDITIONAL||u.type===p.PARTIAL||u.type===p.OBJECT&&!u.fast||u.type===p.ARRAY&&!u.fast)&&(r=!0);let f=Dt(c,t),d={key:c,value:u};(f.type!==p.LITERAL||f.value!==c)&&(d.parsedKey=f),n.push(d),s++}}}let l={type:p.OBJECT,properties:n,fast:!r};return o&&(l.whenCondition=o),l},ui=(e,t,n={})=>{let r=[],o=[],i=t,[s,l]=e[i],c=null,a;if(s.startsWith("$if#")){let f=s.match(/^\$if#(\w+)\s+(.+)$/);if(f)c=f[1],a=f[2];else throw new w(`Invalid conditional syntax: ${s}`)}else a=s.substring(4),a.endsWith(":")&&(a=a.slice(0,-1).trim());Tt(a);let u=W(a,n);for(r.push(u),o.push(pe(l,n)),i++;i<e.length;){let[f,d]=e[i],h=!1,g;if(c?f.startsWith(`$elif#${c} `)?(g=f.substring(`$elif#${c} `.length),g.endsWith(":")&&(g=g.slice(0,-1).trim()),h=!0):(f===`$else#${c}`||f===`$else#${c}:`)&&(h=!0,g=null):f.startsWith("$elif ")?(g=f.substring(6),g.endsWith(":")&&(g=g.slice(0,-1).trim()),h=!0):(f==="$else"||f==="$else:")&&(h=!0,g=null),h){if(g===null)r.push(null);else{Tt(g);let y=W(g,n);r.push(y)}if(o.push(pe(d,n)),i++,g===null)break}else break}return{node:{type:p.CONDITIONAL,conditions:r,bodies:o,id:c},nextIndex:i}},Vt={eq:R.EQ,neq:R.NEQ,gt:R.GT,gte:R.GTE,lt:R.LT,lte:R.LTE,in:R.IN,add:R.ADD,sub:R.SUBTRACT},jt={all:R.AND,any:R.OR},fi=new Set(["var","literal","call","not",...Object.keys(Vt),...Object.keys(jt)]),di=(e,t,n)=>{if(!Array.isArray(e))throw new w(`Condition JSON operator '${t}' at '${J(n)}' requires an array`);if(e.length!==2)throw new w(`Condition JSON operator '${t}' at '${J(n)}' requires exactly 2 operands`);return e},pi=(e,t,n,r,o)=>{if(!Array.isArray(e))throw new w(`Condition JSON operator '${t}' at '${J(o)}' requires an array`);if(e.length===0)throw new w(`Condition JSON operator '${t}' at '${J(o)}' requires at least 1 condition`);return e.map((s,l)=>ne(s,r,[...o,l])).reduce((s,l)=>({type:p.BINARY,op:n,left:s,right:l}))},hi=(e,t,n)=>{let r,o;if(typeof e.call=="string")r=e.call,o=e.args??[],de(e,new Set(["call","args"]),n);else if(Mt(e.call))r=e.call.name,o=e.call.args??[],de(e,new Set(["call"]),n),de(e.call,new Set(["name","args"]),[...n,"call"]);else throw new w(`Condition JSON call at '${J(n)}' requires a function name`);if(typeof r!="string"||r.trim()==="")throw new w(`Condition JSON call at '${J(n)}' requires a non-empty function name`);if(!/^\w+$/.test(r))throw new w(`Invalid condition JSON function name '${r}' at '${J(n)}'`);if(!Array.isArray(o))throw new w(`Condition JSON call '${r}' at '${J(n)}' requires args to be an array`);return{type:p.FUNCTION,name:r,args:o.map((i,s)=>ne(i,t,[...n,"args",s]))}},ne=(e,t={},n=["$when"])=>{if(typeof e=="string"||typeof e=="number"||typeof e=="boolean"||e===null)return{type:p.LITERAL,value:e};if(Array.isArray(e))throw new w(`Condition JSON array at '${J(n)}' must be wrapped in an operator or { literal: [...] }`);if(!Mt(e))throw new w(`Invalid condition JSON value at '${J(n)}'`);let r=tr(e);if(r.length===0)throw new w(`Condition JSON object at '${J(n)}' must contain an operator`);let o=r.filter(s=>fi.has(s));if(o.length===0)throw new w(`Unknown condition JSON operator '${r[0]}' at '${J(n)}'`);if(o.length>1)throw new w(`Condition JSON at '${J(n)}' must contain exactly one operator`);let i=o.includes("call")?"call":o[0];if(i==="var"){if(de(e,new Set(["var"]),n),typeof e.var!="string"||e.var.trim()==="")throw new w(`Condition JSON var at '${J(n)}' requires a non-empty path`);return{type:p.VARIABLE,path:e.var}}if(i==="literal")return de(e,new Set(["literal"]),n),{type:p.LITERAL,value:e.literal};if(i==="call")return hi(e,t,n);if(i==="not")return de(e,new Set(["not"]),n),{type:p.UNARY,op:_e.NOT,operand:ne(e.not,t,[...n,"not"])};if(i in jt)return de(e,new Set([i]),n),pi(e[i],i,jt[i],t,[...n,i]);if(i in Vt){de(e,new Set([i]),n);let s=di(e[i],i,[...n,i]);return{type:p.BINARY,op:Vt[i],left:ne(s[0],t,[...n,i,0]),right:ne(s[1],t,[...n,i,1])}}throw new w(`Unknown condition JSON operator '${i}' at '${J(n)}'`)},Zn=(e,t={})=>{if(e==null)throw new w("Missing condition expression after '$when'");if(typeof e=="string"){if(e.trim()==="")throw new w("Empty condition expression after '$when'");return W(e,t)}return Mt(e)||Array.isArray(e)?ne(e,t):{type:p.LITERAL,value:e}},W=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let a=e.slice(1,-1),u=0,f=!0;for(let d=0;d<a.length;d++)if(a[d]==="("?u++:a[d]===")"&&u--,u<0){f=!1;break}if(f&&u===0)return W(a,t)}let n=ye(e,"||");if(n!==-1)return{type:p.BINARY,op:R.OR,left:W(e.substring(0,n).trim(),t),right:W(e.substring(n+2).trim(),t)};let r=ye(e,"&&");if(r!==-1)return{type:p.BINARY,op:R.AND,left:W(e.substring(0,r).trim(),t),right:W(e.substring(r+2).trim(),t)};let o=[{op:">=",type:R.GTE},{op:"<=",type:R.LTE},{op:"==",type:R.EQ},{op:"!=",type:R.NEQ},{op:">",type:R.GT},{op:"<",type:R.LT},{op:" in ",type:R.IN}];for(let{op:a,type:u}of o){let f=ye(e,a);if(f!==-1)return{type:p.BINARY,op:u,left:W(e.substring(0,f).trim(),t),right:W(e.substring(f+a.length).trim(),t)}}let i=-1,s=null,l=[{op:" + ",type:R.ADD},{op:" - ",type:R.SUBTRACT}];for(let{op:a,type:u}of l){let f=0;for(;f<e.length;){let d=ye(e.substring(f),a);if(d===-1)break;let h=f+d;h>i&&(i=h,s={op:a,type:u}),f=h+a.length}}if(i!==-1&&s)return{type:p.BINARY,op:s.type,left:W(e.substring(0,i).trim(),t),right:W(e.substring(i+s.op.length).trim(),t)};let c=[" * "," / "," % "];for(let a of c)if(ye(e,a)!==-1)throw new w(`Arithmetic operations are not allowed in conditionals: "${a}"`);return e.startsWith("!")?{type:p.UNARY,op:_e.NOT,operand:W(e.substring(1).trim(),t)}:nr(e,t)},ye=(e,t)=>{let n=0,r=0;for(;r<=e.length-t.length;){if(e[r]==="(")n++;else if(e[r]===")")n--;else if(n===0&&e.substring(r,r+t.length)===t)return r;r++}return-1},gi=e=>{if(e=e.trim(),e==="true")return{type:p.LITERAL,value:!0};if(e==="false")return{type:p.LITERAL,value:!1};if(e==="null")return{type:p.LITERAL,value:null};if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:p.LITERAL,value:e.slice(1,-1)};if(e==='""'||e==="''")return{type:p.LITERAL,value:""};if(e==="{}")return{type:p.LITERAL,value:{}};if(e==="[]")return{type:p.LITERAL,value:[]};let t=Number(e);return!isNaN(t)&&isFinite(t)?{type:p.LITERAL,value:t}:{type:p.VARIABLE,path:e}},nr=(e,t)=>{let n=e.trim();if(n.match(/^(\w+)\((.*)\)$/))return De(n,t);let o=gi(n);if(o.type===p.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(n))return{type:p.VARIABLE,path:n};try{return De(n,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},mi=(e,t=!1)=>{let n=t?"$each":"$for";try{Fn(e)}catch(r){if(r instanceof w&&t){let o=r.message.replace(/\$for/g,"$each");throw new w(o.replace("Parse Error: ",""))}throw r}},er=(e,t,n,r=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let I=r?"$each":"$for";throw new w(`Invalid loop syntax (got: '${e.replace("$for",I)}')`)}let s=i[1],l=i[2].trim();mi(l,r);let c=l.match(/^(.+?)\s+in\s+(.+)$/);if(!c){let I=r?"$each":"$for";throw new w(`Invalid loop syntax - missing 'in' keyword (got: '${I} ${l}')`)}let a=c[1].trim(),u=c[2].trim(),f,d=null;if(a.includes(",")){let I=a.split(",").map(b=>b.trim());if(I.length!==2)throw new w(`Invalid loop variables: ${a}. Expected format: "item" or "item, index"`);f=I[0],d=I[1]}else f=a;let h=["this","undefined","null","true","false"];if(h.includes(f))throw new w(`Reserved variable name: ${f}`);if(d&&h.includes(d))throw new w(`Reserved variable name: ${d}`);let g=nr(u,n),y=pe(t,n);return{type:p.LOOP,itemVar:f,indexVar:d,iterable:g,body:y,flatten:s!=="nested"}};var yi=(e,t={})=>{let{functions:n={}}=t;return pe(e,n)},rt=yi;var Ve={};Lo(Ve,{now:()=>bi});var bi=()=>Date.now();var Ii=(e,t,n={})=>{let{functions:r={},partials:o={}}=n,i={...Ve,...r},s=rt(e,{functions:i}),l={};for(let[c,a]of Object.entries(o))l[c]=rt(a,{functions:i});return Nt(s,t,{functions:i,partials:l})},Z=Ii;var Ai=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",wi=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,xi=(e,t)=>{if(Ai(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new w("Empty condition expression");return W(e,t)}return ne(e,t)},Ei=(e,t={},n={})=>{let r=wi(n),o={...Ve,...r},i=xi(e,o);return!!fe(i,{functions:o,partials:{}},t,{})},je=Ei;var rr=(e,t,n={})=>{let r=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=c=>c,transformActionFirstArgument:l=c=>c}=n;for(let[c,a]of Object.entries(t))c!=="createInitialState"&&(c.startsWith("select")?o[c]=(...u)=>a(s(r),...u):i[c]=(...u)=>{r=Pt(r,d=>a(l(d),...u))});return{...o,...i}},ot=(e,t)=>n=>{let r=e(),o=Array.isArray(n)?n:[n];return Pt(r,i=>{o.forEach(s=>{t.forEach(l=>{l(i,s)})})})};var vi=(e,t)=>{if(e.default!==void 0)return e.default;let n=["number","boolean","string","object"];if(!n.includes(e.type))throw new Error(`Invalid variable type: ${e.type} for variable ${t}. Expected one of: ${n.join(", ")}`);switch(e.type){case"number":return 0;case"boolean":return!1;case"string":return"";case"object":return{}}},Ft=e=>{let t={},n={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([r,o])=>{let i=vi(o,r);o.scope==="context"?t[r]=i:n[r]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}},zt=(e,t)=>{let n=["context","device","account"];if(!e)throw new Error(`Variable scope is required for variable: ${t}`);if(!n.includes(e))throw new Error(`Invalid variable scope: ${e} for variable ${t}. Expected one of: ${n.join(", ")}`)},Wt=(e,t,n)=>{let r={number:["set","increment","decrement","multiply","divide"],boolean:["set","toggle"],string:["set"],object:["set"]},o=r[e];if(!o)throw new Error(`Unknown variable type: ${e} for variable ${n}`);if(!Object.values(r).flat().includes(t))throw new Error(`Unknown operation: ${t}`);if(!o.includes(t))throw new Error(`Operation "${t}" is not valid for variable "${n}" of type "${e}". Valid operations: ${o.join(", ")}`)},Yt=(e,t,n)=>{switch(t){case"set":return n;case"multiply":return(e??1)*n;case"divide":return(e??0)/n;case"increment":return(e??0)+(n??1);case"decrement":return(e??0)-(n??1);case"toggle":return!e;default:throw new Error(`Unknown operation: ${t}`)}};var or=(e,t="DD/MM/YYYY - HH:mm")=>{if(!e)return"";let n=new Date(e),r=o=>String(o).padStart(2,"0");return t.replace("DD",r(n.getDate())).replace("MM",r(n.getMonth()+1)).replace("YYYY",n.getFullYear()).replace("YY",String(n.getFullYear()).slice(-2)).replace("HH",r(n.getHours())).replace("mm",r(n.getMinutes())).replace("ss",r(n.getSeconds()))},Si=(e,t)=>{let n=i=>{if(!i)return;let s={};i.ui&&(s.ui=i.ui);let l=i.character?.sprite;return l&&Object.keys(l).length>0&&(s.sprite=l),Object.keys(s).length>0?s:void 0},r=n(e),o=n(t);return JSON.stringify(r)===JSON.stringify(o)?null:r&&!o?{changeType:"delete",data:e}:o&&!r?{changeType:"add",data:t}:o&&r?{changeType:"update",data:t}:null},qt=(e={},t={})=>{let n={},r=["sfx","voice"],o=s=>{let l=e[s],c=t[s];c&&!l?n[s]={changeType:"add",data:c}:l&&!c?r.includes(s)||(n[s]={changeType:"delete",data:l}):l&&c&&JSON.stringify(l)!==JSON.stringify(c)&&(n[s]={changeType:"update",data:c})};o("background"),o("bgm"),o("voice");let i=Si(e.dialogue,t.dialogue);return i&&(n.dialogue=i),o("choice"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),n},Ht=(e={})=>{let t=structuredClone(e);t.background&&(t.background.animations?.playback?.continuity!=="persistent"&&delete t.background.animations,t.background.resourceId||delete t.background);let n=o=>{t[o]&&(delete t[o].animations,Object.keys(t[o]).length===0&&delete t[o])};n("layout"),n("choice"),t.dialogue?.ui&&(delete t.dialogue.ui.animations,Object.keys(t.dialogue.ui).length===0&&delete t.dialogue.ui,Object.keys(t.dialogue).length===0&&delete t.dialogue),t.dialogue?.character?.sprite&&(delete t.dialogue.character.sprite.animations,Object.keys(t.dialogue.character.sprite).length===0&&delete t.dialogue.character.sprite,Object.keys(t.dialogue.character).length===0&&delete t.dialogue.character,Object.keys(t.dialogue).length===0&&delete t.dialogue);let r=(o,i)=>{let s=t[o]?.items;Array.isArray(s)&&(t[o].items=s.map(l=>{let c={...l};return delete c.animations,i(c)?c:null}).filter(Boolean),t[o].items.length===0&&delete t[o])};return r("character",o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId),r("visual",o=>o.resourceId||o.transformId),t},Ci=(e,t)=>{if(!e||!t)return;let n=e;for(let r of t.split(".")){if(n==null||!(r in Object(n)))return;n=n[r]}return n},_i=(e,t)=>{if(typeof e!="string")return e;if(e==="_event"){if(t==null)throw new Error('Action template binding "_event" requires event context "_event".');return t}if(!e.startsWith("_event."))return e;if(t==null)throw new Error(`Action template binding "${e}" requires event context "_event".`);let n=e.slice(7),r=Ci(t,n);if(r===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return r},Ri={conditional:new Set(["branches"]),updateProjectData:new Set(["projectData"]),showConfirmDialog:new Set(["confirmActions","cancelActions"])},ir=(e,t)=>{let n=e[e.length-1];return n?Ri[n]?.has(t)===!0:!1},Ut=(e,t,n=[])=>Array.isArray(e)?e.map(r=>Ut(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,ir(n,r)?o:Ut(o,t,[...n,r])])):_i(e,t),Bt=(e,t,n=[])=>Array.isArray(e)?e.map(r=>Bt(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,ir(n,r)?o:Bt(o,t,[...n,r])])):typeof e=="string"?Z(e,t):e,Jt=(e,t)=>{if(!t)return e;if(Object.prototype.hasOwnProperty.call(t,"event"))throw new Error('Action template context key "event" is no longer supported. Use "_event".');let n=Ut(e,t._event);return Bt(n,t)};var it=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:structuredClone(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},cr=(e,t)=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let n=e.map(r=>structuredClone(r)).filter(r=>t(r)||r.animations);return{hasValidItems:n.length>0,processedItems:n}},Re=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),sr=e=>e?.animations?.playback?.continuity==="persistent",Li=e=>{if(e){if(e.character&&Re(e.character,"name"))return e.character.name;if(Re(e,"characterName"))return e.characterName}},lr=e=>!!e?.character&&Re(e.character,"sprite"),$i=e=>{let t={},n=!1,r=Li(e);return r!==void 0&&(t.name=r,n=!0),lr(e)&&(t.sprite=structuredClone(e.character.sprite),n=!0),n?t:void 0},ar=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},Oi=({dialogueState:e,content:t,append:n=!1})=>{if(!n||!Array.isArray(t)){e.content=t,delete e.initialRevealedContent;return}let r=Array.isArray(e.content)?e.content:[];r.length>0?e.initialRevealedContent=r.map(o=>structuredClone(o)):delete e.initialRevealedContent,e.content=[...r,...t]},ki=()=>({}),Pi=(e,t)=>{if(t.background){let{animationsOnly:n,state:r}=it(t.background,s=>!!s.resourceId);if(n){e.background=e.background?.resourceId?{...structuredClone(e.background),...r}:r;return}if(!t.background.resourceId){delete e.background;return}let o=structuredClone(t.background),i=e.background;i?.resourceId===o.resourceId&&i?.transformId===o.transformId&&!Re(o,"animations")&&sr(i)&&(o.animations=structuredClone(i.animations)),e.background=o}else e.background?.animations&&!sr(e.background)&&(e.background.animations={})},Ti=(e,t)=>{if(!t.dialogue){e.dialogue&&(ar(e.dialogue),e.dialogue.mode==="adv"&&(e.dialogue.content=void 0,delete e.dialogue.initialRevealedContent,e.dialogue.persistCharacter!==!0&&(delete e.dialogue.characterId,delete e.dialogue.character)));return}e.dialogue||(e.dialogue={});let n=e.dialogue.mode;if(t.dialogue.ui){let{animationsOnly:a,state:u}=it(t.dialogue.ui,f=>!!f.resourceId);a?e.dialogue.ui={...e.dialogue.ui,...u}:e.dialogue.ui={...t.dialogue.ui}}else e.dialogue?.ui?.animations&&(e.dialogue.ui.animations={});t.dialogue.mode==="adv"&&(e.dialogue.content=e.dialogue.content||void 0,e.dialogue.characterId=e.dialogue.characterId||void 0,e.dialogue.mode="adv"),t.dialogue.mode==="nvl"&&(e.dialogue?.mode!=="nvl"&&(e.dialogue.lines=[]),e.dialogue.mode="nvl");let r=t.dialogue.append===!0&&n!=="nvl"&&e.dialogue?.mode!=="nvl"&&Array.isArray(t.dialogue.content);t.dialogue.content!==void 0&&Oi({dialogueState:e.dialogue,content:t.dialogue.content,append:r});let o=Re(t.dialogue,"persistCharacter")?t.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;o?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let i=Re(t.dialogue,"characterId"),s=$i(t.dialogue),l=s!==void 0,c=lr(t.dialogue);if(i?t.dialogue.characterId?e.dialogue.characterId=t.dialogue.characterId:delete e.dialogue.characterId:!o&&!r&&delete e.dialogue.characterId,l?e.dialogue.character=!i&&o&&e.dialogue.character?{...structuredClone(e.dialogue.character),...s}:s:(i||!o&&!r)&&delete e.dialogue.character,c||ar(e.dialogue),t.dialogue.clear){delete e.dialogue;return}if(t.dialogue?.clearPage&&e.dialogue?.mode==="nvl"&&(e.dialogue.lines=[]),e.dialogue?.mode==="nvl"&&t.dialogue.content!==void 0){let a={content:t.dialogue.content,characterId:e.dialogue.characterId??null};e.dialogue.character&&(a.character=structuredClone(e.dialogue.character)),e.dialogue.lines.push(a)}},Ni=(e,t)=>{if(t.sfx){if(!t.sfx.items||t.sfx.items.length===0){delete e.sfx;return}e.sfx=t.sfx}else e.sfx&&delete e.sfx},Di=(e,t)=>{if(t.bgm){if(!t.bgm.resourceId){e.bgm=void 0;return}e.bgm={...t.bgm,loop:t.bgm.loop||t.bgm.loop===void 0}}},Vi=(e,t)=>{if(t.visual){let{hasValidItems:n,processedItems:r}=cr(t.visual.items,o=>!!o.resourceId);n?e.visual={items:r}:delete e.visual}else e.visual?.items&&(e.visual.items=e.visual.items.map(n=>n.animations?{...n,animations:{}}:n))},ji=(e,t)=>{if(!t.character){e.character?.items&&(e.character.items=e.character.items.map(o=>o.animations?{...o,animations:{}}:o));return}let{hasValidItems:n,processedItems:r}=cr(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId);n?e.character={items:r}:delete e.character},Mi=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},Ui=(e,t)=>{if(t.layout){let{animationsOnly:n,state:r}=it(t.layout,o=>!!o.resourceId);if(n){e.layout=r;return}if(!t.layout.resourceId){delete e.layout;return}e.layout=t.layout}else e.layout&&delete e.layout},Bi=(e,t)=>{if(t.choice){let{animationsOnly:n,state:r}=it(t.choice,o=>!!o.resourceId);if(n){e.choice={...e.choice,...r};return}if(!t.choice.resourceId){delete e.choice;return}e.choice=t.choice}else e.choice&&delete e.choice},Fi=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},zi=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},Wi=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(n=>{delete e[n]})},Le=e=>ot(ki,[Wi,Pi,Ni,Di,Vi,Ti,ji,Mi,Ui,Bi,Fi,zi])(e);var be={objectValues:e=>Object.entries(e).map(([t,n])=>({id:t,...n})),formatDate:or},Yi=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,qi=(e,t)=>{let n=String(t||"").trim();if(!n)return;let r=n.match(/[A-Za-z_][A-Za-z0-9_]*|\[\d+\]/g)||[],o=e;for(let i of r){if(i.startsWith("[")){let s=Number(i.slice(1,-1));o=Array.isArray(o)?o[s]:void 0;continue}o=o?.[i]}return o},ct=(e,t,n)=>{if(Array.isArray(e)){let o=[];for(let i of e){if(i&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===1){let[s]=Object.keys(i),l=Yi.exec(s);if(l){let[,c,a,u]=l,f=qi(t,u);if(!Array.isArray(f))continue;let d=Array.isArray(i[s])?i[s]:[];f.forEach((h,g)=>{let y={...t,[c]:h};a&&(y[a]=g),d.forEach(I=>{let b=ct(I,y,n),m=Z(b,y,n);Array.isArray(m)?o.push(...m):o.push(m)})});continue}}o.push(ct(i,t,n))}return o}if(!e||typeof e!="object")return e;let r={};return Object.entries(e).forEach(([o,i])=>{r[o]=ct(i,t,n)}),r},cn=({animationType:e,animationId:t,animationPath:n})=>{if(e!==void 0&&!(e==="update"||e==="transition"))throw new Error(`[${n}] Animation "${t}" has unsupported type "${e}". Use "update" or "transition".`)},Hi=({id:e,targetId:t,animation:n,playback:r,animationPath:o="animation"})=>{let i=structuredClone(n);return cn({animationType:i.type,animationId:e,animationPath:o}),delete i.name,delete i.playback,i.id=e,i.targetId=t,r&&(i.playback=structuredClone(r)),i},Ji=(e,{animationId:t="animation",animationPath:n="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return cn({animationType:e.type,animationId:t,animationPath:n}),e.type},Ki=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},Gi=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},Xi=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Ar=e=>e?.playback?.continuity==="persistent",en=e=>Array.isArray(e)?e.map(en):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((t,n)=>(t[n]=en(e[n]),t),{}),lt=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let t=structuredClone(e);return delete t.playback,JSON.stringify(en(t))},wr=(e=[])=>e.filter(t=>Ar(t)).map(t=>structuredClone(t)),xr=e=>Array.isArray(e?.keyframes)?e.keyframes.reduce((t,n)=>{let r=typeof n?.duration=="number"&&Number.isFinite(n.duration)?n.duration:0;return t+r},0):0,Kt=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((t,n)=>Math.max(t,xr(n)),0),Er=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max(Kt(e.tween),Kt(e.prev?.tween),Kt(e.next?.tween),xr(e.mask?.progress)),ur=({animationInstances:e,activePersistentAnimations:t})=>{if(!Array.isArray(e)||e.length===0||!Array.isArray(t)||t.length===0)return!1;let n=new Set(t.map(lt).filter(Boolean));return e.some(r=>{if(!Ar(r))return!1;let o=lt(r);return o?n.has(o):!1})},se=({animationInstances:e,isLineCompleted:t,skipTransitionsAndAnimations:n,activePersistentAnimations:r,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||n?!1:i&&!t||ur({animationInstances:e,activePersistentAnimations:r})?!0:i?!1:ur({animationInstances:e,activePersistentAnimations:o}),Qi=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),Zi=(e,t)=>{if(Qi(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},es=({resources:e,animationId:t,playback:n,instanceId:r,targetId:o,animationPath:i="animation"})=>{if(!t||!o)return!1;let s=e?.animations?.[t];return s?Hi({id:r,targetId:o,animation:s,playback:n,animationPath:i}):null},ts=({hasPrevious:e,hasCurrent:t,previousResourceId:n,currentResourceId:r,sharedTarget:o})=>!e&&t?"enter":e&&!t?"exit":e&&t?n===r&&o?"update":"replace":"none",ns=({animationType:e,animationId:t,animationPath:n,lifecycle:r})=>{if(!(e!=="update"||r==="update"))throw new Error(`[${n}] Animation "${t}" has type "update", but update animations can only be used when the same target persists across the state change. Use type "transition" for enter, exit, and replace.`)},rs=(e,{defaultTargetId:t,defaultId:n,animationPath:r="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return cn({animationType:o.type,animationId:o.id??n,animationPath:r}),o.id??=n,o.targetId??=t,o},ln=({animations:e,transitions:t,defaultTargetId:n,idPrefix:r,animationPathPrefix:o=r})=>{t.forEach((i,s)=>{e.push(rs(i,{defaultTargetId:n,defaultId:`${r}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},tn=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let n=Z(e,t);return n&&typeof n=="object"?e:n},nn=(e,t)=>{if(e===void 0)return[];if(!Array.isArray(e)||e.some(n=>n===null||typeof n!="object"||Array.isArray(n)))throw new Error(`${t} must be an array of objects`);return e},os=({content:e,path:t,variables:n})=>nn(e,t).reduce((r,o)=>{let i=tn(o.text,{variables:n});return r+`${i??""}`.length},0),fr=(e=[])=>{let t=new Map;for(let n of e)n?.id&&t.set(n.id,(t.get(n.id)??0)+1);return new Set(Array.from(t.entries()).filter(([,n])=>n>1).map(([n])=>n))},st=(e,t=0,n=new Set)=>{if(!n.has(e?.id))return`character-container-${e.id}`;let r=e?.sprites?.map(({resourceId:o})=>o)||[];return r.length===0?`character-container-${e.id}`:`character-container-${e.id}-${t}-${r.join("-")}`},Gt=(e,t)=>{if(!t.transformId)throw new Error(`Visual item "${t.id}" requires transformId`);let n=e.transforms?.[t.transformId];if(!n)throw new Error(`Transform "${t.transformId}" not found for visual item "${t.id}"`);return n},is=(e,t={})=>{if(!t?.transformId)return;let n=e.transforms?.[t.transformId];if(!n)throw new Error(`Transform "${t.transformId}" not found for background`);return n},dr=(e={},t)=>{if(t){if(e.images?.[t])return"sprite";if(e.videos?.[t])return"video";if(e.layouts?.[t])return"container"}},at=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},ss=(e={})=>e.textStyles||{},as=(e={})=>e.images||{},cs=(e={})=>e.colors||{},ls=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,Me=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,Oe=(e,t,n)=>{if(typeof e!="string"||e.length===0)throw new Error(`${n} at "${t}" must resolve to a non-empty string`)},pr=(e,t,n)=>{if(e===void 0)return 1;if(typeof e!="number"||!Number.isFinite(e))throw new Error(`${t} for text style "${n}" must be a number between 0 and 1`);if(e<0||e>1)throw new Error(`${t} for text style "${n}" must be a number between 0 and 1`);return e},vr=(e,t)=>{if(typeof e!="string"||!ls.test(e))throw new Error(`${t} must resolve to a hex color`);return e.length===4?`#${e.slice(1).split("").map(n=>n.repeat(2)).join("")}`:e},hr=(e,t,n)=>{let r=vr(e,n);if(t===1)return r;let o=Number.parseInt(r.slice(1,3),16),i=Number.parseInt(r.slice(3,5),16),s=Number.parseInt(r.slice(5,7),16);return`rgba(${o}, ${i}, ${s}, ${t})`},us=(e={},t)=>{let n=ss(e)?.[t];if(!n)throw new Error(`Text style "${t}" not found`);let r=e.fonts?.[n.fontId];if(!r)throw new Error(`Font "${n.fontId}" not found for text style "${t}"`);let o=e.colors?.[n.colorId];if(!o)throw new Error(`Color "${n.colorId}" not found for text style "${t}"`);let i=pr(n.colorAlpha,"colorAlpha",t),s={fontFamily:r.fileId,fontSize:n.fontSize??16,fontWeight:n.fontWeight??"400",fontStyle:n.fontStyle??"normal",lineHeight:n.lineHeight??1.2,fill:hr(o.hex,i,`Color "${n.colorId}" for text style "${t}"`)};if(n.align!==void 0&&(s.align=n.align),n.wordWrap!==void 0&&(s.wordWrap=n.wordWrap),n.breakWords!==void 0&&(s.breakWords=n.breakWords),n.wordWrapWidth!==void 0&&(s.wordWrapWidth=n.wordWrapWidth),n.strokeColorId){let l=e.colors?.[n.strokeColorId];if(!l)throw new Error(`Stroke color "${n.strokeColorId}" not found for text style "${t}"`);let c=pr(n.strokeAlpha,"strokeAlpha",t);s.strokeColor=hr(l.hex,c,`Stroke color "${n.strokeColorId}" for text style "${t}"`)}else if(n.strokeAlpha!==void 0)throw new Error(`strokeAlpha for text style "${t}" requires strokeColorId`);return n.strokeWidth!==void 0&&(s.strokeWidth=n.strokeWidth),s},rn=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>rn(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(Object.prototype.hasOwnProperty.call(e,"textStyle"))throw new Error(`Inline textStyle is not allowed in layout elements at "${n}". Use textStyleId instead`);let r={};for(let[o,i]of Object.entries(e))o!=="textStyleId"&&(r[o]=rn(i,t,Me(n,o)));return e.textStyleId!==void 0&&(Oe(e.textStyleId,n,"textStyleId"),r.textStyle=us(t,e.textStyleId)),r},Sr=(e={},t)=>{let n=cs(e)?.[t];if(!n)throw new Error(`Color "${t}" not found`);return vr(n.hex,`Color "${t}"`)},Cr=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",Xt=(e,t,n)=>{let r=e?.[t];if(!(!r||typeof r!="object"||Array.isArray(r))&&Object.prototype.hasOwnProperty.call(r,"fill"))throw new Error(`Inline ${t}.fill is not allowed in rect layout elements at "${n}". Use ${Cr(`${t}.fill`)} instead`)},fs=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>Ue(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;let r={};for(let[o,i]of Object.entries(e))o!=="colorId"&&(r[o]=Ue(i,t,Me(n,o)));return e.colorId!==void 0&&(Oe(e.colorId,n,"colorId"),r.fill=Sr(t,e.colorId)),r},Ue=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>Ue(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="rect"){if(Object.prototype.hasOwnProperty.call(e,"fill"))throw new Error(`Inline fill is not allowed in rect layout elements at "${n}". Use ${Cr("fill")} instead`);Xt(e,"hover",n),Xt(e,"click",n),Xt(e,"rightClick",n)}let r={};for(let[o,i]of Object.entries(e))if(!(e.type==="rect"&&o==="colorId")){if(e.type==="rect"&&(o==="hover"||o==="click"||o==="rightClick")){r[o]=fs(i,t,Me(n,o));continue}r[o]=Ue(i,t,Me(n,o))}return e.type==="rect"&&e.colorId!==void 0&&(Oe(e.colorId,n,"colorId"),r.fill=Sr(t,e.colorId)),r},Qt=(e={},t)=>{let n=as(e)?.[t];return n||null},_r=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",gr=(e,t,n,r)=>{let o=e?.[t];if(!(!o||typeof o!="object"||Array.isArray(o))&&Object.prototype.hasOwnProperty.call(o,r))throw new Error(`Inline ${t}.${r} is not allowed in sprite layout elements at "${n}". Use ${_r(`${t}.${r}`)} instead`)},mr=(e,t,n)=>{let r=e[t];e[t]={...r&&typeof r=="object"&&!Array.isArray(r)?r:{},src:n}},on=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>on(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="sprite"){for(let o of["url","src","hoverUrl","hoverSrc","clickUrl","clickSrc"])if(Object.prototype.hasOwnProperty.call(e,o))throw new Error(`Inline ${o} is not allowed in sprite layout elements at "${n}". Use ${_r(o)} instead`);gr(e,"hover",n,"src"),gr(e,"click",n,"src")}let r={};for(let[o,i]of Object.entries(e))e.type==="sprite"&&(o==="imageId"||o==="hoverImageId"||o==="clickImageId")||(r[o]=on(i,t,Me(n,o)));if(e.type==="sprite"&&e.imageId!==void 0){Oe(e.imageId,n,"imageId");let o=Qt(t,e.imageId),i=o?.fileId??e.imageId;r.src=i,r.width===void 0&&o?.width!==void 0&&(r.width=o.width),r.height===void 0&&o?.height!==void 0&&(r.height=o.height)}return e.type==="sprite"&&e.hoverImageId!==void 0&&(Oe(e.hoverImageId,n,"hoverImageId"),mr(r,"hover",Qt(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(Oe(e.clickImageId,n,"clickImageId"),mr(r,"click",Qt(t,e.clickImageId)?.fileId??e.clickImageId)),r},un=(e,t={},n="root")=>on(Ue(rn(e,t,n),t,n),t,n),Ie=un,Be=(e=[])=>e.find(t=>t.id==="story");var ds=(e={})=>e?.muteAll?0:e?.musicVolume??50,re=({variables:e,runtime:t,saveSlots:n=[],dialogueState:r,includeInactiveAdvDialogue:o=!1,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:c,canRollback:a,confirmDialog:u,historyDialogue:f=[],characters:d={},dialogueUIHidden:h,skipOnlyViewedLines:g,skipTransitionsAndAnimations:y}={})=>{let I={dialogueTextSpeed:t?.dialogueTextSpeed??50,autoForwardDelay:t?.autoForwardDelay??1e3,skipUnseenText:t?.skipUnseenText??!1,skipTransitionsAndAnimations:t?.skipTransitionsAndAnimations??!1,soundVolume:t?.soundVolume??50,musicVolume:t?.musicVolume??50,muteAll:t?.muteAll??!1,saveLoadPagination:t?.saveLoadPagination??1,menuPage:t?.menuPage??"",menuEntryPoint:t?.menuEntryPoint??"",autoMode:t?.autoMode??s??!1,skipMode:t?.skipMode??l??!1,dialogueUIHidden:t?.dialogueUIHidden??h??!1,isLineCompleted:t?.isLineCompleted??i??!1},b=ms({dialogueState:r,includeInactiveAdvDialogue:o,characters:d,variables:e}),m={variables:e,runtime:I,saveSlots:n,isChoiceVisible:c,canRollback:a,confirmDialog:u,historyDialogue:f,characters:d};return b&&(m.dialogue=b,m.dialogueLines=b.lines),m},yr=100,ut=(e,t)=>{if(Array.isArray(e))return e.map(r=>ut(r,t));if(!e||typeof e!="object")return e;let n={...e};return Object.keys(n).forEach(r=>{n[r]=ut(n[r],t)}),n.type==="text-revealing"?t(n):n},ps=e=>ut(e,t=>({...t,revealEffect:"none"})),hs=e=>ut(e,t=>{let n=Number(t.speed??t.displaySpeed),r=Number.isFinite(n)?Math.max(n,yr):yr;return{...t,speed:r,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:r}:{}}}),Ae=(e,{isLineCompleted:t=!1,skipMode:n=!1,skipTransitionsAndAnimations:r=!1}={})=>t||r?ps(e):n?hs(e):e,Rr=({id:e,screen:t={width:1920,height:1080}})=>({id:e,type:"rect",fill:"transparent",width:t.width,height:t.height,x:0,y:0,click:{payload:{actions:{}}}}),sn=e=>{if(Array.isArray(e))return e.map(sn);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=sn(s);let n=t.click?.payload;if(!n||typeof n!="object"||Array.isArray(n))return t;let r=n.actions,o=r&&typeof r=="object"&&!Array.isArray(r)&&Object.prototype.hasOwnProperty.call(r,"nextLine")?{...r.nextLine,_interactionSource:"choice"}:void 0;return{...t,click:{...t.click,payload:{...n,_interactionSource:"choice",...o?{actions:{...r,nextLine:o}}:{}}}}},an=({characterId:e,character:t,characterName:n,characters:r={}}={})=>{let o=e?r?.[e]:void 0,i=t?.name!==void 0?t.name:n!==void 0?n:o?.name||"";return{...o||{},...t||{},name:i}},Lr=(e=[],t={})=>e.map(n=>{let r=an({characterId:n.characterId,character:n.character,characterName:n.characterName,characters:t}),o=typeof n.text=="string"?n.text:Array.isArray(n.content)?n.content.map(i=>i?.text??"").join(""):"";return{...n,text:o,character:r,characterName:r.name}}),gs=e=>!(!e||e.mode==="adv"&&e.content===void 0),ms=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:n={},variables:r}={})=>{if(!t&&!gs(e))return;let o=e.content===void 0?[{text:""}]:nn(e.content,"dialogue.content"),i=e.content===void 0?0:os({content:e.initialRevealedContent,path:"dialogue.initialRevealedContent",variables:r}),s=(e.lines||[]).map((c,a)=>{let u=nn(c.content,`dialogue.lines[${a}].content`),f=an({characterId:c.characterId,character:c.character,characterName:c.characterName,characters:n});return{...c,content:u.map(d=>({...d,text:tn(d.text,{variables:r})})),character:f,characterName:f.name}}),l=an({characterId:e.characterId,character:e.character,characters:n});return{characterId:e.characterId,persistCharacter:e.persistCharacter,character:l,content:o.map(c=>({...c,text:tn(c.text,{variables:r})})),initialRevealedCharacters:i,lines:s}},$r=({container:e,resources:t,templateData:n,isLineCompleted:r=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=Z(e,n,{functions:be});return Ie(Ae(s,{isLineCompleted:r,skipMode:o,skipTransitionsAndAnimations:i}),t)},Zt=(e,t={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(t),br=({renderStateKeyboard:e,keyboard:t,phase:n})=>{!t||typeof t!="object"||Array.isArray(t)||Object.entries(t).forEach(([r,o])=>{let i=e[r]??{},s=n==="keydown"?o?.keydown:o?.keyup;if(n==="keydown"&&s&&typeof s=="object"){e[r]={...i,keydown:{payload:Zt(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[r].keyup={payload:Zt(o.keyup)});return}e[r]={...i,[n]:{payload:Zt(o)}}})},ys=(e={},t={})=>{let n={};return br({renderStateKeyboard:n,keyboard:e,phase:"keydown"}),br({renderStateKeyboard:n,keyboard:t,phase:"keyup"}),Object.keys(n).length>0?n:void 0},we=({animationsDef:e,resources:t,previousResourceId:n,currentResourceId:r,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:l,allowIncomingUpdateFallback:c=!1})=>{if(!e)return[];let a=[],u=({instanceId:S,targetId:$})=>{let O=es({resources:t,animationId:y,playback:I,instanceId:S,targetId:$,animationPath:s});O&&a.push(O)},f=n!=null&&n!==!1,d=r!=null&&r!==!1,h=o&&i&&o===i,g=ts({hasPrevious:f,hasCurrent:d,previousResourceId:n,currentResourceId:r,sharedTarget:h});Zi(e,s);let y=Ki(e),I=Gi(e),b=t?.animations?.[y],m=Ji(b,{animationId:y,animationPath:s}),E=c&&m==="update"&&g!=="update"&&d&&i;if(E||ns({animationType:m,animationId:y,animationPath:s,lifecycle:g}),m==="update")return f&&d&&n===r&&h?u({instanceId:`${l}-animation-update`,targetId:i}):E&&u({instanceId:`${l}-animation-update`,targetId:i}),a;if(m==="transition"){let S=`${l}-animation-transition`,$=I?.continuity==="persistent"?S:`${l}-animation-in`;if(f&&d&&h)return u({instanceId:S,targetId:i}),a;f&&u({instanceId:`${l}-animation-out`,targetId:o}),d&&u({instanceId:$,targetId:i})}return a},bs=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),Is=(e,{presentationState:t,previousPresentationState:n,currentLineActions:r,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:l,variables:c,runtime:a,activePersistentAnimations:u,restoredPersistentAnimations:f,autoMode:d,skipMode:h,isChoiceVisible:g,canRollback:y,saveSlots:I=[]})=>{let{elements:b,animations:m}=e;if(t.background){let E=r===void 0?!0:Xi(r?.background??{},"animations"),S=b.find(P=>P.id==="story");if(!S)return e;let $=is(o,t.background),O=n?.background?.resourceId,_=t.background.resourceId??(t.background.animations?O:void 0),D=dr(o,O),N=dr(o,_);if(_){let{images:P={},videos:x={}}=o,C=P[_]||x[_];if(C){let M=x[_]!==void 0,z={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...$},Y={id:at({resourceId:_,kind:M?"video":"sprite"}),type:M?"video":"sprite",x:z.x,y:z.y,src:C.fileId,width:C.width,height:C.height,alpha:1,anchorX:z.anchorX,anchorY:z.anchorY,rotation:z.rotation,scaleX:z.scaleX,scaleY:z.scaleY};M&&(Y.loop=t.background.loop??!1,Y.volume=C.volume??50),S.children.push(Y)}}if(_){let{layouts:P={}}=o,x=P[_];if(x){let C={id:at({resourceId:_,kind:"container"}),type:"container",children:x.elements};$&&Object.assign(C,{x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...$});let M=Z(C,re({variables:c,runtime:a,saveSlots:I,dialogueState:t.dialogue,isLineCompleted:s,autoMode:d,skipMode:h,isChoiceVisible:g,canRollback:y,characters:o.characters||{},skipTransitionsAndAnimations:l}),{functions:be});S.children.push(Ie(Ae(M,{isLineCompleted:s,skipMode:h,skipTransitionsAndAnimations:l}),o))}}let k=we({animationsDef:t.background.animations,resources:o,previousResourceId:O,currentResourceId:_,previousTargetId:at({resourceId:O,kind:D}),currentTargetId:at({resourceId:_,kind:N}),animationPath:"background.animations",idPrefix:"bg-cg",allowIncomingUpdateFallback:!0});se({animationInstances:k,isLineCompleted:s,skipTransitionsAndAnimations:l,activePersistentAnimations:u,restoredPersistentAnimations:f,isAuthoredOnCurrentLine:E})&&m.push(...k)}return e},As=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:l,animations:c}=e;if(t.character&&r){let a=l.find(g=>g.id==="story");if(!a)return e;let u=t.character.items||[],f=n?.character?.items||[],d=fr(u),h=fr(f);for(let g=0;g<u.length;g++){let y=u[g],{transformId:I,sprites:b}=y,m=f.find(P=>P.id===y.id),E=f.findIndex(P=>P.id===y.id),S=m?.sprites&&m.sprites.length>0,$=b&&b.length>0,O=E>=0?st(m,E,h):void 0,_=we({animationsDef:y.animations,resources:r,previousResourceId:O,currentResourceId:$?st(y,g,d):void 0,previousTargetId:O,currentTargetId:$?st(y,g,d):void 0,animationPath:`character.items[${g}].animations`,idPrefix:"character"});if(y.animations&&!b&&!I&&S&&se({animationInstances:_,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){c.push(..._);continue}if(y.animations&&!b&&!I)continue;if(!b||b.length===0||!I){console.warn("Character item missing sprites or transformId:",y);continue}let D=st(y,g,d),N=r.transforms[I];if(!N){console.warn("Transform not found:",I);continue}let k={type:"container",id:D,x:y.x??N.x,y:y.y??N.y,anchorX:N.anchorX,anchorY:N.anchorY,rotation:N.rotation,scaleX:N.scaleX,scaleY:N.scaleY,children:[]};for(let P of b){let x=r.images[P.resourceId];if(!x){console.warn(`Image resource not found: ${P.resourceId}`);continue}k.children.push({type:"sprite",id:`${D}-${P.id}`,src:x.fileId,width:x.width,height:x.height,x:0,y:0})}a.children.push(k),se({animationInstances:_,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(..._)}}return e},ws=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,runtime:l,activePersistentAnimations:c,autoMode:a,skipMode:u,isChoiceVisible:f,canRollback:d,saveSlots:h=[]})=>{let{elements:g,animations:y}=e;if(t.visual&&r){let I=g.find(m=>m.id==="story");if(!I)return e;let b=t.visual.items;for(let m of b){if(m.resourceId){let{images:O={},videos:_={},spritesheets:D={}}=r,N=D[m.resourceId];if(N){let k=Gt(r,m),P=m.animationName;if(P){let x=N.animations?.[P];if(!x)throw new Error(`Animation '${P}' not found in spritesheet resource '${m.resourceId}'`);let C={id:`visual-${m.id}`,type:"animated-sprite",x:m.x??k.x,y:m.y??k.y,width:m.width??N.width,height:m.height??N.height,alpha:m.alpha??1,anchorX:k.anchorX,anchorY:k.anchorY,rotation:k.rotation,scaleX:k.scaleX,scaleY:k.scaleY,spritesheetSrc:N.fileId,spritesheetData:N.jsonData,animation:{frames:x.frames,animationSpeed:m.animationSpeed??x.animationSpeed??.5,loop:m.loop??x.loop??!0}};I.children.push(structuredClone(C))}}else{let k=O[m.resourceId]||_[m.resourceId];if(k){let P=_[m.resourceId]!==void 0,x=Gt(r,m),C={id:`visual-${m.id}`,type:P?"video":"sprite",src:k.fileId,width:k.width,height:k.height,x:x.x,y:x.y,anchorX:x.anchorX,anchorY:x.anchorY,rotation:x.rotation,scaleX:x.scaleX,scaleY:x.scaleY};P&&(C.loop=k.loop??!1,C.volume=k.volume??50),I.children.push(C)}}}if(m.resourceId){let{layouts:O={}}=r,_=O[m.resourceId];if(_){let D=Gt(r,m),N={id:`visual-${m.id}`,type:"container",children:structuredClone(_.elements),x:D.x,y:D.y,anchorX:D.anchorX,anchorY:D.anchorY,rotation:D.rotation,scaleX:D.scaleX,scaleY:D.scaleY},k=Z(N,re({variables:s,runtime:l,saveSlots:h,dialogueState:t.dialogue,isLineCompleted:o,autoMode:a,skipMode:u,isChoiceVisible:f,canRollback:d,characters:r.characters||{},skipTransitionsAndAnimations:i}),{functions:be});I.children.push(Ie(Ae(k,{isLineCompleted:o,skipMode:u,skipTransitionsAndAnimations:i}),r))}}let S=(n?.visual?.items||[]).find(O=>O.id===m.id),$=we({animationsDef:m.animations,resources:r,previousResourceId:S?.resourceId,currentResourceId:m.resourceId,previousTargetId:S?.resourceId?`visual-${m.id}`:void 0,currentTargetId:m.resourceId?`visual-${m.id}`:void 0,animationPath:`visual.items[${m.id}].animations`,idPrefix:m.id});se({animationInstances:$,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:c})&&y.push(...$)}}return e},$e="dialogue-character-sprite",Ir=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,xs=(e,{presentationState:t,previousPresentationState:n,resources:r={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:l}=e,c=Be(e.elements);if(!c)return e;let a=t.dialogue?.character?.sprite,u=n?.dialogue?.character?.sprite,f=Ir(a),d=Ir(u),h=we({animationsDef:a?.animations,resources:r,previousResourceId:d?$e:void 0,currentResourceId:f?$e:void 0,previousTargetId:d?$e:void 0,currentTargetId:f?$e:void 0,animationPath:"dialogue.character.sprite.animations",idPrefix:"dialogue-character-sprite"});if(!f)return a?.animations&&d&&se({animationInstances:h,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...h),e;let g=r.transforms?.[a.transformId];if(!g)return console.warn("Transform not found:",a.transformId),e;let y={type:"container",id:$e,x:g.x,y:g.y,anchorX:g.anchorX,anchorY:g.anchorY,rotation:g.rotation,scaleX:g.scaleX,scaleY:g.scaleY,children:[]};for(let I of a.items){let b=r.images?.[I.resourceId];if(!b){console.warn(`Image resource not found: ${I.resourceId}`);continue}y.children.push({type:"sprite",id:`${$e}-${I.id}`,src:b.fileId,width:b.width,height:b.height,x:0,y:0})}return c.children.push(y),se({animationInstances:h,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...h),e},Es=(e,{presentationState:t,previousPresentationState:n,resources:r={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:l,canRollback:c,skipOnlyViewedLines:a,isLineCompleted:u,skipTransitionsAndAnimations:f,variables:d,runtime:h,activePersistentAnimations:g,saveSlots:y=[]})=>{let{elements:I,animations:b}=e;if(!t.dialogue||o)return e;let m=I.find(S=>S.id==="story");if(!m)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:S={}}=r,$=S[t.dialogue.ui.resourceId];if($){let O={elements:$.elements},_=re({variables:d,runtime:h,saveSlots:y,dialogueState:t.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:u,autoMode:i,skipMode:s,isChoiceVisible:l,canRollback:c,characters:r.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:a,skipTransitionsAndAnimations:f}),D={functions:be},N=ct(O,_,D),k=Z(N,_,D),P=Ie(Ae(k?.elements,{isLineCompleted:u,skipMode:s,skipTransitionsAndAnimations:f}),r);if(Array.isArray(P))for(let x of P)m.children.push(x);else P&&m.children.push(P)}}xs(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:u,skipTransitionsAndAnimations:f,activePersistentAnimations:g});let E=we({animationsDef:t.dialogue.ui?.animations,resources:r,previousResourceId:n?.dialogue?.ui?.resourceId,currentResourceId:t.dialogue.ui?.resourceId,previousTargetId:n?.dialogue?.ui?.resourceId?"dialogue-container":void 0,currentTargetId:t.dialogue.ui?.resourceId?"dialogue-container":void 0,animationPath:"dialogue.ui.animations",idPrefix:"dialogue-ui"});return se({animationInstances:E,isLineCompleted:u,skipTransitionsAndAnimations:f,activePersistentAnimations:g})&&b.push(...E),e},vs=(e,{presentationState:t,previousPresentationState:n,resources:r,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,runtime:c,autoMode:a,skipMode:u,isChoiceVisible:f,canRollback:d,activePersistentAnimations:h,saveSlots:g=[]})=>{let{elements:y,animations:I}=e;if(t.choice&&r){let b=Be(y);if(!b)return e;let m=r?.layouts[t.choice.resourceId];if(m&&m.elements){let S={elements:m.elements},$=Z(S,{...re({variables:l,runtime:c,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:i,autoMode:a,skipMode:u,isChoiceVisible:f??!!t.choice,canRollback:d,characters:r.characters||{},skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}},{functions:be}),O=sn(Ie(Ae($?.elements,{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),r));if(Array.isArray(O))for(let _ of O)b.children.push(_);else O&&b.children.push(O)}let E=we({animationsDef:t.choice.animations,resources:r,previousResourceId:n?.choice?.resourceId,currentResourceId:t.choice.resourceId,previousTargetId:n?.choice?.resourceId?"choice-container":void 0,currentTargetId:t.choice.resourceId?"choice-container":void 0,animationPath:"choice.animations",idPrefix:"choice"});se({animationInstances:E,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:h})&&I.push(...E)}return e},Ss=(e,{presentationState:t,resources:n={},variables:r,runtime:o,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:c,canRollback:a,saveSlots:u=[],skipTransitionsAndAnimations:f})=>{if(!t.control?.resourceId)return e;let d=n.controls?.[t.control.resourceId];if(!d)return e;let h=ys(d.keyboard,d.keyup);if(h&&Object.keys(h).length>0&&(e.global.keyboard=h),!Array.isArray(d.elements)||d.elements.length===0)return e;let g=Be(e.elements);if(!g)return e;let y={id:`control-${t.control.resourceId}`,type:"container",x:0,y:0,children:d.elements};return g.children.push($r({container:y,resources:n,templateData:re({variables:r,runtime:o,saveSlots:u,dialogueState:t.dialogue,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:c,canRollback:a,characters:n.characters||{},skipTransitionsAndAnimations:f}),isLineCompleted:i,skipMode:l,skipTransitionsAndAnimations:f})),e},Cs=(e,{presentationState:t,resources:n,runtime:r,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&n){if(!Be(i))return e;let c=n.sounds[t.bgm.resourceId];if(!c)return e;let a=re({variables:o,runtime:r}).runtime;s.push({id:"bgm",type:"sound",src:c.fileId,loop:t.bgm.loop??!0,volume:ds(a),delay:t.bgm.delay??null})}return e},_s=(e,{presentationState:t,resources:n})=>{let{audio:r}=e;if(t.sfx&&n){let o=t.sfx.items;for(let i of o){let s=n.sounds?.[i.resourceId];s&&r.push({id:i.id,type:"sound",src:s.fileId,loop:i.loop??s.loop??!1,volume:i.volume??s.volume??50,delay:i.delay??s.delay??null})}}return e},Rs=(e,t,n)=>{if(!(!t||!n))return e?.voices?.[t]?.[n]},Ls=(e={},t={})=>t.muteAll?0:e.volume??t.soundVolume??50,$s=(e,{presentationState:t,resources:n,currentSceneId:r,runtime:o,variables:i})=>{let{audio:s}=e;if(!t?.voice)return e;let l=t.voice,{resourceId:c,loop:a,delay:u}=l,f=Rs(n,r,c);if(!f)return e;let d=re({variables:i,runtime:o}).runtime;return s.push({id:`voice-${r}-${c}`,type:"sound",src:f.fileId,volume:Ls(l,d),loop:a??!1,delay:u??null}),e},Os=(e,{presentationState:t,previousPresentationState:n,resources:r={},variables:o,runtime:i,autoMode:s,skipMode:l,isChoiceVisible:c,canRollback:a,saveSlots:u=[],isLineCompleted:f,skipTransitionsAndAnimations:d,activePersistentAnimations:h})=>{let{elements:g,animations:y}=e;if(t.layout){let E=Be(g);if(!E)return e;let S=r.layouts[t.layout.resourceId];if(!S)return e;Array.isArray(S.transitions)&&!f&&!d&&ln({animations:y,transitions:S.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let $={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:S.elements||[]};E.children.push($r({container:$,resources:r,templateData:re({variables:o,runtime:i,saveSlots:u,dialogueState:t.dialogue,isLineCompleted:f,autoMode:s,skipMode:l,isChoiceVisible:c,canRollback:a,characters:r.characters||{},skipTransitionsAndAnimations:d}),isLineCompleted:f,skipMode:l,skipTransitionsAndAnimations:d}))}let I=n?.layout?.resourceId,b=t.layout?.resourceId,m=we({animationsDef:t.layout?.animations,resources:r,previousResourceId:I,currentResourceId:b,previousTargetId:I?`layout-${I}`:void 0,currentTargetId:b?`layout-${b}`:void 0,animationPath:"layout.animations",idPrefix:"layout"});return se({animationInstances:m,isLineCompleted:f,skipTransitionsAndAnimations:d,activePersistentAnimations:h})&&y.push(...m),e},ks=(e,{presentationState:t,resources:n={},variables:r,runtime:o,autoMode:i,skipMode:s,isChoiceVisible:l,canRollback:c,overlayStack:a=[],dialogueHistory:u=[],saveSlots:f=[],screen:d,isLineCompleted:h,skipTransitionsAndAnimations:g})=>{let{elements:y,animations:I}=e;return a&&a.length>0&&a.forEach((b,m)=>{let E=n.layouts[b.resourceId];if(!E){console.warn(`Overlay layout not found: ${b.resourceId}`);return}Array.isArray(E.transitions)&&(g||ln({animations:I,transitions:E.transitions,defaultTargetId:`overlayStack-${m}`,idPrefix:`overlayStack-${m}`,animationPathPrefix:`overlayStack[${m}]`}));let S={id:`overlayStack-${m}`,type:"container",x:0,y:0,children:[Rr({id:`overlayStack-${m}-blocker`,screen:d}),...E.elements||[]]},$=Lr(u,n.characters),O=re({variables:r,runtime:o,saveSlots:f,dialogueState:t?.dialogue,isLineCompleted:h,autoMode:i,skipMode:s,isChoiceVisible:l,canRollback:c,historyDialogue:$,characters:n.characters||{},skipTransitionsAndAnimations:g}),_=Z(S,O,{functions:be}),[D,...N]=_.children||[],k=Ie(Ae({..._,children:N},{isLineCompleted:h,skipMode:s,skipTransitionsAndAnimations:g}),n);y.push({...k,children:D?[D,...k.children||[]]:k.children})}),e},Ps=(e,{presentationState:t,resources:n={},variables:r,runtime:o,saveSlots:i=[],autoMode:s,skipMode:l,isChoiceVisible:c,canRollback:a,confirmDialog:u,dialogueHistory:f=[],screen:d,isLineCompleted:h,skipTransitionsAndAnimations:g})=>{let{elements:y,animations:I}=e;if(!u?.resourceId)return e;let b=n.layouts?.[u.resourceId];if(!b)return console.warn(`ConfirmDialog layout not found: ${u.resourceId}`),e;Array.isArray(b.transitions)&&!g&&ln({animations:I,transitions:b.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let m={id:"confirmDialog",type:"container",x:0,y:0,children:[Rr({id:"confirmDialog-blocker",screen:d}),...b.elements||[]]},E=Lr(f,n.characters),S=Z(m,re({variables:r,runtime:o,saveSlots:i,dialogueState:t?.dialogue,isLineCompleted:h,autoMode:s,skipMode:l,isChoiceVisible:c,canRollback:a,confirmDialog:u,historyDialogue:E,characters:n.characters||{},skipTransitionsAndAnimations:g}),{functions:be}),[$,...O]=S.children||[],_=Ie(Ae({...S,children:O},{isLineCompleted:h,skipMode:l,skipTransitionsAndAnimations:g}),n);return y.push({..._,children:$?[$,..._.children||[]]:_.children}),e},Or=e=>ot(bs,[Ss,Is,As,ws,Es,vs,Os,Cs,_s,$s,ks,Ps])(e);var Ts=Object.freeze({dialogueTextSpeed:{source:"global.dialogueTextSpeed"},autoForwardDelay:{source:"global.autoForwardDelay"},skipUnseenText:{source:"global.skipUnseenText"},skipTransitionsAndAnimations:{source:"global.skipTransitionsAndAnimations"},soundVolume:{source:"global.soundVolume"},musicVolume:{source:"global.musicVolume"},muteAll:{source:"global.muteAll"},saveLoadPagination:{source:"context.runtime.saveLoadPagination"},menuPage:{source:"context.runtime.menuPage"},menuEntryPoint:{source:"context.runtime.menuEntryPoint"},autoMode:{source:"global.autoMode"},skipMode:{source:"global.skipMode"},dialogueUIHidden:{source:"global.dialogueUIHidden"},isLineCompleted:{source:"global.isLineCompleted"}}),ft=Object.freeze({dialogueTextSpeed:50,autoForwardDelay:1e3,skipUnseenText:!1,skipTransitionsAndAnimations:!1,soundVolume:50,musicVolume:50,muteAll:!1,autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isLineCompleted:!1}),Fe=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),kr=Object.freeze({dialogueTextSpeed:"number",autoForwardDelay:"number",skipUnseenText:"boolean",skipTransitionsAndAnimations:"boolean",soundVolume:"number",musicVolume:"number",muteAll:"boolean",saveLoadPagination:"number",menuPage:"string",menuEntryPoint:"string",autoMode:"boolean",skipMode:"boolean",dialogueUIHidden:"boolean",isLineCompleted:"boolean"}),fn=Object.freeze(["dialogueTextSpeed","autoForwardDelay","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),dn=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),Ns=(e,t)=>{if(t.startsWith("global.")){let n=t.slice(7);return e?.global?.[n]}if(t.startsWith("context.runtime.")){let n=t.slice(16),r=Array.isArray(e?.contexts)?e.contexts:[];return r[r.length-1]?.runtime?.[n]}},dt=e=>Object.fromEntries(Object.entries(Ts).map(([t,n])=>{let r=Ns(e,n.source),o=r!==void 0?r:ft[t]??Fe[t];return[t,o]})),ae=(e,t)=>dt(e)[t],Pr=(e={})=>Object.fromEntries(fn.map(t=>[t,e[t]??ft[t]]));var pt={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},jr=1,gt=()=>({manual:{...pt.manual},auto:{...pt.auto},applyMode:pt.applyMode}),pn=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let n=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...gt()},n&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},F=e=>{let t=ue(e)?kt(e):e;return structuredClone(t)},j=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),mt=e=>String(e),Mr=()=>({sections:[],resources:[]}),Ds=e=>j(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):Mr(),Vs=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",js=({sectionId:e,lineId:t,content:n,dialogueState:r,characterName:o})=>({sectionId:e,lineId:t,content:n,text:Vs(n),characterId:r.characterId,character:{...r.character||{},name:o},characterName:o}),Ms=()=>({resourceId:void 0}),Us=e=>{if(!j(e))return e;let t={...e};return Object.prototype.hasOwnProperty.call(t,"requireComplete")&&!Object.prototype.hasOwnProperty.call(t,"requireLineCompleted")&&(t.requireLineCompleted=t.requireComplete),delete t.requireComplete,t},hn=(e,t)=>{let n=e?.story?.scenes??{};for(let[r,o]of Object.entries(n))if(o?.sections?.[t])return{sceneId:r,section:o.sections[t]};return{sceneId:void 0,section:void 0}},Ur=e=>{let t=e?.story?.scenes??{},n=new Map;for(let[r,o]of Object.entries(t)){let i=o?.sections??{};for(let s of Object.keys(i)){let l=n.get(s);if(l!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${l}" and "${r}". Section IDs must be globally unique.`);n.set(s,r)}}},Br=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},Fr=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==jr)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},Bs=(e,t={})=>{let n;try{n=Fr(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let r={...t,formatVersion:n,slotId:Br(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete r.slotKey,delete r.date,r},Fs=(e={})=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Bs(t,n)])),zr=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:n})=>bc(n));return t.length>0?t:void 0},zs=e=>{!j(e)||!Array.isArray(e.timeline)||e.timeline.forEach(t=>{if(!j(t))return;let n=zr(t.executedActions);if(n){t.executedActions=n;return}delete t.executedActions})},Tr=(e,t,n,r="viewedRegistry")=>{let o=t==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[o]:String(e)};if(!j(e))throw new Error(`Malformed ${r}.${t}[${n}] entry.`);if(typeof e[o]!="string"||e[o].length===0)throw new Error(`Malformed ${r}.${t}[${n}] entry: missing ${o}.`);if(t==="sections"){let i={sectionId:e.sectionId};if(e.lastLineId!==void 0&&e.lastLineId!==null&&typeof e.lastLineId!="string")throw new Error(`Malformed ${r}.sections[${n}] entry: invalid lastLineId.`);return typeof e.lastLineId=="string"&&e.lastLineId.length>0&&(i.lastLineId=e.lastLineId),i}return{resourceId:e.resourceId}},Ws=(e,t="viewedRegistry")=>{if(e===void 0)return Mr();if(!j(e))throw new Error(`Malformed ${t}.`);if(e.sections!==void 0&&!Array.isArray(e.sections))throw new Error(`Malformed ${t}.sections.`);if(e.resources!==void 0&&!Array.isArray(e.resources))throw new Error(`Malformed ${t}.resources.`);let n=e.sections??[],r=e.resources??[];return{sections:Object.values(Object.fromEntries(n.map((o,i)=>{let s=Tr(o,"sections",i,t);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(r.map((o,i)=>{let s=Tr(o,"resources",i,t);return[s.resourceId,s]})))}},Wr=(e,t,n)=>{if(!j(e))throw new Error(`Malformed save slot ${n}.`);let{sectionId:r,lineId:o}=e;if(typeof r!="string"||r.length===0)throw new Error(`Malformed save slot ${n}: missing sectionId.`);if(typeof o!="string"||o.length===0)throw new Error(`Malformed save slot ${n}: missing lineId.`);let{sceneId:i,section:s}=hn(t,r);if(!s)throw new Error(`Malformed save slot ${n}: section "${r}" does not exist in projectData.`);if(!s.lines?.some(c=>c.id===o))throw new Error(`Malformed save slot ${n}: line "${o}" does not exist in section "${r}".`);return{sceneId:i,sectionId:r,lineId:o}},Ys=(e,t,n)=>{if(!j(e)||!Array.isArray(e.timeline))return ze({pointer:t,replayStartIndex:1});let r=e.timeline.flatMap((l,c)=>{if(!j(l))return[];try{let a=Wr(l,n,`rollback.timeline[${c}]`),u=ht({sectionId:a.sectionId,lineId:a.lineId,rollbackPolicy:l.rollbackPolicy}),f=zr(F(l.executedActions));return f&&(u.executedActions=f),[u]}catch{return[]}});if(r.length===0)return ze({pointer:t,replayStartIndex:1});let o=typeof e.currentIndex=="number"?Math.trunc(e.currentIndex):r.length-1;(o<0||o>=r.length)&&(o=r.length-1);let i=r[o];if(i?.sectionId!==t.sectionId||i?.lineId!==t.lineId){let l=r.findLastIndex(c=>c.sectionId===t.sectionId&&c.lineId===t.lineId);l>=0?o=l:(r.push(ht({sectionId:t.sectionId,lineId:t.lineId})),o=r.length-1)}let s=typeof e.replayStartIndex=="number"?Math.min(Math.max(Math.trunc(e.replayStartIndex),0),o):0;return{currentIndex:o,isRestoring:!1,replayStartIndex:s,timeline:r}},qs=(e,t,n)=>{if(!j(e))throw new Error(`Malformed save slot contexts[${n}] entry.`);let r=mn(t),o=Wr(e.pointers?.read,t,`contexts[${n}].pointers.read`);if(e.variables!==void 0&&!j(e.variables))throw new Error(`Malformed save slot contexts[${n}].variables entry.`);if(e.runtime!==void 0&&!j(e.runtime))throw new Error(`Malformed save slot contexts[${n}].runtime entry.`);let i=e.variables?F(e.variables):{},s=Xs({loadedContextRuntime:j(e.runtime)?F(e.runtime):{}}),l={currentPointerMode:"read",pointers:{read:o},configuration:j(e.configuration)?F(e.configuration):{},views:Array.isArray(e.views)?F(e.views):[],bgm:j(e.bgm)?F(e.bgm):{resourceId:void 0},variables:{...r,...i},rollback:Ys(e.rollback,o,t)};return s&&(l.runtime=s),l},Hs=(e,t)=>{if(!j(e))throw new Error("Malformed save slot state.");if(!Array.isArray(e.contexts)||e.contexts.length===0)throw new Error("Malformed save slot state: contexts must be a non-empty array.");return{contexts:e.contexts.map((n,r)=>qs(n,t,r))}},Js=(e,t)=>{if(!j(e))throw new Error("Malformed save slot.");let n=Fr(e.formatVersion);return{...e,formatVersion:n,state:Hs(e.state,t)}},Nr=(e,t,{required:n=!1}={})=>{if(e===void 0){if(n)throw new Error(`showConfirmDialog requires ${t}`);return{hideConfirmDialog:{}}}if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`showConfirmDialog ${t} must be an action object`);let r=F(e);return Object.prototype.hasOwnProperty.call(r,"hideConfirmDialog")||(r.hideConfirmDialog={}),r},Ks=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:Nr(e.confirmActions,"confirmActions",{required:!0}),cancelActions:Nr(e.cancelActions,"cancelActions")}},ke=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},xe=[],Dr="line",gn="interaction",ht=({sectionId:e,lineId:t,rollbackPolicy:n})=>({sectionId:e,lineId:t,rollbackPolicy:n??"free"}),mn=e=>{let{contextVariableDefaultValues:t}=Ft(e??{});return F(t)},Yr=()=>({...F(Fe)}),qr=({loadedRuntime:e,runtimeIds:t,defaults:n={},path:r})=>{if(e===void 0)return{runtimeState:F(n),hasLoadedValues:!1};if(!j(e))throw new Error(`Malformed ${r}.`);let o=F(n),i=!1;return t.forEach(s=>{e[s]!==void 0&&(o[s]=Hr(s,F(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},Gs=({loadedGlobalRuntime:e={}})=>qr({loadedRuntime:e,runtimeIds:fn,defaults:ft,path:"global.runtime"}).runtimeState,Xs=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:n}=qr({loadedRuntime:e,runtimeIds:dn,defaults:Yr(),path:"context.runtime"});return n?t:void 0},yn=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},Qs=e=>e.runtime?(dn.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=F(Fe[t]))}),e.runtime):(e.runtime=Yr(),e.runtime),Zs=e=>Pr(e.global),ea=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:Zs(e)}})},ta=e=>kr[e],na=(e,t)=>{let n=ta(e);if(n==="number"){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} requires a finite numeric value`);return}if(n==="boolean"){if(typeof t!="boolean")throw new Error(`${e} requires a boolean value`);return}if(n==="string"){if(typeof t!="string")throw new Error(`${e} requires a string value`);return}throw new Error(`Unsupported runtime field "${e}"`)},Hr=(e,t)=>(na(e,t),e==="saveLoadPagination"?Math.max(1,Math.trunc(t)):t),Jr=(e,t,n)=>{let r=Hr(t,n);if(t in Fe){let o=yn(e);if(!o)return r;let i=Qs(o);return i[t]=r,r}return e.global[t]=r,r},Kr=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:F(e)},configuration:{},views:[],bgm:Ms(),variables:mn(t),rollback:ze({pointer:e})}),Pe=e=>e?(e.currentPointerMode="read",j(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,ra=e=>{let t=e.contexts?.[e.contexts.length-1],n=t?.pointers?.read;if(!t||!n?.sectionId||!n?.lineId)return null;let r=Kr({pointer:n,projectData:e.projectData});return e.contexts[e.contexts.length-1]=r,oa(e),r},oa=e=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,ke(e),e.global.nextLineConfig=gt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})},Gr=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},ze=({pointer:e,replayStartIndex:t=0})=>{let n=e?.sectionId&&e?.lineId;return{currentIndex:n?0:-1,isRestoring:!1,replayStartIndex:t,timeline:n?[ht({sectionId:e.sectionId,lineId:e.lineId})]:[]}},ve=(e,t={})=>{if(e?.rollback)return Gr(e.rollback),Array.isArray(e.rollback.timeline)||(e.rollback.timeline=[]),typeof e.rollback.currentIndex!="number"&&(e.rollback.currentIndex=e.rollback.timeline.length>0?e.rollback.timeline.length-1:-1),typeof e.rollback.isRestoring!="boolean"&&(e.rollback.isRestoring=!1),typeof e.rollback.replayStartIndex!="number"&&(e.rollback.replayStartIndex=0),e.rollback;let n=e?.pointers?.read;return e.rollback=ze({pointer:n,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},bn=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return;let r=ve(n);if(r.isRestoring)return;r.currentIndex<r.timeline.length-1&&(r.timeline=r.timeline.slice(0,r.currentIndex+1));let o=r.timeline[r.timeline.length-1];if(o?.sectionId===t.sectionId&&o?.lineId===t.lineId&&(o?.rollbackPolicy??"free")===(t.rollbackPolicy??"free")){r.currentIndex=r.timeline.length-1;return}r.timeline.push(ht(t)),r.currentIndex=r.timeline.length-1},ia=e=>{let n=e.contexts?.[e.contexts.length-1]?.rollback;if(!n||n.isRestoring||!Array.isArray(n.timeline)||typeof n.currentIndex!="number")return null;let r=xe[xe.length-1],o=typeof r?.checkpointIndex=="number"?r.checkpointIndex:n.currentIndex;return o<0||o>=n.timeline.length?null:(typeof r?.checkpointIndex!="number"&&o<n.timeline.length-1&&(n.timeline=n.timeline.slice(0,o+1)),n.timeline[o]??null)},sa=({state:e},t={})=>{let n=t?.source===Dr?Dr:gn,o=e.contexts?.[e.contexts.length-1]?.rollback;return!o||o.isRestoring||!Array.isArray(o.timeline)||typeof o.currentIndex!="number"||o.currentIndex<0||o.currentIndex>=o.timeline.length?(xe.push({checkpointIndex:null,source:n}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),xe.push({checkpointIndex:o.currentIndex,source:n}),e)},aa=({state:e})=>(xe.pop(),e),ce=(e,t,n)=>{let o=xe[xe.length-1]?.source??gn;if(!Ic(t,o))return;let i=ia(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:F(n)}))},Vr=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return;let r=t?.operations??[];for(let{variableId:o,op:i,value:s}of r){let l=e.projectData.resources?.variables?.[o],c=l?.scope,a=l?.type;zt(c,o),Wt(a,i,o),c==="context"&&(n.variables[o]=Yt(n.variables[o],i,s))}},ca=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:n,payload:r})=>{Ac(e,n,r)})},la=(e,t)=>{let{sectionId:n,lineId:r}=t,s=G({state:e},{sectionId:n})?.lines?.find(l=>l.id===r)?.actions;s&&Object.entries(s).forEach(([l,c])=>{go(e,l,c)})},Xr=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return e;let r=ve(n),o=r.timeline[t];if(!o)return e;e.global.autoMode&&Ye({state:e}),e.global.skipMode&&Ee({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),r.isRestoring=!0,r.currentIndex=t;try{n.variables=mn(e.projectData),delete n.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=F(pt),e.global.overlayStack=[],ke(e),e.global.isLineCompleted=!0;let i=r.replayStartIndex??0;for(let l=i;l<=t;l++)l>i&&pn(e),la(e,r.timeline[l]),ca(e,r.timeline[l]);let s=Pe(n);s.read={sectionId:o.sectionId,lineId:o.lineId},e.global.pendingEffects=e.global.pendingEffects.filter(l=>l?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{r.isRestoring=!1}return e},ua=e=>{let{projectData:t}=e,n=e.global??{},{saveSlots:r={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=n;Ur(t);let l=t.story.initialSceneId,c=t.story.scenes[l],a=c.initialSectionId,u=c.sections[a],f={sceneId:l,sectionId:a,lineId:u.initialLineId??u.lines[0].id},{globalVariablesDefaultValues:d}=Ft(t),h={...d,...o};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,accountViewedRegistry:Ws(s,"accountViewedRegistry"),nextLineConfig:gt(),saveSlots:Fs(r),overlayStack:[],variables:h,...Gs({loadedGlobalRuntime:i})},contexts:[Kr({pointer:f,projectData:t})]}},fa=({state:e})=>e.global.overlayStack||[],da=({state:e})=>e.global.pendingEffects,Qr=({state:e})=>e.global.skipMode,pa=({state:e})=>e.global.autoMode,Zr=({state:e})=>e.global.dialogueUIHidden,eo=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],n=t[t.length-1];if(!n)return[];let{sectionId:r,lineId:o}=n.pointers.read,i=G({state:e},{sectionId:r});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(u=>u.id===o),l=i.lines.slice(0,s+1),c=[],a={};for(let u of l){let f=u.actions||{};if(a=Le([a,f]),!f.dialogue)continue;let d=a.dialogue||{},h="";d.character?.name!==void 0?h=d.character.name:d.characterId&&(h=e.projectData.resources?.characters?.[d.characterId]?.name||"");let g=js({sectionId:r,lineId:u.id,content:f.dialogue.append===!0?d.content:f.dialogue.content,dialogueState:d,characterName:h});if(f.dialogue.append===!0&&c.length>0){c[c.length-1]={...c[c.length-1],content:g.content,text:g.text,characterId:g.characterId,character:g.character,characterName:g.characterName};continue}c.push(g)}return c},ha=({state:e})=>e.global.confirmDialog??null,ga=({state:e,registry:t},n)=>{let{sectionId:r,lineId:o}=n,s=(Array.isArray(t?.sections)?t.sections:[]).find(u=>u.sectionId===r);if(!s)return!1;if(s.lastLineId===void 0||o===void 0)return!0;let l=G({state:e},{sectionId:r});if(!l||!l.lines||!Array.isArray(l.lines))return s.lastLineId===o;let c=l.lines.findIndex(u=>u.id===s.lastLineId),a=l.lines.findIndex(u=>u.id===o);return c===-1||a===-1?s.lastLineId===o:a<=c},ma=({registry:e},t)=>{let{resourceId:n}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===n)},In=({state:e},t)=>ga({state:e,registry:e.global.accountViewedRegistry},t),ya=({state:e},t)=>ma({registry:e.global.accountViewedRegistry},t),ba=({state:e})=>e.global.nextLineConfig,to=({state:e,pointer:t}={})=>{let n=t??oe({state:e})?.pointer;if(!n)return;let r=n?.sectionId,o=n?.lineId,s=G({state:e},{sectionId:r})?.lines||[],l=s.findIndex(a=>a.id===o);if(l<0)return;let c;for(let a of s.slice(0,l+1)){let u=a?.actions;if(u?.cleanAll&&(c=void 0),!u||!Object.prototype.hasOwnProperty.call(u,"choice")){c=void 0;continue}let f=u.choice;if(f?.resourceId){c=f.resourceId;continue}f?.animations||(c=void 0)}return c},ie=({state:e})=>!!to({state:e}),Ia=({state:e})=>structuredClone(e),no=({state:e})=>e.global.saveSlots,Aa=({state:e},t)=>{let n=t?.slotId,r=mt(n);return e.global.saveSlots[r]},An=({state:e})=>dt(e),wa=({state:e},t)=>ae(e,t?.runtimeId),ro=({state:e})=>({...e.global?.variables??{},...yn(e)?.variables??{}}),oe=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],n=t[t.length-1];if(n)return{currentPointerMode:"read",pointer:n.pointers?.read}},G=({state:e},t)=>{let{sectionId:n}=t;return hn(e.projectData,n).section},wn=({state:e})=>{let t=oe({state:e});if(!t?.pointer)return;let{sectionId:n,lineId:r}=t.pointer,o=G({state:e},{sectionId:n});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===r)},oo=({state:e})=>{let{sectionId:t,lineId:n}=oe({state:e}).pointer,o=G({state:e},{sectionId:t})?.lines||[],i=o.findIndex(a=>a.id===n),l=o.slice(0,i+1).map(a=>{let u=a.actions||{},f={};return Object.keys(u).forEach(d=>{f[d]=u[d]}),f});return Le(l)},xa=({state:e})=>{let t=io({state:e}),r=wn({state:e})?.actions??{},o=Le([t??{},r]);return qt(t??{},o??{})},Ea=({state:e},{sectionId:t})=>{let n=G({state:e},{sectionId:t});if(!n?.lines)return[];let r=[],o={};for(let i of n.lines){let s=i.actions||{},l=Le([o,s]),c=qt(o,l);r.push({id:i.id,changes:c,presentationState:l}),o=Ht(l)}return r},va=({state:e},{sectionId:t,includePresentationState:n=!1})=>{let r=Ea({state:e},{sectionId:t});return n?{lines:r}:{lines:r.map(({presentationState:o,...i})=>i)}},io=({state:e})=>{let{sectionId:t,lineId:n}=oe({state:e}).pointer,o=G({state:e},{sectionId:t})?.lines||[],i=o.findIndex(c=>c.id===n);if(i<=0)return null;let l=o.slice(0,i).map(c=>{let a=c.actions||{},u={};return Object.keys(a).forEach(f=>{u[f]=a[f]}),u});return Ht(Le(l))},xn=({state:e},{slotsPerPage:t=6}={})=>{let o=((An({state:e}).saveLoadPagination??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let l=o+s,c=e.global.saveSlots&&e.global.saveSlots[mt(l)]||{};i.push({...c,slotId:l})}return{saveSlots:i}},Sa=no,Ca=xn,_a=e=>{let n=e.contexts?.[e.contexts.length-1]?.rollback;return!n||!Array.isArray(n.timeline)||typeof n.currentIndex!="number"?!1:n.currentIndex>=0&&n.currentIndex<n.timeline.length-1},Ra=({state:e},t={})=>{let n=oo({state:e}),r=io({state:e}),o=wn({state:e})?.actions??{},{sectionId:i}=oe({state:e}).pointer,{sceneId:s}=hn(e.projectData,i),l=An({state:e}),c=t?.activePersistentAnimations??[],a=t?.restoredPersistentAnimations??[],u=ro({state:e}),{saveSlots:f}=xn({state:e}),d=_a(e);return Or({presentationState:n,previousPresentationState:r,currentLineActions:o,resources:e.projectData.resources,currentSceneId:s,screen:e.projectData.screen,dialogueUIHidden:l.dialogueUIHidden,autoMode:l.autoMode,skipMode:l.skipMode,isChoiceVisible:ie({state:e}),canRollback:yo({state:e}),skipOnlyViewedLines:!l.skipUnseenText,isLineCompleted:l.isLineCompleted,skipTransitionsAndAnimations:!!l.skipTransitionsAndAnimations||d,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,dialogueHistory:eo({state:e}),saveSlots:f,variables:u,runtime:l,activePersistentAnimations:c,restoredPersistentAnimations:a})},La=({state:e},t)=>(e.global.confirmDialog=Ks(t),e.global.pendingEffects.push({name:"render"}),e),$a=({state:e})=>(e.global.confirmDialog&&(ke(e),e.global.pendingEffects.push({name:"render"})),e),Oa=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),ce(e,"pushOverlay",t),e),ka=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),ce(e,"popOverlay",void 0),e),Pa=({state:e},t)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=t),e.global.pendingEffects.push({name:"render"}),ce(e,"replaceLastOverlay",t),e),Ta=({state:e})=>(e.global.overlayStack=[],ke(e),e.global.pendingEffects.push({name:"render"}),ce(e,"clearOverlays",void 0),e),Na=e=>{e.global.autoMode&&(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"})),e.global.skipMode&&(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"})),e.global.nextLineConfig?.auto?.enabled&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},yt=(e,t)=>{e.global.isLineCompleted=!1;let n=!!to({state:e,pointer:t});return n&&Na(e),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:n}},so=({state:e})=>(ie({state:e})||(e.global.skipMode&&(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"})),e.global.autoMode=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.isLineCompleted&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:ae(e,"autoForwardDelay")}}),e.global.pendingEffects.push({name:"render"})),e),Ye=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Da=({state:e})=>{let t=e.global.autoMode;return ie({state:e})&&!t||(t?Ye({state:e}):so({state:e})),e},ao=({state:e})=>(ie({state:e})||(e.global.autoMode&&(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"})),e.global.skipMode=!0,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"startSkipNextTimer"}),e.global.pendingEffects.push({name:"render"})),e),Ee=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Va=({state:e})=>{let t=Qr({state:e});return ie({state:e})&&!t||(t?Ee({state:e}):ao({state:e})),e},bt=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),ce(e,"showDialogueUI",void 0),e),co=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),ce(e,"hideDialogueUI",void 0),e),ja=({state:e})=>(Zr({state:e})?bt({state:e}):co({state:e}),e),Se=(e,t,n)=>(Jr(e,t,n),ea(e),e.global.pendingEffects.push({name:"render"}),e),qe=(e,t,n,r)=>{let o=Jr(e,t,n);return e.global.pendingEffects.push({name:"render"}),ce(e,r,{value:o}),e},Ma=({state:e},t)=>Se(e,"dialogueTextSpeed",t?.value),Ua=({state:e},t)=>Se(e,"autoForwardDelay",t?.value),Ba=({state:e},t)=>Se(e,"skipUnseenText",t?.value),Fa=({state:e},t)=>Se(e,"skipTransitionsAndAnimations",t?.value),za=({state:e},t)=>Se(e,"soundVolume",t?.value),Wa=({state:e},t)=>Se(e,"musicVolume",t?.value),Ya=({state:e},t)=>Se(e,"muteAll",t?.value),qa=({state:e},t)=>qe(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),Ha=({state:e})=>{let t=ae(e,"saveLoadPagination")+1;return qe(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},Ja=({state:e})=>{let t=ae(e,"saveLoadPagination")-1;return qe(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},Ka=({state:e},t)=>qe(e,"menuPage",t?.value,"setMenuPage"),Ga=({state:e},t)=>qe(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),Xa=({state:e})=>(e.global.pendingEffects=[],e),Qa=({state:e},t)=>(e.global.pendingEffects.push(t),e),lo=(e,{sectionId:t,resetStoryState:n=!1})=>{let r=G({state:e},{sectionId:t});if(!r)return console.warn(`Section not found: ${t}`),e;let o=r.lines?.[0];if(!o)return console.warn(`Section ${t} has no lines`),e;if(n&&!ra(e))return e;e.global.autoMode&&Ye({state:e}),e.global.skipMode&&Ee({state:e});let i=e.contexts?.[e.contexts.length-1];if(i){let s=Pe(i);i.rollback||ve(i,{compatibilityAnchor:!0}),s.read={sectionId:t,lineId:o.id},n?i.rollback=ze({pointer:s.read}):bn(e,{sectionId:t,lineId:o.id})}return yt(e,i?.pointers?.read),e},Za=({state:e},t)=>lo(e,{sectionId:t?.sectionId,resetStoryState:!0}),uo=e=>(e.global.accountViewedRegistry=Ds(e.global.accountViewedRegistry),e.global.accountViewedRegistry),fo=(e,t)=>{!Array.isArray(t)||t.length===0||e.global.pendingEffects.push({name:"applyScopedDataUpdates",payload:{updates:t.map(n=>({scope:n.scope,path:n.path,op:n.op,value:F(n.value)}))}})},po=(e,t)=>{fo(e,[{scope:"account",path:"viewedRegistry",op:"markViewed",value:{sections:(Array.isArray(t?.sections)?t.sections:[]).map(n=>({sectionId:n.sectionId,...n.lastLineId===void 0?{}:{lineId:n.lastLineId}})),resources:Array.isArray(t?.resources)?t.resources:[]}}])},ec=(e,t,{sectionId:n,lineId:r})=>{if(!n||!r)return!1;let o=j(t)?t:{};Array.isArray(o.sections)||(o.sections=[]);let i=o.sections.find(s=>s.sectionId===n);if(i){if(i.lastLineId===void 0)return!1;let s=G({state:e},{sectionId:n});if(s?.lines){let l=s.lines.findIndex(a=>a.id===i.lastLineId),c=s.lines.findIndex(a=>a.id===r);if(l===-1||c>l)return i.lastLineId===r?!1:(i.lastLineId=r,!0)}else return i.lastLineId===r?!1:(i.lastLineId=r,!0);return!1}else return o.sections.push({sectionId:n,lastLineId:r}),!0},We=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;ec(e,uo(e),t)&&po(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},tc=({state:e},t)=>(We(e,t),e.global.pendingEffects.push({name:"render"}),e),nc=({state:e},t)=>{let{resourceId:n}=t;if(e.global.accountViewedRegistry!==void 0){let r=uo(e);r.resources.find(i=>i.resourceId===n)||(r.resources.push({resourceId:n}),po(e,{sections:[],resources:[{resourceId:n}]}))}return e.global.pendingEffects.push({name:"render"}),e},ho=({state:e},t)=>{let n=Us(t.manual),{auto:r,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,l=e.contexts?.[e.contexts.length-1]?.rollback?.isRestoring===!0;n&&r?(e.global.nextLineConfig={manual:n,auto:r},o!==void 0?e.global.nextLineConfig.applyMode=o:s!==void 0&&(e.global.nextLineConfig.applyMode=s)):(n&&(e.global.nextLineConfig.manual=n),r&&(e.global.nextLineConfig.auto=r),o!==void 0&&(e.global.nextLineConfig.applyMode=o));let c=e.global.nextLineConfig.auto?.enabled,a=ie({state:e});return!l&&!a&&c===!0&&!i?e.global.nextLineConfig.auto?.trigger==="fromStart"?e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):e.global.isLineCompleted&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):!l&&c===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),ce(e,"setNextLineConfig",t),e},rc=({state:e},t)=>{let n=t?.slotId;if(n==null||n==="")throw new Error("saveSlot requires slotId");let{thumbnailImage:r}=t,o=t?.savedAt,i=mt(n),s=F(e.contexts);s?.forEach(a=>{Pe(a),Gr(a.rollback),zs(a.rollback)});let l={contexts:s},c={formatVersion:jr,slotId:Br(n),savedAt:typeof o=="number"?o:Date.now(),image:r,state:l};return e.global.saveSlots[i]=c,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},oc=({state:e},t)=>{let n=t?.slotId;if(n==null||n==="")throw new Error("loadSlot requires slotId");let r=mt(n),o=e.global.saveSlots[r];if(o){let i=Js(o,e.projectData);e.contexts=i.state.contexts,e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=gt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,ke(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},ic=({state:e},t)=>{let{projectData:n}=t;return Ur(n),e.projectData=n,ke(e),e.global.pendingEffects.push({name:"render"}),e},sc=({state:e},t)=>{let{sectionId:n,lineId:r}=t;if(!r)return console.warn("jumpToLine requires lineId parameter"),e;let o=e.contexts[e.contexts.length-1];if(!o)return console.warn("No context available for jumpToLine"),e;let i=n||o.pointers.read?.sectionId;if(n&&!G({state:e},{sectionId:n}))return console.warn(`Section not found: ${n}`),e;let s=G({state:e},{sectionId:i});if(!s?.lines||!Array.isArray(s.lines))return console.warn(`Section ${i} has no lines`),e;if(!s.lines.find(a=>a.id===r))return console.warn(`Line not found: ${r} in section ${i}`),e;let c=Pe(o);return c.read={sectionId:i,lineId:r},yt(e,c.read),e},ac=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return bt({state:e}),e;if(ie({state:e})&&t?._interactionSource!=="choice")return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0;let a=oe({state:e})?.pointer,u=a?.sectionId,f=a?.lineId;u&&f&&We(e,{sectionId:u,lineId:f}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:ae(e,"autoForwardDelay")}});let d=e.global.nextLineConfig;return d?.auto?.enabled&&d.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:d.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e}let n=oe({state:e})?.pointer,r=n?.sectionId,o=G({state:e},{sectionId:r}),i=e.contexts[e.contexts.length-1],s=o?.lines||[],c=s.findIndex(a=>a.id===n?.lineId)+1;if(c<s.length){let a=s[c],u=!ae(e,"skipUnseenText");if(e.global.skipMode&&u&&!In({state:e},{sectionId:r,lineId:a.id}))return Ee({state:e}),e;if(i&&!i.rollback&&ve(i,{compatibilityAnchor:!0}),i){let h=Pe(i),g=h.read?.lineId;g&&r&&We(e,{sectionId:r,lineId:g}),h.read={sectionId:r,lineId:a.id}}bn(e,{sectionId:r,lineId:a.id}),pn(e);let{isChoiceVisible:f}=yt(e,{sectionId:r,lineId:a.id}),d=e.global.nextLineConfig;d?.auto?.enabled&&!f&&d.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:d.auto.delay}})}else e.global.autoMode&&Ye({state:e}),e.global.skipMode&&Ee({state:e});return e},cc=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0;let t=ie({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:ae(e,"autoForwardDelay")}});let n=oe({state:e})?.pointer,r=n?.sectionId,o=n?.lineId;r&&o&&We(e,{sectionId:r,lineId:o});let i=e.global.nextLineConfig;return i?.auto?.enabled&&!t&&i.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:i.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e},lc=({state:e},t)=>lo(e,{sectionId:t?.sectionId}),uc=({state:e})=>{if(e.global.dialogueUIHidden)return bt({state:e}),e;if(ie({state:e}))return e;let t=oe({state:e})?.pointer,n=t?.sectionId,r=G({state:e},{sectionId:n}),o=e.contexts[e.contexts.length-1],i=r?.lines||[],l=i.findIndex(c=>c.id===t?.lineId)+1;if(l<i.length){let c=i[l],a=!ae(e,"skipUnseenText");if(e.global.skipMode&&a&&!In({state:e},{sectionId:n,lineId:c.id}))return Ee({state:e}),e;if(o&&!o.rollback&&ve(o,{compatibilityAnchor:!0}),o){let f=Pe(o),d=f.read?.lineId;d&&n&&We(e,{sectionId:n,lineId:d}),f.read={sectionId:n,lineId:c.id}}bn(e,{sectionId:n,lineId:c.id}),pn(e);let{isChoiceVisible:u}=yt(e,{sectionId:n,lineId:c.id});e.global.nextLineConfig.auto?.enabled&&!u&&e.global.nextLineConfig.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}})}else e.global.nextLineConfig.auto?.enabled&&(e.global.nextLineConfig.auto.enabled=!1,e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}));return e},fc=({state:e},t)=>{let{id:n,operations:r=[]}=t;if(!n)throw new Error("updateVariable requires an id field");if(typeof n!="string"||!/^[a-zA-Z0-9]+$/.test(n))throw new Error(`updateVariable id must be alphanumeric, got: "${n}"`);let o=e.contexts[e.contexts.length-1];if(o?.rollback?.isRestoring)return e;let i=!1,s=[],l=[];return r.forEach(({variableId:c,op:a,value:u})=>{let f=e.projectData.resources?.variables?.[c],d=f?.scope,h=f?.type;zt(d,c),Wt(h,a,c);let g=d==="context"?o.variables:e.global.variables;d==="context"&&(i=!0,l.push({variableId:c,op:a,value:u})),g[c]=Yt(g[c],a,u),(d==="device"||d==="account")&&s.push({scope:d,path:`variables.${c}`,op:"set",value:F(g[c])})}),i&&ce(e,"updateVariable",{id:n,operations:l}),fo(e,s),e.global.pendingEffects.push({name:"render"}),e},dc=e=>(t,n)=>e({state:t},n),pc=e=>({variables:{...e.global?.variables??{},...yn(e)?.variables??{}},runtime:dt(e)}),hc=e=>{if(!j(e))throw new Error("conditional action payload must be an object");if(!Array.isArray(e.branches))throw new Error("conditional action requires branches array");if(e.branches.length===0)throw new Error("conditional action requires at least one branch")},gc=(e,t,n)=>{if(!j(e))throw new Error(`conditional branch at index ${t} must be an object`);if(!j(e.actions))throw new Error(`conditional branch at index ${t} requires actions object`);if(!Object.prototype.hasOwnProperty.call(e,"when")&&t!==n-1)throw new Error("conditional else branch must be the last branch")},mc=(e,t)=>{hc(t);for(let n=0;n<t.branches.length;n+=1){let r=t.branches[n];if(gc(r,n,t.branches.length),!(Object.prototype.hasOwnProperty.call(r,"when")&&!je(r.when,pc(e)))){Object.entries(r.actions).forEach(([i,s])=>{go(e,i,s)});return}}},yc={conditional:{replayLine:mc},updateVariable:{recordSources:[gn],replayLine:Vr,replayRecorded:Vr,persistInSaveSlot:!0},setNextLineConfig:{replayLine:dc(ho)}},It=e=>yc[e]??null,bc=e=>It(e)?.persistInSaveSlot===!0,Ic=(e,t)=>{let n=It(e)?.recordSources;return Array.isArray(n)&&n.includes(t)},Ac=(e,t,n)=>{It(t)?.replayRecorded?.(e,n)},go=(e,t,n)=>{It(t)?.replayLine?.(e,n)},mo=({state:e},t)=>{let{offset:n}=t;if(n===void 0||typeof n!="number")return console.warn("selectLineIdByOffset requires a numeric offset"),null;let r=e.contexts[e.contexts.length-1];if(!r)return null;let o=r.rollback;if(!Array.isArray(o?.timeline)||typeof o?.currentIndex!="number")return null;let i=o.currentIndex+n;if(i<0||i>=o.timeline.length)return null;let s=o.timeline[i];return{sectionId:s.sectionId,lineId:s.lineId}},yo=({state:e})=>mo({state:e},{offset:-1})!==null,wc=({state:e},t)=>{let{offset:n=-1}=t;if(n>=0)throw new Error("rollbackByOffset requires a negative offset");let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let o=ve(r,{compatibilityAnchor:!r.rollback}),i=o.currentIndex+n;return i<0||i>=o.timeline.length?e:Xr(e,i)},xc=({state:e},t)=>{let{sectionId:n,lineId:r}=t,o=e.contexts[e.contexts.length-1];if(!o)throw new Error("No context available for rollbackToLine");let i=ve(o,{compatibilityAnchor:!o.rollback}),l=i.timeline.slice(0,i.currentIndex+1).findLastIndex(c=>c.sectionId===n&&c.lineId===r);if(l===-1)throw new Error(`Line ${r} not found in section ${n} rollback timeline`);return l===i.currentIndex?e:Xr(e,l)},bo=e=>{let t=ua(e);return rr(t,{selectPendingEffects:da,selectSkipMode:Qr,selectAutoMode:pa,selectIsChoiceVisible:ie,selectDialogueUIHidden:Zr,selectDialogueHistory:eo,selectConfirmDialog:ha,selectIsLineAccountViewed:In,selectIsResourceAccountViewed:ya,selectNextLineConfig:ba,selectSystemState:Ia,selectSaveSlotMap:no,selectSaveSlots:Sa,selectSaveSlot:Aa,selectRuntime:An,selectRuntimeValue:wa,selectAllVariables:ro,selectCurrentPointer:oe,selectSection:G,selectCurrentLine:wn,selectPresentationState:oo,selectPresentationChanges:xa,selectSectionLineChanges:va,selectSaveSlotPage:xn,selectCurrentPageSlots:Ca,selectRenderState:Ra,selectOverlayStack:fa,selectLineIdByOffset:mo,selectCanRollback:yo,startAutoMode:so,stopAutoMode:Ye,toggleAutoMode:Da,startSkipMode:ao,stopSkipMode:Ee,toggleSkipMode:Va,showDialogueUI:bt,hideDialogueUI:co,toggleDialogueUI:ja,setDialogueTextSpeed:Ma,setAutoForwardDelay:Ua,setSkipUnseenText:Ba,setSkipTransitionsAndAnimations:Fa,setSoundVolume:za,setMusicVolume:Wa,setMuteAll:Ya,setSaveLoadPagination:qa,incrementSaveLoadPagination:Ha,decrementSaveLoadPagination:Ja,setMenuPage:Ka,setMenuEntryPoint:Ga,showConfirmDialog:La,hideConfirmDialog:$a,resetStoryAtSection:Za,clearPendingEffects:Xa,appendPendingEffect:Qa,beginRollbackActionBatch:sa,endRollbackActionBatch:aa,addViewedLine:tc,addViewedResource:nc,setNextLineConfig:ho,saveSlot:rc,loadSlot:oc,updateProjectData:ic,sectionTransition:lc,jumpToLine:sc,nextLine:ac,markLineCompleted:cc,rollbackToLine:xc,rollbackByOffset:wc,pushOverlay:Oa,popOverlay:ka,replaceLastOverlay:Pa,clearOverlays:Ta,updateVariable:fc,nextLineFromSystem:uc},{transformActionFirstArgument:r=>({state:r}),transformSelectorFirstArgument:r=>({state:r})})};var Ec="route-engine",vc="projectPersistence";var Ao=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),H=e=>Object.prototype.toString.call(e)==="[object Object]",Io="variables.",Sc=(e={})=>{let t=H(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(n=>typeof n=="string"||typeof n=="number"?{sectionId:String(n)}:!H(n)||typeof n.sectionId!="string"||n.sectionId.length===0?null:{sectionId:n.sectionId,...typeof n.lineId=="string"?{lineId:n.lineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(n=>typeof n=="string"||typeof n=="number"?{resourceId:String(n)}:!H(n)||typeof n.resourceId!="string"||n.resourceId.length===0?null:{resourceId:n.resourceId}).filter(Boolean)}},Cc=(e={})=>{let t=H(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(n=>typeof n=="string"||typeof n=="number"?{sectionId:String(n)}:!H(n)||typeof n.sectionId!="string"||n.sectionId.length===0?null:{sectionId:n.sectionId,...typeof n.lastLineId=="string"?{lastLineId:n.lastLineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(n=>typeof n=="string"||typeof n=="number"?{resourceId:String(n)}:!H(n)||typeof n.resourceId!="string"||n.resourceId.length===0?null:{resourceId:n.resourceId}).filter(Boolean)}},_c=(e,t)=>{let n=Cc(e),r=Sc(t),o=n.sections.map(s=>({...s})),i=n.resources.map(s=>({...s}));return r.sections.forEach(s=>{let l=o.find(c=>c.sectionId===s.sectionId);if(!l){o.push({sectionId:s.sectionId,...s.lineId===void 0?{}:{lastLineId:s.lineId}});return}if(l.lastLineId!==void 0){if(s.lineId===void 0){delete l.lastLineId;return}l.lastLineId=s.lineId}}),r.resources.forEach(s=>{i.find(c=>c.resourceId===s.resourceId)||i.push({...s})}),{sections:o,resources:i}},wo=(e={})=>{let t=H(e)?e:{};return{saveSlots:H(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:H(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:H(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:H(t.globalRuntime)?t.globalRuntime:{},accountViewedRegistry:H(t.accountViewedRegistry)?t.accountViewedRegistry:{}}},Rc=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((t,n)=>{if(!H(t))throw new Error(`Malformed applyScopedDataUpdates.updates[${n}] entry.`);let r=t.path?.startsWith(Io)?t.path.slice(Io.length):null;if(r!==null){if(!["device","account"].includes(t.scope))throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${n}].`);if(r.length===0)throw new Error(`Malformed applyScopedDataUpdates path "${t.path}" at updates[${n}].`);if(t.op!=="set")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${n}].`);return{scope:t.scope,path:t.path,op:t.op,value:t.value,variableId:r}}if(t.path==="viewedRegistry"){if(t.scope!=="account")throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${n}].`);if(t.op!=="markViewed")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${n}].`);return t}throw typeof t.path!="string"?new Error(`Malformed applyScopedDataUpdates path at updates[${n}].`):new Error(`Unsupported applyScopedDataUpdates path "${t.path}" at updates[${n}].`)})},Lc=(e,t)=>{let n={};return Rc(t).forEach(r=>{if(r.path==="viewedRegistry"){n.accountViewedRegistry=_c(n.accountViewedRegistry??e.accountViewedRegistry,r.value);return}let o=r.scope==="device"?"globalDeviceVariables":"globalAccountVariables";n[o]={...e[o],...n[o],[r.variableId]:r.value}}),n},En=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},$c=e=>{let t=En(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},Oc=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},kc=({indexedDB:e,databaseName:t,objectStoreName:n})=>new Promise((r,o)=>{let i=e.open(t,1);i.onupgradeneeded=()=>{let s=i.result;s.objectStoreNames.contains(n)||s.createObjectStore(n,{keyPath:"namespace"})},i.onsuccess=()=>{r(i.result)},i.onerror=()=>{o(i.error??new Error(`Failed to open IndexedDB database "${t}".`))}}),Pc=async({databasePromise:e,objectStoreName:t,namespace:n})=>{let r=await e;return new Promise((o,i)=>{let c=r.transaction(t,"readonly").objectStore(t).get(n);c.onsuccess=()=>{o(c.result??null)},c.onerror=()=>{i(c.error??new Error(`Failed to read persisted namespace "${n}" from IndexedDB.`))}})},He=async({databasePromise:e,objectStoreName:t,namespace:n,patch:r})=>{let o=await e;return new Promise((i,s)=>{let l=o.transaction(t,"readwrite"),c=l.objectStore(t),a=c.get(n),u=!1,f=h=>{u||(u=!0,s(h))},d=()=>{u||(u=!0,i())};a.onerror=()=>{f(a.error??new Error(`Failed to read persisted namespace "${n}" before updating IndexedDB.`))},a.onsuccess=()=>{let h=wo(a.result),g=typeof r=="function"?r(h):r,y={namespace:n,version:1,...Ao(),...h,...g},I=c.put(y);I.onerror=()=>{f(I.error??new Error(`Failed to persist namespace "${n}" to IndexedDB.`))}},l.oncomplete=()=>{d()},l.onerror=()=>{f(l.error??new Error(`IndexedDB transaction failed while updating namespace "${n}".`))},l.onabort=()=>{f(l.error??new Error(`IndexedDB transaction aborted while updating namespace "${n}".`))}})},Tc=async({databasePromise:e,objectStoreName:t,namespace:n})=>{let r=await e;return new Promise((o,i)=>{let s=r.transaction(t,"readwrite"),c=s.objectStore(t).delete(n),a=!1,u=d=>{a||(a=!0,i(d))},f=()=>{a||(a=!0,o())};c.onerror=()=>{u(c.error??new Error(`Failed to clear persisted namespace "${n}" from IndexedDB.`))},s.oncomplete=()=>{f()},s.onerror=()=>{u(s.error??new Error(`IndexedDB transaction failed while clearing namespace "${n}".`))},s.onabort=()=>{u(s.error??new Error(`IndexedDB transaction aborted while clearing namespace "${n}".`))}})},vn=(e={})=>{let{indexedDB:t,databaseName:n=Ec,objectStoreName:r=vc,namespace:o}=e,i=Oc(t),s=$c(o),l=kc({indexedDB:i,databaseName:n,objectStoreName:r});return{namespace:s,load:async()=>{let c=await Pc({databasePromise:l,objectStoreName:r,namespace:s});return{...Ao(),...wo(c)}},clear:async()=>Tc({databasePromise:l,objectStoreName:r,namespace:s}),saveSlots:async c=>He({databasePromise:l,objectStoreName:r,namespace:s,patch:{saveSlots:H(c)?c:{}}}),saveGlobalDeviceVariables:async c=>He({databasePromise:l,objectStoreName:r,namespace:s,patch:{globalDeviceVariables:H(c)?c:{}}}),saveGlobalAccountVariables:async c=>He({databasePromise:l,objectStoreName:r,namespace:s,patch:{globalAccountVariables:H(c)?c:{}}}),saveGlobalRuntime:async c=>He({databasePromise:l,objectStoreName:r,namespace:s,patch:{globalRuntime:H(c)?c:{}}}),applyScopedDataUpdates:async c=>He({databasePromise:l,objectStoreName:r,namespace:s,patch:a=>Lc(a,c)})}},Nc=vn;var Dc=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),Vc=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),xo="conditional",Eo="choice",At=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function Sn(e){let t,n=0,r=null,o=new Map,i=new Map,s=new Map,{handlePendingEffects:l}=e,c=(A=new Map,v=Date.now())=>new Map(Array.from(A.entries()).filter(([,T])=>v<T.expiresAt).map(([T,V])=>[T,{animation:structuredClone(V.animation),startedAt:V.startedAt,expiresAt:V.expiresAt}])),a=(A=new Map)=>Array.from(A.values()).map(v=>structuredClone(v.animation)),u=(A=Date.now())=>{o=new Map(Array.from(o.entries()).filter(([,v])=>A<v.expiresAt))},f=()=>{for(;t.selectPendingEffects().length>0;){let A=[...t.selectPendingEffects()];t.clearPendingEffects();try{l(A)}catch(v){throw t.clearPendingEffects(),A.forEach(T=>{t.appendPendingEffect(T)}),v}}},d=({initialState:A,namespace:v})=>{t=bo(A),n=0,r=En(v),o=new Map,i=new Map,s=new Map,t.appendPendingEffect({name:"handleLineActions"}),f()},h=()=>r,g=()=>t.selectPresentationState(),y=()=>t.selectPresentationChanges(),I=A=>t.selectSectionLineChanges(A),b=(A={})=>{n+=1;let v=Date.now();u(v);let T=i.size>0,V=c(o,v),q=T?c(i,v):new Map,le={...t.selectRenderState({activePersistentAnimations:a(V),restoredPersistentAnimations:a(q)}),id:`render-${n}`};return s.set(le.id,{builtAt:v,persistentAnimationSessions:new Map([...q.entries(),...V.entries()]),usedRestoredPersistentAnimationSessions:T}),le},m=(A={})=>b(A),E=(A={})=>b(A),S=A=>{let v=typeof A?.id=="string"&&A.id.length>0?A.id:null,T=v?s.get(v):null;v&&s.delete(v);let V=new Map;wr(A?.animations).forEach(q=>{let te=lt(q);if(!te)return;let le=T?.persistentAnimationSessions?.get(te)??o.get(te),_o=Math.max(0,Er(q)),$n=le?.startedAt??T?.builtAt??Date.now();V.set(te,{animation:structuredClone(q),startedAt:$n,expiresAt:$n+_o})}),o=V,T?.usedRestoredPersistentAnimationSessions&&(i=new Map)},$=()=>t.selectSystemState(),O=()=>t.selectSaveSlotMap(),_=A=>t.selectSaveSlot(A),D=A=>t.selectSaveSlotPage(A),N=()=>t.selectSkipMode(),k=()=>t.selectAutoMode(),P=()=>t.selectRuntime(),x=()=>t.selectIsChoiceVisible(),C=(A,v,T={})=>T.interactionSource!==Eo||A!=="nextLine"||!At(v)?v:{...v,_interactionSource:Eo},M=(A,v)=>{t[A]&&(Dc.has(A)&&(Vc.has(A)?i=c(o):i=new Map,o=new Map),t[A](v),f())},z=(A,v,T,V={})=>{if(A===xo){let q=U(T),te=Jt({[A]:v},q);_n(te[A],T,V);return}M(A,v)},Y=(A,v)=>{z(A,v)},U=A=>{if(!A)return{variables:t.selectAllVariables?t.selectAllVariables():void 0,runtime:t.selectRuntime?t.selectRuntime():{}};if(Object.prototype.hasOwnProperty.call(A,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:v,...T}=A,V=t.selectAllVariables?t.selectAllVariables():void 0;return{...T,_event:v,variables:V,runtime:t.selectRuntime?t.selectRuntime():{}}},Je=A=>{if(!At(A))throw new Error("conditional action payload must be an object");if(!Array.isArray(A.branches))throw new Error("conditional action requires branches array");if(A.branches.length===0)throw new Error("conditional action requires at least one branch")},Ke=(A,v,T)=>{if(!At(A))throw new Error(`conditional branch at index ${v} must be an object`);if(!At(A.actions))throw new Error(`conditional branch at index ${v} requires actions object`);if(!Object.prototype.hasOwnProperty.call(A,"when")&&v!==T-1)throw new Error("conditional else branch must be the last branch")},_n=(A,v,T)=>{Je(A);for(let V=0;V<A.branches.length;V+=1){let q=A.branches[V];Ke(q,V,A.branches.length);let te=U(v);if(!(Object.prototype.hasOwnProperty.call(q,"when")&&!je(q.when,te))){Rn(q.actions,v,T);return}}},Co=(A,v,T,V)=>{let q=U(T),le=Jt({[A]:v},q)[A];if(A===xo){_n(le,T,V);return}M(A,C(A,le,V))},Rn=(A,v,T)=>{Object.entries(A).forEach(([V,q])=>{Co(V,q,v,T)})},Ln=(A,v,T={})=>{t.beginRollbackActionBatch({source:T.rollbackSource});try{Rn(A,v,T)}finally{t.endRollbackActionBatch({})}};return{init:d,handleAction:z,handleInternalAction:Y,handleActions:Ln,selectRenderState:m,prepareRenderState:E,commitRenderState:S,selectPresentationState:g,selectPresentationChanges:y,selectSectionLineChanges:I,selectSystemState:$,selectSaveSlotMap:O,selectSaveSlot:_,selectSaveSlotPage:D,selectSaveSlots:O,selectRuntime:P,selectIsChoiceVisible:x,handleLineActions:()=>{let A=t.selectCurrentLine();return A?.actions?(Ln(A.actions,void 0,{rollbackSource:"line"}),!0):!1},getNamespace:h}}var Cn=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:n=>{e=n},addElapsed:n=>{e+=n},getCallback:()=>t,setCallback:n=>{t=n}}},jc=80,So=({engine:e,routeGraphics:t,trackRenderDispatch:n},r)=>{let o=e.prepareRenderState?.(r)??e.selectRenderState(r);n?.(o),t.render(o),e.commitRenderState?.(o)},Mc=({engine:e,routeGraphics:t,trackRenderDispatch:n,getRenderDispatchCount:r},o)=>{let i=r?.()??0,s=e.handleLineActions();(r?.()??0)===i&&So({engine:e,routeGraphics:t,trackRenderDispatch:n},o)},Uc=({engine:e,ticker:t,autoTimer:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let l=r.delay??1e3;n.getElapsed()>=l&&(t.remove(i),n.setCallback(null),n.setElapsed(0),wt(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},Bc=({ticker:e,autoTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Fc=({engine:e,ticker:t,skipTimer:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let l=r?.delay??jc;n.getElapsed()>=l&&(n.setElapsed(0),wt(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},zc=({ticker:e,skipTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Wc=({engine:e,ticker:t,nextLineConfigTimerState:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let l=r.delay??1e3;n.getElapsed()>=l&&(n.setElapsed(0),wt(e,"nextLineFromSystem",{}),t.remove(i),n.setCallback(null))};n.setCallback(i),t.add(i)},Yc=({ticker:e,nextLineConfigTimerState:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},qc=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveSlots(t?.saveSlots))},Hc=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalDeviceVariables(t?.globalDeviceVariables))},Jc=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalAccountVariables(t?.globalAccountVariables))},Kc=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalRuntime(t?.globalRuntime))},Gc=({enqueuePersistenceWrite:e},t)=>{e(n=>{if(typeof n.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return n.applyScopedDataUpdates(t?.updates)})},vo={render:So,saveSlots:qc,saveGlobalDeviceVariables:Hc,saveGlobalAccountVariables:Jc,saveGlobalRuntime:Kc,applyScopedDataUpdates:Gc,handleLineActions:Mc,startAutoNextTimer:Uc,clearAutoNextTimer:Bc,startSkipNextTimer:Fc,clearSkipNextTimer:zc,nextLineConfigTimer:Wc,clearNextLineConfigTimer:Yc},Xc=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),wt=(e,t,n)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,n)},Qc=(e=[])=>{let t=new Set,n=[];for(let r=e.length-1;r>=0;r-=1){let o=e[r];if(typeof o?.name!="string"||o.name.length===0)throw new Error("Pending effect is missing a valid name.");if(!Xc.has(o.name)){n.unshift(o);continue}t.has(o.name)||(t.add(o.name),n.unshift(o))}return n},Zc=({getEngine:e,routeGraphics:t,ticker:n,handleUnhandledEffect:r,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:l})=>{let c=Cn(),a=Cn(),u=Cn(),f=s??null,d=Promise.resolve(),h=null,g=null,y=!1,I=0,b=x=>{if(o){o(x);return}console.error("RouteEngine persistence write failed.",x)},m=()=>{if(f)return f;let x=e();return f=vn({indexedDB:i,namespace:l??x?.getNamespace?.()}),f},E=x=>{d=d.catch(()=>{}).then(()=>{let C=m();return x(C)}).catch(C=>{b(C)})},S=x=>{let C=typeof x?.id=="string"&&x.id.length>0?x.id:null;I+=1,h=C,y=!1},$=()=>I,O=(x={})=>{if(x?.aborted===!0)return!1;let C=typeof x?.id=="string"&&x.id.length>0?x.id:null;return C?C!==h||C===g?!1:(g=C,!0):h!==null||y?!1:(y=!0,!0)},_=(x,C={})=>{if(x!=="renderComplete"||!O(C))return!1;let M=e();return wt(M,"markLineCompleted",{}),!0},D=(x={})=>{if(x?._interactionSource==="choice")return!0;let C=x?.actions;return!C||typeof C!="object"||Array.isArray(C)?!1:Object.values(C).some(M=>M?._interactionSource==="choice")},N=(x,C={})=>!C?.actions||typeof x?.selectIsChoiceVisible!="function"||!x.selectIsChoiceVisible()?!1:!D(C),k=({preprocessPayload:x,onEvent:C}={})=>async(M,z={})=>{let Y=e();if(N(Y,z))return C?.(M,z);let U=await x?.(M,z)??z;if(N(Y,U))return C?.(M,U);if(_(M,U),U?.actions){let Je=U?._event?{_event:U._event}:U?.event?{_event:U.event}:void 0,Ke=U?._interactionSource?{interactionSource:U._interactionSource}:void 0;Ke?Y.handleActions(U.actions,Je,Ke):Y.handleActions(U.actions,Je)}return C?.(M,U)},P=x=>{let C=e(),M=Qc(x);M.forEach(Y=>{if(!vo[Y.name]&&!r)throw new Error(`Unhandled pending effect "${Y.name}".`)});let z={engine:C,routeGraphics:t,ticker:n,autoTimer:c,skipTimer:a,nextLineConfigTimerState:u,trackRenderDispatch:S,getRenderDispatchCount:$,enqueuePersistenceWrite:E};for(let Y of M){let U=vo[Y.name];if(U){U(z,Y.payload);continue}r(Y,z)}};return P.handleRouteGraphicsEvent=_,P.createRouteGraphicsEventHandler=k,P},el=Zc;var tl=(e,t={})=>{let{resources:n={}}=t;return un(e,n)};var yu=Sn;export{el as createEffectsHandler,Nc as createIndexedDbPersistence,yu as default,tl as resolveLayoutReferences};
|
|
1
|
+
var Bo=Object.defineProperty;var Uo=(e,t)=>{for(var n in t)Bo(e,n,{get:t[n],enumerable:!0})};var Yn=Symbol.for("immer-nothing"),Un=Symbol.for("immer-draftable"),X=Symbol.for("immer-state");function te(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var Le=Object.getPrototypeOf;function ie(e){return!!e&&!!e[X]}function be(e){return e?Hn(e)||Array.isArray(e)||!!e[Un]||!!e.constructor?.[Un]||ct(e)||lt(e):!1}var Fo=Object.prototype.constructor.toString();function Hn(e){if(!e||typeof e!="object")return!1;let t=Le(e);if(t===null)return!0;let n=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return n===Object?!0:typeof n=="function"&&Function.toString.call(n)===Fo}function ot(e,t){at(e)===0?Reflect.ownKeys(e).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function at(e){let t=e[X];return t?t.type_:Array.isArray(e)?1:ct(e)?2:lt(e)?3:0}function Pt(e,t){return at(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Jn(e,t,n){let r=at(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function zo(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function ct(e){return e instanceof Map}function lt(e){return e instanceof Set}function ye(e){return e.copy_||e.base_}function Tt(e,t){if(ct(e))return new Map(e);if(lt(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let n=Hn(e);if(t===!0||t==="class_only"&&!n){let r=Object.getOwnPropertyDescriptors(e);delete r[X];let o=Reflect.ownKeys(r);for(let i=0;i<o.length;i++){let s=o[i],a=r[s];a.writable===!1&&(a.writable=!0,a.configurable=!0),(a.get||a.set)&&(r[s]={configurable:!0,writable:!0,enumerable:a.enumerable,value:e[s]})}return Object.create(Le(e),r)}else{let r=Le(e);if(r!==null&&n)return{...e};let o=Object.create(r);return Object.assign(o,e)}}function Mt(e,t=!1){return ut(e)||ie(e)||!be(e)||(at(e)>1&&(e.set=e.add=e.clear=e.delete=Wo),Object.freeze(e),t&&Object.entries(e).forEach(([n,r])=>Mt(r,!0))),e}function Wo(){te(2)}function ut(e){return Object.isFrozen(e)}var qo={};function Ie(e){let t=qo[e];return t||te(0,e),t}var Ue;function Kn(){return Ue}function Yo(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function Fn(e,t){t&&(Ie("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Nt(e){Dt(e),e.drafts_.forEach(Ho),e.drafts_=null}function Dt(e){e===Ue&&(Ue=e.parent_)}function zn(e){return Ue=Yo(Ue,e)}function Ho(e){let t=e[X];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function Wn(e,t){t.unfinalizedDrafts_=t.drafts_.length;let n=t.drafts_[0];return e!==void 0&&e!==n?(n[X].modified_&&(Nt(t),te(4)),be(e)&&(e=it(t,e),t.parent_||st(t,e)),t.patches_&&Ie("Patches").generateReplacementPatches_(n[X].base_,e,t.patches_,t.inversePatches_)):e=it(t,n,[]),Nt(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Yn?e:void 0}function it(e,t,n){if(ut(t))return t;let r=t[X];if(!r)return ot(t,(o,i)=>qn(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return st(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;let o=r.copy_,i=o,s=!1;r.type_===3&&(i=new Set(o),o.clear(),s=!0),ot(i,(a,c)=>qn(e,r,o,a,c,n,s)),st(e,o,!1),n&&e.patches_&&Ie("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function qn(e,t,n,r,o,i,s){if(ie(o)){let a=i&&t&&t.type_!==3&&!Pt(t.assigned_,r)?i.concat(r):void 0,c=it(e,o,a);if(Jn(n,r,c),ie(c))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if(be(o)&&!ut(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;it(e,o),(!t||!t.scope_.parent_)&&typeof r!="symbol"&&Object.prototype.propertyIsEnumerable.call(n,r)&&st(e,o)}}function st(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&Mt(t,n)}function Jo(e,t){let n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:Kn(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=r,i=Bt;n&&(o=[r],i=Fe);let{revoke:s,proxy:a}=Proxy.revocable(o,i);return r.draft_=a,r.revoke_=s,a}var Bt={get(e,t){if(t===X)return e;let n=ye(e);if(!Pt(n,t))return Ko(e,n,t);let r=n[t];return e.finalized_||!be(r)?r:r===Lt(e.base_,t)?(kt(e),e.copy_[t]=jt(r,e)):r},has(e,t){return t in ye(e)},ownKeys(e){return Reflect.ownKeys(ye(e))},set(e,t,n){let r=Gn(ye(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){let o=Lt(ye(e),t),i=o?.[X];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(zo(n,o)&&(n!==void 0||Pt(e.base_,t)))return!0;kt(e),Vt(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return Lt(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,kt(e),Vt(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let n=ye(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){te(11)},getPrototypeOf(e){return Le(e.base_)},setPrototypeOf(){te(12)}},Fe={};ot(Bt,(e,t)=>{Fe[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});Fe.deleteProperty=function(e,t){return Fe.set.call(this,e,t,void 0)};Fe.set=function(e,t,n){return Bt.set.call(this,e[0],t,n,e[0])};function Lt(e,t){let n=e[X];return(n?ye(n):e)[t]}function Ko(e,t,n){let r=Gn(t,n);return r?"value"in r?r.value:r.get?.call(e.draft_):void 0}function Gn(e,t){if(!(t in e))return;let n=Le(e);for(;n;){let r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=Le(n)}}function Vt(e){e.modified_||(e.modified_=!0,e.parent_&&Vt(e.parent_))}function kt(e){e.copy_||(e.copy_=Tt(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Go=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){let i=n;n=t;let s=this;return function(c=i,...l){return s.produce(c,u=>n.call(this,u,...l))}}typeof n!="function"&&te(6),r!==void 0&&typeof r!="function"&&te(7);let o;if(be(t)){let i=zn(this),s=jt(t,void 0),a=!0;try{o=n(s),a=!1}finally{a?Nt(i):Dt(i)}return Fn(i,r),Wn(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===Yn&&(o=void 0),this.autoFreeze_&&Mt(o,!0),r){let i=[],s=[];Ie("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else te(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...a)=>this.produceWithPatches(s,c=>t(c,...a));let r,o;return[this.produce(t,n,(s,a)=>{r=s,o=a}),r,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){be(e)||te(8),ie(e)&&(e=ze(e));let t=zn(this),n=jt(e,void 0);return n[X].isManual_=!0,Dt(t),n}finishDraft(e,t){let n=e&&e[X];(!n||!n.isManual_)&&te(9);let{scope_:r}=n;return Fn(r,t),Wn(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){let o=t[n];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}n>-1&&(t=t.slice(n+1));let r=Ie("Patches").applyPatches_;return ie(e)?r(e,t):this.produce(e,o=>r(o,t))}};function jt(e,t){let n=ct(e)?Ie("MapSet").proxyMap_(e,t):lt(e)?Ie("MapSet").proxySet_(e,t):Jo(e,t);return(t?t.scope_:Kn()).drafts_.push(n),n}function ze(e){return ie(e)||te(10,e),Xn(e)}function Xn(e){if(!be(e)||ut(e))return e;let t=e[X],n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=Tt(e,t.scope_.immer_.useStrictShallowCopy_)}else n=Tt(e,!0);return ot(n,(r,o)=>{Jn(n,r,Xn(o))}),t&&(t.finalized_=!1),n}var Q=new Go,Ut=Q.produce,Sl=Q.produceWithPatches.bind(Q),_l=Q.setAutoFreeze.bind(Q),$l=Q.setUseStrictShallowCopy.bind(Q),Rl=Q.applyPatches.bind(Q),Ol=Q.createDraft.bind(Q),Ll=Q.finishDraft.bind(Q);var m={LITERAL:0,VARIABLE:1,INTERPOLATION:2,FUNCTION:3,BINARY:4,UNARY:5,CONDITIONAL:6,LOOP:7,OBJECT:8,ARRAY:9,PARTIAL:10,PATH_REFERENCE:11},$={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},ke={NOT:0};var A=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},K=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var Ft=e=>{if(!e||e.trim()==="")throw new A("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let n=e.includes("===")?"==":"!=";throw new A(`Invalid comparison operator '${e.includes("===")?"===":"!=="}' - did you mean '${n}'? (got: '${e}')`)}let t=["<",">","<=",">=","==","!="];for(let n of t)if(e.trim().endsWith(n))throw new A(`Incomplete comparison expression - missing right operand (got: '${e}')`)},Qn=e=>{if(e.trim().endsWith(" in"))throw new A(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new A(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,n]=e.split(" in ");if(!n||n.trim()==="")throw new A(`Missing iterable expression after 'in' (got: '$for ${e}')`);let r=t.includes(",")?t.split(",").map(o=>o.trim()):[t.trim()];for(let o of r){if(!o)throw new A(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new A(`Invalid loop syntax (got: '$for ${e}')`)}};var Zn=(e,t,n=!1)=>{if(t===null)return new K(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new K(`Cannot iterate over undefined value at '$for ${e}'`);let r=typeof t;return n?new K(`Cannot iterate over non-array value in loop '${e}' - got ${r} instead`):new K(`Cannot iterate over non-array value (got: ${r}) at '$for ${e}'`)},er=(e,t)=>{let n=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new K(`Unknown function '${e}' (${n})`)};var Xo=(e,t,n={})=>{let r={},o={};n&&typeof n=="object"&&(n.functions!==void 0||n.partials!==void 0?(r=n.functions||{},o=n.partials||{}):typeof n=="object"&&(r=n));let s=R(e,{functions:r,partials:o},t,{});return s===void 0?{}:s},R=(e,t,n,r)=>{let o=t.functions||t;if(e.var&&!e.type)return U(e.var,n,r);if(e.type===m.LITERAL)return e.value;if(e.type===m.VARIABLE)return U(e.path,n,r);if(e.type===m.INTERPOLATION)return Zo(e.parts,t,n,r);switch(e.type){case m.FUNCTION:return nr(e,t,n,r);case m.BINARY:return rr(e,t,n,r);case m.UNARY:return or(e,t,n,r);case m.CONDITIONAL:return ti(e,t,n,r);case m.LOOP:return si(e,t,n,r);case m.OBJECT:return ci(e,t,n,r);case m.ARRAY:return li(e,t,n,r);case m.PARTIAL:return ui(e,t,n,r);case m.PATH_REFERENCE:return fi(e,t,n,r);default:throw new Error(`Unknown node type: ${e.type}`)}},tr=new Map,Qo=e=>{let t=[],n="",r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(i==="[")n&&(t.push({type:"property",value:n}),n=""),r=!0;else if(i==="]"){if(r&&n){let s=n.trim();if(/^\d+$/.test(s))t.push({type:"index",value:parseInt(s,10)});else if(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'")){let a=s.slice(1,-1);t.push({type:"property",value:a})}else t.push({type:"property",value:s});n=""}r=!1}else n+=i}return n&&t.push({type:"property",value:n}),t},U=(e,t,n)=>{if(!e)return;if(e in n)return n[e];let r=tr.get(e);if(!r){let i=[],s="",a=0;for(let c=0;c<e.length;c++){let l=e[c];l==="["?(a++,s+=l):l==="]"?(a--,s+=l):l==="."&&a===0?s&&(i.push(s),s=""):s+=l}s&&i.push(s),r=[];for(let c of i){let l=Qo(c.trim());r.push(...l)}tr.set(e,r)}let o=t;for(let i=0;i<r.length;i++){let s=r[i];if(s.type==="property"&&s.value in n){o=n[s.value];continue}if(o==null)return;(s.type==="property"||s.type==="index")&&(o=o[s.value])}return o},Zo=(e,t,n,r)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=R(i,t,n,r);o.push(s!=null?String(s):"")}return o.join("")},nr=(e,t,n,r)=>{let o=t.functions||t,i=o[e.name];if(!i)throw er(e.name,o);let s=e.args.map(a=>R(a,t,n,r));return i(...s)},he=(e,t,n,r)=>{if(e.var&&!e.type)return U(e.var,n,r);switch(e.type){case m.VARIABLE:return U(e.path,n,r);case m.LITERAL:return e.value;case m.BINARY:return rr(e,t,n,r);case m.UNARY:return or(e,t,n,r);case m.FUNCTION:return nr(e,t,n,r);default:return R(e,t,n,r)}},rr=(e,t,n,r)=>{if(e.op===$.AND||e.op===$.OR){let s=he(e.left,t,n,r),a=he(e.right,t,n,r);switch(e.op){case $.AND:return s&&a;case $.OR:return s||a}}let o=R(e.left,t,n,r),i=R(e.right,t,n,r);switch(e.op){case $.EQ:return o==i;case $.NEQ:return o!=i;case $.GT:return o>i;case $.LT:return o<i;case $.GTE:return o>=i;case $.LTE:return o<=i;case $.IN:return Array.isArray(i)?i.includes(o):!1;case $.ADD:if(typeof o!="number"||typeof i!="number")throw new K(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case $.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new K(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},or=(e,t,n,r)=>{let o=e.op===ke.NOT?he(e.operand,t,n,r):R(e.operand,t,n,r);if(e.op===ke.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},ei=(e,t,n,r)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===m.VARIABLE)if(U(o.path,n,r)){let s=e.bodies[0];if(s.type===m.OBJECT&&s.properties.length<=5){let a={};for(let c of s.properties){let l=c.parsedKey?R(c.parsedKey,t,n,r):c.key,u=c.value;if(u.type===m.LITERAL)a[l]=u.value;else if(u.type===m.VARIABLE)a[l]=U(u.path,n,r);else if(u.type===m.INTERPOLATION){let f=[];for(let d of u.parts)if(typeof d=="string")f.push(d);else if(d.type===m.VARIABLE){let p=U(d.path,n,r);f.push(p!=null?String(p):"")}else{let p=R(d,t,n,r);f.push(p!=null?String(p):"")}a[l]=f.join("")}else a[l]=R(u,t,n,r)}return a}}else{let s=e.bodies[1];if(s.type===m.OBJECT&&s.properties.length<=5){let a={};for(let c of s.properties){let l=c.parsedKey?R(c.parsedKey,t,n,r):c.key,u=c.value;if(u.type===m.LITERAL)a[l]=u.value;else if(u.type===m.VARIABLE)a[l]=U(u.path,n,r);else if(u.type===m.INTERPOLATION){let f=[];for(let d of u.parts)if(typeof d=="string")f.push(d);else if(d.type===m.VARIABLE){let p=U(d.path,n,r);f.push(p!=null?String(p):"")}else{let p=R(d,t,n,r);f.push(p!=null?String(p):"")}a[l]=f.join("")}else a[l]=R(u,t,n,r)}return a}}}return null},ti=(e,t,n,r)=>{let o=ei(e,t,n,r);if(o!==null)return o;for(let i=0;i<e.conditions.length;i++){let s=e.conditions[i];if(s===null||he(s,t,n,r))return R(e.bodies[i],t,n,r)}return ir},ni=(e,t)=>{let n=e.body,r=e.itemVar;if(n.type===m.CONDITIONAL&&n.conditions.length===1&&n.conditions[0].type===m.VARIABLE){let o=n.conditions[0].path,i=n.bodies[0];if(o.startsWith(r+".")){let s=o.substring(r.length+1);if(i.type===m.OBJECT&&i.properties.length<=5){for(let c of i.properties)if(c.parsedKey)return null;let a=[];for(let c=0;c<t.length;c++){let l=t[c];if(l[s]){let u={};for(let f of i.properties){let d=f.key,p=f.value;if(p.type===m.LITERAL)u[d]=p.value;else if(p.type===m.VARIABLE){let h=p.path;if(h===r)u[d]=l;else if(h.startsWith(r+".")){let y=h.substring(r.length+1);u[d]=l[y]}else return null}else if(p.type===m.INTERPOLATION){let h=[],y=!0;for(let I of p.parts)if(typeof I=="string")h.push(I);else if(I.type===m.VARIABLE){let b=I.path;if(b===r)h.push(l!=null?String(l):"");else if(b.startsWith(r+".")){let g=b.substring(r.length+1),x=l[g];h.push(x!=null?String(x):"")}else{y=!1;break}}else{y=!1;break}if(!y)return null;u[d]=h.join("")}else return null}a.push(u)}}return a}}}return null},ri=(e,t)=>{let n=e.body,r=e.itemVar,o=ni(e,t);if(o!==null)return o;if(n.type===m.OBJECT&&n.properties.length<=5&&!n.whenCondition){for(let a of n.properties)if(a.parsedKey)return null;let i=[],s=!0;for(let a of n.properties){let c=a.key,l=a.value;if(l.type===m.LITERAL)i.push({key:c,type:"literal",value:l.value});else if(l.type===m.VARIABLE){let u=l.path;if(u===r)i.push({key:c,type:"item"});else if(u.startsWith(r+".")){let f=u.substring(r.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:c,type:"prop",prop:f});else{s=!1;break}}else{s=!1;break}}else if(l.type===m.INTERPOLATION&&l.parts.length===1){let u=l.parts[0];if(u.type===m.VARIABLE){let f=u.path;if(f===r)i.push({key:c,type:"item_string"});else if(f.startsWith(r+".")){let d=f.substring(r.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:c,type:"prop_string",prop:d});else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}if(s){let a=new Array(t.length);if(i.length===3&&i[0].type==="prop"&&i[0].key==="id"&&i[1].type==="prop_string"&&i[1].key==="title"&&i[2].type==="prop"&&i[2].key==="completed")for(let c=0;c<t.length;c++){let l=t[c];a[c]={id:l.id,title:l.title!=null?String(l.title):"",completed:l.completed}}else for(let c=0;c<t.length;c++){let l=t[c],u={};for(let f of i)if(f.type==="literal")u[f.key]=f.value;else if(f.type==="item")u[f.key]=l;else if(f.type==="prop")u[f.key]=l[f.prop];else if(f.type==="item_string")u[f.key]=l!=null?String(l):"";else if(f.type==="prop_string"){let d=l[f.prop];u[f.key]=d!=null?String(d):""}a[c]=u}return a}}return null},oi=(e,t,n,r,o)=>{let i=[],s=e.body;if(s.type===m.OBJECT&&s.fast!==!1){let a=e.itemVar,c=e.indexVar;for(let l=0;l<o.length;l++){let u=o[l],f={},d={...r,[a]:u,...c&&{[c]:l}};d.__paths__||(d.__paths__=r.__paths__||{});let p=e.iterable.path||"";if(r&&r.__paths__&&p){let h=p.split("."),y=h[0];y in r.__paths__&&(p=r.__paths__[y],h.length>1&&(p+="."+h.slice(1).join(".")))}d.__paths__={...d.__paths__,[a]:`${p}[${l}]`,...c&&{[c]:l}};for(let h of s.properties){let y=h.parsedKey?R(h.parsedKey,t,n,d):h.key,I=h.value;if(I.type===m.LITERAL)f[y]=I.value;else if(I.type===m.VARIABLE){let b=I.path;if(b===a)f[y]=u;else if(b===c)f[y]=l;else if(b.startsWith(a+".")){let g=b.substring(a.length+1);!g.includes(".")&&!g.includes("[")?f[y]=u[g]:f[y]=U(b,n,{...r,[a]:u,...c&&{[c]:l}})}else f[y]=U(b,n,{...r,[a]:u,...c&&{[c]:l}})}else if(I.type===m.INTERPOLATION){let b=[];for(let g of I.parts)if(typeof g=="string")b.push(g);else if(g.type===m.VARIABLE){let x=g.path,C;if(x===a)C=u;else if(x===c)C=l;else if(x.startsWith(a+".")){let O=x.substring(a.length+1);!O.includes(".")&&!O.includes("[")?C=u[O]:C=U(x,n,{...r,[a]:u,...c&&{[c]:l}})}else C=U(x,n,{...r,[a]:u,...c&&{[c]:l}});b.push(C!=null?String(C):"")}else{let x={...r,[a]:u,...c&&{[c]:l}},C=R(g,t,n,x);b.push(C!=null?String(C):"")}f[y]=b.join("")}else{let b={...r,[a]:u,...c&&{[c]:l}};f[y]=R(I,t,n,b)}}i.push(f)}return i}return null},ii=(e,t,n)=>{let r=e.body;if(r.type===m.OBJECT&&r.properties.length===1&&r.properties[0].key==="$if item.visible"){let i=r.properties[0].value;if(i.type===m.CONDITIONAL&&i.conditions.length===1&&i.conditions[0].type===m.VARIABLE&&i.conditions[0].path==="item.visible"){let s=i.bodies[0];if(s.type===m.OBJECT&&s.properties.length===2){let a=s.properties[0],c=s.properties[1];if(a.key==="id"&&a.value.type===m.VARIABLE&&a.value.path==="item.id"&&c.key==="$if item.highlighted"&&c.value.type===m.CONDITIONAL){let l=[];for(let u=0;u<t.length;u++){let f=t[u];if(f.visible){let d={id:f.id};f.highlighted?(d.highlight=!0,d.message=`This item is highlighted: ${f.name}`):(d.highlight=!1,d.message=f.name),l.push(d)}}return l}}}}return null},si=(e,t,n,r)=>{let o=R(e.iterable,t,n,r);if(!Array.isArray(o)){let l,u=!1;if(e.iterable.type===m.FUNCTION){u=!0;let d=e.iterable.args.map(p=>p.type===m.LITERAL?typeof p.value=="string"?`'${p.value}'`:String(p.value):p.type===m.VARIABLE?p.path:p.type===m.FUNCTION?`${p.name}(...)`:"?").join(", ");l=`${e.iterable.name}(${d})`}else l=e.iterable.path||"undefined";let f=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${l}`;throw Zn(f,o,u)}if(!e.indexVar){let l=ii(e,o,e.itemVar);if(l!==null)return l}if(!e.indexVar){let l=ri(e,o);if(l!==null)return l}let i=oi(e,t,n,r,o);if(i!==null)return i;let s=[],a=e.iterable.path||"";if(r&&r.__paths__&&a){let l=a.split("."),u=l[0];u in r.__paths__&&(a=r.__paths__[u],l.length>1&&(a+="."+l.slice(1).join(".")))}let c=!1;e.body.type===m.ARRAY&&(e.body.items.length<=1?c=!1:c=e.body._shouldPreserveArray??=e.body.items.some(l=>l.type===m.OBJECT&&l.properties.some(u=>u.key.startsWith("$if ")||u.key.startsWith("$when "))));for(let l=0;l<o.length;l++){let u=e.indexVar?{...r,[e.itemVar]:o[l],[e.indexVar]:l}:{...r,[e.itemVar]:o[l]};u.__paths__||(u.__paths__=r.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${a}[${l}]`},e.indexVar&&(u.__paths__[e.indexVar]=l);let f=R(e.body,t,n,u);if(Array.isArray(f)&&f.length===1&&!c){let d=f[0];s.push(d===void 0?{}:d)}else s.push(f===void 0?{}:f)}return s},ai=(e,t,n,r)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?R(o.parsedKey,t,n,r):o.key,s=o.value;if(s.type===m.OBJECT&&s.properties.length<=10&&!s.whenCondition){let a={},c={},l=!0;for(let u of s.properties){let f=u.parsedKey?R(u.parsedKey,t,n,r):u.key,d=u.value;if(d.type===m.LITERAL)c[f]=d.value;else if(d.type===m.VARIABLE)c[f]=U(d.path,n,r);else if(d.type===m.INTERPOLATION){let p=[];for(let h of d.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let y=U(h.path,n,r);p.push(y!=null?String(y):"")}else{l=!1;break}if(!l)break;c[f]=p.join("")}else if(d.type===m.OBJECT&&d.properties.length<=5){let p={};for(let h of d.properties){let y=h.key,I=h.value;if(I.type===m.LITERAL)p[y]=I.value;else if(I.type===m.VARIABLE)p[y]=U(I.path,n,r);else if(I.type===m.INTERPOLATION){let b=[];for(let g of I.parts)if(typeof g=="string")b.push(g);else if(g.type===m.VARIABLE){let x=U(g.path,n,r);b.push(x!=null?String(x):"")}else{l=!1;break}if(!l)break;p[y]=b.join("")}else{l=!1;break}}if(!l)break;c[f]=p}else{l=!1;break}}if(l)return a[i]=c,a}}return null},ci=(e,t,n,r)=>{let o=t.functions||t;if(e.whenCondition&&!he(e.whenCondition,o,n,r))return;let i=ai(e,t,n,r);if(i!==null)return i;if(e.fast){let l={};for(let u of e.properties){let f=u.parsedKey?R(u.parsedKey,t,n,r):u.key,d=u.value;if(d.type===m.LITERAL)l[f]=d.value;else if(d.type===m.VARIABLE)l[f]=U(d.path,n,r);else if(d.type===m.INTERPOLATION){let p=[];for(let h of d.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let y=U(h.path,n,r);p.push(y!=null?String(y):"")}else{let y=R(h,t,n,r);p.push(y!=null?String(y):"")}l[f]=p.join("")}else l[f]=R(d,t,n,r)}return l}let s={},a=null,c=!1;for(let l of e.properties)if(!l.key.startsWith("$if ")&&!l.key.match(/^\$if\s+\w+.*:?$/)&&!l.key.startsWith("$elif")&&!l.key.startsWith("$else")&&!l.key.startsWith("$for ")){c=!0;break}for(let l of e.properties)if(l.key.startsWith("$if ")||l.key.match(/^\$if\s+\w+.*:?$/)){let u=R(l.value,t,n,r);if(!c&&u!==null&&u!==void 0)return Array.isArray(u)&&u.length===1?u[0]:u;typeof u=="object"&&u!==null&&!Array.isArray(u)&&Object.assign(s,u)}else if(l.key.startsWith("$for ")){if(e.properties.length===1)return R(l.value,t,n,r)}else{let u=l.value;if(u&&u.type===m.OBJECT&&u.properties){let f=u.properties.find(d=>d.key.startsWith("$for "));if(f){let d=R(f.value,t,n,r);d!==void 0&&(s[l.key]=d)}else{let d=R(l.value,t,n,r);d!==void 0&&(s[l.key]=d)}}else{let f=l.parsedKey?R(l.parsedKey,t,n,r):l.key,d=R(l.value,t,n,r);d!==void 0&&(s[f]=d)}}return s},ir={},li=(e,t,n,r)=>{let o=[];for(let i of e.items)if(i.type===m.LOOP){let s=R(i,t,n,r);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=R(i,t,n,r);s!==ir&&s!==void 0&&o.push(s)}return o},ui=(e,t,n,r)=>{let{name:o,data:i,whenCondition:s}=e,a=t.partials||{},c=t.functions||t;if(s&&!he(s,c,n,r))return;if(!a[o])throw new K(`Partial '${o}' is not defined`);let l=r._partialStack||[];if(l.includes(o))throw new K(`Circular partial reference detected: ${o}`);let u=a[o],f=n,d={...r,_partialStack:[...l,o]};if(r){f={...n};for(let p of Object.keys(r))p.startsWith("_")||(f[p]=r[p])}if(i){let p=R(i,t,n,r);f={...f,...p}}return R(u,t,f,d)},fi=(e,t,n,r)=>{let{path:o}=e,i=o.split("."),s=i[0],a=i.slice(1);if(!r||!(s in r))throw new K(`Path reference '#{${o}}' refers to '${s}' which is not a loop variable in the current scope`);if(r.__paths__||(r.__paths__={}),!(s in r.__paths__))throw new K(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let c=r.__paths__[s];if(typeof c=="number"){if(a.length>0)throw new K(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(c)}return a.length>0&&(c+="."+a.join(".")),c};var zt=Xo;var di=/\$\{([^}]*)\}/g,pi=/#\{([^}]*)\}/g,ar=(e,t={})=>{let n=e.match(/^(\w+)\((.*)\)$/);if(!n)return{isFunction:!1};let[,r,o]=n,i=hi(o,t);return{isFunction:!0,type:m.FUNCTION,name:r,args:i}},hi=(e,t={})=>e.trim()?mi(e).map(r=>gi(r.trim(),t)):[],mi=e=>{let t=[],n="",r=0,o=!1,i="";for(let s=0;s<e.length;s++){let a=e[s],c=s>0?e[s-1]:"";!o&&(a==='"'||a==="'")?(o=!0,i=a,n+=a):o&&a===i&&c!=="\\"?(o=!1,i="",n+=a):!o&&a==="("?(r++,n+=a):!o&&a===")"?(r--,n+=a):!o&&a===","&&r===0?(t.push(n),n=""):n+=a}return n&&t.push(n),t},gi=(e,t={})=>{if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:m.LITERAL,value:e.slice(1,-1)};if(/^-?\d+(\.\d+)?$/.test(e))return{type:m.LITERAL,value:parseFloat(e)};if(e==="true")return{type:m.LITERAL,value:!0};if(e==="false")return{type:m.LITERAL,value:!1};if(e==="null")return{type:m.LITERAL,value:null};let n=ar(e,t);if(n.isFunction)return{type:n.type,name:n.name,args:n.args};let r=e.trim(),o=[{op:" + ",type:"ADD"},{op:" - ",type:"SUBTRACT"}],i=-1,s=null;for(let{op:a,type:c}of o){let l=0;for(;l<r.length;){let u=we(r.substring(l),a);if(u===-1)break;let f=l+u;f>i&&(i=f,s={op:a,type:c}),l=f+a.length}}if(i!==-1)try{return W(r,t)}catch{return{type:m.VARIABLE,path:r}}return{type:m.VARIABLE,path:r}},cr=/^\w+\(.*\)$/,yi=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,bi=e=>{if(!(!e||e.trim()===""||cr.test(e))&&yi.test(e))throw e.includes("?")&&e.includes(":")?new A(`Complex expressions not supported in variable replacements - consider calculating the value in your data instead. Offending expression: "${e}"`):e.includes("||")||e.includes("&&")||e.includes("??")?new A(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new A(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},sr=e=>{let t=e.trim();if(cr.test(t))throw new A(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new A(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new A(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new A(`Logical operators not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("?")&&t.includes(":"))throw new A(`Complex expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);return{type:m.PATH_REFERENCE,path:t}},We=(e,t={})=>{let n=e.trim();bi(n);let r=ar(n,t);if(r.isFunction)return{type:r.type,name:r.name,args:r.args};if(n.includes("[")&&!/[\s+\-*/%|&?:]/.test(n)){let o=0;for(let i of n)i==="["?o++:i==="]"&&o--;if(o!==0)throw new Error("Invalid array index syntax")}return{type:m.VARIABLE,path:n}},Wt=(e,t={})=>{let n=e,r=[];(e.includes("\\${")||e.includes("\\#{"))&&(n=e.replace(/\\\\(\$\{[^}]*\})/g,"\\DOUBLE_ESC_VAR$1"),n=n.replace(/\\\\(#\{[^}]*\})/g,"\\DOUBLE_ESC_PATH$1"),n=n.replace(/\\(\$\{[^}]*\})/g,(l,u)=>{let f=`__ESCAPED_${r.length}__`;return r.push(u),f}),n=n.replace(/\\(#\{[^}]*\})/g,(l,u)=>{let f=`__ESCAPED_${r.length}__`;return r.push(u),f}),n=n.replace(/\\DOUBLE_ESC_VAR/g,"\\"),n=n.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...n.matchAll(di)],i=[...n.matchAll(pi)],s=[...o.map(l=>({match:l,type:"variable"})),...i.map(l=>({match:l,type:"pathref"}))].sort((l,u)=>l.match.index-u.match.index);if(s.length===0){let l=n;for(let u=0;u<r.length;u++)l=l.replace(`__ESCAPED_${u}__`,r[u]);return{type:m.LITERAL,value:l}}if(s.length===1&&s[0].match[0]===n&&r.length===0){let{match:l,type:u}=s[0];try{return u==="variable"?We(l[1],t):sr(l[1])}catch(f){if(f.message==="Invalid array index syntax")return{type:m.LITERAL,value:n};throw f}}let a=[],c=0;for(let{match:l,type:u}of s){let[f,d]=l,p=l.index;if(p>c){let h=n.substring(c,p);for(let y=0;y<r.length;y++)h=h.replace(`__ESCAPED_${y}__`,r[y]);h&&a.push(h)}try{let h;u==="variable"?h=We(d.trim(),t):h=sr(d.trim()),a.push(h)}catch(h){if(h.message==="Invalid array index syntax")a.push(f);else throw h}c=p+f.length}if(c<n.length){let l=n.substring(c);for(let u=0;u<r.length;u++)l=l.replace(`__ESCAPED_${u}__`,r[u]);l&&a.push(l)}return{type:m.INTERPOLATION,parts:a}};var Ht=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),fr=e=>Object.keys(e),J=e=>e.join("."),me=(e,t,n)=>{let r=fr(e).filter(o=>!t.has(o));if(r.length>0)throw new A(`Unexpected key '${r[0]}' in condition JSON at '${J(n)}'`)},ge=(e,t)=>typeof e=="string"?Wt(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?wi(e,t):Ai(e,t):{type:m.LITERAL,value:e},Ii=e=>{let{$each:t,...n}=e;if(typeof t!="string")throw new A("$each value must be a non-empty string");let r=t.trim();if(r==="")throw new A("$each value must be a non-empty string");if(Object.keys(n).length===0)throw new A("Empty $each body not allowed");if(n.$partial!==void 0)throw new A("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${r}`]:n}},wi=(e,t)=>{let n=[],r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(typeof i=="object"&&i!==null&&!Array.isArray(i)){if(i.$each!==void 0)try{let c=Ii(i),l=Object.keys(c);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let u=ur(l[0],c[l[0]],t,!0);n.push(u),r=!0;continue}}catch(c){throw c instanceof A?c:new A(c.message)}let a=Object.keys(i);if(a.length===1&&/^\$for(?::\w+)?\s/.test(a[0])){let c=ur(a[0],i[a[0]],t);n.push(c),r=!0;continue}}let s=ge(i,t);n.push(s),(s.type===m.FUNCTION||s.type===m.CONDITIONAL||s.type===m.LOOP||s.type===m.PARTIAL||s.type===m.OBJECT&&!s.fast||s.type===m.ARRAY&&!s.fast)&&(r=!0)}return{type:m.ARRAY,items:n,fast:!r}},Ai=(e,t)=>{let n=[],r=!1,o=null,i=Object.entries(e),s=0;if(e.$partial!==void 0){if(typeof e.$partial!="string")throw new A("$partial value must be a string");if(e.$partial.trim()==="")throw new A("$partial value cannot be an empty string");let c=["$if","$elif","$else","$for"],l=[];for(let[b]of i)for(let g of c)if(b===g||b.startsWith(g+" ")||b.startsWith(g+"#")){l.push(g);break}if(l.length>0)throw new A(`Cannot use $partial with ${l.join(", ")} at the same level. Wrap $partial in a parent object if you need conditionals.`);let{$partial:u,$when:f,...d}=e,p={},h=!1;for(let[b,g]of Object.entries(d)){let x=b;(b.startsWith("\\$")||b.startsWith("$$"))&&(x=b.slice(1)),p[x]=g,h=!0}let y=null;if(h&&(y=ge(p,t),y.type===m.OBJECT)){let b=!1;for(let g of y.properties)if(g.value.type===m.VARIABLE||g.value.type===m.INTERPOLATION||g.value.type===m.FUNCTION||g.value.type===m.CONDITIONAL||g.value.type===m.OBJECT&&!g.value.fast||g.value.type===m.ARRAY&&!g.value.fast){b=!0;break}b&&(y.fast=!1)}let I={type:m.PARTIAL,name:u,data:y};return f!==void 0&&(I.whenCondition=lr(f,t)),I}for(let[c,l]of i)if(c==="$when"){if(o!==null)throw new A("Multiple '$when' directives on the same object are not allowed");if(l==null)throw new A("Missing condition expression after '$when'");o=lr(l,t),r=!0}else if(c.startsWith("$when#")||c.startsWith("$when "))throw new A("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<i.length;){let[c,l]=i[s];if(c==="$when"){s++;continue}if(c==="$each")throw new A("$each can only be used inside arrays");if(c.startsWith("$if ")||c.match(/^\$if#\w+\s/)||c.match(/^\$if\s+\w+.*:$/)){let u=Ei(i,s,t);n.push({key:c,value:u.node}),r=!0,s=u.nextIndex}else if(/^\$for(?::\w+)?\s/.test(c)){let u=c.match(/^\$for(?::(\w+))?\s/)?.[1]||"",f=u?`:${u}`:"";throw new A(`$for loops must be inside arrays - use '- $for${f} item in items:' instead of '$for${f} item in items:'. For cleaner object generation syntax, consider using $each.`)}else{if(c.startsWith("$elif ")||c.startsWith("$else"))throw new A(`'${c.split(" ")[0]}' without matching '$if'`);if(c==="$if"||c==="$if:")throw new A("Missing condition expression after '$if'");{let u=ge(l,t);(u.type===m.FUNCTION||u.type===m.CONDITIONAL||u.type===m.PARTIAL||u.type===m.OBJECT&&!u.fast||u.type===m.ARRAY&&!u.fast)&&(r=!0);let f=Wt(c,t),d={key:c,value:u};(f.type!==m.LITERAL||f.value!==c)&&(d.parsedKey=f),n.push(d),s++}}}let a={type:m.OBJECT,properties:n,fast:!r};return o&&(a.whenCondition=o),a},Ei=(e,t,n={})=>{let r=[],o=[],i=t,[s,a]=e[i],c=null,l;if(s.startsWith("$if#")){let f=s.match(/^\$if#(\w+)\s+(.+)$/);if(f)c=f[1],l=f[2];else throw new A(`Invalid conditional syntax: ${s}`)}else l=s.substring(4),l.endsWith(":")&&(l=l.slice(0,-1).trim());Ft(l);let u=W(l,n);for(r.push(u),o.push(ge(a,n)),i++;i<e.length;){let[f,d]=e[i],p=!1,h;if(c?f.startsWith(`$elif#${c} `)?(h=f.substring(`$elif#${c} `.length),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(f===`$else#${c}`||f===`$else#${c}:`)&&(p=!0,h=null):f.startsWith("$elif ")?(h=f.substring(6),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(f==="$else"||f==="$else:")&&(p=!0,h=null),p){if(h===null)r.push(null);else{Ft(h);let y=W(h,n);r.push(y)}if(o.push(ge(d,n)),i++,h===null)break}else break}return{node:{type:m.CONDITIONAL,conditions:r,bodies:o,id:c},nextIndex:i}},qt={eq:$.EQ,neq:$.NEQ,gt:$.GT,gte:$.GTE,lt:$.LT,lte:$.LTE,in:$.IN,add:$.ADD,sub:$.SUBTRACT},Yt={all:$.AND,any:$.OR},xi=new Set(["var","literal","call","not",...Object.keys(qt),...Object.keys(Yt)]),vi=(e,t,n)=>{if(!Array.isArray(e))throw new A(`Condition JSON operator '${t}' at '${J(n)}' requires an array`);if(e.length!==2)throw new A(`Condition JSON operator '${t}' at '${J(n)}' requires exactly 2 operands`);return e},Ci=(e,t,n,r,o)=>{if(!Array.isArray(e))throw new A(`Condition JSON operator '${t}' at '${J(o)}' requires an array`);if(e.length===0)throw new A(`Condition JSON operator '${t}' at '${J(o)}' requires at least 1 condition`);return e.map((s,a)=>se(s,r,[...o,a])).reduce((s,a)=>({type:m.BINARY,op:n,left:s,right:a}))},Si=(e,t,n)=>{let r,o;if(typeof e.call=="string")r=e.call,o=e.args??[],me(e,new Set(["call","args"]),n);else if(Ht(e.call))r=e.call.name,o=e.call.args??[],me(e,new Set(["call"]),n),me(e.call,new Set(["name","args"]),[...n,"call"]);else throw new A(`Condition JSON call at '${J(n)}' requires a function name`);if(typeof r!="string"||r.trim()==="")throw new A(`Condition JSON call at '${J(n)}' requires a non-empty function name`);if(!/^\w+$/.test(r))throw new A(`Invalid condition JSON function name '${r}' at '${J(n)}'`);if(!Array.isArray(o))throw new A(`Condition JSON call '${r}' at '${J(n)}' requires args to be an array`);return{type:m.FUNCTION,name:r,args:o.map((i,s)=>se(i,t,[...n,"args",s]))}},se=(e,t={},n=["$when"])=>{if(typeof e=="string"||typeof e=="number"||typeof e=="boolean"||e===null)return{type:m.LITERAL,value:e};if(Array.isArray(e))throw new A(`Condition JSON array at '${J(n)}' must be wrapped in an operator or { literal: [...] }`);if(!Ht(e))throw new A(`Invalid condition JSON value at '${J(n)}'`);let r=fr(e);if(r.length===0)throw new A(`Condition JSON object at '${J(n)}' must contain an operator`);let o=r.filter(s=>xi.has(s));if(o.length===0)throw new A(`Unknown condition JSON operator '${r[0]}' at '${J(n)}'`);if(o.length>1)throw new A(`Condition JSON at '${J(n)}' must contain exactly one operator`);let i=o.includes("call")?"call":o[0];if(i==="var"){if(me(e,new Set(["var"]),n),typeof e.var!="string"||e.var.trim()==="")throw new A(`Condition JSON var at '${J(n)}' requires a non-empty path`);return{type:m.VARIABLE,path:e.var}}if(i==="literal")return me(e,new Set(["literal"]),n),{type:m.LITERAL,value:e.literal};if(i==="call")return Si(e,t,n);if(i==="not")return me(e,new Set(["not"]),n),{type:m.UNARY,op:ke.NOT,operand:se(e.not,t,[...n,"not"])};if(i in Yt)return me(e,new Set([i]),n),Ci(e[i],i,Yt[i],t,[...n,i]);if(i in qt){me(e,new Set([i]),n);let s=vi(e[i],i,[...n,i]);return{type:m.BINARY,op:qt[i],left:se(s[0],t,[...n,i,0]),right:se(s[1],t,[...n,i,1])}}throw new A(`Unknown condition JSON operator '${i}' at '${J(n)}'`)},lr=(e,t={})=>{if(e==null)throw new A("Missing condition expression after '$when'");if(typeof e=="string"){if(e.trim()==="")throw new A("Empty condition expression after '$when'");return W(e,t)}return Ht(e)||Array.isArray(e)?se(e,t):{type:m.LITERAL,value:e}},W=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let l=e.slice(1,-1),u=0,f=!0;for(let d=0;d<l.length;d++)if(l[d]==="("?u++:l[d]===")"&&u--,u<0){f=!1;break}if(f&&u===0)return W(l,t)}let n=we(e,"||");if(n!==-1)return{type:m.BINARY,op:$.OR,left:W(e.substring(0,n).trim(),t),right:W(e.substring(n+2).trim(),t)};let r=we(e,"&&");if(r!==-1)return{type:m.BINARY,op:$.AND,left:W(e.substring(0,r).trim(),t),right:W(e.substring(r+2).trim(),t)};let o=[{op:">=",type:$.GTE},{op:"<=",type:$.LTE},{op:"==",type:$.EQ},{op:"!=",type:$.NEQ},{op:">",type:$.GT},{op:"<",type:$.LT},{op:" in ",type:$.IN}];for(let{op:l,type:u}of o){let f=we(e,l);if(f!==-1)return{type:m.BINARY,op:u,left:W(e.substring(0,f).trim(),t),right:W(e.substring(f+l.length).trim(),t)}}let i=-1,s=null,a=[{op:" + ",type:$.ADD},{op:" - ",type:$.SUBTRACT}];for(let{op:l,type:u}of a){let f=0;for(;f<e.length;){let d=we(e.substring(f),l);if(d===-1)break;let p=f+d;p>i&&(i=p,s={op:l,type:u}),f=p+l.length}}if(i!==-1&&s)return{type:m.BINARY,op:s.type,left:W(e.substring(0,i).trim(),t),right:W(e.substring(i+s.op.length).trim(),t)};let c=[" * "," / "," % "];for(let l of c)if(we(e,l)!==-1)throw new A(`Arithmetic operations are not allowed in conditionals: "${l}"`);return e.startsWith("!")?{type:m.UNARY,op:ke.NOT,operand:W(e.substring(1).trim(),t)}:dr(e,t)},we=(e,t)=>{let n=0,r=0;for(;r<=e.length-t.length;){if(e[r]==="(")n++;else if(e[r]===")")n--;else if(n===0&&e.substring(r,r+t.length)===t)return r;r++}return-1},_i=e=>{if(e=e.trim(),e==="true")return{type:m.LITERAL,value:!0};if(e==="false")return{type:m.LITERAL,value:!1};if(e==="null")return{type:m.LITERAL,value:null};if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:m.LITERAL,value:e.slice(1,-1)};if(e==='""'||e==="''")return{type:m.LITERAL,value:""};if(e==="{}")return{type:m.LITERAL,value:{}};if(e==="[]")return{type:m.LITERAL,value:[]};let t=Number(e);return!isNaN(t)&&isFinite(t)?{type:m.LITERAL,value:t}:{type:m.VARIABLE,path:e}},dr=(e,t)=>{let n=e.trim();if(n.match(/^(\w+)\((.*)\)$/))return We(n,t);let o=_i(n);if(o.type===m.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(n))return{type:m.VARIABLE,path:n};try{return We(n,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},$i=(e,t=!1)=>{let n=t?"$each":"$for";try{Qn(e)}catch(r){if(r instanceof A&&t){let o=r.message.replace(/\$for/g,"$each");throw new A(o.replace("Parse Error: ",""))}throw r}},ur=(e,t,n,r=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let I=r?"$each":"$for";throw new A(`Invalid loop syntax (got: '${e.replace("$for",I)}')`)}let s=i[1],a=i[2].trim();$i(a,r);let c=a.match(/^(.+?)\s+in\s+(.+)$/);if(!c){let I=r?"$each":"$for";throw new A(`Invalid loop syntax - missing 'in' keyword (got: '${I} ${a}')`)}let l=c[1].trim(),u=c[2].trim(),f,d=null;if(l.includes(",")){let I=l.split(",").map(b=>b.trim());if(I.length!==2)throw new A(`Invalid loop variables: ${l}. Expected format: "item" or "item, index"`);f=I[0],d=I[1]}else f=l;let p=["this","undefined","null","true","false"];if(p.includes(f))throw new A(`Reserved variable name: ${f}`);if(d&&p.includes(d))throw new A(`Reserved variable name: ${d}`);let h=dr(u,n),y=ge(t,n);return{type:m.LOOP,itemVar:f,indexVar:d,iterable:h,body:y,flatten:s!=="nested"}};var Ri=(e,t={})=>{let{functions:n={}}=t;return ge(e,n)},ft=Ri;var qe={};Uo(qe,{now:()=>Oi});var Oi=()=>Date.now();var Li=(e,t,n={})=>{let{functions:r={},partials:o={}}=n,i={...qe,...r},s=ft(e,{functions:i}),a={};for(let[c,l]of Object.entries(o))a[c]=ft(l,{functions:i});return zt(s,t,{functions:i,partials:a})},Z=Li;var ki=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",Pi=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,Ti=(e,t)=>{if(ki(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new A("Empty condition expression");return W(e,t)}return se(e,t)},Ni=(e,t={},n={})=>{let r=Pi(n),o={...qe,...r},i=Ti(e,o);return!!he(i,{functions:o,partials:{}},t,{})},Ae=Ni;var hr=(e,t,n={})=>{let r=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=c=>c,transformActionFirstArgument:a=c=>c}=n;for(let[c,l]of Object.entries(t))c!=="createInitialState"&&(c.startsWith("select")?o[c]=(...u)=>l(s(r),...u):i[c]=(...u)=>{r=Ut(r,d=>l(a(d),...u))});return{...o,...i}},pt=(e,t)=>n=>{let r=e(),o=Array.isArray(n)?n:[n];return Ut(r,i=>{o.forEach(s=>{t.forEach(a=>{a(i,s)})})})};var Di=(e,t)=>{if(e.default!==void 0)return e.default;let n=["number","boolean","string","object"];if(!n.includes(e.type))throw new Error(`Invalid variable type: ${e.type} for variable ${t}. Expected one of: ${n.join(", ")}`);switch(e.type){case"number":return 0;case"boolean":return!1;case"string":return"";case"object":return{}}},re=(e,t)=>Object.prototype.hasOwnProperty.call(e??{},t),Ye=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),mr=e=>{let t=ie(e)?ze(e):e;return structuredClone(t)},Ee=e=>re(e,"computed"),Pe=(e={},t={})=>Object.fromEntries(Object.entries(e??{}).filter(([n])=>!Ee(t[n]))),Vi=e=>String(e).replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean),Jt=(e,t)=>{let n=e;for(let r of t){if(n==null)return;n=n[r]}return n},ji=(e,t={})=>{if(typeof e!="string"||e.trim()==="")throw new Error("Computed expression var requires a non-empty string path");let n=Vi(e),[r,o,...i]=n;if(r==="variables"){if(!o)return t.variables;let s=typeof t.resolveVariable=="function"?t.resolveVariable(o):t.variables?.[o];return Jt(s,i)}return r==="runtime"?Jt(t.runtime,n.slice(1)):Jt(t,n)},Mi=(e,t,n)=>{if(!Array.isArray(t))throw new Error(`Computed expression operator "${e}" requires an array`);if(n!==void 0&&t.length!==n)throw new Error(`Computed expression operator "${e}" requires ${n} operand(s)`)},pr=(e,t)=>{if(!Array.isArray(t))throw new Error(`Computed expression operator "${e}" requires an array`);if(t.length===0)throw new Error(`Computed expression operator "${e}" requires at least one operand`)},Bi=(e,t)=>{if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Computed expression operator "${e}" requires finite numeric operands`)},ne=(e,t,n,r)=>(Mi(e,t,r),t.map(o=>dt(o,n))),ee=(e,t,n,r)=>{let o=ne(e,t,n,r);return o.forEach(i=>Bi(e,i)),o},Ui=(e,t,n)=>{switch(e){case"var":return ji(t,n);case"add":{let[r,o]=ee(e,t,n,2);return r+o}case"sub":{let[r,o]=ee(e,t,n,2);return r-o}case"mul":{let[r,o]=ee(e,t,n,2);return r*o}case"div":{let[r,o]=ee(e,t,n,2);return r/o}case"mod":{let[r,o]=ee(e,t,n,2);return r%o}case"neg":{let[r]=ee(e,t,n,1);return-r}case"round":{let[r]=ee(e,t,n,1);return Math.round(r)}case"floor":{let[r]=ee(e,t,n,1);return Math.floor(r)}case"ceil":{let[r]=ee(e,t,n,1);return Math.ceil(r)}case"min":{let[r,o]=ee(e,t,n,2);return Math.min(r,o)}case"max":{let[r,o]=ee(e,t,n,2);return Math.max(r,o)}case"clamp":{let[r,o,i]=ee(e,t,n,3);return Math.min(i,Math.max(o,r))}case"eq":{let[r,o]=ne(e,t,n,2);return r==o}case"neq":{let[r,o]=ne(e,t,n,2);return r!=o}case"gt":{let[r,o]=ne(e,t,n,2);return r>o}case"gte":{let[r,o]=ne(e,t,n,2);return r>=o}case"lt":{let[r,o]=ne(e,t,n,2);return r<o}case"lte":{let[r,o]=ne(e,t,n,2);return r<=o}case"in":{let[r,o]=ne(e,t,n,2);return Array.isArray(o)?o.includes(r):!1}case"and":case"all":return pr(e,t),t.every(r=>!!dt(r,n));case"or":case"any":return pr(e,t),t.some(r=>!!dt(r,n));case"not":{let[r]=ne(e,t,n,1);return!r}case"length":{let[r]=ne(e,t,n,1);return typeof r=="string"||Array.isArray(r)?r.length:Ye(r)?Object.keys(r).length:0}case"includes":{let[r,o]=ne(e,t,n,2);return typeof r=="string"||Array.isArray(r)?r.includes(o):!1}case"literal":return mr(t);default:throw new Error(`Unknown computed expression operator: ${e}`)}},dt=(e,t={})=>{if(e===null||typeof e!="object")return e;if(Array.isArray(e))throw new Error("Computed expression arrays are not valid; use value for literal arrays");let n=Object.entries(e);if(n.length!==1)throw new Error("Computed expression objects must contain exactly one operator");let[[r,o]]=n;return Ui(r,o,t)},Fi=(e,t={})=>Ae(e,{variables:t.variables,runtime:t.runtime}),zi=(e,t)=>{if(!Ye(e))throw new Error(`${t} must be an object`);let n=re(e,"expr"),r=re(e,"value");if(n===r)throw new Error(`${t} must contain exactly one of expr or value`)},Kt=(e,t,n)=>(zi(e,t),re(e,"value")?mr(e.value):dt(e.expr,n)),Wi=(e,t={},n="unknown")=>{if(!Ye(e))throw new Error(`Computed variable "${n}" computed must be an object`);let r=re(e,"expr"),o=re(e,"value");if(re(e,"branches")){if(r||o)throw new Error(`Computed variable "${n}" cannot combine branches with expr or value`);if(!Array.isArray(e.branches))throw new Error(`Computed variable "${n}" branches must be an array`);if(e.branches.length===0)throw new Error(`Computed variable "${n}" branches must not be empty`);if(!Ye(e.default))throw new Error(`Computed variable "${n}" requires default`);for(let s=0;s<e.branches.length;s+=1){let a=e.branches[s];if(!Ye(a))throw new Error(`Computed variable "${n}" branch ${s} must be an object`);if(!re(a,"when"))throw new Error(`Computed variable "${n}" branch ${s} requires when`);if(Fi(a.when,t))return Kt(a,`Computed variable "${n}" branch ${s}`,t)}return Kt(e.default,`Computed variable "${n}" default`,t)}if(r===o)throw new Error(`Computed variable "${n}" must contain exactly one of expr, value, or branches`);return Kt(e,`Computed variable "${n}"`,t)},qi=(e,t,n)=>{switch(t){case"number":if(typeof n!="number"||!Number.isFinite(n))throw new Error(`Computed variable "${e}" expected type number, got ${Array.isArray(n)?"array":typeof n}`);return;case"boolean":if(typeof n!="boolean")throw new Error(`Computed variable "${e}" expected type boolean, got ${Array.isArray(n)?"array":typeof n}`);return;case"string":if(typeof n!="string")throw new Error(`Computed variable "${e}" expected type string, got ${Array.isArray(n)?"array":typeof n}`);return;case"object":if(n===null||typeof n!="object")throw new Error(`Computed variable "${e}" expected type object, got ${typeof n}`);return;default:throw new Error(`Invalid variable type: ${t} for computed variable ${e}`)}},ht=({variables:e={},runtime:t={},variableConfigs:n={},eager:r=!0}={})=>{let o=Pe(e,n),i=Object.entries(n).filter(([,f])=>Ee(f)).map(([f])=>f),s={},a=[],c=f=>{if(re(s,f))return s[f];let d=n[f];if(!Ee(d))return o[f];let p=a.indexOf(f);if(p>=0){let h=[...a.slice(p),f].join(" -> ");throw new Error(`Computed variable cycle detected: ${h}`)}a.push(f);try{let h=Wi(d.computed,u,f);return qi(f,d.type,h),s[f]=h,h}finally{a.pop()}},l=new Proxy({},{get:(f,d)=>{if(typeof d=="string")return c(d)},has:(f,d)=>typeof d=="string"&&(re(o,d)||i.includes(d)),ownKeys:()=>[...new Set([...Object.keys(o),...i])],getOwnPropertyDescriptor:(f,d)=>{if(!(typeof d!="string"||!re(o,d)&&!i.includes(d)))return{enumerable:!0,configurable:!0}}}),u={variables:l,runtime:t,resolveVariable:c};return r?(i.forEach(f=>{c(f)}),{...o,...s}):l},Yi=({variables:e={},runtime:t={},variableConfigs:n,projectData:r}={})=>ht({variables:e,runtime:t,variableConfigs:n??r?.resources?.variables??{},eager:!0}),Qt=e=>{let t={},n={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([r,o])=>{if(Ee(o))return;let i=Di(o,r);o.scope==="context"?t[r]=i:n[r]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}},Zt=(e,t)=>{let n=["context","device","account"];if(!e)throw new Error(`Variable scope is required for variable: ${t}`);if(!n.includes(e))throw new Error(`Invalid variable scope: ${e} for variable ${t}. Expected one of: ${n.join(", ")}`)},en=(e,t,n)=>{let r={number:["set","increment","decrement","multiply","divide"],boolean:["set","toggle"],string:["set"],object:["set"]},o=r[e];if(!o)throw new Error(`Unknown variable type: ${e} for variable ${n}`);if(!Object.values(r).flat().includes(t))throw new Error(`Unknown operation: ${t}`);if(!o.includes(t))throw new Error(`Operation "${t}" is not valid for variable "${n}" of type "${e}". Valid operations: ${o.join(", ")}`)},tn=(e,t,n)=>{switch(t){case"set":return n;case"multiply":return(e??1)*n;case"divide":return(e??0)/n;case"increment":return(e??0)+(n??1);case"decrement":return(e??0)-(n??1);case"toggle":return!e;default:throw new Error(`Unknown operation: ${t}`)}};var gr=(e,t="DD/MM/YYYY - HH:mm")=>{if(!e)return"";let n=new Date(e),r=o=>String(o).padStart(2,"0");return t.replace("DD",r(n.getDate())).replace("MM",r(n.getMonth()+1)).replace("YYYY",n.getFullYear()).replace("YY",String(n.getFullYear()).slice(-2)).replace("HH",r(n.getHours())).replace("mm",r(n.getMinutes())).replace("ss",r(n.getSeconds()))},Hi=(e,t)=>{let n=i=>{if(!i)return;let s={};i.ui&&(s.ui=i.ui);let a=i.character?.sprite;return a&&Object.keys(a).length>0&&(s.sprite=a),Object.keys(s).length>0?s:void 0},r=n(e),o=n(t);return JSON.stringify(r)===JSON.stringify(o)?null:r&&!o?{changeType:"delete",data:e}:o&&!r?{changeType:"add",data:t}:o&&r?{changeType:"update",data:t}:null},nn=(e={},t={})=>{let n={},r=["sfx","voice"],o=s=>{let a=e[s],c=t[s];c&&!a?n[s]={changeType:"add",data:c}:a&&!c?r.includes(s)||(n[s]={changeType:"delete",data:a}):a&&c&&JSON.stringify(a)!==JSON.stringify(c)&&(n[s]={changeType:"update",data:c})};o("background"),o("bgm"),o("voice");let i=Hi(e.dialogue,t.dialogue);return i&&(n.dialogue=i),o("choice"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),n},rn=(e={})=>{let t=structuredClone(e);t.background&&(t.background.animations?.playback?.continuity!=="persistent"&&delete t.background.animations,t.background.resourceId||delete t.background);let n=o=>{t[o]&&(delete t[o].animations,Object.keys(t[o]).length===0&&delete t[o])};n("layout"),n("choice"),t.dialogue?.ui&&(delete t.dialogue.ui.animations,Object.keys(t.dialogue.ui).length===0&&delete t.dialogue.ui,Object.keys(t.dialogue).length===0&&delete t.dialogue),t.dialogue?.character?.sprite&&(delete t.dialogue.character.sprite.animations,Object.keys(t.dialogue.character.sprite).length===0&&delete t.dialogue.character.sprite,Object.keys(t.dialogue.character).length===0&&delete t.dialogue.character,Object.keys(t.dialogue).length===0&&delete t.dialogue);let r=(o,i)=>{let s=t[o]?.items;Array.isArray(s)&&(t[o].items=s.map(a=>{let c={...a};return delete c.animations,i(c)?c:null}).filter(Boolean),t[o].items.length===0&&delete t[o])};return r("character",o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId),r("visual",o=>o.resourceId||o.transformId),t},Ji=(e,t)=>{if(!e||!t)return;let n=e;for(let r of t.split(".")){if(n==null||!(r in Object(n)))return;n=n[r]}return n},Ki=(e,t)=>{if(typeof e!="string")return e;if(e==="_event"){if(t==null)throw new Error('Action template binding "_event" requires event context "_event".');return t}if(!e.startsWith("_event."))return e;if(t==null)throw new Error(`Action template binding "${e}" requires event context "_event".`);let n=e.slice(7),r=Ji(t,n);if(r===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return r},Gi={conditional:new Set(["branches"]),updateProjectData:new Set(["projectData"]),showConfirmDialog:new Set(["confirmActions","cancelActions"])},yr=(e,t)=>{let n=e[e.length-1];return n?Gi[n]?.has(t)===!0:!1},Gt=(e,t,n=[])=>Array.isArray(e)?e.map(r=>Gt(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,yr(n,r)?o:Gt(o,t,[...n,r])])):Ki(e,t),Xt=(e,t,n=[])=>Array.isArray(e)?e.map(r=>Xt(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,yr(n,r)?o:Xt(o,t,[...n,r])])):typeof e=="string"?Z(e,t):e,on=(e,t)=>{if(!t)return e;if(Object.prototype.hasOwnProperty.call(t,"event"))throw new Error('Action template context key "event" is no longer supported. Use "_event".');let n=Gt(e,t._event);return Xt(n,t)};var mt=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:structuredClone(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},wr=(e,t)=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let n=e.map(r=>structuredClone(r)).filter(r=>t(r)||r.animations);return{hasValidItems:n.length>0,processedItems:n}},Te=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),br=e=>e?.animations?.playback?.continuity==="persistent",Xi=e=>{if(e){if(e.character&&Te(e.character,"name"))return e.character.name;if(Te(e,"characterName"))return e.characterName}},Ar=e=>!!e?.character&&Te(e.character,"sprite"),Qi=e=>{let t={},n=!1,r=Xi(e);return r!==void 0&&(t.name=r,n=!0),Ar(e)&&(t.sprite=structuredClone(e.character.sprite),n=!0),n?t:void 0},Ir=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},Zi=({dialogueState:e,content:t,append:n=!1})=>{if(!n||!Array.isArray(t)){e.content=t,delete e.initialRevealedContent;return}let r=Array.isArray(e.content)?e.content:[];r.length>0?e.initialRevealedContent=r.map(o=>structuredClone(o)):delete e.initialRevealedContent,e.content=[...r,...t]},es=()=>({}),ts=(e,t)=>{if(t.background){let{animationsOnly:n,state:r}=mt(t.background,s=>!!s.resourceId);if(n){e.background=e.background?.resourceId?{...structuredClone(e.background),...r}:r;return}if(!t.background.resourceId){delete e.background;return}let o=structuredClone(t.background),i=e.background;i?.resourceId===o.resourceId&&i?.transformId===o.transformId&&!Te(o,"animations")&&br(i)&&(o.animations=structuredClone(i.animations)),e.background=o}else e.background?.animations&&!br(e.background)&&(e.background.animations={})},ns=(e,t)=>{if(!t.dialogue){e.dialogue&&(Ir(e.dialogue),e.dialogue.mode==="adv"&&(e.dialogue.content=void 0,delete e.dialogue.initialRevealedContent,e.dialogue.persistCharacter!==!0&&(delete e.dialogue.characterId,delete e.dialogue.character)));return}e.dialogue||(e.dialogue={});let n=e.dialogue.mode;if(t.dialogue.ui){let{animationsOnly:l,state:u}=mt(t.dialogue.ui,f=>!!f.resourceId);l?e.dialogue.ui={...e.dialogue.ui,...u}:e.dialogue.ui={...t.dialogue.ui}}else e.dialogue?.ui?.animations&&(e.dialogue.ui.animations={});t.dialogue.mode==="adv"&&(e.dialogue.content=e.dialogue.content||void 0,e.dialogue.characterId=e.dialogue.characterId||void 0,e.dialogue.mode="adv"),t.dialogue.mode==="nvl"&&(e.dialogue?.mode!=="nvl"&&(e.dialogue.lines=[]),e.dialogue.mode="nvl");let r=t.dialogue.append===!0&&n!=="nvl"&&e.dialogue?.mode!=="nvl"&&Array.isArray(t.dialogue.content);t.dialogue.content!==void 0&&Zi({dialogueState:e.dialogue,content:t.dialogue.content,append:r});let o=Te(t.dialogue,"persistCharacter")?t.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;o?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let i=Te(t.dialogue,"characterId"),s=Qi(t.dialogue),a=s!==void 0,c=Ar(t.dialogue);if(i?t.dialogue.characterId?e.dialogue.characterId=t.dialogue.characterId:delete e.dialogue.characterId:!o&&!r&&delete e.dialogue.characterId,a?e.dialogue.character=!i&&o&&e.dialogue.character?{...structuredClone(e.dialogue.character),...s}:s:(i||!o&&!r)&&delete e.dialogue.character,c||Ir(e.dialogue),t.dialogue.clear){delete e.dialogue;return}if(t.dialogue?.clearPage&&e.dialogue?.mode==="nvl"&&(e.dialogue.lines=[]),e.dialogue?.mode==="nvl"&&t.dialogue.content!==void 0){let l={content:t.dialogue.content,characterId:e.dialogue.characterId??null};e.dialogue.character&&(l.character=structuredClone(e.dialogue.character)),e.dialogue.lines.push(l)}},rs=(e,t)=>{if(t.sfx){if(!t.sfx.items||t.sfx.items.length===0){delete e.sfx;return}e.sfx=t.sfx}else e.sfx&&delete e.sfx},os=(e,t)=>{if(t.bgm){if(!t.bgm.resourceId){e.bgm=void 0;return}e.bgm={...t.bgm,loop:t.bgm.loop||t.bgm.loop===void 0}}},is=(e,t)=>{if(t.visual){let{hasValidItems:n,processedItems:r}=wr(t.visual.items,o=>!!o.resourceId);n?e.visual={items:r}:delete e.visual}else e.visual?.items&&(e.visual.items=e.visual.items.map(n=>n.animations?{...n,animations:{}}:n))},ss=(e,t)=>{if(!t.character){e.character?.items&&(e.character.items=e.character.items.map(o=>o.animations?{...o,animations:{}}:o));return}let{hasValidItems:n,processedItems:r}=wr(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId);n?e.character={items:r}:delete e.character},as=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},cs=(e,t)=>{if(t.layout){let{animationsOnly:n,state:r}=mt(t.layout,o=>!!o.resourceId);if(n){e.layout=r;return}if(!t.layout.resourceId){delete e.layout;return}e.layout=t.layout}else e.layout&&delete e.layout},ls=(e,t)=>{if(t.choice){let{animationsOnly:n,state:r}=mt(t.choice,o=>!!o.resourceId);if(n){e.choice={...e.choice,...r};return}if(!t.choice.resourceId){delete e.choice;return}e.choice=t.choice}else e.choice&&delete e.choice},us=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},fs=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},ds=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(n=>{delete e[n]})},Ne=e=>pt(es,[ds,ts,rs,os,is,ns,ss,as,cs,ls,us,fs])(e);var xe={objectValues:e=>Object.entries(e).map(([t,n])=>({id:t,...n})),formatDate:gr},ps=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,hs=(e,t)=>{let n=String(t||"").trim();if(!n)return;let r=n.match(/[A-Za-z_][A-Za-z0-9_]*|\[\d+\]/g)||[],o=e;for(let i of r){if(i.startsWith("[")){let s=Number(i.slice(1,-1));o=Array.isArray(o)?o[s]:void 0;continue}o=o?.[i]}return o},bt=(e,t,n)=>{if(Array.isArray(e)){let o=[];for(let i of e){if(i&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===1){let[s]=Object.keys(i),a=ps.exec(s);if(a){let[,c,l,u]=a,f=hs(t,u);if(!Array.isArray(f))continue;let d=Array.isArray(i[s])?i[s]:[];f.forEach((p,h)=>{let y={...t,[c]:p};l&&(y[l]=h),d.forEach(I=>{let b=bt(I,y,n),g=Z(b,y,n);Array.isArray(g)?o.push(...g):o.push(g)})});continue}}o.push(bt(i,t,n))}return o}if(!e||typeof e!="object")return e;let r={};return Object.entries(e).forEach(([o,i])=>{r[o]=bt(i,t,n)}),r},bn=({animationType:e,animationId:t,animationPath:n})=>{if(e!==void 0&&!(e==="update"||e==="transition"))throw new Error(`[${n}] Animation "${t}" has unsupported type "${e}". Use "update" or "transition".`)},ms=({id:e,targetId:t,animation:n,playback:r,animationPath:o="animation"})=>{let i=structuredClone(n);return bn({animationType:i.type,animationId:e,animationPath:o}),delete i.name,delete i.playback,i.id=e,i.targetId=t,r&&(i.playback=structuredClone(r)),i},gs=(e,{animationId:t="animation",animationPath:n="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return bn({animationType:e.type,animationId:t,animationPath:n}),e.type},ys=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},bs=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},Is=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),kr=e=>e?.playback?.continuity==="persistent",fn=e=>Array.isArray(e)?e.map(fn):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((t,n)=>(t[n]=fn(e[n]),t),{}),It=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let t=structuredClone(e);return delete t.playback,JSON.stringify(fn(t))},Pr=(e=[])=>e.filter(t=>kr(t)).map(t=>structuredClone(t)),Tr=e=>Array.isArray(e?.keyframes)?e.keyframes.reduce((t,n)=>{let r=typeof n?.duration=="number"&&Number.isFinite(n.duration)?n.duration:0;return t+r},0):0,sn=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((t,n)=>Math.max(t,Tr(n)),0),Nr=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max(sn(e.tween),sn(e.prev?.tween),sn(e.next?.tween),Tr(e.mask?.progress)),Er=({animationInstances:e,activePersistentAnimations:t})=>{if(!Array.isArray(e)||e.length===0||!Array.isArray(t)||t.length===0)return!1;let n=new Set(t.map(It).filter(Boolean));return e.some(r=>{if(!kr(r))return!1;let o=It(r);return o?n.has(o):!1})},ue=({animationInstances:e,isLineCompleted:t,skipTransitionsAndAnimations:n,activePersistentAnimations:r,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||n?!1:i&&!t||Er({animationInstances:e,activePersistentAnimations:r})?!0:i?!1:Er({animationInstances:e,activePersistentAnimations:o}),ws=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),As=(e,t)=>{if(ws(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},Es=({resources:e,animationId:t,playback:n,instanceId:r,targetId:o,animationPath:i="animation"})=>{if(!t||!o)return!1;let s=e?.animations?.[t];return s?ms({id:r,targetId:o,animation:s,playback:n,animationPath:i}):null},xs=({hasPrevious:e,hasCurrent:t,previousResourceId:n,currentResourceId:r,sharedTarget:o})=>!e&&t?"enter":e&&!t?"exit":e&&t?n===r&&o?"update":"replace":"none",vs=({animationType:e,animationId:t,animationPath:n,lifecycle:r})=>{if(!(e!=="update"||r==="update"))throw new Error(`[${n}] Animation "${t}" has type "update", but update animations can only be used when the same target persists across the state change. Use type "transition" for enter, exit, and replace.`)},Cs=(e,{defaultTargetId:t,defaultId:n,animationPath:r="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return bn({animationType:o.type,animationId:o.id??n,animationPath:r}),o.id??=n,o.targetId??=t,o},In=({animations:e,transitions:t,defaultTargetId:n,idPrefix:r,animationPathPrefix:o=r})=>{t.forEach((i,s)=>{e.push(Cs(i,{defaultTargetId:n,defaultId:`${r}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},dn=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let n=Z(e,t);return n&&typeof n=="object"?e:n},pn=(e,t)=>{if(e===void 0)return[];if(!Array.isArray(e)||e.some(n=>n===null||typeof n!="object"||Array.isArray(n)))throw new Error(`${t} must be an array of objects`);return e},Ss=({content:e,path:t,variables:n})=>pn(e,t).reduce((r,o)=>{let i=dn(o.text,{variables:n});return r+`${i??""}`.length},0),xr=(e=[])=>{let t=new Map;for(let n of e)n?.id&&t.set(n.id,(t.get(n.id)??0)+1);return new Set(Array.from(t.entries()).filter(([,n])=>n>1).map(([n])=>n))},gt=(e,t=0,n=new Set)=>{if(!n.has(e?.id))return`character-container-${e.id}`;let r=e?.sprites?.map(({resourceId:o})=>o)||[];return r.length===0?`character-container-${e.id}`:`character-container-${e.id}-${t}-${r.join("-")}`},an=(e,t)=>{if(!t.transformId)throw new Error(`Visual item "${t.id}" requires transformId`);let n=e.transforms?.[t.transformId];if(!n)throw new Error(`Transform "${t.transformId}" not found for visual item "${t.id}"`);return n},_s=(e,t={})=>{if(!t?.transformId)return;let n=e.transforms?.[t.transformId];if(!n)throw new Error(`Transform "${t.transformId}" not found for background`);return n},vr=(e={},t)=>{if(t){if(e.images?.[t])return"sprite";if(e.videos?.[t])return"video";if(e.layouts?.[t])return"container"}},yt=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},$s=(e={})=>e.textStyles||{},Rs=(e={})=>e.images||{},Os=(e={})=>e.colors||{},Ls=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,He=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,Ve=(e,t,n)=>{if(typeof e!="string"||e.length===0)throw new Error(`${n} at "${t}" must resolve to a non-empty string`)},Cr=(e,t,n)=>{if(e===void 0)return 1;if(typeof e!="number"||!Number.isFinite(e))throw new Error(`${t} for text style "${n}" must be a number between 0 and 1`);if(e<0||e>1)throw new Error(`${t} for text style "${n}" must be a number between 0 and 1`);return e},Dr=(e,t)=>{if(typeof e!="string"||!Ls.test(e))throw new Error(`${t} must resolve to a hex color`);return e.length===4?`#${e.slice(1).split("").map(n=>n.repeat(2)).join("")}`:e},Sr=(e,t,n)=>{let r=Dr(e,n);if(t===1)return r;let o=Number.parseInt(r.slice(1,3),16),i=Number.parseInt(r.slice(3,5),16),s=Number.parseInt(r.slice(5,7),16);return`rgba(${o}, ${i}, ${s}, ${t})`},ks=(e={},t)=>{let n=$s(e)?.[t];if(!n)throw new Error(`Text style "${t}" not found`);let r=e.fonts?.[n.fontId];if(!r)throw new Error(`Font "${n.fontId}" not found for text style "${t}"`);let o=e.colors?.[n.colorId];if(!o)throw new Error(`Color "${n.colorId}" not found for text style "${t}"`);let i=Cr(n.colorAlpha,"colorAlpha",t),s={fontFamily:r.fileId,fontSize:n.fontSize??16,fontWeight:n.fontWeight??"400",fontStyle:n.fontStyle??"normal",lineHeight:n.lineHeight??1.2,fill:Sr(o.hex,i,`Color "${n.colorId}" for text style "${t}"`)};if(n.align!==void 0&&(s.align=n.align),n.wordWrap!==void 0&&(s.wordWrap=n.wordWrap),n.breakWords!==void 0&&(s.breakWords=n.breakWords),n.wordWrapWidth!==void 0&&(s.wordWrapWidth=n.wordWrapWidth),n.strokeColorId){let a=e.colors?.[n.strokeColorId];if(!a)throw new Error(`Stroke color "${n.strokeColorId}" not found for text style "${t}"`);let c=Cr(n.strokeAlpha,"strokeAlpha",t);s.strokeColor=Sr(a.hex,c,`Stroke color "${n.strokeColorId}" for text style "${t}"`)}else if(n.strokeAlpha!==void 0)throw new Error(`strokeAlpha for text style "${t}" requires strokeColorId`);return n.strokeWidth!==void 0&&(s.strokeWidth=n.strokeWidth),s},hn=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>hn(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(Object.prototype.hasOwnProperty.call(e,"textStyle"))throw new Error(`Inline textStyle is not allowed in layout elements at "${n}". Use textStyleId instead`);let r={};for(let[o,i]of Object.entries(e))o!=="textStyleId"&&(r[o]=hn(i,t,He(n,o)));return e.textStyleId!==void 0&&(Ve(e.textStyleId,n,"textStyleId"),r.textStyle=ks(t,e.textStyleId)),r},Vr=(e={},t)=>{let n=Os(e)?.[t];if(!n)throw new Error(`Color "${t}" not found`);return Dr(n.hex,`Color "${t}"`)},jr=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",cn=(e,t,n)=>{let r=e?.[t];if(!(!r||typeof r!="object"||Array.isArray(r))&&Object.prototype.hasOwnProperty.call(r,"fill"))throw new Error(`Inline ${t}.fill is not allowed in rect layout elements at "${n}". Use ${jr(`${t}.fill`)} instead`)},Ps=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>Je(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;let r={};for(let[o,i]of Object.entries(e))o!=="colorId"&&(r[o]=Je(i,t,He(n,o)));return e.colorId!==void 0&&(Ve(e.colorId,n,"colorId"),r.fill=Vr(t,e.colorId)),r},Je=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>Je(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="rect"){if(Object.prototype.hasOwnProperty.call(e,"fill"))throw new Error(`Inline fill is not allowed in rect layout elements at "${n}". Use ${jr("fill")} instead`);cn(e,"hover",n),cn(e,"click",n),cn(e,"rightClick",n)}let r={};for(let[o,i]of Object.entries(e))if(!(e.type==="rect"&&o==="colorId")){if(e.type==="rect"&&(o==="hover"||o==="click"||o==="rightClick")){r[o]=Ps(i,t,He(n,o));continue}r[o]=Je(i,t,He(n,o))}return e.type==="rect"&&e.colorId!==void 0&&(Ve(e.colorId,n,"colorId"),r.fill=Vr(t,e.colorId)),r},ln=(e={},t)=>{let n=Rs(e)?.[t];return n||null},Mr=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",_r=(e,t,n,r)=>{let o=e?.[t];if(!(!o||typeof o!="object"||Array.isArray(o))&&Object.prototype.hasOwnProperty.call(o,r))throw new Error(`Inline ${t}.${r} is not allowed in sprite layout elements at "${n}". Use ${Mr(`${t}.${r}`)} instead`)},$r=(e,t,n)=>{let r=e[t];e[t]={...r&&typeof r=="object"&&!Array.isArray(r)?r:{},src:n}},mn=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>mn(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="sprite"){for(let o of["url","src","hoverUrl","hoverSrc","clickUrl","clickSrc"])if(Object.prototype.hasOwnProperty.call(e,o))throw new Error(`Inline ${o} is not allowed in sprite layout elements at "${n}". Use ${Mr(o)} instead`);_r(e,"hover",n,"src"),_r(e,"click",n,"src")}let r={};for(let[o,i]of Object.entries(e))e.type==="sprite"&&(o==="imageId"||o==="hoverImageId"||o==="clickImageId")||(r[o]=mn(i,t,He(n,o)));if(e.type==="sprite"&&e.imageId!==void 0){Ve(e.imageId,n,"imageId");let o=ln(t,e.imageId),i=o?.fileId??e.imageId;r.src=i,r.width===void 0&&o?.width!==void 0&&(r.width=o.width),r.height===void 0&&o?.height!==void 0&&(r.height=o.height)}return e.type==="sprite"&&e.hoverImageId!==void 0&&(Ve(e.hoverImageId,n,"hoverImageId"),$r(r,"hover",ln(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(Ve(e.clickImageId,n,"clickImageId"),$r(r,"click",ln(t,e.clickImageId)?.fileId??e.clickImageId)),r},wn=(e,t={},n="root")=>mn(Je(hn(e,t,n),t,n),t,n),ve=wn,Ke=(e=[])=>e.find(t=>t.id==="story");var Ts=(e={})=>e?.muteAll?0:e?.musicVolume??50,ae=({variables:e,runtime:t,saveSlots:n=[],dialogueState:r,includeInactiveAdvDialogue:o=!1,isLineCompleted:i,autoMode:s,skipMode:a,isChoiceVisible:c,canRollback:l,confirmDialog:u,historyDialogue:f=[],characters:d={},dialogueUIHidden:p,skipOnlyViewedLines:h,skipTransitionsAndAnimations:y}={})=>{let I={dialogueTextSpeed:t?.dialogueTextSpeed??50,autoForwardDelay:t?.autoForwardDelay??1e3,skipUnseenText:t?.skipUnseenText??!1,skipTransitionsAndAnimations:t?.skipTransitionsAndAnimations??!1,soundVolume:t?.soundVolume??50,musicVolume:t?.musicVolume??50,muteAll:t?.muteAll??!1,saveLoadPagination:t?.saveLoadPagination??1,menuPage:t?.menuPage??"",menuEntryPoint:t?.menuEntryPoint??"",autoMode:t?.autoMode??s??!1,skipMode:t?.skipMode??a??!1,dialogueUIHidden:t?.dialogueUIHidden??p??!1,isLineCompleted:t?.isLineCompleted??i??!1},b=js({dialogueState:r,includeInactiveAdvDialogue:o,characters:d,variables:e}),g={variables:e,runtime:I,saveSlots:n,isChoiceVisible:c,canRollback:l,confirmDialog:u,historyDialogue:f,characters:d};return b&&(g.dialogue=b,g.dialogueLines=b.lines),g},Rr=100,wt=(e,t)=>{if(Array.isArray(e))return e.map(r=>wt(r,t));if(!e||typeof e!="object")return e;let n={...e};return Object.keys(n).forEach(r=>{n[r]=wt(n[r],t)}),n.type==="text-revealing"?t(n):n},Ns=e=>wt(e,t=>({...t,revealEffect:"none"})),Ds=e=>wt(e,t=>{let n=Number(t.speed??t.displaySpeed),r=Number.isFinite(n)?Math.max(n,Rr):Rr;return{...t,speed:r,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:r}:{}}}),Ce=(e,{isLineCompleted:t=!1,skipMode:n=!1,skipTransitionsAndAnimations:r=!1}={})=>t||r?Ns(e):n?Ds(e):e,Br=({id:e,screen:t={width:1920,height:1080}})=>({id:e,type:"rect",fill:"transparent",width:t.width,height:t.height,x:0,y:0,click:{payload:{actions:{}}}}),gn=e=>{if(Array.isArray(e))return e.map(gn);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=gn(s);let n=t.click?.payload;if(!n||typeof n!="object"||Array.isArray(n))return t;let r=n.actions,o=r&&typeof r=="object"&&!Array.isArray(r)&&Object.prototype.hasOwnProperty.call(r,"nextLine")?{...r.nextLine,_interactionSource:"choice"}:void 0;return{...t,click:{...t.click,payload:{...n,_interactionSource:"choice",...o?{actions:{...r,nextLine:o}}:{}}}}},yn=({characterId:e,character:t,characterName:n,characters:r={}}={})=>{let o=e?r?.[e]:void 0,i=t?.name!==void 0?t.name:n!==void 0?n:o?.name||"";return{...o||{},...t||{},name:i}},Ur=(e=[],t={})=>e.map(n=>{let r=yn({characterId:n.characterId,character:n.character,characterName:n.characterName,characters:t}),o=typeof n.text=="string"?n.text:Array.isArray(n.content)?n.content.map(i=>i?.text??"").join(""):"";return{...n,text:o,character:r,characterName:r.name}}),Vs=e=>!(!e||e.mode==="adv"&&e.content===void 0),js=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:n={},variables:r}={})=>{if(!t&&!Vs(e))return;let o=e.content===void 0?[{text:""}]:pn(e.content,"dialogue.content"),i=e.content===void 0?0:Ss({content:e.initialRevealedContent,path:"dialogue.initialRevealedContent",variables:r}),s=(e.lines||[]).map((c,l)=>{let u=pn(c.content,`dialogue.lines[${l}].content`),f=yn({characterId:c.characterId,character:c.character,characterName:c.characterName,characters:n});return{...c,content:u.map(d=>({...d,text:dn(d.text,{variables:r})})),character:f,characterName:f.name}}),a=yn({characterId:e.characterId,character:e.character,characters:n});return{characterId:e.characterId,persistCharacter:e.persistCharacter,character:a,content:o.map(c=>({...c,text:dn(c.text,{variables:r})})),initialRevealedCharacters:i,lines:s}},Fr=({container:e,resources:t,templateData:n,isLineCompleted:r=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=Z(e,n,{functions:xe});return ve(Ce(s,{isLineCompleted:r,skipMode:o,skipTransitionsAndAnimations:i}),t)},un=(e,t={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(t),Or=({renderStateKeyboard:e,keyboard:t,phase:n})=>{!t||typeof t!="object"||Array.isArray(t)||Object.entries(t).forEach(([r,o])=>{let i=e[r]??{},s=n==="keydown"?o?.keydown:o?.keyup;if(n==="keydown"&&s&&typeof s=="object"){e[r]={...i,keydown:{payload:un(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[r].keyup={payload:un(o.keyup)});return}e[r]={...i,[n]:{payload:un(o)}}})},Ms=(e={},t={})=>{let n={};return Or({renderStateKeyboard:n,keyboard:e,phase:"keydown"}),Or({renderStateKeyboard:n,keyboard:t,phase:"keyup"}),Object.keys(n).length>0?n:void 0},Se=({animationsDef:e,resources:t,previousResourceId:n,currentResourceId:r,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:a,allowIncomingUpdateFallback:c=!1})=>{if(!e)return[];let l=[],u=({instanceId:C,targetId:O})=>{let L=Es({resources:t,animationId:y,playback:I,instanceId:C,targetId:O,animationPath:s});L&&l.push(L)},f=n!=null&&n!==!1,d=r!=null&&r!==!1,p=o&&i&&o===i,h=xs({hasPrevious:f,hasCurrent:d,previousResourceId:n,currentResourceId:r,sharedTarget:p});As(e,s);let y=ys(e),I=bs(e),b=t?.animations?.[y],g=gs(b,{animationId:y,animationPath:s}),x=c&&g==="update"&&h!=="update"&&d&&i;if(x||vs({animationType:g,animationId:y,animationPath:s,lifecycle:h}),g==="update")return f&&d&&n===r&&p?u({instanceId:`${a}-animation-update`,targetId:i}):x&&u({instanceId:`${a}-animation-update`,targetId:i}),l;if(g==="transition"){let C=`${a}-animation-transition`,O=I?.continuity==="persistent"?C:`${a}-animation-in`;if(f&&d&&p)return u({instanceId:C,targetId:i}),l;f&&u({instanceId:`${a}-animation-out`,targetId:o}),d&&u({instanceId:O,targetId:i})}return l},Bs=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),Us=(e,{presentationState:t,previousPresentationState:n,currentLineActions:r,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:a,variables:c,runtime:l,activePersistentAnimations:u,restoredPersistentAnimations:f,autoMode:d,skipMode:p,isChoiceVisible:h,canRollback:y,saveSlots:I=[]})=>{let{elements:b,animations:g}=e;if(t.background){let x=r===void 0?!0:Is(r?.background??{},"animations"),C=b.find(P=>P.id==="story");if(!C)return e;let O=_s(o,t.background),L=n?.background?.resourceId,_=t.background.resourceId??(t.background.animations?L:void 0),D=vr(o,L),N=vr(o,_);if(_){let{images:P={},videos:E={}}=o,S=P[_]||E[_];if(S){let M=E[_]!==void 0,z={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...O},q={id:yt({resourceId:_,kind:M?"video":"sprite"}),type:M?"video":"sprite",x:z.x,y:z.y,src:S.fileId,width:S.width,height:S.height,alpha:1,anchorX:z.anchorX,anchorY:z.anchorY,rotation:z.rotation,scaleX:z.scaleX,scaleY:z.scaleY};M&&(q.loop=t.background.loop??!1,q.volume=S.volume??50),C.children.push(q)}}if(_){let{layouts:P={}}=o,E=P[_];if(E){let S={id:yt({resourceId:_,kind:"container"}),type:"container",children:E.elements};O&&Object.assign(S,{x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...O});let M=Z(S,ae({variables:c,runtime:l,saveSlots:I,dialogueState:t.dialogue,isLineCompleted:s,autoMode:d,skipMode:p,isChoiceVisible:h,canRollback:y,characters:o.characters||{},skipTransitionsAndAnimations:a}),{functions:xe});C.children.push(ve(Ce(M,{isLineCompleted:s,skipMode:p,skipTransitionsAndAnimations:a}),o))}}let k=Se({animationsDef:t.background.animations,resources:o,previousResourceId:L,currentResourceId:_,previousTargetId:yt({resourceId:L,kind:D}),currentTargetId:yt({resourceId:_,kind:N}),animationPath:"background.animations",idPrefix:"bg-cg",allowIncomingUpdateFallback:!0});ue({animationInstances:k,isLineCompleted:s,skipTransitionsAndAnimations:a,activePersistentAnimations:u,restoredPersistentAnimations:f,isAuthoredOnCurrentLine:x})&&g.push(...k)}return e},Fs=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:a,animations:c}=e;if(t.character&&r){let l=a.find(h=>h.id==="story");if(!l)return e;let u=t.character.items||[],f=n?.character?.items||[],d=xr(u),p=xr(f);for(let h=0;h<u.length;h++){let y=u[h],{transformId:I,sprites:b}=y,g=f.find(P=>P.id===y.id),x=f.findIndex(P=>P.id===y.id),C=g?.sprites&&g.sprites.length>0,O=b&&b.length>0,L=x>=0?gt(g,x,p):void 0,_=Se({animationsDef:y.animations,resources:r,previousResourceId:L,currentResourceId:O?gt(y,h,d):void 0,previousTargetId:L,currentTargetId:O?gt(y,h,d):void 0,animationPath:`character.items[${h}].animations`,idPrefix:"character"});if(y.animations&&!b&&!I&&C&&ue({animationInstances:_,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){c.push(..._);continue}if(y.animations&&!b&&!I)continue;if(!b||b.length===0||!I){console.warn("Character item missing sprites or transformId:",y);continue}let D=gt(y,h,d),N=r.transforms[I];if(!N){console.warn("Transform not found:",I);continue}let k={type:"container",id:D,x:y.x??N.x,y:y.y??N.y,anchorX:N.anchorX,anchorY:N.anchorY,rotation:N.rotation,scaleX:N.scaleX,scaleY:N.scaleY,children:[]};for(let P of b){let E=r.images[P.resourceId];if(!E){console.warn(`Image resource not found: ${P.resourceId}`);continue}k.children.push({type:"sprite",id:`${D}-${P.id}`,src:E.fileId,width:E.width,height:E.height,x:0,y:0})}l.children.push(k),ue({animationInstances:_,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(..._)}}return e},zs=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,runtime:a,activePersistentAnimations:c,autoMode:l,skipMode:u,isChoiceVisible:f,canRollback:d,saveSlots:p=[]})=>{let{elements:h,animations:y}=e;if(t.visual&&r){let I=h.find(g=>g.id==="story");if(!I)return e;let b=t.visual.items;for(let g of b){if(g.resourceId){let{images:L={},videos:_={},spritesheets:D={}}=r,N=D[g.resourceId];if(N){let k=an(r,g),P=g.animationName;if(P){let E=N.animations?.[P];if(!E)throw new Error(`Animation '${P}' not found in spritesheet resource '${g.resourceId}'`);let S={id:`visual-${g.id}`,type:"animated-sprite",x:g.x??k.x,y:g.y??k.y,width:g.width??N.width,height:g.height??N.height,alpha:g.alpha??1,anchorX:k.anchorX,anchorY:k.anchorY,rotation:k.rotation,scaleX:k.scaleX,scaleY:k.scaleY,spritesheetSrc:N.fileId,spritesheetData:N.jsonData,animation:{frames:E.frames,animationSpeed:g.animationSpeed??E.animationSpeed??.5,loop:g.loop??E.loop??!0}};I.children.push(structuredClone(S))}}else{let k=L[g.resourceId]||_[g.resourceId];if(k){let P=_[g.resourceId]!==void 0,E=an(r,g),S={id:`visual-${g.id}`,type:P?"video":"sprite",src:k.fileId,width:k.width,height:k.height,x:E.x,y:E.y,anchorX:E.anchorX,anchorY:E.anchorY,rotation:E.rotation,scaleX:E.scaleX,scaleY:E.scaleY};P&&(S.loop=k.loop??!1,S.volume=k.volume??50),I.children.push(S)}}}if(g.resourceId){let{layouts:L={}}=r,_=L[g.resourceId];if(_){let D=an(r,g),N={id:`visual-${g.id}`,type:"container",children:structuredClone(_.elements),x:D.x,y:D.y,anchorX:D.anchorX,anchorY:D.anchorY,rotation:D.rotation,scaleX:D.scaleX,scaleY:D.scaleY},k=Z(N,ae({variables:s,runtime:a,saveSlots:p,dialogueState:t.dialogue,isLineCompleted:o,autoMode:l,skipMode:u,isChoiceVisible:f,canRollback:d,characters:r.characters||{},skipTransitionsAndAnimations:i}),{functions:xe});I.children.push(ve(Ce(k,{isLineCompleted:o,skipMode:u,skipTransitionsAndAnimations:i}),r))}}let C=(n?.visual?.items||[]).find(L=>L.id===g.id),O=Se({animationsDef:g.animations,resources:r,previousResourceId:C?.resourceId,currentResourceId:g.resourceId,previousTargetId:C?.resourceId?`visual-${g.id}`:void 0,currentTargetId:g.resourceId?`visual-${g.id}`:void 0,animationPath:`visual.items[${g.id}].animations`,idPrefix:g.id});ue({animationInstances:O,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:c})&&y.push(...O)}}return e},De="dialogue-character-sprite",Lr=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,Ws=(e,{presentationState:t,previousPresentationState:n,resources:r={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:a}=e,c=Ke(e.elements);if(!c)return e;let l=t.dialogue?.character?.sprite,u=n?.dialogue?.character?.sprite,f=Lr(l),d=Lr(u),p=Se({animationsDef:l?.animations,resources:r,previousResourceId:d?De:void 0,currentResourceId:f?De:void 0,previousTargetId:d?De:void 0,currentTargetId:f?De:void 0,animationPath:"dialogue.character.sprite.animations",idPrefix:"dialogue-character-sprite"});if(!f)return l?.animations&&d&&ue({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...p),e;let h=r.transforms?.[l.transformId];if(!h)return console.warn("Transform not found:",l.transformId),e;let y={type:"container",id:De,x:h.x,y:h.y,anchorX:h.anchorX,anchorY:h.anchorY,rotation:h.rotation,scaleX:h.scaleX,scaleY:h.scaleY,children:[]};for(let I of l.items){let b=r.images?.[I.resourceId];if(!b){console.warn(`Image resource not found: ${I.resourceId}`);continue}y.children.push({type:"sprite",id:`${De}-${I.id}`,src:b.fileId,width:b.width,height:b.height,x:0,y:0})}return c.children.push(y),ue({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...p),e},qs=(e,{presentationState:t,previousPresentationState:n,resources:r={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:c,skipOnlyViewedLines:l,isLineCompleted:u,skipTransitionsAndAnimations:f,variables:d,runtime:p,activePersistentAnimations:h,saveSlots:y=[]})=>{let{elements:I,animations:b}=e;if(!t.dialogue||o)return e;let g=I.find(C=>C.id==="story");if(!g)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:C={}}=r,O=C[t.dialogue.ui.resourceId];if(O){let L={elements:O.elements},_=ae({variables:d,runtime:p,saveSlots:y,dialogueState:t.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:u,autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:c,characters:r.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:l,skipTransitionsAndAnimations:f}),D={functions:xe},N=bt(L,_,D),k=Z(N,_,D),P=ve(Ce(k?.elements,{isLineCompleted:u,skipMode:s,skipTransitionsAndAnimations:f}),r);if(Array.isArray(P))for(let E of P)g.children.push(E);else P&&g.children.push(P)}}Ws(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:u,skipTransitionsAndAnimations:f,activePersistentAnimations:h});let x=Se({animationsDef:t.dialogue.ui?.animations,resources:r,previousResourceId:n?.dialogue?.ui?.resourceId,currentResourceId:t.dialogue.ui?.resourceId,previousTargetId:n?.dialogue?.ui?.resourceId?"dialogue-container":void 0,currentTargetId:t.dialogue.ui?.resourceId?"dialogue-container":void 0,animationPath:"dialogue.ui.animations",idPrefix:"dialogue-ui"});return ue({animationInstances:x,isLineCompleted:u,skipTransitionsAndAnimations:f,activePersistentAnimations:h})&&b.push(...x),e},Ys=(e,{presentationState:t,previousPresentationState:n,resources:r,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:a,runtime:c,autoMode:l,skipMode:u,isChoiceVisible:f,canRollback:d,activePersistentAnimations:p,saveSlots:h=[]})=>{let{elements:y,animations:I}=e;if(t.choice&&r){let b=Ke(y);if(!b)return e;let g=r?.layouts[t.choice.resourceId];if(g&&g.elements){let C={elements:g.elements},O=Z(C,{...ae({variables:a,runtime:c,saveSlots:h,dialogueState:t.dialogue,isLineCompleted:i,autoMode:l,skipMode:u,isChoiceVisible:f??!!t.choice,canRollback:d,characters:r.characters||{},skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}},{functions:xe}),L=gn(ve(Ce(O?.elements,{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),r));if(Array.isArray(L))for(let _ of L)b.children.push(_);else L&&b.children.push(L)}let x=Se({animationsDef:t.choice.animations,resources:r,previousResourceId:n?.choice?.resourceId,currentResourceId:t.choice.resourceId,previousTargetId:n?.choice?.resourceId?"choice-container":void 0,currentTargetId:t.choice.resourceId?"choice-container":void 0,animationPath:"choice.animations",idPrefix:"choice"});ue({animationInstances:x,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:p})&&I.push(...x)}return e},Hs=(e,{presentationState:t,resources:n={},variables:r,runtime:o,isLineCompleted:i,autoMode:s,skipMode:a,isChoiceVisible:c,canRollback:l,saveSlots:u=[],skipTransitionsAndAnimations:f})=>{if(!t.control?.resourceId)return e;let d=n.controls?.[t.control.resourceId];if(!d)return e;let p=Ms(d.keyboard,d.keyup);if(p&&Object.keys(p).length>0&&(e.global.keyboard=p),!Array.isArray(d.elements)||d.elements.length===0)return e;let h=Ke(e.elements);if(!h)return e;let y={id:`control-${t.control.resourceId}`,type:"container",x:0,y:0,children:d.elements};return h.children.push(Fr({container:y,resources:n,templateData:ae({variables:r,runtime:o,saveSlots:u,dialogueState:t.dialogue,isLineCompleted:i,autoMode:s,skipMode:a,isChoiceVisible:c,canRollback:l,characters:n.characters||{},skipTransitionsAndAnimations:f}),isLineCompleted:i,skipMode:a,skipTransitionsAndAnimations:f})),e},Js=(e,{presentationState:t,resources:n,runtime:r,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&n){if(!Ke(i))return e;let c=n.sounds[t.bgm.resourceId];if(!c)return e;let l=ae({variables:o,runtime:r}).runtime;s.push({id:"bgm",type:"sound",src:c.fileId,loop:t.bgm.loop??!0,volume:Ts(l),startDelayMs:t.bgm.startDelayMs??null})}return e},Ks=(e,{presentationState:t,resources:n})=>{let{audio:r}=e;if(t.sfx&&n){let o=t.sfx.items;for(let i of o){let s=n.sounds?.[i.resourceId];s&&r.push({id:i.id,type:"sound",src:s.fileId,loop:i.loop??s.loop??!1,volume:i.volume??s.volume??50,startDelayMs:i.startDelayMs??s.startDelayMs??null})}}return e},Gs=(e,t,n)=>{if(!(!t||!n))return e?.voices?.[t]?.[n]},Xs=(e={},t={})=>t.muteAll?0:e.volume??t.soundVolume??50,Qs=(e,{presentationState:t,resources:n,currentSceneId:r,runtime:o,variables:i})=>{let{audio:s}=e;if(!t?.voice)return e;let a=t.voice,{resourceId:c,loop:l,startDelayMs:u}=a,f=Gs(n,r,c);if(!f)return e;let d=ae({variables:i,runtime:o}).runtime;return s.push({id:`voice-${r}-${c}`,type:"sound",src:f.fileId,volume:Xs(a,d),loop:l??!1,startDelayMs:u??null}),e},Zs=(e,{presentationState:t,previousPresentationState:n,resources:r={},variables:o,runtime:i,autoMode:s,skipMode:a,isChoiceVisible:c,canRollback:l,saveSlots:u=[],isLineCompleted:f,skipTransitionsAndAnimations:d,activePersistentAnimations:p})=>{let{elements:h,animations:y}=e;if(t.layout){let x=Ke(h);if(!x)return e;let C=r.layouts[t.layout.resourceId];if(!C)return e;Array.isArray(C.transitions)&&!f&&!d&&In({animations:y,transitions:C.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let O={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:C.elements||[]};x.children.push(Fr({container:O,resources:r,templateData:ae({variables:o,runtime:i,saveSlots:u,dialogueState:t.dialogue,isLineCompleted:f,autoMode:s,skipMode:a,isChoiceVisible:c,canRollback:l,characters:r.characters||{},skipTransitionsAndAnimations:d}),isLineCompleted:f,skipMode:a,skipTransitionsAndAnimations:d}))}let I=n?.layout?.resourceId,b=t.layout?.resourceId,g=Se({animationsDef:t.layout?.animations,resources:r,previousResourceId:I,currentResourceId:b,previousTargetId:I?`layout-${I}`:void 0,currentTargetId:b?`layout-${b}`:void 0,animationPath:"layout.animations",idPrefix:"layout"});return ue({animationInstances:g,isLineCompleted:f,skipTransitionsAndAnimations:d,activePersistentAnimations:p})&&y.push(...g),e},ea=(e,{presentationState:t,resources:n={},variables:r,runtime:o,autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:c,overlayStack:l=[],dialogueHistory:u=[],saveSlots:f=[],screen:d,isLineCompleted:p,skipTransitionsAndAnimations:h})=>{let{elements:y,animations:I}=e;return l&&l.length>0&&l.forEach((b,g)=>{let x=n.layouts[b.resourceId];if(!x){console.warn(`Overlay layout not found: ${b.resourceId}`);return}Array.isArray(x.transitions)&&(h||In({animations:I,transitions:x.transitions,defaultTargetId:`overlayStack-${g}`,idPrefix:`overlayStack-${g}`,animationPathPrefix:`overlayStack[${g}]`}));let C={id:`overlayStack-${g}`,type:"container",x:0,y:0,children:[Br({id:`overlayStack-${g}-blocker`,screen:d}),...x.elements||[]]},O=Ur(u,n.characters),L=ae({variables:r,runtime:o,saveSlots:f,dialogueState:t?.dialogue,isLineCompleted:p,autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:c,historyDialogue:O,characters:n.characters||{},skipTransitionsAndAnimations:h}),_=Z(C,L,{functions:xe}),[D,...N]=_.children||[],k=ve(Ce({..._,children:N},{isLineCompleted:p,skipMode:s,skipTransitionsAndAnimations:h}),n);y.push({...k,children:D?[D,...k.children||[]]:k.children})}),e},ta=(e,{presentationState:t,resources:n={},variables:r,runtime:o,saveSlots:i=[],autoMode:s,skipMode:a,isChoiceVisible:c,canRollback:l,confirmDialog:u,dialogueHistory:f=[],screen:d,isLineCompleted:p,skipTransitionsAndAnimations:h})=>{let{elements:y,animations:I}=e;if(!u?.resourceId)return e;let b=n.layouts?.[u.resourceId];if(!b)return console.warn(`ConfirmDialog layout not found: ${u.resourceId}`),e;Array.isArray(b.transitions)&&!h&&In({animations:I,transitions:b.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let g={id:"confirmDialog",type:"container",x:0,y:0,children:[Br({id:"confirmDialog-blocker",screen:d}),...b.elements||[]]},x=Ur(f,n.characters),C=Z(g,ae({variables:r,runtime:o,saveSlots:i,dialogueState:t?.dialogue,isLineCompleted:p,autoMode:s,skipMode:a,isChoiceVisible:c,canRollback:l,confirmDialog:u,historyDialogue:x,characters:n.characters||{},skipTransitionsAndAnimations:h}),{functions:xe}),[O,...L]=C.children||[],_=ve(Ce({...C,children:L},{isLineCompleted:p,skipMode:a,skipTransitionsAndAnimations:h}),n);return y.push({..._,children:O?[O,..._.children||[]]:_.children}),e},zr=e=>pt(Bs,[Hs,Us,Fs,zs,qs,Ys,Zs,Js,Ks,Qs,ea,ta])(e);var na=Object.freeze({dialogueTextSpeed:{source:"global.dialogueTextSpeed"},autoForwardDelay:{source:"global.autoForwardDelay"},skipUnseenText:{source:"global.skipUnseenText"},skipTransitionsAndAnimations:{source:"global.skipTransitionsAndAnimations"},soundVolume:{source:"global.soundVolume"},musicVolume:{source:"global.musicVolume"},muteAll:{source:"global.muteAll"},saveLoadPagination:{source:"context.runtime.saveLoadPagination"},menuPage:{source:"context.runtime.menuPage"},menuEntryPoint:{source:"context.runtime.menuEntryPoint"},autoMode:{source:"global.autoMode"},skipMode:{source:"global.skipMode"},dialogueUIHidden:{source:"global.dialogueUIHidden"},isLineCompleted:{source:"global.isLineCompleted"}}),At=Object.freeze({dialogueTextSpeed:50,autoForwardDelay:1e3,skipUnseenText:!1,skipTransitionsAndAnimations:!1,soundVolume:50,musicVolume:50,muteAll:!1,autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isLineCompleted:!1}),Ge=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),Wr=Object.freeze({dialogueTextSpeed:"number",autoForwardDelay:"number",skipUnseenText:"boolean",skipTransitionsAndAnimations:"boolean",soundVolume:"number",musicVolume:"number",muteAll:"boolean",saveLoadPagination:"number",menuPage:"string",menuEntryPoint:"string",autoMode:"boolean",skipMode:"boolean",dialogueUIHidden:"boolean",isLineCompleted:"boolean"}),An=Object.freeze(["dialogueTextSpeed","autoForwardDelay","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),En=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),ra=(e,t)=>{if(t.startsWith("global.")){let n=t.slice(7);return e?.global?.[n]}if(t.startsWith("context.runtime.")){let n=t.slice(16),r=Array.isArray(e?.contexts)?e.contexts:[];return r[r.length-1]?.runtime?.[n]}},je=e=>Object.fromEntries(Object.entries(na).map(([t,n])=>{let r=ra(e,n.source),o=r!==void 0?r:At[t]??Ge[t];return[t,o]})),fe=(e,t)=>je(e)[t],qr=(e={})=>Object.fromEntries(An.map(t=>[t,e[t]??At[t]]));var Et={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},Gr=1,vt=()=>({manual:{...Et.manual},auto:{...Et.auto},applyMode:Et.applyMode}),xn=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let n=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...vt()},n&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},F=e=>{let t=ie(e)?ze(e):e;return structuredClone(t)},j=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Ct=e=>String(e),Xr=()=>({sections:[],resources:[]}),oa=e=>j(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):Xr(),ia=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",sa=({sectionId:e,lineId:t,content:n,dialogueState:r,characterName:o})=>({sectionId:e,lineId:t,content:n,text:ia(n),characterId:r.characterId,character:{...r.character||{},name:o},characterName:o}),aa=()=>({resourceId:void 0}),ca=e=>{if(!j(e))return e;let t={...e};return Object.prototype.hasOwnProperty.call(t,"requireComplete")&&!Object.prototype.hasOwnProperty.call(t,"requireLineCompleted")&&(t.requireLineCompleted=t.requireComplete),delete t.requireComplete,t},vn=(e,t)=>{let n=e?.story?.scenes??{};for(let[r,o]of Object.entries(n))if(o?.sections?.[t])return{sceneId:r,section:o.sections[t]};return{sceneId:void 0,section:void 0}},Qr=e=>{let t=e?.story?.scenes??{},n=new Map;for(let[r,o]of Object.entries(t)){let i=o?.sections??{};for(let s of Object.keys(i)){let a=n.get(s);if(a!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${a}" and "${r}". Section IDs must be globally unique.`);n.set(s,r)}}},Zr=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},eo=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==Gr)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},la=(e,t={})=>{let n;try{n=eo(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let r={...t,formatVersion:n,slotId:Zr(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete r.slotKey,delete r.date,r},ua=(e={})=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,la(t,n)])),to=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:n})=>Bc(n));return t.length>0?t:void 0},fa=e=>{!j(e)||!Array.isArray(e.timeline)||e.timeline.forEach(t=>{if(!j(t))return;let n=to(t.executedActions);if(n){t.executedActions=n;return}delete t.executedActions})},Yr=(e,t,n,r="viewedRegistry")=>{let o=t==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[o]:String(e)};if(!j(e))throw new Error(`Malformed ${r}.${t}[${n}] entry.`);if(typeof e[o]!="string"||e[o].length===0)throw new Error(`Malformed ${r}.${t}[${n}] entry: missing ${o}.`);if(t==="sections"){let i={sectionId:e.sectionId};if(e.lastLineId!==void 0&&e.lastLineId!==null&&typeof e.lastLineId!="string")throw new Error(`Malformed ${r}.sections[${n}] entry: invalid lastLineId.`);return typeof e.lastLineId=="string"&&e.lastLineId.length>0&&(i.lastLineId=e.lastLineId),i}return{resourceId:e.resourceId}},da=(e,t="viewedRegistry")=>{if(e===void 0)return Xr();if(!j(e))throw new Error(`Malformed ${t}.`);if(e.sections!==void 0&&!Array.isArray(e.sections))throw new Error(`Malformed ${t}.sections.`);if(e.resources!==void 0&&!Array.isArray(e.resources))throw new Error(`Malformed ${t}.resources.`);let n=e.sections??[],r=e.resources??[];return{sections:Object.values(Object.fromEntries(n.map((o,i)=>{let s=Yr(o,"sections",i,t);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(r.map((o,i)=>{let s=Yr(o,"resources",i,t);return[s.resourceId,s]})))}},no=(e,t,n)=>{if(!j(e))throw new Error(`Malformed save slot ${n}.`);let{sectionId:r,lineId:o}=e;if(typeof r!="string"||r.length===0)throw new Error(`Malformed save slot ${n}: missing sectionId.`);if(typeof o!="string"||o.length===0)throw new Error(`Malformed save slot ${n}: missing lineId.`);let{sceneId:i,section:s}=vn(t,r);if(!s)throw new Error(`Malformed save slot ${n}: section "${r}" does not exist in projectData.`);if(!s.lines?.some(c=>c.id===o))throw new Error(`Malformed save slot ${n}: line "${o}" does not exist in section "${r}".`);return{sceneId:i,sectionId:r,lineId:o}},pa=(e,t,n)=>{if(!j(e)||!Array.isArray(e.timeline))return Xe({pointer:t,replayStartIndex:1});let r=e.timeline.flatMap((a,c)=>{if(!j(a))return[];try{let l=no(a,n,`rollback.timeline[${c}]`),u=xt({sectionId:l.sectionId,lineId:l.lineId,rollbackPolicy:a.rollbackPolicy}),f=to(F(a.executedActions));return f&&(u.executedActions=f),[u]}catch{return[]}});if(r.length===0)return Xe({pointer:t,replayStartIndex:1});let o=typeof e.currentIndex=="number"?Math.trunc(e.currentIndex):r.length-1;(o<0||o>=r.length)&&(o=r.length-1);let i=r[o];if(i?.sectionId!==t.sectionId||i?.lineId!==t.lineId){let a=r.findLastIndex(c=>c.sectionId===t.sectionId&&c.lineId===t.lineId);a>=0?o=a:(r.push(xt({sectionId:t.sectionId,lineId:t.lineId})),o=r.length-1)}let s=typeof e.replayStartIndex=="number"?Math.min(Math.max(Math.trunc(e.replayStartIndex),0),o):0;return{currentIndex:o,isRestoring:!1,replayStartIndex:s,timeline:r}},ha=(e,t,n)=>{if(!j(e))throw new Error(`Malformed save slot contexts[${n}] entry.`);let r=Sn(t),o=no(e.pointers?.read,t,`contexts[${n}].pointers.read`);if(e.variables!==void 0&&!j(e.variables))throw new Error(`Malformed save slot contexts[${n}].variables entry.`);if(e.runtime!==void 0&&!j(e.runtime))throw new Error(`Malformed save slot contexts[${n}].runtime entry.`);let i=e.variables?Pe(F(e.variables),t.resources?.variables??{}):{},s=Ia({loadedContextRuntime:j(e.runtime)?F(e.runtime):{}}),a={currentPointerMode:"read",pointers:{read:o},configuration:j(e.configuration)?F(e.configuration):{},views:Array.isArray(e.views)?F(e.views):[],bgm:j(e.bgm)?F(e.bgm):{resourceId:void 0},variables:{...r,...i},rollback:pa(e.rollback,o,t)};return s&&(a.runtime=s),a},ma=(e,t)=>{if(!j(e))throw new Error("Malformed save slot state.");if(!Array.isArray(e.contexts)||e.contexts.length===0)throw new Error("Malformed save slot state: contexts must be a non-empty array.");return{contexts:e.contexts.map((n,r)=>ha(n,t,r))}},ga=(e,t)=>{if(!j(e))throw new Error("Malformed save slot.");let n=eo(e.formatVersion);return{...e,formatVersion:n,state:ma(e.state,t)}},Hr=(e,t,{required:n=!1}={})=>{if(e===void 0){if(n)throw new Error(`showConfirmDialog requires ${t}`);return{hideConfirmDialog:{}}}if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`showConfirmDialog ${t} must be an action object`);let r=F(e);return Object.prototype.hasOwnProperty.call(r,"hideConfirmDialog")||(r.hideConfirmDialog={}),r},ya=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:Hr(e.confirmActions,"confirmActions",{required:!0}),cancelActions:Hr(e.cancelActions,"cancelActions")}},Me=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},_e=[],Jr="line",Cn="interaction",xt=({sectionId:e,lineId:t,rollbackPolicy:n})=>({sectionId:e,lineId:t,rollbackPolicy:n??"free"}),Sn=e=>{let{contextVariableDefaultValues:t}=Qt(e??{});return F(t)},ro=()=>({...F(Ge)}),oo=({loadedRuntime:e,runtimeIds:t,defaults:n={},path:r})=>{if(e===void 0)return{runtimeState:F(n),hasLoadedValues:!1};if(!j(e))throw new Error(`Malformed ${r}.`);let o=F(n),i=!1;return t.forEach(s=>{e[s]!==void 0&&(o[s]=io(s,F(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},ba=({loadedGlobalRuntime:e={}})=>oo({loadedRuntime:e,runtimeIds:An,defaults:At,path:"global.runtime"}).runtimeState,Ia=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:n}=oo({loadedRuntime:e,runtimeIds:En,defaults:ro(),path:"context.runtime"});return n?t:void 0},_n=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},wa=e=>e.runtime?(En.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=F(Ge[t]))}),e.runtime):(e.runtime=ro(),e.runtime),Aa=e=>qr(e.global),Ea=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:Aa(e)}})},xa=e=>Wr[e],va=(e,t)=>{let n=xa(e);if(n==="number"){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} requires a finite numeric value`);return}if(n==="boolean"){if(typeof t!="boolean")throw new Error(`${e} requires a boolean value`);return}if(n==="string"){if(typeof t!="string")throw new Error(`${e} requires a string value`);return}throw new Error(`Unsupported runtime field "${e}"`)},io=(e,t)=>(va(e,t),e==="saveLoadPagination"?Math.max(1,Math.trunc(t)):t),so=(e,t,n)=>{let r=io(t,n);if(t in Ge){let o=_n(e);if(!o)return r;let i=wa(o);return i[t]=r,r}return e.global[t]=r,r},ao=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:F(e)},configuration:{},views:[],bgm:aa(),variables:Sn(t),rollback:Xe({pointer:e})}),Be=e=>e?(e.currentPointerMode="read",j(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,Ca=e=>{let t=e.contexts?.[e.contexts.length-1],n=t?.pointers?.read;if(!t||!n?.sectionId||!n?.lineId)return null;let r=ao({pointer:n,projectData:e.projectData});return e.contexts[e.contexts.length-1]=r,Sa(e),r},Sa=e=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,Me(e),e.global.nextLineConfig=vt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})},co=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},Xe=({pointer:e,replayStartIndex:t=0})=>{let n=e?.sectionId&&e?.lineId;return{currentIndex:n?0:-1,isRestoring:!1,replayStartIndex:t,timeline:n?[xt({sectionId:e.sectionId,lineId:e.lineId})]:[]}},Re=(e,t={})=>{if(e?.rollback)return co(e.rollback),Array.isArray(e.rollback.timeline)||(e.rollback.timeline=[]),typeof e.rollback.currentIndex!="number"&&(e.rollback.currentIndex=e.rollback.timeline.length>0?e.rollback.timeline.length-1:-1),typeof e.rollback.isRestoring!="boolean"&&(e.rollback.isRestoring=!1),typeof e.rollback.replayStartIndex!="number"&&(e.rollback.replayStartIndex=0),e.rollback;let n=e?.pointers?.read;return e.rollback=Xe({pointer:n,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},$n=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return;let r=Re(n);if(r.isRestoring)return;r.currentIndex<r.timeline.length-1&&(r.timeline=r.timeline.slice(0,r.currentIndex+1));let o=r.timeline[r.timeline.length-1];if(o?.sectionId===t.sectionId&&o?.lineId===t.lineId&&(o?.rollbackPolicy??"free")===(t.rollbackPolicy??"free")){r.currentIndex=r.timeline.length-1;return}r.timeline.push(xt(t)),r.currentIndex=r.timeline.length-1},_a=e=>{let n=e.contexts?.[e.contexts.length-1]?.rollback;if(!n||n.isRestoring||!Array.isArray(n.timeline)||typeof n.currentIndex!="number")return null;let r=_e[_e.length-1],o=typeof r?.checkpointIndex=="number"?r.checkpointIndex:n.currentIndex;return o<0||o>=n.timeline.length?null:(typeof r?.checkpointIndex!="number"&&o<n.timeline.length-1&&(n.timeline=n.timeline.slice(0,o+1)),n.timeline[o]??null)},$a=({state:e},t={})=>{let n=t?.source===Jr?Jr:Cn,o=e.contexts?.[e.contexts.length-1]?.rollback;return!o||o.isRestoring||!Array.isArray(o.timeline)||typeof o.currentIndex!="number"||o.currentIndex<0||o.currentIndex>=o.timeline.length?(_e.push({checkpointIndex:null,source:n}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),_e.push({checkpointIndex:o.currentIndex,source:n}),e)},Ra=({state:e})=>(_e.pop(),e),de=(e,t,n)=>{let o=_e[_e.length-1]?.source??Cn;if(!Uc(t,o))return;let i=_a(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:F(n)}))},Kr=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return;let r=t?.operations??[];for(let{variableId:o,op:i,value:s}of r){let a=e.projectData.resources?.variables?.[o],c=a?.scope,l=a?.type;if(Ee(a))throw new Error(`Cannot update computed variable: ${o}`);if(a?.readonly===!0)throw new Error(`Cannot update readonly variable: ${o}`);Zt(c,o),en(l,i,o),c==="context"&&(n.variables[o]=tn(n.variables[o],i,s))}},Oa=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:n,payload:r})=>{Fc(e,n,r)})},La=(e,t)=>{let{sectionId:n,lineId:r}=t,s=G({state:e},{sectionId:n})?.lines?.find(a=>a.id===r)?.actions;s&&Object.entries(s).forEach(([a,c])=>{_o(e,a,c)})},lo=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return e;let r=Re(n),o=r.timeline[t];if(!o)return e;e.global.autoMode&&Ze({state:e}),e.global.skipMode&&$e({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),r.isRestoring=!0,r.currentIndex=t;try{n.variables=Sn(e.projectData),delete n.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=F(Et),e.global.overlayStack=[],Me(e),e.global.isLineCompleted=!0;let i=r.replayStartIndex??0;for(let a=i;a<=t;a++)a>i&&xn(e),La(e,r.timeline[a]),Oa(e,r.timeline[a]);let s=Be(n);s.read={sectionId:o.sectionId,lineId:o.lineId},e.global.pendingEffects=e.global.pendingEffects.filter(a=>a?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{r.isRestoring=!1}return e},ka=e=>{let{projectData:t}=e,n=e.global??{},{saveSlots:r={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=n;Qr(t);let a=t.story.initialSceneId,c=t.story.scenes[a],l=c.initialSectionId,u=c.sections[l],f={sceneId:a,sectionId:l,lineId:u.initialLineId??u.lines[0].id},{globalVariablesDefaultValues:d}=Qt(t),p={...d,...Pe(o,t.resources?.variables??{})};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,accountViewedRegistry:da(s,"accountViewedRegistry"),nextLineConfig:vt(),saveSlots:ua(r),overlayStack:[],variables:p,...ba({loadedGlobalRuntime:i})},contexts:[ao({pointer:f,projectData:t})]}},Pa=({state:e})=>e.global.overlayStack||[],Ta=({state:e})=>e.global.pendingEffects,uo=({state:e})=>e.global.skipMode,Na=({state:e})=>e.global.autoMode,fo=({state:e})=>e.global.dialogueUIHidden,po=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],n=t[t.length-1];if(!n)return[];let{sectionId:r,lineId:o}=n.pointers.read,i=G({state:e},{sectionId:r});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(u=>u.id===o),a=i.lines.slice(0,s+1),c=[],l={};for(let u of a){let f=u.actions||{};if(l=Ne([l,f]),!f.dialogue)continue;let d=l.dialogue||{},p="";d.character?.name!==void 0?p=d.character.name:d.characterId&&(p=e.projectData.resources?.characters?.[d.characterId]?.name||"");let h=sa({sectionId:r,lineId:u.id,content:f.dialogue.append===!0?d.content:f.dialogue.content,dialogueState:d,characterName:p});if(f.dialogue.append===!0&&c.length>0){c[c.length-1]={...c[c.length-1],content:h.content,text:h.text,characterId:h.characterId,character:h.character,characterName:h.characterName};continue}c.push(h)}return c},Da=({state:e})=>e.global.confirmDialog??null,Va=({state:e,registry:t},n)=>{let{sectionId:r,lineId:o}=n,s=(Array.isArray(t?.sections)?t.sections:[]).find(u=>u.sectionId===r);if(!s)return!1;if(s.lastLineId===void 0||o===void 0)return!0;let a=G({state:e},{sectionId:r});if(!a||!a.lines||!Array.isArray(a.lines))return s.lastLineId===o;let c=a.lines.findIndex(u=>u.id===s.lastLineId),l=a.lines.findIndex(u=>u.id===o);return c===-1||l===-1?s.lastLineId===o:l<=c},ja=({registry:e},t)=>{let{resourceId:n}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===n)},Rn=({state:e},t)=>Va({state:e,registry:e.global.accountViewedRegistry},t),Ma=({state:e},t)=>ja({registry:e.global.accountViewedRegistry},t),Ba=({state:e})=>e.global.nextLineConfig,ho=({state:e,pointer:t}={})=>{let n=t??ce({state:e})?.pointer;if(!n)return;let r=n?.sectionId,o=n?.lineId,s=G({state:e},{sectionId:r})?.lines||[],a=s.findIndex(l=>l.id===o);if(a<0)return;let c;for(let l of s.slice(0,a+1)){let u=l?.actions;if(u?.cleanAll&&(c=void 0),!u||!Object.prototype.hasOwnProperty.call(u,"choice")){c=void 0;continue}let f=u.choice;if(f?.resourceId){c=f.resourceId;continue}f?.animations||(c=void 0)}return c},le=({state:e})=>!!ho({state:e}),Ua=({state:e})=>structuredClone(e),mo=({state:e})=>e.global.saveSlots,Fa=({state:e},t)=>{let n=t?.slotId,r=Ct(n);return e.global.saveSlots[r]},On=({state:e})=>je(e),za=({state:e},t)=>fe(e,t?.runtimeId),go=({state:e})=>{let t={...e.global?.variables??{},..._n(e)?.variables??{}};return ht({variables:t,runtime:je(e),variableConfigs:e.projectData.resources?.variables??{}})},ce=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],n=t[t.length-1];if(n)return{currentPointerMode:"read",pointer:n.pointers?.read}},G=({state:e},t)=>{let{sectionId:n}=t;return vn(e.projectData,n).section},Ln=({state:e})=>{let t=ce({state:e});if(!t?.pointer)return;let{sectionId:n,lineId:r}=t.pointer,o=G({state:e},{sectionId:n});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===r)},yo=({state:e})=>{let{sectionId:t,lineId:n}=ce({state:e}).pointer,o=G({state:e},{sectionId:t})?.lines||[],i=o.findIndex(l=>l.id===n),a=o.slice(0,i+1).map(l=>{let u=l.actions||{},f={};return Object.keys(u).forEach(d=>{f[d]=u[d]}),f});return Ne(a)},Wa=({state:e})=>{let t=bo({state:e}),r=Ln({state:e})?.actions??{},o=Ne([t??{},r]);return nn(t??{},o??{})},qa=({state:e},{sectionId:t})=>{let n=G({state:e},{sectionId:t});if(!n?.lines)return[];let r=[],o={};for(let i of n.lines){let s=i.actions||{},a=Ne([o,s]),c=nn(o,a);r.push({id:i.id,changes:c,presentationState:a}),o=rn(a)}return r},Ya=({state:e},{sectionId:t,includePresentationState:n=!1})=>{let r=qa({state:e},{sectionId:t});return n?{lines:r}:{lines:r.map(({presentationState:o,...i})=>i)}},bo=({state:e})=>{let{sectionId:t,lineId:n}=ce({state:e}).pointer,o=G({state:e},{sectionId:t})?.lines||[],i=o.findIndex(c=>c.id===n);if(i<=0)return null;let a=o.slice(0,i).map(c=>{let l=c.actions||{},u={};return Object.keys(l).forEach(f=>{u[f]=l[f]}),u});return rn(Ne(a))},kn=({state:e},{slotsPerPage:t=6}={})=>{let o=((On({state:e}).saveLoadPagination??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let a=o+s,c=e.global.saveSlots&&e.global.saveSlots[Ct(a)]||{};i.push({...c,slotId:a})}return{saveSlots:i}},Ha=mo,Ja=kn,Ka=e=>{let n=e.contexts?.[e.contexts.length-1]?.rollback;return!n||!Array.isArray(n.timeline)||typeof n.currentIndex!="number"?!1:n.currentIndex>=0&&n.currentIndex<n.timeline.length-1},Ga=({state:e},t={})=>{let n=yo({state:e}),r=bo({state:e}),o=Ln({state:e})?.actions??{},{sectionId:i}=ce({state:e}).pointer,{sceneId:s}=vn(e.projectData,i),a=On({state:e}),c=t?.activePersistentAnimations??[],l=t?.restoredPersistentAnimations??[],u=go({state:e}),{saveSlots:f}=kn({state:e}),d=Ka(e);return zr({presentationState:n,previousPresentationState:r,currentLineActions:o,resources:e.projectData.resources,currentSceneId:s,screen:e.projectData.screen,dialogueUIHidden:a.dialogueUIHidden,autoMode:a.autoMode,skipMode:a.skipMode,isChoiceVisible:le({state:e}),canRollback:Ro({state:e}),skipOnlyViewedLines:!a.skipUnseenText,isLineCompleted:a.isLineCompleted,skipTransitionsAndAnimations:!!a.skipTransitionsAndAnimations||d,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,dialogueHistory:po({state:e}),saveSlots:f,variables:u,runtime:a,activePersistentAnimations:c,restoredPersistentAnimations:l})},Xa=({state:e},t)=>(e.global.confirmDialog=ya(t),e.global.pendingEffects.push({name:"render"}),e),Qa=({state:e})=>(e.global.confirmDialog&&(Me(e),e.global.pendingEffects.push({name:"render"})),e),Za=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),de(e,"pushOverlay",t),e),ec=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),de(e,"popOverlay",void 0),e),tc=({state:e},t)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=t),e.global.pendingEffects.push({name:"render"}),de(e,"replaceLastOverlay",t),e),nc=({state:e})=>(e.global.overlayStack=[],Me(e),e.global.pendingEffects.push({name:"render"}),de(e,"clearOverlays",void 0),e),rc=e=>{e.global.autoMode&&(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"})),e.global.skipMode&&(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"})),e.global.nextLineConfig?.auto?.enabled&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},St=(e,t)=>{e.global.isLineCompleted=!1;let n=!!ho({state:e,pointer:t});return n&&rc(e),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:n}},Io=({state:e})=>(le({state:e})||(e.global.skipMode&&(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"})),e.global.autoMode=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.isLineCompleted&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:fe(e,"autoForwardDelay")}}),e.global.pendingEffects.push({name:"render"})),e),Ze=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),oc=({state:e})=>{let t=e.global.autoMode;return le({state:e})&&!t||(t?Ze({state:e}):Io({state:e})),e},wo=({state:e})=>(le({state:e})||(e.global.autoMode&&(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"})),e.global.skipMode=!0,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"startSkipNextTimer"}),e.global.pendingEffects.push({name:"render"})),e),$e=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),ic=({state:e})=>{let t=uo({state:e});return le({state:e})&&!t||(t?$e({state:e}):wo({state:e})),e},_t=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),de(e,"showDialogueUI",void 0),e),Ao=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),de(e,"hideDialogueUI",void 0),e),sc=({state:e})=>(fo({state:e})?_t({state:e}):Ao({state:e}),e),Oe=(e,t,n)=>(so(e,t,n),Ea(e),e.global.pendingEffects.push({name:"render"}),e),et=(e,t,n,r)=>{let o=so(e,t,n);return e.global.pendingEffects.push({name:"render"}),de(e,r,{value:o}),e},ac=({state:e},t)=>Oe(e,"dialogueTextSpeed",t?.value),cc=({state:e},t)=>Oe(e,"autoForwardDelay",t?.value),lc=({state:e},t)=>Oe(e,"skipUnseenText",t?.value),uc=({state:e},t)=>Oe(e,"skipTransitionsAndAnimations",t?.value),fc=({state:e},t)=>Oe(e,"soundVolume",t?.value),dc=({state:e},t)=>Oe(e,"musicVolume",t?.value),pc=({state:e},t)=>Oe(e,"muteAll",t?.value),hc=({state:e},t)=>et(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),mc=({state:e})=>{let t=fe(e,"saveLoadPagination")+1;return et(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},gc=({state:e})=>{let t=fe(e,"saveLoadPagination")-1;return et(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},yc=({state:e},t)=>et(e,"menuPage",t?.value,"setMenuPage"),bc=({state:e},t)=>et(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),Ic=({state:e})=>(e.global.pendingEffects=[],e),wc=({state:e},t)=>(e.global.pendingEffects.push(t),e),Eo=(e,{sectionId:t,resetStoryState:n=!1})=>{let r=G({state:e},{sectionId:t});if(!r)return console.warn(`Section not found: ${t}`),e;let o=r.lines?.[0];if(!o)return console.warn(`Section ${t} has no lines`),e;if(n&&!Ca(e))return e;e.global.autoMode&&Ze({state:e}),e.global.skipMode&&$e({state:e});let i=e.contexts?.[e.contexts.length-1];if(i){let s=Be(i);i.rollback||Re(i,{compatibilityAnchor:!0}),s.read={sectionId:t,lineId:o.id},n?i.rollback=Xe({pointer:s.read}):$n(e,{sectionId:t,lineId:o.id})}return St(e,i?.pointers?.read),e},Ac=({state:e},t)=>Eo(e,{sectionId:t?.sectionId,resetStoryState:!0}),xo=e=>(e.global.accountViewedRegistry=oa(e.global.accountViewedRegistry),e.global.accountViewedRegistry),vo=(e,t)=>{!Array.isArray(t)||t.length===0||e.global.pendingEffects.push({name:"applyScopedDataUpdates",payload:{updates:t.map(n=>({scope:n.scope,path:n.path,op:n.op,value:F(n.value)}))}})},Co=(e,t)=>{vo(e,[{scope:"account",path:"viewedRegistry",op:"markViewed",value:{sections:(Array.isArray(t?.sections)?t.sections:[]).map(n=>({sectionId:n.sectionId,...n.lastLineId===void 0?{}:{lineId:n.lastLineId}})),resources:Array.isArray(t?.resources)?t.resources:[]}}])},Ec=(e,t,{sectionId:n,lineId:r})=>{if(!n||!r)return!1;let o=j(t)?t:{};Array.isArray(o.sections)||(o.sections=[]);let i=o.sections.find(s=>s.sectionId===n);if(i){if(i.lastLineId===void 0)return!1;let s=G({state:e},{sectionId:n});if(s?.lines){let a=s.lines.findIndex(l=>l.id===i.lastLineId),c=s.lines.findIndex(l=>l.id===r);if(a===-1||c>a)return i.lastLineId===r?!1:(i.lastLineId=r,!0)}else return i.lastLineId===r?!1:(i.lastLineId=r,!0);return!1}else return o.sections.push({sectionId:n,lastLineId:r}),!0},Qe=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;Ec(e,xo(e),t)&&Co(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},xc=({state:e},t)=>(Qe(e,t),e.global.pendingEffects.push({name:"render"}),e),vc=({state:e},t)=>{let{resourceId:n}=t;if(e.global.accountViewedRegistry!==void 0){let r=xo(e);r.resources.find(i=>i.resourceId===n)||(r.resources.push({resourceId:n}),Co(e,{sections:[],resources:[{resourceId:n}]}))}return e.global.pendingEffects.push({name:"render"}),e},So=({state:e},t)=>{let n=ca(t.manual),{auto:r,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,a=e.contexts?.[e.contexts.length-1]?.rollback?.isRestoring===!0;n&&r?(e.global.nextLineConfig={manual:n,auto:r},o!==void 0?e.global.nextLineConfig.applyMode=o:s!==void 0&&(e.global.nextLineConfig.applyMode=s)):(n&&(e.global.nextLineConfig.manual=n),r&&(e.global.nextLineConfig.auto=r),o!==void 0&&(e.global.nextLineConfig.applyMode=o));let c=e.global.nextLineConfig.auto?.enabled,l=le({state:e});return!a&&!l&&c===!0&&!i?e.global.nextLineConfig.auto?.trigger==="fromStart"?e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):e.global.isLineCompleted&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):!a&&c===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),de(e,"setNextLineConfig",t),e},Cc=({state:e},t)=>{let n=t?.slotId;if(n==null||n==="")throw new Error("saveSlot requires slotId");let{thumbnailImage:r}=t,o=t?.savedAt,i=Ct(n),s=F(e.contexts);s?.forEach(l=>{Be(l),co(l.rollback),fa(l.rollback)});let a={contexts:s},c={formatVersion:Gr,slotId:Zr(n),savedAt:typeof o=="number"?o:Date.now(),image:r,state:a};return e.global.saveSlots[i]=c,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},Sc=({state:e},t)=>{let n=t?.slotId;if(n==null||n==="")throw new Error("loadSlot requires slotId");let r=Ct(n),o=e.global.saveSlots[r];if(o){let i=ga(o,e.projectData);e.contexts=i.state.contexts,e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=vt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,Me(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},_c=({state:e},t)=>{let{projectData:n}=t;Qr(n),e.projectData=n;let r=n?.resources?.variables??{};return Object.prototype.hasOwnProperty.call(e.global??{},"variables")&&(e.global.variables=Pe(e.global.variables,r)),e.contexts?.forEach(o=>{Object.prototype.hasOwnProperty.call(o??{},"variables")&&(o.variables=Pe(o.variables,r))}),Me(e),e.global.pendingEffects.push({name:"render"}),e},$c=({state:e},t)=>{let{sectionId:n,lineId:r}=t;if(!r)return console.warn("jumpToLine requires lineId parameter"),e;let o=e.contexts[e.contexts.length-1];if(!o)return console.warn("No context available for jumpToLine"),e;let i=n||o.pointers.read?.sectionId;if(n&&!G({state:e},{sectionId:n}))return console.warn(`Section not found: ${n}`),e;let s=G({state:e},{sectionId:i});if(!s?.lines||!Array.isArray(s.lines))return console.warn(`Section ${i} has no lines`),e;if(!s.lines.find(l=>l.id===r))return console.warn(`Line not found: ${r} in section ${i}`),e;let c=Be(o);return c.read={sectionId:i,lineId:r},St(e,c.read),e},Rc=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return _t({state:e}),e;if(le({state:e})&&t?._interactionSource!=="choice")return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0;let l=ce({state:e})?.pointer,u=l?.sectionId,f=l?.lineId;u&&f&&Qe(e,{sectionId:u,lineId:f}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:fe(e,"autoForwardDelay")}});let d=e.global.nextLineConfig;return d?.auto?.enabled&&d.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:d.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e}let n=ce({state:e})?.pointer,r=n?.sectionId,o=G({state:e},{sectionId:r}),i=e.contexts[e.contexts.length-1],s=o?.lines||[],c=s.findIndex(l=>l.id===n?.lineId)+1;if(c<s.length){let l=s[c],u=!fe(e,"skipUnseenText");if(e.global.skipMode&&u&&!Rn({state:e},{sectionId:r,lineId:l.id}))return $e({state:e}),e;if(i&&!i.rollback&&Re(i,{compatibilityAnchor:!0}),i){let p=Be(i),h=p.read?.lineId;h&&r&&Qe(e,{sectionId:r,lineId:h}),p.read={sectionId:r,lineId:l.id}}$n(e,{sectionId:r,lineId:l.id}),xn(e);let{isChoiceVisible:f}=St(e,{sectionId:r,lineId:l.id}),d=e.global.nextLineConfig;d?.auto?.enabled&&!f&&d.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:d.auto.delay}})}else e.global.autoMode&&Ze({state:e}),e.global.skipMode&&$e({state:e});return e},Oc=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0;let t=le({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:fe(e,"autoForwardDelay")}});let n=ce({state:e})?.pointer,r=n?.sectionId,o=n?.lineId;r&&o&&Qe(e,{sectionId:r,lineId:o});let i=e.global.nextLineConfig;return i?.auto?.enabled&&!t&&i.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:i.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e},Lc=({state:e},t)=>Eo(e,{sectionId:t?.sectionId}),kc=({state:e})=>{if(e.global.dialogueUIHidden)return _t({state:e}),e;if(le({state:e}))return e;let t=ce({state:e})?.pointer,n=t?.sectionId,r=G({state:e},{sectionId:n}),o=e.contexts[e.contexts.length-1],i=r?.lines||[],a=i.findIndex(c=>c.id===t?.lineId)+1;if(a<i.length){let c=i[a],l=!fe(e,"skipUnseenText");if(e.global.skipMode&&l&&!Rn({state:e},{sectionId:n,lineId:c.id}))return $e({state:e}),e;if(o&&!o.rollback&&Re(o,{compatibilityAnchor:!0}),o){let f=Be(o),d=f.read?.lineId;d&&n&&Qe(e,{sectionId:n,lineId:d}),f.read={sectionId:n,lineId:c.id}}$n(e,{sectionId:n,lineId:c.id}),xn(e);let{isChoiceVisible:u}=St(e,{sectionId:n,lineId:c.id});e.global.nextLineConfig.auto?.enabled&&!u&&e.global.nextLineConfig.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}})}else e.global.nextLineConfig.auto?.enabled&&(e.global.nextLineConfig.auto.enabled=!1,e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}));return e},Pc=({state:e},t)=>{let{id:n,operations:r=[]}=t;if(!n)throw new Error("updateVariable requires an id field");if(typeof n!="string"||!/^[a-zA-Z0-9]+$/.test(n))throw new Error(`updateVariable id must be alphanumeric, got: "${n}"`);let o=e.contexts[e.contexts.length-1];if(o?.rollback?.isRestoring)return e;let i=!1,s=[],a=[];return r.forEach(({variableId:c,op:l,value:u})=>{let f=e.projectData.resources?.variables?.[c],d=f?.scope,p=f?.type;if(Ee(f))throw new Error(`Cannot update computed variable: ${c}`);if(f?.readonly===!0)throw new Error(`Cannot update readonly variable: ${c}`);Zt(d,c),en(p,l,c);let h=d==="context"?o.variables:e.global.variables;d==="context"&&(i=!0,a.push({variableId:c,op:l,value:u})),h[c]=tn(h[c],l,u),(d==="device"||d==="account")&&s.push({scope:d,path:`variables.${c}`,op:"set",value:F(h[c])})}),i&&de(e,"updateVariable",{id:n,operations:a}),vo(e,s),e.global.pendingEffects.push({name:"render"}),e},Tc=e=>(t,n)=>e({state:t},n),Nc=e=>({variables:ht({variables:{...e.global?.variables??{},..._n(e)?.variables??{}},runtime:je(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1}),runtime:je(e)}),Dc=e=>{if(!j(e))throw new Error("conditional action payload must be an object");if(!Array.isArray(e.branches))throw new Error("conditional action requires branches array");if(e.branches.length===0)throw new Error("conditional action requires at least one branch")},Vc=(e,t,n)=>{if(!j(e))throw new Error(`conditional branch at index ${t} must be an object`);if(!j(e.actions))throw new Error(`conditional branch at index ${t} requires actions object`);if(!Object.prototype.hasOwnProperty.call(e,"when")&&t!==n-1)throw new Error("conditional else branch must be the last branch")},jc=(e,t)=>{Dc(t);for(let n=0;n<t.branches.length;n+=1){let r=t.branches[n];if(Vc(r,n,t.branches.length),!(Object.prototype.hasOwnProperty.call(r,"when")&&!Ae(r.when,Nc(e)))){Object.entries(r.actions).forEach(([i,s])=>{_o(e,i,s)});return}}},Mc={conditional:{replayLine:jc},updateVariable:{recordSources:[Cn],replayLine:Kr,replayRecorded:Kr,persistInSaveSlot:!0},setNextLineConfig:{replayLine:Tc(So)}},$t=e=>Mc[e]??null,Bc=e=>$t(e)?.persistInSaveSlot===!0,Uc=(e,t)=>{let n=$t(e)?.recordSources;return Array.isArray(n)&&n.includes(t)},Fc=(e,t,n)=>{$t(t)?.replayRecorded?.(e,n)},_o=(e,t,n)=>{$t(t)?.replayLine?.(e,n)},$o=({state:e},t)=>{let{offset:n}=t;if(n===void 0||typeof n!="number")return console.warn("selectLineIdByOffset requires a numeric offset"),null;let r=e.contexts[e.contexts.length-1];if(!r)return null;let o=r.rollback;if(!Array.isArray(o?.timeline)||typeof o?.currentIndex!="number")return null;let i=o.currentIndex+n;if(i<0||i>=o.timeline.length)return null;let s=o.timeline[i];return{sectionId:s.sectionId,lineId:s.lineId}},Ro=({state:e})=>$o({state:e},{offset:-1})!==null,zc=({state:e},t)=>{let{offset:n=-1}=t;if(n>=0)throw new Error("rollbackByOffset requires a negative offset");let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let o=Re(r,{compatibilityAnchor:!r.rollback}),i=o.currentIndex+n;return i<0||i>=o.timeline.length?e:lo(e,i)},Wc=({state:e},t)=>{let{sectionId:n,lineId:r}=t,o=e.contexts[e.contexts.length-1];if(!o)throw new Error("No context available for rollbackToLine");let i=Re(o,{compatibilityAnchor:!o.rollback}),a=i.timeline.slice(0,i.currentIndex+1).findLastIndex(c=>c.sectionId===n&&c.lineId===r);if(a===-1)throw new Error(`Line ${r} not found in section ${n} rollback timeline`);return a===i.currentIndex?e:lo(e,a)},Oo=e=>{let t=ka(e);return hr(t,{selectPendingEffects:Ta,selectSkipMode:uo,selectAutoMode:Na,selectIsChoiceVisible:le,selectDialogueUIHidden:fo,selectDialogueHistory:po,selectConfirmDialog:Da,selectIsLineAccountViewed:Rn,selectIsResourceAccountViewed:Ma,selectNextLineConfig:Ba,selectSystemState:Ua,selectSaveSlotMap:mo,selectSaveSlots:Ha,selectSaveSlot:Fa,selectRuntime:On,selectRuntimeValue:za,selectAllVariables:go,selectCurrentPointer:ce,selectSection:G,selectCurrentLine:Ln,selectPresentationState:yo,selectPresentationChanges:Wa,selectSectionLineChanges:Ya,selectSaveSlotPage:kn,selectCurrentPageSlots:Ja,selectRenderState:Ga,selectOverlayStack:Pa,selectLineIdByOffset:$o,selectCanRollback:Ro,startAutoMode:Io,stopAutoMode:Ze,toggleAutoMode:oc,startSkipMode:wo,stopSkipMode:$e,toggleSkipMode:ic,showDialogueUI:_t,hideDialogueUI:Ao,toggleDialogueUI:sc,setDialogueTextSpeed:ac,setAutoForwardDelay:cc,setSkipUnseenText:lc,setSkipTransitionsAndAnimations:uc,setSoundVolume:fc,setMusicVolume:dc,setMuteAll:pc,setSaveLoadPagination:hc,incrementSaveLoadPagination:mc,decrementSaveLoadPagination:gc,setMenuPage:yc,setMenuEntryPoint:bc,showConfirmDialog:Xa,hideConfirmDialog:Qa,resetStoryAtSection:Ac,clearPendingEffects:Ic,appendPendingEffect:wc,beginRollbackActionBatch:$a,endRollbackActionBatch:Ra,addViewedLine:xc,addViewedResource:vc,setNextLineConfig:So,saveSlot:Cc,loadSlot:Sc,updateProjectData:_c,sectionTransition:Lc,jumpToLine:$c,nextLine:Rc,markLineCompleted:Oc,rollbackToLine:Wc,rollbackByOffset:zc,pushOverlay:Za,popOverlay:ec,replaceLastOverlay:tc,clearOverlays:nc,updateVariable:Pc,nextLineFromSystem:kc},{transformActionFirstArgument:r=>({state:r}),transformSelectorFirstArgument:r=>({state:r})})};var qc="route-engine",Yc="projectPersistence";var ko=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),H=e=>Object.prototype.toString.call(e)==="[object Object]",Lo="variables.",Hc=(e={})=>{let t=H(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(n=>typeof n=="string"||typeof n=="number"?{sectionId:String(n)}:!H(n)||typeof n.sectionId!="string"||n.sectionId.length===0?null:{sectionId:n.sectionId,...typeof n.lineId=="string"?{lineId:n.lineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(n=>typeof n=="string"||typeof n=="number"?{resourceId:String(n)}:!H(n)||typeof n.resourceId!="string"||n.resourceId.length===0?null:{resourceId:n.resourceId}).filter(Boolean)}},Jc=(e={})=>{let t=H(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(n=>typeof n=="string"||typeof n=="number"?{sectionId:String(n)}:!H(n)||typeof n.sectionId!="string"||n.sectionId.length===0?null:{sectionId:n.sectionId,...typeof n.lastLineId=="string"?{lastLineId:n.lastLineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(n=>typeof n=="string"||typeof n=="number"?{resourceId:String(n)}:!H(n)||typeof n.resourceId!="string"||n.resourceId.length===0?null:{resourceId:n.resourceId}).filter(Boolean)}},Kc=(e,t)=>{let n=Jc(e),r=Hc(t),o=n.sections.map(s=>({...s})),i=n.resources.map(s=>({...s}));return r.sections.forEach(s=>{let a=o.find(c=>c.sectionId===s.sectionId);if(!a){o.push({sectionId:s.sectionId,...s.lineId===void 0?{}:{lastLineId:s.lineId}});return}if(a.lastLineId!==void 0){if(s.lineId===void 0){delete a.lastLineId;return}a.lastLineId=s.lineId}}),r.resources.forEach(s=>{i.find(c=>c.resourceId===s.resourceId)||i.push({...s})}),{sections:o,resources:i}},Po=(e={})=>{let t=H(e)?e:{};return{saveSlots:H(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:H(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:H(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:H(t.globalRuntime)?t.globalRuntime:{},accountViewedRegistry:H(t.accountViewedRegistry)?t.accountViewedRegistry:{}}},Gc=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((t,n)=>{if(!H(t))throw new Error(`Malformed applyScopedDataUpdates.updates[${n}] entry.`);let r=t.path?.startsWith(Lo)?t.path.slice(Lo.length):null;if(r!==null){if(!["device","account"].includes(t.scope))throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${n}].`);if(r.length===0)throw new Error(`Malformed applyScopedDataUpdates path "${t.path}" at updates[${n}].`);if(t.op!=="set")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${n}].`);return{scope:t.scope,path:t.path,op:t.op,value:t.value,variableId:r}}if(t.path==="viewedRegistry"){if(t.scope!=="account")throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${n}].`);if(t.op!=="markViewed")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${n}].`);return t}throw typeof t.path!="string"?new Error(`Malformed applyScopedDataUpdates path at updates[${n}].`):new Error(`Unsupported applyScopedDataUpdates path "${t.path}" at updates[${n}].`)})},Xc=(e,t)=>{let n={};return Gc(t).forEach(r=>{if(r.path==="viewedRegistry"){n.accountViewedRegistry=Kc(n.accountViewedRegistry??e.accountViewedRegistry,r.value);return}let o=r.scope==="device"?"globalDeviceVariables":"globalAccountVariables";n[o]={...e[o],...n[o],[r.variableId]:r.value}}),n},Pn=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},Qc=e=>{let t=Pn(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},Zc=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},el=({indexedDB:e,databaseName:t,objectStoreName:n})=>new Promise((r,o)=>{let i=e.open(t,1);i.onupgradeneeded=()=>{let s=i.result;s.objectStoreNames.contains(n)||s.createObjectStore(n,{keyPath:"namespace"})},i.onsuccess=()=>{r(i.result)},i.onerror=()=>{o(i.error??new Error(`Failed to open IndexedDB database "${t}".`))}}),tl=async({databasePromise:e,objectStoreName:t,namespace:n})=>{let r=await e;return new Promise((o,i)=>{let c=r.transaction(t,"readonly").objectStore(t).get(n);c.onsuccess=()=>{o(c.result??null)},c.onerror=()=>{i(c.error??new Error(`Failed to read persisted namespace "${n}" from IndexedDB.`))}})},tt=async({databasePromise:e,objectStoreName:t,namespace:n,patch:r})=>{let o=await e;return new Promise((i,s)=>{let a=o.transaction(t,"readwrite"),c=a.objectStore(t),l=c.get(n),u=!1,f=p=>{u||(u=!0,s(p))},d=()=>{u||(u=!0,i())};l.onerror=()=>{f(l.error??new Error(`Failed to read persisted namespace "${n}" before updating IndexedDB.`))},l.onsuccess=()=>{let p=Po(l.result),h=typeof r=="function"?r(p):r,y={namespace:n,version:1,...ko(),...p,...h},I=c.put(y);I.onerror=()=>{f(I.error??new Error(`Failed to persist namespace "${n}" to IndexedDB.`))}},a.oncomplete=()=>{d()},a.onerror=()=>{f(a.error??new Error(`IndexedDB transaction failed while updating namespace "${n}".`))},a.onabort=()=>{f(a.error??new Error(`IndexedDB transaction aborted while updating namespace "${n}".`))}})},nl=async({databasePromise:e,objectStoreName:t,namespace:n})=>{let r=await e;return new Promise((o,i)=>{let s=r.transaction(t,"readwrite"),c=s.objectStore(t).delete(n),l=!1,u=d=>{l||(l=!0,i(d))},f=()=>{l||(l=!0,o())};c.onerror=()=>{u(c.error??new Error(`Failed to clear persisted namespace "${n}" from IndexedDB.`))},s.oncomplete=()=>{f()},s.onerror=()=>{u(s.error??new Error(`IndexedDB transaction failed while clearing namespace "${n}".`))},s.onabort=()=>{u(s.error??new Error(`IndexedDB transaction aborted while clearing namespace "${n}".`))}})},Tn=(e={})=>{let{indexedDB:t,databaseName:n=qc,objectStoreName:r=Yc,namespace:o}=e,i=Zc(t),s=Qc(o),a=el({indexedDB:i,databaseName:n,objectStoreName:r});return{namespace:s,load:async()=>{let c=await tl({databasePromise:a,objectStoreName:r,namespace:s});return{...ko(),...Po(c)}},clear:async()=>nl({databasePromise:a,objectStoreName:r,namespace:s}),saveSlots:async c=>tt({databasePromise:a,objectStoreName:r,namespace:s,patch:{saveSlots:H(c)?c:{}}}),saveGlobalDeviceVariables:async c=>tt({databasePromise:a,objectStoreName:r,namespace:s,patch:{globalDeviceVariables:H(c)?c:{}}}),saveGlobalAccountVariables:async c=>tt({databasePromise:a,objectStoreName:r,namespace:s,patch:{globalAccountVariables:H(c)?c:{}}}),saveGlobalRuntime:async c=>tt({databasePromise:a,objectStoreName:r,namespace:s,patch:{globalRuntime:H(c)?c:{}}}),applyScopedDataUpdates:async c=>tt({databasePromise:a,objectStoreName:r,namespace:s,patch:l=>Xc(l,c)})}},rl=Tn;var ol=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),il=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),To="conditional",No="choice",Rt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function Nn(e){let t,n=0,r=null,o=new Map,i=new Map,s=new Map,{handlePendingEffects:a}=e,c=(w=new Map,v=Date.now())=>new Map(Array.from(w.entries()).filter(([,T])=>v<T.expiresAt).map(([T,V])=>[T,{animation:structuredClone(V.animation),startedAt:V.startedAt,expiresAt:V.expiresAt}])),l=(w=new Map)=>Array.from(w.values()).map(v=>structuredClone(v.animation)),u=(w=Date.now())=>{o=new Map(Array.from(o.entries()).filter(([,v])=>w<v.expiresAt))},f=()=>{for(;t.selectPendingEffects().length>0;){let w=[...t.selectPendingEffects()];t.clearPendingEffects();try{a(w)}catch(v){throw t.clearPendingEffects(),w.forEach(T=>{t.appendPendingEffect(T)}),v}}},d=({initialState:w,namespace:v})=>{t=Oo(w),n=0,r=Pn(v),o=new Map,i=new Map,s=new Map,t.appendPendingEffect({name:"handleLineActions"}),f()},p=()=>r,h=()=>t.selectPresentationState(),y=()=>t.selectPresentationChanges(),I=w=>t.selectSectionLineChanges(w),b=(w={})=>{n+=1;let v=Date.now();u(v);let T=i.size>0,V=c(o,v),Y=T?c(i,v):new Map,pe={...t.selectRenderState({activePersistentAnimations:l(V),restoredPersistentAnimations:l(Y)}),id:`render-${n}`};return s.set(pe.id,{builtAt:v,persistentAnimationSessions:new Map([...Y.entries(),...V.entries()]),usedRestoredPersistentAnimationSessions:T}),pe},g=(w={})=>b(w),x=(w={})=>b(w),C=w=>{let v=typeof w?.id=="string"&&w.id.length>0?w.id:null,T=v?s.get(v):null;v&&s.delete(v);let V=new Map;Pr(w?.animations).forEach(Y=>{let oe=It(Y);if(!oe)return;let pe=T?.persistentAnimationSessions?.get(oe)??o.get(oe),Mo=Math.max(0,Nr(Y)),Bn=pe?.startedAt??T?.builtAt??Date.now();V.set(oe,{animation:structuredClone(Y),startedAt:Bn,expiresAt:Bn+Mo})}),o=V,T?.usedRestoredPersistentAnimationSessions&&(i=new Map)},O=()=>t.selectSystemState(),L=()=>t.selectSaveSlotMap(),_=w=>t.selectSaveSlot(w),D=w=>t.selectSaveSlotPage(w),N=()=>t.selectSkipMode(),k=()=>t.selectAutoMode(),P=()=>t.selectRuntime(),E=()=>t.selectIsChoiceVisible(),S=(w,v,T={})=>T.interactionSource!==No||w!=="nextLine"||!Rt(v)?v:{...v,_interactionSource:No},M=(w,v)=>{t[w]&&(ol.has(w)&&(il.has(w)?i=c(o):i=new Map,o=new Map),t[w](v),f())},z=(w,v,T,V={})=>{if(w===To){let Y=B(T),oe=on({[w]:v},Y);Vn(oe[w],T,V);return}M(w,v)},q=(w,v)=>{z(w,v)},B=w=>{if(!w)return{variables:t.selectAllVariables?t.selectAllVariables():void 0,runtime:t.selectRuntime?t.selectRuntime():{}};if(Object.prototype.hasOwnProperty.call(w,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:v,...T}=w,V=t.selectAllVariables?t.selectAllVariables():void 0;return{...T,_event:v,variables:V,runtime:t.selectRuntime?t.selectRuntime():{}}},nt=w=>{if(!Rt(w))throw new Error("conditional action payload must be an object");if(!Array.isArray(w.branches))throw new Error("conditional action requires branches array");if(w.branches.length===0)throw new Error("conditional action requires at least one branch")},rt=(w,v,T)=>{if(!Rt(w))throw new Error(`conditional branch at index ${v} must be an object`);if(!Rt(w.actions))throw new Error(`conditional branch at index ${v} requires actions object`);if(!Object.prototype.hasOwnProperty.call(w,"when")&&v!==T-1)throw new Error("conditional else branch must be the last branch")},Vn=(w,v,T)=>{nt(w);for(let V=0;V<w.branches.length;V+=1){let Y=w.branches[V];rt(Y,V,w.branches.length);let oe=B(v);if(!(Object.prototype.hasOwnProperty.call(Y,"when")&&!Ae(Y.when,oe))){jn(Y.actions,v,T);return}}},jo=(w,v,T,V)=>{let Y=B(T),pe=on({[w]:v},Y)[w];if(w===To){Vn(pe,T,V);return}M(w,S(w,pe,V))},jn=(w,v,T)=>{Object.entries(w).forEach(([V,Y])=>{jo(V,Y,v,T)})},Mn=(w,v,T={})=>{t.beginRollbackActionBatch({source:T.rollbackSource});try{jn(w,v,T)}finally{t.endRollbackActionBatch({})}};return{init:d,handleAction:z,handleInternalAction:q,handleActions:Mn,selectRenderState:g,prepareRenderState:x,commitRenderState:C,selectPresentationState:h,selectPresentationChanges:y,selectSectionLineChanges:I,selectSystemState:O,selectSaveSlotMap:L,selectSaveSlot:_,selectSaveSlotPage:D,selectSaveSlots:L,selectRuntime:P,selectIsChoiceVisible:E,handleLineActions:()=>{let w=t.selectCurrentLine();return w?.actions?(Mn(w.actions,void 0,{rollbackSource:"line"}),!0):!1},getNamespace:p}}var Dn=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:n=>{e=n},addElapsed:n=>{e+=n},getCallback:()=>t,setCallback:n=>{t=n}}},sl=80,Vo=({engine:e,routeGraphics:t,trackRenderDispatch:n},r)=>{let o=e.prepareRenderState?.(r)??e.selectRenderState(r);n?.(o),t.render(o),e.commitRenderState?.(o)},al=({engine:e,routeGraphics:t,trackRenderDispatch:n,getRenderDispatchCount:r},o)=>{let i=r?.()??0,s=e.handleLineActions();(r?.()??0)===i&&Vo({engine:e,routeGraphics:t,trackRenderDispatch:n},o)},cl=({engine:e,ticker:t,autoTimer:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let a=r.delay??1e3;n.getElapsed()>=a&&(t.remove(i),n.setCallback(null),n.setElapsed(0),Ot(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},ll=({ticker:e,autoTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},ul=({engine:e,ticker:t,skipTimer:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let a=r?.delay??sl;n.getElapsed()>=a&&(n.setElapsed(0),Ot(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},fl=({ticker:e,skipTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},dl=({engine:e,ticker:t,nextLineConfigTimerState:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let a=r.delay??1e3;n.getElapsed()>=a&&(n.setElapsed(0),Ot(e,"nextLineFromSystem",{}),t.remove(i),n.setCallback(null))};n.setCallback(i),t.add(i)},pl=({ticker:e,nextLineConfigTimerState:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},hl=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveSlots(t?.saveSlots))},ml=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalDeviceVariables(t?.globalDeviceVariables))},gl=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalAccountVariables(t?.globalAccountVariables))},yl=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalRuntime(t?.globalRuntime))},bl=({enqueuePersistenceWrite:e},t)=>{e(n=>{if(typeof n.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return n.applyScopedDataUpdates(t?.updates)})},Do={render:Vo,saveSlots:hl,saveGlobalDeviceVariables:ml,saveGlobalAccountVariables:gl,saveGlobalRuntime:yl,applyScopedDataUpdates:bl,handleLineActions:al,startAutoNextTimer:cl,clearAutoNextTimer:ll,startSkipNextTimer:ul,clearSkipNextTimer:fl,nextLineConfigTimer:dl,clearNextLineConfigTimer:pl},Il=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),Ot=(e,t,n)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,n)},wl=(e=[])=>{let t=new Set,n=[];for(let r=e.length-1;r>=0;r-=1){let o=e[r];if(typeof o?.name!="string"||o.name.length===0)throw new Error("Pending effect is missing a valid name.");if(!Il.has(o.name)){n.unshift(o);continue}t.has(o.name)||(t.add(o.name),n.unshift(o))}return n},Al=({getEngine:e,routeGraphics:t,ticker:n,handleUnhandledEffect:r,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:a})=>{let c=Dn(),l=Dn(),u=Dn(),f=s??null,d=Promise.resolve(),p=null,h=null,y=!1,I=0,b=E=>{if(o){o(E);return}console.error("RouteEngine persistence write failed.",E)},g=()=>{if(f)return f;let E=e();return f=Tn({indexedDB:i,namespace:a??E?.getNamespace?.()}),f},x=E=>{d=d.catch(()=>{}).then(()=>{let S=g();return E(S)}).catch(S=>{b(S)})},C=E=>{let S=typeof E?.id=="string"&&E.id.length>0?E.id:null;I+=1,p=S,y=!1},O=()=>I,L=(E={})=>{if(E?.aborted===!0)return!1;let S=typeof E?.id=="string"&&E.id.length>0?E.id:null;return S?S!==p||S===h?!1:(h=S,!0):p!==null||y?!1:(y=!0,!0)},_=(E,S={})=>{if(E!=="renderComplete"||!L(S))return!1;let M=e();return Ot(M,"markLineCompleted",{}),!0},D=(E={})=>{if(E?._interactionSource==="choice")return!0;let S=E?.actions;return!S||typeof S!="object"||Array.isArray(S)?!1:Object.values(S).some(M=>M?._interactionSource==="choice")},N=(E,S={})=>!S?.actions||typeof E?.selectIsChoiceVisible!="function"||!E.selectIsChoiceVisible()?!1:!D(S),k=({preprocessPayload:E,onEvent:S}={})=>async(M,z={})=>{let q=e();if(N(q,z))return S?.(M,z);let B=await E?.(M,z)??z;if(N(q,B))return S?.(M,B);if(_(M,B),B?.actions){let nt=B?._event?{_event:B._event}:B?.event?{_event:B.event}:void 0,rt=B?._interactionSource?{interactionSource:B._interactionSource}:void 0;rt?q.handleActions(B.actions,nt,rt):q.handleActions(B.actions,nt)}return S?.(M,B)},P=E=>{let S=e(),M=wl(E);M.forEach(q=>{if(!Do[q.name]&&!r)throw new Error(`Unhandled pending effect "${q.name}".`)});let z={engine:S,routeGraphics:t,ticker:n,autoTimer:c,skipTimer:l,nextLineConfigTimerState:u,trackRenderDispatch:C,getRenderDispatchCount:O,enqueuePersistenceWrite:x};for(let q of M){let B=Do[q.name];if(B){B(z,q.payload);continue}r(q,z)}};return P.handleRouteGraphicsEvent=_,P.createRouteGraphicsEventHandler=k,P},El=Al;var xl=(e,t={})=>{let{resources:n={}}=t;return wn(e,n)};var Bu=Nn;export{El as createEffectsHandler,rl as createIndexedDbPersistence,Bu as default,Yi as resolveComputedVariables,xl as resolveLayoutReferences};
|
package/package.json
CHANGED