route-engine-js 1.27.0 → 1.29.0

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.
@@ -1 +1 @@
1
- var Yi=Object.defineProperty;var Ki=(e,t)=>{for(var r in t)Yi(e,r,{get:t[r],enumerable:!0})};var Tn=Symbol.for("immer-nothing"),Rn=Symbol.for("immer-draftable"),de=Symbol.for("immer-state");function Ie(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var Ze=Object.getPrototypeOf;function fe(e){return!!e&&!!e[de]}function Fe(e){return e?Dn(e)||Array.isArray(e)||!!e[Rn]||!!e.constructor?.[Rn]||$t(e)||kt(e):!1}var Gi=Object.prototype.constructor.toString();function Dn(e){if(!e||typeof e!="object")return!1;let t=Ze(e);if(t===null)return!0;let r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return r===Object?!0:typeof r=="function"&&Function.toString.call(r)===Gi}function _t(e,t){Lt(e)===0?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,n)=>t(n,r,e))}function Lt(e){let t=e[de];return t?t.type_:Array.isArray(e)?1:$t(e)?2:kt(e)?3:0}function dr(e,t){return Lt(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Pn(e,t,r){let n=Lt(e);n===2?e.set(t,r):n===3?e.add(r):e[t]=r}function Ji(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function $t(e){return e instanceof Map}function kt(e){return e instanceof Set}function Me(e){return e.copy_||e.base_}function fr(e,t){if($t(e))return new Map(e);if(kt(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=Dn(e);if(t===!0||t==="class_only"&&!r){let n=Object.getOwnPropertyDescriptors(e);delete n[de];let o=Reflect.ownKeys(n);for(let i=0;i<o.length;i++){let s=o[i],c=n[s];c.writable===!1&&(c.writable=!0,c.configurable=!0),(c.get||c.set)&&(n[s]={configurable:!0,writable:!0,enumerable:c.enumerable,value:e[s]})}return Object.create(Ze(e),n)}else{let n=Ze(e);if(n!==null&&r)return{...e};let o=Object.create(n);return Object.assign(o,e)}}function yr(e,t=!1){return Tt(e)||fe(e)||!Fe(e)||(Lt(e)>1&&(e.set=e.add=e.clear=e.delete=Xi),Object.freeze(e),t&&Object.entries(e).forEach(([r,n])=>yr(n,!0))),e}function Xi(){Ie(2)}function Tt(e){return Object.isFrozen(e)}var Qi={};function Ue(e){let t=Qi[e];return t||Ie(0,e),t}var ct;function Nn(){return ct}function Zi(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function On(e,t){t&&(Ue("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function pr(e){hr(e),e.drafts_.forEach(es),e.drafts_=null}function hr(e){e===ct&&(ct=e.parent_)}function Ln(e){return ct=Zi(ct,e)}function es(e){let t=e[de];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function $n(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[de].modified_&&(pr(t),Ie(4)),Fe(e)&&(e=Rt(t,e),t.parent_||Ot(t,e)),t.patches_&&Ue("Patches").generateReplacementPatches_(r[de].base_,e,t.patches_,t.inversePatches_)):e=Rt(t,r,[]),pr(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Tn?e:void 0}function Rt(e,t,r){if(Tt(t))return t;let n=t[de];if(!n)return _t(t,(o,i)=>kn(e,n,t,o,i,r)),t;if(n.scope_!==e)return t;if(!n.modified_)return Ot(e,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;let o=n.copy_,i=o,s=!1;n.type_===3&&(i=new Set(o),o.clear(),s=!0),_t(i,(c,a)=>kn(e,n,o,c,a,r,s)),Ot(e,o,!1),r&&e.patches_&&Ue("Patches").generatePatches_(n,r,e.patches_,e.inversePatches_)}return n.copy_}function kn(e,t,r,n,o,i,s){if(fe(o)){let c=i&&t&&t.type_!==3&&!dr(t.assigned_,n)?i.concat(n):void 0,a=Rt(e,o,c);if(Pn(r,n,a),fe(a))e.canAutoFreeze_=!1;else return}else s&&r.add(o);if(Fe(o)&&!Tt(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Rt(e,o),(!t||!t.scope_.parent_)&&typeof n!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,n)&&Ot(e,o)}}function Ot(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&yr(t,r)}function ts(e,t){let r=Array.isArray(e),n={type_:r?1:0,scope_:t?t.scope_:Nn(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=n,i=br;r&&(o=[n],i=lt);let{revoke:s,proxy:c}=Proxy.revocable(o,i);return n.draft_=c,n.revoke_=s,c}var br={get(e,t){if(t===de)return e;let r=Me(e);if(!dr(r,t))return rs(e,r,t);let n=r[t];return e.finalized_||!Fe(n)?n:n===lr(e.base_,t)?(ur(e),e.copy_[t]=gr(n,e)):n},has(e,t){return t in Me(e)},ownKeys(e){return Reflect.ownKeys(Me(e))},set(e,t,r){let n=Vn(Me(e),t);if(n?.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){let o=lr(Me(e),t),i=o?.[de];if(i&&i.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(Ji(r,o)&&(r!==void 0||dr(e.base_,t)))return!0;ur(e),mr(e)}return e.copy_[t]===r&&(r!==void 0||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_[t]=!0),!0},deleteProperty(e,t){return lr(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,ur(e),mr(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=Me(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:n.enumerable,value:r[t]}},defineProperty(){Ie(11)},getPrototypeOf(e){return Ze(e.base_)},setPrototypeOf(){Ie(12)}},lt={};_t(br,(e,t)=>{lt[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});lt.deleteProperty=function(e,t){return lt.set.call(this,e,t,void 0)};lt.set=function(e,t,r){return br.set.call(this,e[0],t,r,e[0])};function lr(e,t){let r=e[de];return(r?Me(r):e)[t]}function rs(e,t,r){let n=Vn(t,r);return n?"value"in n?n.value:n.get?.call(e.draft_):void 0}function Vn(e,t){if(!(t in e))return;let r=Ze(e);for(;r;){let n=Object.getOwnPropertyDescriptor(r,t);if(n)return n;r=Ze(r)}}function mr(e){e.modified_||(e.modified_=!0,e.parent_&&mr(e.parent_))}function ur(e){e.copy_||(e.copy_=fr(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var ns=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,r,n)=>{if(typeof t=="function"&&typeof r!="function"){let i=r;r=t;let s=this;return function(a=i,...l){return s.produce(a,d=>r.call(this,d,...l))}}typeof r!="function"&&Ie(6),n!==void 0&&typeof n!="function"&&Ie(7);let o;if(Fe(t)){let i=Ln(this),s=gr(t,void 0),c=!0;try{o=r(s),c=!1}finally{c?pr(i):hr(i)}return On(i,n),$n(o,i)}else if(!t||typeof t!="object"){if(o=r(t),o===void 0&&(o=t),o===Tn&&(o=void 0),this.autoFreeze_&&yr(o,!0),n){let i=[],s=[];Ue("Patches").generateReplacementPatches_(t,o,i,s),n(i,s)}return o}else Ie(1,t)},this.produceWithPatches=(t,r)=>{if(typeof t=="function")return(s,...c)=>this.produceWithPatches(s,a=>t(a,...c));let n,o;return[this.produce(t,r,(s,c)=>{n=s,o=c}),n,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){Fe(e)||Ie(8),fe(e)&&(e=Be(e));let t=Ln(this),r=gr(e,void 0);return r[de].isManual_=!0,hr(t),r}finishDraft(e,t){let r=e&&e[de];(!r||!r.isManual_)&&Ie(9);let{scope_:n}=r;return On(n,t),$n(void 0,n)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){let o=t[r];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}r>-1&&(t=t.slice(r+1));let n=Ue("Patches").applyPatches_;return fe(e)?n(e,t):this.produce(e,o=>n(o,t))}};function gr(e,t){let r=$t(e)?Ue("MapSet").proxyMap_(e,t):kt(e)?Ue("MapSet").proxySet_(e,t):ts(e,t);return(t?t.scope_:Nn()).drafts_.push(r),r}function Be(e){return fe(e)||Ie(10,e),jn(e)}function jn(e){if(!Fe(e)||Tt(e))return e;let t=e[de],r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=fr(e,t.scope_.immer_.useStrictShallowCopy_)}else r=fr(e,!0);return _t(r,(n,o)=>{Pn(r,n,jn(o))}),t&&(t.finalized_=!1),r}var pe=new ns,Ir=pe.produce,kd=pe.produceWithPatches.bind(pe),Td=pe.setAutoFreeze.bind(pe),Dd=pe.setUseStrictShallowCopy.bind(pe),Pd=pe.applyPatches.bind(pe),Nd=pe.createDraft.bind(pe),Vd=pe.finishDraft.bind(pe);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},O={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},et={NOT:0};var E=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},le=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var Ar=e=>{if(!e||e.trim()==="")throw new E("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let r=e.includes("===")?"==":"!=";throw new E(`Invalid comparison operator '${e.includes("===")?"===":"!=="}' - did you mean '${r}'? (got: '${e}')`)}let t=["<",">","<=",">=","==","!="];for(let r of t)if(e.trim().endsWith(r))throw new E(`Incomplete comparison expression - missing right operand (got: '${e}')`)},Mn=e=>{if(e.trim().endsWith(" in"))throw new E(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new E(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,r]=e.split(" in ");if(!r||r.trim()==="")throw new E(`Missing iterable expression after 'in' (got: '$for ${e}')`);let n=t.includes(",")?t.split(",").map(o=>o.trim()):[t.trim()];for(let o of n){if(!o)throw new E(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new E(`Invalid loop syntax (got: '$for ${e}')`)}};var Fn=(e,t,r=!1)=>{if(t===null)return new le(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new le(`Cannot iterate over undefined value at '$for ${e}'`);let n=typeof t;return r?new le(`Cannot iterate over non-array value in loop '${e}' - got ${n} instead`):new le(`Cannot iterate over non-array value (got: ${n}) at '$for ${e}'`)},Un=(e,t)=>{let r=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new le(`Unknown function '${e}' (${r})`)};var os=(e,t,r={})=>{let n={},o={};r&&typeof r=="object"&&(r.functions!==void 0||r.partials!==void 0?(n=r.functions||{},o=r.partials||{}):typeof r=="object"&&(n=r));let s=L(e,{functions:n,partials:o},t,{});return s===void 0?{}:s},L=(e,t,r,n)=>{let o=t.functions||t;if(e.var&&!e.type)return H(e.var,r,n);if(e.type===m.LITERAL)return e.value;if(e.type===m.VARIABLE)return H(e.path,r,n);if(e.type===m.INTERPOLATION)return ss(e.parts,t,r,n);switch(e.type){case m.FUNCTION:return zn(e,t,r,n);case m.BINARY:return Wn(e,t,r,n);case m.UNARY:return qn(e,t,r,n);case m.CONDITIONAL:return cs(e,t,r,n);case m.LOOP:return ps(e,t,r,n);case m.OBJECT:return ms(e,t,r,n);case m.ARRAY:return gs(e,t,r,n);case m.PARTIAL:return ys(e,t,r,n);case m.PATH_REFERENCE:return bs(e,t,r,n);default:throw new Error(`Unknown node type: ${e.type}`)}},Bn=new Map,is=e=>{let t=[],r="",n=!1;for(let o=0;o<e.length;o++){let i=e[o];if(i==="[")r&&(t.push({type:"property",value:r}),r=""),n=!0;else if(i==="]"){if(n&&r){let s=r.trim();if(/^\d+$/.test(s))t.push({type:"index",value:parseInt(s,10)});else if(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'")){let c=s.slice(1,-1);t.push({type:"property",value:c})}else t.push({type:"property",value:s});r=""}n=!1}else r+=i}return r&&t.push({type:"property",value:r}),t},H=(e,t,r)=>{if(!e)return;if(e in r)return r[e];let n=Bn.get(e);if(!n){let i=[],s="",c=0;for(let a=0;a<e.length;a++){let l=e[a];l==="["?(c++,s+=l):l==="]"?(c--,s+=l):l==="."&&c===0?s&&(i.push(s),s=""):s+=l}s&&i.push(s),n=[];for(let a of i){let l=is(a.trim());n.push(...l)}Bn.set(e,n)}let o=t;for(let i=0;i<n.length;i++){let s=n[i];if(s.type==="property"&&s.value in r){o=r[s.value];continue}if(o==null)return;(s.type==="property"||s.type==="index")&&(o=o[s.value])}return o},ss=(e,t,r,n)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=L(i,t,r,n);o.push(s!=null?String(s):"")}return o.join("")},zn=(e,t,r,n)=>{let o=t.functions||t,i=o[e.name];if(!i)throw Un(e.name,o);let s=e.args.map(c=>L(c,t,r,n));return i(...s)},ke=(e,t,r,n)=>{if(e.var&&!e.type)return H(e.var,r,n);switch(e.type){case m.VARIABLE:return H(e.path,r,n);case m.LITERAL:return e.value;case m.BINARY:return Wn(e,t,r,n);case m.UNARY:return qn(e,t,r,n);case m.FUNCTION:return zn(e,t,r,n);default:return L(e,t,r,n)}},Wn=(e,t,r,n)=>{if(e.op===O.AND||e.op===O.OR){let s=ke(e.left,t,r,n),c=ke(e.right,t,r,n);switch(e.op){case O.AND:return s&&c;case O.OR:return s||c}}let o=L(e.left,t,r,n),i=L(e.right,t,r,n);switch(e.op){case O.EQ:return o==i;case O.NEQ:return o!=i;case O.GT:return o>i;case O.LT:return o<i;case O.GTE:return o>=i;case O.LTE:return o<=i;case O.IN:return Array.isArray(i)?i.includes(o):!1;case O.ADD:if(typeof o!="number"||typeof i!="number")throw new le(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case O.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new le(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},qn=(e,t,r,n)=>{let o=e.op===et.NOT?ke(e.operand,t,r,n):L(e.operand,t,r,n);if(e.op===et.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},as=(e,t,r,n)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===m.VARIABLE)if(H(o.path,r,n)){let s=e.bodies[0];if(s.type===m.OBJECT&&s.properties.length<=5){let c={};for(let a of s.properties){let l=a.parsedKey?L(a.parsedKey,t,r,n):a.key,d=a.value;if(d.type===m.LITERAL)c[l]=d.value;else if(d.type===m.VARIABLE)c[l]=H(d.path,r,n);else if(d.type===m.INTERPOLATION){let u=[];for(let f of d.parts)if(typeof f=="string")u.push(f);else if(f.type===m.VARIABLE){let p=H(f.path,r,n);u.push(p!=null?String(p):"")}else{let p=L(f,t,r,n);u.push(p!=null?String(p):"")}c[l]=u.join("")}else c[l]=L(d,t,r,n)}return c}}else{let s=e.bodies[1];if(s.type===m.OBJECT&&s.properties.length<=5){let c={};for(let a of s.properties){let l=a.parsedKey?L(a.parsedKey,t,r,n):a.key,d=a.value;if(d.type===m.LITERAL)c[l]=d.value;else if(d.type===m.VARIABLE)c[l]=H(d.path,r,n);else if(d.type===m.INTERPOLATION){let u=[];for(let f of d.parts)if(typeof f=="string")u.push(f);else if(f.type===m.VARIABLE){let p=H(f.path,r,n);u.push(p!=null?String(p):"")}else{let p=L(f,t,r,n);u.push(p!=null?String(p):"")}c[l]=u.join("")}else c[l]=L(d,t,r,n)}return c}}}return null},cs=(e,t,r,n)=>{let o=as(e,t,r,n);if(o!==null)return o;for(let i=0;i<e.conditions.length;i++){let s=e.conditions[i];if(s===null||ke(s,t,r,n))return L(e.bodies[i],t,r,n)}return Hn},ls=(e,t)=>{let r=e.body,n=e.itemVar;if(r.type===m.CONDITIONAL&&r.conditions.length===1&&r.conditions[0].type===m.VARIABLE){let o=r.conditions[0].path,i=r.bodies[0];if(o.startsWith(n+".")){let s=o.substring(n.length+1);if(i.type===m.OBJECT&&i.properties.length<=5){for(let a of i.properties)if(a.parsedKey)return null;let c=[];for(let a=0;a<t.length;a++){let l=t[a];if(l[s]){let d={};for(let u of i.properties){let f=u.key,p=u.value;if(p.type===m.LITERAL)d[f]=p.value;else if(p.type===m.VARIABLE){let h=p.path;if(h===n)d[f]=l;else if(h.startsWith(n+".")){let g=h.substring(n.length+1);d[f]=l[g]}else return null}else if(p.type===m.INTERPOLATION){let h=[],g=!0;for(let y of p.parts)if(typeof y=="string")h.push(y);else if(y.type===m.VARIABLE){let b=y.path;if(b===n)h.push(l!=null?String(l):"");else if(b.startsWith(n+".")){let A=b.substring(n.length+1),v=l[A];h.push(v!=null?String(v):"")}else{g=!1;break}}else{g=!1;break}if(!g)return null;d[f]=h.join("")}else return null}c.push(d)}}return c}}}return null},us=(e,t)=>{let r=e.body,n=e.itemVar,o=ls(e,t);if(o!==null)return o;if(r.type===m.OBJECT&&r.properties.length<=5&&!r.whenCondition){for(let c of r.properties)if(c.parsedKey)return null;let i=[],s=!0;for(let c of r.properties){let a=c.key,l=c.value;if(l.type===m.LITERAL)i.push({key:a,type:"literal",value:l.value});else if(l.type===m.VARIABLE){let d=l.path;if(d===n)i.push({key:a,type:"item"});else if(d.startsWith(n+".")){let u=d.substring(n.length+1);if(!u.includes(".")&&!u.includes("["))i.push({key:a,type:"prop",prop:u});else{s=!1;break}}else{s=!1;break}}else if(l.type===m.INTERPOLATION&&l.parts.length===1){let d=l.parts[0];if(d.type===m.VARIABLE){let u=d.path;if(u===n)i.push({key:a,type:"item_string"});else if(u.startsWith(n+".")){let f=u.substring(n.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:a,type:"prop_string",prop:f});else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}if(s){let c=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 a=0;a<t.length;a++){let l=t[a];c[a]={id:l.id,title:l.title!=null?String(l.title):"",completed:l.completed}}else for(let a=0;a<t.length;a++){let l=t[a],d={};for(let u of i)if(u.type==="literal")d[u.key]=u.value;else if(u.type==="item")d[u.key]=l;else if(u.type==="prop")d[u.key]=l[u.prop];else if(u.type==="item_string")d[u.key]=l!=null?String(l):"";else if(u.type==="prop_string"){let f=l[u.prop];d[u.key]=f!=null?String(f):""}c[a]=d}return c}}return null},ds=(e,t,r,n,o)=>{let i=[],s=e.body;if(s.type===m.OBJECT&&s.fast!==!1){let c=e.itemVar,a=e.indexVar;for(let l=0;l<o.length;l++){let d=o[l],u={},f={...n,[c]:d,...a&&{[a]:l}};f.__paths__||(f.__paths__=n.__paths__||{});let p=e.iterable.path||"";if(n&&n.__paths__&&p){let h=p.split("."),g=h[0];g in n.__paths__&&(p=n.__paths__[g],h.length>1&&(p+="."+h.slice(1).join(".")))}f.__paths__={...f.__paths__,[c]:`${p}[${l}]`,...a&&{[a]:l}};for(let h of s.properties){let g=h.parsedKey?L(h.parsedKey,t,r,f):h.key,y=h.value;if(y.type===m.LITERAL)u[g]=y.value;else if(y.type===m.VARIABLE){let b=y.path;if(b===c)u[g]=d;else if(b===a)u[g]=l;else if(b.startsWith(c+".")){let A=b.substring(c.length+1);!A.includes(".")&&!A.includes("[")?u[g]=d[A]:u[g]=H(b,r,{...n,[c]:d,...a&&{[a]:l}})}else u[g]=H(b,r,{...n,[c]:d,...a&&{[a]:l}})}else if(y.type===m.INTERPOLATION){let b=[];for(let A of y.parts)if(typeof A=="string")b.push(A);else if(A.type===m.VARIABLE){let v=A.path,S;if(v===c)S=d;else if(v===a)S=l;else if(v.startsWith(c+".")){let P=v.substring(c.length+1);!P.includes(".")&&!P.includes("[")?S=d[P]:S=H(v,r,{...n,[c]:d,...a&&{[a]:l}})}else S=H(v,r,{...n,[c]:d,...a&&{[a]:l}});b.push(S!=null?String(S):"")}else{let v={...n,[c]:d,...a&&{[a]:l}},S=L(A,t,r,v);b.push(S!=null?String(S):"")}u[g]=b.join("")}else{let b={...n,[c]:d,...a&&{[a]:l}};u[g]=L(y,t,r,b)}}i.push(u)}return i}return null},fs=(e,t,r)=>{let n=e.body;if(n.type===m.OBJECT&&n.properties.length===1&&n.properties[0].key==="$if item.visible"){let i=n.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 c=s.properties[0],a=s.properties[1];if(c.key==="id"&&c.value.type===m.VARIABLE&&c.value.path==="item.id"&&a.key==="$if item.highlighted"&&a.value.type===m.CONDITIONAL){let l=[];for(let d=0;d<t.length;d++){let u=t[d];if(u.visible){let f={id:u.id};u.highlighted?(f.highlight=!0,f.message=`This item is highlighted: ${u.name}`):(f.highlight=!1,f.message=u.name),l.push(f)}}return l}}}}return null},ps=(e,t,r,n)=>{let o=L(e.iterable,t,r,n);if(!Array.isArray(o)){let l,d=!1;if(e.iterable.type===m.FUNCTION){d=!0;let f=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}(${f})`}else l=e.iterable.path||"undefined";let u=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${l}`;throw Fn(u,o,d)}if(!e.indexVar){let l=fs(e,o,e.itemVar);if(l!==null)return l}if(!e.indexVar){let l=us(e,o);if(l!==null)return l}let i=ds(e,t,r,n,o);if(i!==null)return i;let s=[],c=e.iterable.path||"";if(n&&n.__paths__&&c){let l=c.split("."),d=l[0];d in n.__paths__&&(c=n.__paths__[d],l.length>1&&(c+="."+l.slice(1).join(".")))}let a=!1;e.body.type===m.ARRAY&&(e.body.items.length<=1?a=!1:a=e.body._shouldPreserveArray??=e.body.items.some(l=>l.type===m.OBJECT&&l.properties.some(d=>d.key.startsWith("$if ")||d.key.startsWith("$when "))));for(let l=0;l<o.length;l++){let d=e.indexVar?{...n,[e.itemVar]:o[l],[e.indexVar]:l}:{...n,[e.itemVar]:o[l]};d.__paths__||(d.__paths__=n.__paths__||{}),d.__paths__={...d.__paths__,[e.itemVar]:`${c}[${l}]`},e.indexVar&&(d.__paths__[e.indexVar]=l);let u=L(e.body,t,r,d);if(Array.isArray(u)&&u.length===1&&!a){let f=u[0];s.push(f===void 0?{}:f)}else s.push(u===void 0?{}:u)}return s},hs=(e,t,r,n)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?L(o.parsedKey,t,r,n):o.key,s=o.value;if(s.type===m.OBJECT&&s.properties.length<=10&&!s.whenCondition){let c={},a={},l=!0;for(let d of s.properties){let u=d.parsedKey?L(d.parsedKey,t,r,n):d.key,f=d.value;if(f.type===m.LITERAL)a[u]=f.value;else if(f.type===m.VARIABLE)a[u]=H(f.path,r,n);else if(f.type===m.INTERPOLATION){let p=[];for(let h of f.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let g=H(h.path,r,n);p.push(g!=null?String(g):"")}else{l=!1;break}if(!l)break;a[u]=p.join("")}else if(f.type===m.OBJECT&&f.properties.length<=5){let p={};for(let h of f.properties){let g=h.key,y=h.value;if(y.type===m.LITERAL)p[g]=y.value;else if(y.type===m.VARIABLE)p[g]=H(y.path,r,n);else if(y.type===m.INTERPOLATION){let b=[];for(let A of y.parts)if(typeof A=="string")b.push(A);else if(A.type===m.VARIABLE){let v=H(A.path,r,n);b.push(v!=null?String(v):"")}else{l=!1;break}if(!l)break;p[g]=b.join("")}else{l=!1;break}}if(!l)break;a[u]=p}else{l=!1;break}}if(l)return c[i]=a,c}}return null},ms=(e,t,r,n)=>{let o=t.functions||t;if(e.whenCondition&&!ke(e.whenCondition,o,r,n))return;let i=hs(e,t,r,n);if(i!==null)return i;if(e.fast){let l={};for(let d of e.properties){let u=d.parsedKey?L(d.parsedKey,t,r,n):d.key,f=d.value;if(f.type===m.LITERAL)l[u]=f.value;else if(f.type===m.VARIABLE)l[u]=H(f.path,r,n);else if(f.type===m.INTERPOLATION){let p=[];for(let h of f.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let g=H(h.path,r,n);p.push(g!=null?String(g):"")}else{let g=L(h,t,r,n);p.push(g!=null?String(g):"")}l[u]=p.join("")}else l[u]=L(f,t,r,n)}return l}let s={},c=null,a=!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 ")){a=!0;break}for(let l of e.properties)if(l.key.startsWith("$if ")||l.key.match(/^\$if\s+\w+.*:?$/)){let d=L(l.value,t,r,n);if(!a&&d!==null&&d!==void 0)return Array.isArray(d)&&d.length===1?d[0]:d;typeof d=="object"&&d!==null&&!Array.isArray(d)&&Object.assign(s,d)}else if(l.key.startsWith("$for ")){if(e.properties.length===1)return L(l.value,t,r,n)}else{let d=l.value;if(d&&d.type===m.OBJECT&&d.properties){let u=d.properties.find(f=>f.key.startsWith("$for "));if(u){let f=L(u.value,t,r,n);f!==void 0&&(s[l.key]=f)}else{let f=L(l.value,t,r,n);f!==void 0&&(s[l.key]=f)}}else{let u=l.parsedKey?L(l.parsedKey,t,r,n):l.key,f=L(l.value,t,r,n);f!==void 0&&(s[u]=f)}}return s},Hn={},gs=(e,t,r,n)=>{let o=[];for(let i of e.items)if(i.type===m.LOOP){let s=L(i,t,r,n);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=L(i,t,r,n);s!==Hn&&s!==void 0&&o.push(s)}return o},ys=(e,t,r,n)=>{let{name:o,data:i,whenCondition:s}=e,c=t.partials||{},a=t.functions||t;if(s&&!ke(s,a,r,n))return;if(!c[o])throw new le(`Partial '${o}' is not defined`);let l=n._partialStack||[];if(l.includes(o))throw new le(`Circular partial reference detected: ${o}`);let d=c[o],u=r,f={...n,_partialStack:[...l,o]};if(n){u={...r};for(let p of Object.keys(n))p.startsWith("_")||(u[p]=n[p])}if(i){let p=L(i,t,r,n);u={...u,...p}}return L(d,t,u,f)},bs=(e,t,r,n)=>{let{path:o}=e,i=o.split("."),s=i[0],c=i.slice(1);if(!n||!(s in n))throw new le(`Path reference '#{${o}}' refers to '${s}' which is not a loop variable in the current scope`);if(n.__paths__||(n.__paths__={}),!(s in n.__paths__))throw new le(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let a=n.__paths__[s];if(typeof a=="number"){if(c.length>0)throw new le(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(a)}return c.length>0&&(a+="."+c.join(".")),a};var wr=os;var Is=/\$\{([^}]*)\}/g,As=/#\{([^}]*)\}/g,Kn=(e,t={})=>{let r=e.match(/^(\w+)\((.*)\)$/);if(!r)return{isFunction:!1};let[,n,o]=r,i=ws(o,t);return{isFunction:!0,type:m.FUNCTION,name:n,args:i}},ws=(e,t={})=>e.trim()?Es(e).map(n=>vs(n.trim(),t)):[],Es=e=>{let t=[],r="",n=0,o=!1,i="";for(let s=0;s<e.length;s++){let c=e[s],a=s>0?e[s-1]:"";!o&&(c==='"'||c==="'")?(o=!0,i=c,r+=c):o&&c===i&&a!=="\\"?(o=!1,i="",r+=c):!o&&c==="("?(n++,r+=c):!o&&c===")"?(n--,r+=c):!o&&c===","&&n===0?(t.push(r),r=""):r+=c}return r&&t.push(r),t},vs=(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 r=Kn(e,t);if(r.isFunction)return{type:r.type,name:r.name,args:r.args};let n=e.trim(),o=[{op:" + ",type:"ADD"},{op:" - ",type:"SUBTRACT"}],i=-1,s=null;for(let{op:c,type:a}of o){let l=0;for(;l<n.length;){let d=ze(n.substring(l),c);if(d===-1)break;let u=l+d;u>i&&(i=u,s={op:c,type:a}),l=u+c.length}}if(i!==-1)try{return Q(n,t)}catch{return{type:m.VARIABLE,path:n}}return{type:m.VARIABLE,path:n}},Gn=/^\w+\(.*\)$/,xs=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,Cs=e=>{if(!(!e||e.trim()===""||Gn.test(e))&&xs.test(e))throw e.includes("?")&&e.includes(":")?new E(`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 E(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new E(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},Yn=e=>{let t=e.trim();if(Gn.test(t))throw new E(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new E(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new E(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new E(`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 E(`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}},ut=(e,t={})=>{let r=e.trim();Cs(r);let n=Kn(r,t);if(n.isFunction)return{type:n.type,name:n.name,args:n.args};if(r.includes("[")&&!/[\s+\-*/%|&?:]/.test(r)){let o=0;for(let i of r)i==="["?o++:i==="]"&&o--;if(o!==0)throw new Error("Invalid array index syntax")}return{type:m.VARIABLE,path:r}},Er=(e,t={})=>{let r=e,n=[];(e.includes("\\${")||e.includes("\\#{"))&&(r=e.replace(/\\\\(\$\{[^}]*\})/g,"\\DOUBLE_ESC_VAR$1"),r=r.replace(/\\\\(#\{[^}]*\})/g,"\\DOUBLE_ESC_PATH$1"),r=r.replace(/\\(\$\{[^}]*\})/g,(l,d)=>{let u=`__ESCAPED_${n.length}__`;return n.push(d),u}),r=r.replace(/\\(#\{[^}]*\})/g,(l,d)=>{let u=`__ESCAPED_${n.length}__`;return n.push(d),u}),r=r.replace(/\\DOUBLE_ESC_VAR/g,"\\"),r=r.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...r.matchAll(Is)],i=[...r.matchAll(As)],s=[...o.map(l=>({match:l,type:"variable"})),...i.map(l=>({match:l,type:"pathref"}))].sort((l,d)=>l.match.index-d.match.index);if(s.length===0){let l=r;for(let d=0;d<n.length;d++)l=l.replace(`__ESCAPED_${d}__`,n[d]);return{type:m.LITERAL,value:l}}if(s.length===1&&s[0].match[0]===r&&n.length===0){let{match:l,type:d}=s[0];try{return d==="variable"?ut(l[1],t):Yn(l[1])}catch(u){if(u.message==="Invalid array index syntax")return{type:m.LITERAL,value:r};throw u}}let c=[],a=0;for(let{match:l,type:d}of s){let[u,f]=l,p=l.index;if(p>a){let h=r.substring(a,p);for(let g=0;g<n.length;g++)h=h.replace(`__ESCAPED_${g}__`,n[g]);h&&c.push(h)}try{let h;d==="variable"?h=ut(f.trim(),t):h=Yn(f.trim()),c.push(h)}catch(h){if(h.message==="Invalid array index syntax")c.push(u);else throw h}a=p+u.length}if(a<r.length){let l=r.substring(a);for(let d=0;d<n.length;d++)l=l.replace(`__ESCAPED_${d}__`,n[d]);l&&c.push(l)}return{type:m.INTERPOLATION,parts:c}};var Cr=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Qn=e=>Object.keys(e),ae=e=>e.join("."),Te=(e,t,r)=>{let n=Qn(e).filter(o=>!t.has(o));if(n.length>0)throw new E(`Unexpected key '${n[0]}' in condition JSON at '${ae(r)}'`)},De=(e,t)=>typeof e=="string"?Er(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?_s(e,t):Rs(e,t):{type:m.LITERAL,value:e},Ss=e=>{let{$each:t,...r}=e;if(typeof t!="string")throw new E("$each value must be a non-empty string");let n=t.trim();if(n==="")throw new E("$each value must be a non-empty string");if(Object.keys(r).length===0)throw new E("Empty $each body not allowed");if(r.$partial!==void 0)throw new E("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${n}`]:r}},_s=(e,t)=>{let r=[],n=!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 a=Ss(i),l=Object.keys(a);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let d=Xn(l[0],a[l[0]],t,!0);r.push(d),n=!0;continue}}catch(a){throw a instanceof E?a:new E(a.message)}let c=Object.keys(i);if(c.length===1&&/^\$for(?::\w+)?\s/.test(c[0])){let a=Xn(c[0],i[c[0]],t);r.push(a),n=!0;continue}}let s=De(i,t);r.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)&&(n=!0)}return{type:m.ARRAY,items:r,fast:!n}},Rs=(e,t)=>{let r=[],n=!1,o=null,i=Object.entries(e),s=0;if(e.$partial!==void 0){if(typeof e.$partial!="string")throw new E("$partial value must be a string");if(e.$partial.trim()==="")throw new E("$partial value cannot be an empty string");let a=["$if","$elif","$else","$for"],l=[];for(let[b]of i)for(let A of a)if(b===A||b.startsWith(A+" ")||b.startsWith(A+"#")){l.push(A);break}if(l.length>0)throw new E(`Cannot use $partial with ${l.join(", ")} at the same level. Wrap $partial in a parent object if you need conditionals.`);let{$partial:d,$when:u,...f}=e,p={},h=!1;for(let[b,A]of Object.entries(f)){let v=b;(b.startsWith("\\$")||b.startsWith("$$"))&&(v=b.slice(1)),p[v]=A,h=!0}let g=null;if(h&&(g=De(p,t),g.type===m.OBJECT)){let b=!1;for(let A of g.properties)if(A.value.type===m.VARIABLE||A.value.type===m.INTERPOLATION||A.value.type===m.FUNCTION||A.value.type===m.CONDITIONAL||A.value.type===m.OBJECT&&!A.value.fast||A.value.type===m.ARRAY&&!A.value.fast){b=!0;break}b&&(g.fast=!1)}let y={type:m.PARTIAL,name:d,data:g};return u!==void 0&&(y.whenCondition=Jn(u,t)),y}for(let[a,l]of i)if(a==="$when"){if(o!==null)throw new E("Multiple '$when' directives on the same object are not allowed");if(l==null)throw new E("Missing condition expression after '$when'");o=Jn(l,t),n=!0}else if(a.startsWith("$when#")||a.startsWith("$when "))throw new E("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<i.length;){let[a,l]=i[s];if(a==="$when"){s++;continue}if(a==="$each")throw new E("$each can only be used inside arrays");if(a.startsWith("$if ")||a.match(/^\$if#\w+\s/)||a.match(/^\$if\s+\w+.*:$/)){let d=Os(i,s,t);r.push({key:a,value:d.node}),n=!0,s=d.nextIndex}else if(/^\$for(?::\w+)?\s/.test(a)){let d=a.match(/^\$for(?::(\w+))?\s/)?.[1]||"",u=d?`:${d}`:"";throw new E(`$for loops must be inside arrays - use '- $for${u} item in items:' instead of '$for${u} item in items:'. For cleaner object generation syntax, consider using $each.`)}else{if(a.startsWith("$elif ")||a.startsWith("$else"))throw new E(`'${a.split(" ")[0]}' without matching '$if'`);if(a==="$if"||a==="$if:")throw new E("Missing condition expression after '$if'");{let d=De(l,t);(d.type===m.FUNCTION||d.type===m.CONDITIONAL||d.type===m.PARTIAL||d.type===m.OBJECT&&!d.fast||d.type===m.ARRAY&&!d.fast)&&(n=!0);let u=Er(a,t),f={key:a,value:d};(u.type!==m.LITERAL||u.value!==a)&&(f.parsedKey=u),r.push(f),s++}}}let c={type:m.OBJECT,properties:r,fast:!n};return o&&(c.whenCondition=o),c},Os=(e,t,r={})=>{let n=[],o=[],i=t,[s,c]=e[i],a=null,l;if(s.startsWith("$if#")){let u=s.match(/^\$if#(\w+)\s+(.+)$/);if(u)a=u[1],l=u[2];else throw new E(`Invalid conditional syntax: ${s}`)}else l=s.substring(4),l.endsWith(":")&&(l=l.slice(0,-1).trim());Ar(l);let d=Q(l,r);for(n.push(d),o.push(De(c,r)),i++;i<e.length;){let[u,f]=e[i],p=!1,h;if(a?u.startsWith(`$elif#${a} `)?(h=u.substring(`$elif#${a} `.length),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(u===`$else#${a}`||u===`$else#${a}:`)&&(p=!0,h=null):u.startsWith("$elif ")?(h=u.substring(6),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(u==="$else"||u==="$else:")&&(p=!0,h=null),p){if(h===null)n.push(null);else{Ar(h);let g=Q(h,r);n.push(g)}if(o.push(De(f,r)),i++,h===null)break}else break}return{node:{type:m.CONDITIONAL,conditions:n,bodies:o,id:a},nextIndex:i}},vr={eq:O.EQ,neq:O.NEQ,gt:O.GT,gte:O.GTE,lt:O.LT,lte:O.LTE,in:O.IN,add:O.ADD,sub:O.SUBTRACT},xr={all:O.AND,any:O.OR},Ls=new Set(["var","literal","call","not",...Object.keys(vr),...Object.keys(xr)]),$s=(e,t,r)=>{if(!Array.isArray(e))throw new E(`Condition JSON operator '${t}' at '${ae(r)}' requires an array`);if(e.length!==2)throw new E(`Condition JSON operator '${t}' at '${ae(r)}' requires exactly 2 operands`);return e},ks=(e,t,r,n,o)=>{if(!Array.isArray(e))throw new E(`Condition JSON operator '${t}' at '${ae(o)}' requires an array`);if(e.length===0)throw new E(`Condition JSON operator '${t}' at '${ae(o)}' requires at least 1 condition`);return e.map((s,c)=>Ce(s,n,[...o,c])).reduce((s,c)=>({type:m.BINARY,op:r,left:s,right:c}))},Ts=(e,t,r)=>{let n,o;if(typeof e.call=="string")n=e.call,o=e.args??[],Te(e,new Set(["call","args"]),r);else if(Cr(e.call))n=e.call.name,o=e.call.args??[],Te(e,new Set(["call"]),r),Te(e.call,new Set(["name","args"]),[...r,"call"]);else throw new E(`Condition JSON call at '${ae(r)}' requires a function name`);if(typeof n!="string"||n.trim()==="")throw new E(`Condition JSON call at '${ae(r)}' requires a non-empty function name`);if(!/^\w+$/.test(n))throw new E(`Invalid condition JSON function name '${n}' at '${ae(r)}'`);if(!Array.isArray(o))throw new E(`Condition JSON call '${n}' at '${ae(r)}' requires args to be an array`);return{type:m.FUNCTION,name:n,args:o.map((i,s)=>Ce(i,t,[...r,"args",s]))}},Ce=(e,t={},r=["$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 E(`Condition JSON array at '${ae(r)}' must be wrapped in an operator or { literal: [...] }`);if(!Cr(e))throw new E(`Invalid condition JSON value at '${ae(r)}'`);let n=Qn(e);if(n.length===0)throw new E(`Condition JSON object at '${ae(r)}' must contain an operator`);let o=n.filter(s=>Ls.has(s));if(o.length===0)throw new E(`Unknown condition JSON operator '${n[0]}' at '${ae(r)}'`);if(o.length>1)throw new E(`Condition JSON at '${ae(r)}' must contain exactly one operator`);let i=o.includes("call")?"call":o[0];if(i==="var"){if(Te(e,new Set(["var"]),r),typeof e.var!="string"||e.var.trim()==="")throw new E(`Condition JSON var at '${ae(r)}' requires a non-empty path`);return{type:m.VARIABLE,path:e.var}}if(i==="literal")return Te(e,new Set(["literal"]),r),{type:m.LITERAL,value:e.literal};if(i==="call")return Ts(e,t,r);if(i==="not")return Te(e,new Set(["not"]),r),{type:m.UNARY,op:et.NOT,operand:Ce(e.not,t,[...r,"not"])};if(i in xr)return Te(e,new Set([i]),r),ks(e[i],i,xr[i],t,[...r,i]);if(i in vr){Te(e,new Set([i]),r);let s=$s(e[i],i,[...r,i]);return{type:m.BINARY,op:vr[i],left:Ce(s[0],t,[...r,i,0]),right:Ce(s[1],t,[...r,i,1])}}throw new E(`Unknown condition JSON operator '${i}' at '${ae(r)}'`)},Jn=(e,t={})=>{if(e==null)throw new E("Missing condition expression after '$when'");if(typeof e=="string"){if(e.trim()==="")throw new E("Empty condition expression after '$when'");return Q(e,t)}return Cr(e)||Array.isArray(e)?Ce(e,t):{type:m.LITERAL,value:e}},Q=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let l=e.slice(1,-1),d=0,u=!0;for(let f=0;f<l.length;f++)if(l[f]==="("?d++:l[f]===")"&&d--,d<0){u=!1;break}if(u&&d===0)return Q(l,t)}let r=ze(e,"||");if(r!==-1)return{type:m.BINARY,op:O.OR,left:Q(e.substring(0,r).trim(),t),right:Q(e.substring(r+2).trim(),t)};let n=ze(e,"&&");if(n!==-1)return{type:m.BINARY,op:O.AND,left:Q(e.substring(0,n).trim(),t),right:Q(e.substring(n+2).trim(),t)};let o=[{op:">=",type:O.GTE},{op:"<=",type:O.LTE},{op:"==",type:O.EQ},{op:"!=",type:O.NEQ},{op:">",type:O.GT},{op:"<",type:O.LT},{op:" in ",type:O.IN}];for(let{op:l,type:d}of o){let u=ze(e,l);if(u!==-1)return{type:m.BINARY,op:d,left:Q(e.substring(0,u).trim(),t),right:Q(e.substring(u+l.length).trim(),t)}}let i=-1,s=null,c=[{op:" + ",type:O.ADD},{op:" - ",type:O.SUBTRACT}];for(let{op:l,type:d}of c){let u=0;for(;u<e.length;){let f=ze(e.substring(u),l);if(f===-1)break;let p=u+f;p>i&&(i=p,s={op:l,type:d}),u=p+l.length}}if(i!==-1&&s)return{type:m.BINARY,op:s.type,left:Q(e.substring(0,i).trim(),t),right:Q(e.substring(i+s.op.length).trim(),t)};let a=[" * "," / "," % "];for(let l of a)if(ze(e,l)!==-1)throw new E(`Arithmetic operations are not allowed in conditionals: "${l}"`);return e.startsWith("!")?{type:m.UNARY,op:et.NOT,operand:Q(e.substring(1).trim(),t)}:Zn(e,t)},ze=(e,t)=>{let r=0,n=0;for(;n<=e.length-t.length;){if(e[n]==="(")r++;else if(e[n]===")")r--;else if(r===0&&e.substring(n,n+t.length)===t)return n;n++}return-1},Ds=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}},Zn=(e,t)=>{let r=e.trim();if(r.match(/^(\w+)\((.*)\)$/))return ut(r,t);let o=Ds(r);if(o.type===m.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(r))return{type:m.VARIABLE,path:r};try{return ut(r,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},Ps=(e,t=!1)=>{let r=t?"$each":"$for";try{Mn(e)}catch(n){if(n instanceof E&&t){let o=n.message.replace(/\$for/g,"$each");throw new E(o.replace("Parse Error: ",""))}throw n}},Xn=(e,t,r,n=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let y=n?"$each":"$for";throw new E(`Invalid loop syntax (got: '${e.replace("$for",y)}')`)}let s=i[1],c=i[2].trim();Ps(c,n);let a=c.match(/^(.+?)\s+in\s+(.+)$/);if(!a){let y=n?"$each":"$for";throw new E(`Invalid loop syntax - missing 'in' keyword (got: '${y} ${c}')`)}let l=a[1].trim(),d=a[2].trim(),u,f=null;if(l.includes(",")){let y=l.split(",").map(b=>b.trim());if(y.length!==2)throw new E(`Invalid loop variables: ${l}. Expected format: "item" or "item, index"`);u=y[0],f=y[1]}else u=l;let p=["this","undefined","null","true","false"];if(p.includes(u))throw new E(`Reserved variable name: ${u}`);if(f&&p.includes(f))throw new E(`Reserved variable name: ${f}`);let h=Zn(d,r),g=De(t,r);return{type:m.LOOP,itemVar:u,indexVar:f,iterable:h,body:g,flatten:s!=="nested"}};var Ns=(e,t={})=>{let{functions:r={}}=t;return De(e,r)},Dt=Ns;var dt={};Ki(dt,{now:()=>Vs});var Vs=()=>Date.now();var js=(e,t,r={})=>{let{functions:n={},partials:o={}}=r,i={...dt,...n},s=Dt(e,{functions:i}),c={};for(let[a,l]of Object.entries(o))c[a]=Dt(l,{functions:i});return wr(s,t,{functions:i,partials:c})},ue=js;var Ms=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",Fs=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,Us=(e,t)=>{if(Ms(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new E("Empty condition expression");return Q(e,t)}return Ce(e,t)},Bs=(e,t={},r={})=>{let n=Fs(r),o={...dt,...n},i=Us(e,o);return!!ke(i,{functions:o,partials:{}},t,{})},Sr=Bs;var pt=(e,t={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return Sr(e,t)},io=(e,t,r={})=>{let n=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=a=>a,transformActionFirstArgument:c=a=>a}=r;for(let[a,l]of Object.entries(t))a!=="createInitialState"&&(a.startsWith("select")?o[a]=(...d)=>l(s(n),...d):i[a]=(...d)=>{let u;return n=Ir(n,p=>{let h=l(c(p),...d);u=h!==void 0&&!fe(h)?h:void 0}),u});return{...o,...i}},Vt=(e,t)=>r=>{let n=e(),o=Array.isArray(r)?r:[r];return Ir(n,i=>{o.forEach(s=>{t.forEach(c=>{c(i,s)})})})};var zs=(e,t)=>{if(e.default!==void 0)return e.default;let r=["number","boolean","string","object"];if(!r.includes(e.type))throw new Error(`Invalid variable type: ${e.type} for variable ${t}. Expected one of: ${r.join(", ")}`);switch(e.type){case"number":return 0;case"boolean":return!1;case"string":return"";case"object":return{}}},ge=(e,t)=>Object.prototype.hasOwnProperty.call(e??{},t),ft=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),so=e=>{let t=fe(e)?Be(e):e;return structuredClone(t)},Ws=({characterId:e,resourceCharacter:t,variables:r={}}={})=>{if(!ge(t,"nameVariableId"))return;let n=t.nameVariableId,o=r?.[n];if(typeof o!="string")throw new Error(`Character "${e}" nameVariableId "${n}" must resolve to a string variable`);return o},jt=({characterId:e,character:t,characterName:r,characters:n={},variables:o={}}={})=>{let i=e?n?.[e]:void 0;if(t?.name!==void 0)return t.name;if(r!==void 0)return r;let s=Ws({characterId:e,resourceCharacter:i,variables:o});return s!==void 0?s:i?.name||""},Pe=e=>ge(e,"computed"),tt=(e={},t={})=>Object.fromEntries(Object.entries(e??{}).filter(([r])=>!Pe(t[r]))),qs=e=>String(e).replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean),_r=(e,t)=>{let r=e;for(let n of t){if(r==null)return;r=r[n]}return r},Hs=(e,t={})=>{if(typeof e!="string"||e.trim()==="")throw new Error("Computed expression var requires a non-empty string path");let r=qs(e),[n,o,...i]=r;if(n==="variables"){if(!o)return t.variables;let s=typeof t.resolveVariable=="function"?t.resolveVariable(o):t.variables?.[o];return _r(s,i)}return n==="runtime"?_r(t.runtime,r.slice(1)):_r(t,r)},Ys=(e,t,r)=>{if(!Array.isArray(t))throw new Error(`Computed expression operator "${e}" requires an array`);if(r!==void 0&&t.length!==r)throw new Error(`Computed expression operator "${e}" requires ${r} operand(s)`)},eo=(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`)},Ks=(e,t)=>{if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Computed expression operator "${e}" requires finite numeric operands`)},Ae=(e,t,r,n)=>(Ys(e,t,n),t.map(o=>Nt(o,r))),me=(e,t,r,n)=>{let o=Ae(e,t,r,n);return o.forEach(i=>Ks(e,i)),o},Gs=(e,t,r)=>{switch(e){case"var":return Hs(t,r);case"add":{let[n,o]=me(e,t,r,2);return n+o}case"sub":{let[n,o]=me(e,t,r,2);return n-o}case"mul":{let[n,o]=me(e,t,r,2);return n*o}case"div":{let[n,o]=me(e,t,r,2);return n/o}case"mod":{let[n,o]=me(e,t,r,2);return n%o}case"neg":{let[n]=me(e,t,r,1);return-n}case"round":{let[n]=me(e,t,r,1);return Math.round(n)}case"floor":{let[n]=me(e,t,r,1);return Math.floor(n)}case"ceil":{let[n]=me(e,t,r,1);return Math.ceil(n)}case"min":{let[n,o]=me(e,t,r,2);return Math.min(n,o)}case"max":{let[n,o]=me(e,t,r,2);return Math.max(n,o)}case"clamp":{let[n,o,i]=me(e,t,r,3);return Math.min(i,Math.max(o,n))}case"eq":{let[n,o]=Ae(e,t,r,2);return n==o}case"neq":{let[n,o]=Ae(e,t,r,2);return n!=o}case"gt":{let[n,o]=Ae(e,t,r,2);return n>o}case"gte":{let[n,o]=Ae(e,t,r,2);return n>=o}case"lt":{let[n,o]=Ae(e,t,r,2);return n<o}case"lte":{let[n,o]=Ae(e,t,r,2);return n<=o}case"in":{let[n,o]=Ae(e,t,r,2);return Array.isArray(o)?o.includes(n):!1}case"and":case"all":return eo(e,t),t.every(n=>!!Nt(n,r));case"or":case"any":return eo(e,t),t.some(n=>!!Nt(n,r));case"not":{let[n]=Ae(e,t,r,1);return!n}case"length":{let[n]=Ae(e,t,r,1);return typeof n=="string"||Array.isArray(n)?n.length:ft(n)?Object.keys(n).length:0}case"includes":{let[n,o]=Ae(e,t,r,2);return typeof n=="string"||Array.isArray(n)?n.includes(o):!1}case"literal":return so(t);default:throw new Error(`Unknown computed expression operator: ${e}`)}},Nt=(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 r=Object.entries(e);if(r.length!==1)throw new Error("Computed expression objects must contain exactly one operator");let[[n,o]]=r;return Gs(n,o,t)},Js=(e,t={})=>pt(e,{variables:t.variables,runtime:t.runtime}),Xs=(e,t)=>{if(!ft(e))throw new Error(`${t} must be an object`);let r=ge(e,"expr"),n=ge(e,"value");if(r===n)throw new Error(`${t} must contain exactly one of expr or value`)},Rr=(e,t,r)=>(Xs(e,t),ge(e,"value")?so(e.value):Nt(e.expr,r)),Qs=(e,t={},r="unknown")=>{if(!ft(e))throw new Error(`Computed variable "${r}" computed must be an object`);let n=ge(e,"expr"),o=ge(e,"value");if(ge(e,"branches")){if(n||o)throw new Error(`Computed variable "${r}" cannot combine branches with expr or value`);if(!Array.isArray(e.branches))throw new Error(`Computed variable "${r}" branches must be an array`);if(e.branches.length===0)throw new Error(`Computed variable "${r}" branches must not be empty`);if(!ft(e.default))throw new Error(`Computed variable "${r}" requires default`);for(let s=0;s<e.branches.length;s+=1){let c=e.branches[s];if(!ft(c))throw new Error(`Computed variable "${r}" branch ${s} must be an object`);if(!ge(c,"when"))throw new Error(`Computed variable "${r}" branch ${s} requires when`);if(Js(c.when,t))return Rr(c,`Computed variable "${r}" branch ${s}`,t)}return Rr(e.default,`Computed variable "${r}" default`,t)}if(n===o)throw new Error(`Computed variable "${r}" must contain exactly one of expr, value, or branches`);return Rr(e,`Computed variable "${r}"`,t)},Zs=(e,t,r)=>{switch(t){case"number":if(typeof r!="number"||!Number.isFinite(r))throw new Error(`Computed variable "${e}" expected type number, got ${Array.isArray(r)?"array":typeof r}`);return;case"boolean":if(typeof r!="boolean")throw new Error(`Computed variable "${e}" expected type boolean, got ${Array.isArray(r)?"array":typeof r}`);return;case"string":if(typeof r!="string")throw new Error(`Computed variable "${e}" expected type string, got ${Array.isArray(r)?"array":typeof r}`);return;case"object":if(r===null||typeof r!="object")throw new Error(`Computed variable "${e}" expected type object, got ${typeof r}`);return;default:throw new Error(`Invalid variable type: ${t} for computed variable ${e}`)}},ht=({variables:e={},runtime:t={},variableConfigs:r={},eager:n=!0}={})=>{let o=tt(e,r),i=Object.entries(r).filter(([,u])=>Pe(u)).map(([u])=>u),s={},c=[],a=u=>{if(ge(s,u))return s[u];let f=r[u];if(!Pe(f))return o[u];let p=c.indexOf(u);if(p>=0){let h=[...c.slice(p),u].join(" -> ");throw new Error(`Computed variable cycle detected: ${h}`)}c.push(u);try{let h=Qs(f.computed,d,u);return Zs(u,f.type,h),s[u]=h,h}finally{c.pop()}},l=new Proxy({},{get:(u,f)=>{if(typeof f=="string")return a(f)},has:(u,f)=>typeof f=="string"&&(ge(o,f)||i.includes(f)),ownKeys:()=>[...new Set([...Object.keys(o),...i])],getOwnPropertyDescriptor:(u,f)=>{if(!(typeof f!="string"||!ge(o,f)&&!i.includes(f)))return{enumerable:!0,configurable:!0}}}),d={variables:l,runtime:t,resolveVariable:a};return n?(i.forEach(u=>{a(u)}),{...o,...s}):l},ea=({variables:e={},runtime:t={},variableConfigs:r,projectData:n}={})=>ht({variables:e,runtime:t,variableConfigs:r??n?.resources?.variables??{},eager:!0}),Mt=e=>{let t={},r={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([n,o])=>{if(Pe(o))return;let i=zs(o,n);o.scope==="context"?t[n]=i:r[n]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}},Ft=(e,t)=>{let r=["context","device","account"];if(!e)throw new Error(`Variable scope is required for variable: ${t}`);if(!r.includes(e))throw new Error(`Invalid variable scope: ${e} for variable ${t}. Expected one of: ${r.join(", ")}`)},Ut=(e,t,r)=>{let n={number:["set","increment","decrement","multiply","divide"],boolean:["set","toggle"],string:["set"],object:["set"]},o=n[e];if(!o)throw new Error(`Unknown variable type: ${e} for variable ${r}`);if(!Object.values(n).flat().includes(t))throw new Error(`Unknown operation: ${t}`);if(!o.includes(t))throw new Error(`Operation "${t}" is not valid for variable "${r}" of type "${e}". Valid operations: ${o.join(", ")}`)},ta=2,to=12,ao=(e=ta)=>{if(!Number.isInteger(e)||e<0||e>to)throw new Error(`Operation "divide" requires roundTo to be an integer between 0 and ${to}.`);return e},ra=(e,t)=>{let r=10**t;return Math.round((e+Number.EPSILON)*r)/r},Pt=e=>typeof e=="number"&&Number.isFinite(e),$r=(e,t,r,n,o={})=>{if(e==="number"){if(t==="set"&&!Pt(r))throw new Error(`Operation "set" requires value to be a number for variable "${n}".`);if(t==="multiply"&&!Pt(r))throw new Error(`Operation "multiply" requires value to be a number for variable "${n}".`);if(t==="divide"&&!Pt(r))throw new Error(`Operation "divide" requires value to be a number for variable "${n}".`);if(t==="divide"){if(r===0)throw new Error(`Operation "divide" requires value to be a non-zero number for variable "${n}".`);ao(o.roundTo)}}},Bt=(e,t,r,n={})=>{let o=(s,c,a)=>{let l=s??c;if(!Pt(l))throw new Error(`Operation "${t}" requires ${a} to be a number.`);return l},i=s=>{let c=o(s,void 0,"value");if(c===0)throw new Error(`Operation "${t}" requires value to be a non-zero number.`);return c};switch(t){case"set":return r;case"multiply":return o(e,1,"current value")*o(r,void 0,"value");case"divide":return ra(o(e,0,"current value")/i(r),ao(n.roundTo));case"increment":return o(e,0,"current value")+o(r,1,"value");case"decrement":return o(e,0,"current value")-o(r,1,"value");case"toggle":return!e;default:throw new Error(`Unknown operation: ${t}`)}};var co=(e,t="DD/MM/YYYY - HH:mm")=>{if(!e)return"";let r=new Date(e),n=o=>String(o).padStart(2,"0");return t.replace("DD",n(r.getDate())).replace("MM",n(r.getMonth()+1)).replace("YYYY",r.getFullYear()).replace("YY",String(r.getFullYear()).slice(-2)).replace("HH",n(r.getHours())).replace("mm",n(r.getMinutes())).replace("ss",n(r.getSeconds()))},na=(e,t)=>{let r=i=>{if(!i)return;let s={};i.ui&&(s.ui=i.ui);let c=i.character?.sprite;return c&&Object.keys(c).length>0&&(s.sprite=c),Object.keys(s).length>0?s:void 0},n=r(e),o=r(t);return JSON.stringify(n)===JSON.stringify(o)?null:n&&!o?{changeType:"delete",data:e}:o&&!n?{changeType:"add",data:t}:o&&n?{changeType:"update",data:t}:null},ro=e=>{if(e?.resourceId===void 0)return;let t={resourceId:e.resourceId};e.transformId!==void 0&&(t.transformId=e.transformId);for(let r of["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"])e[r]!==void 0&&(t[r]=e[r]);for(let r of["animationName","animationSpeed","loop"])e[r]!==void 0&&(t[r]=e[r]);return t},no=e=>{if(e?.colorId!==void 0)return{colorId:e.colorId}},oo=(e,t)=>t&&!e?{changeType:"add",data:t}:e&&!t?{changeType:"delete",data:e}:e&&t&&JSON.stringify(e)!==JSON.stringify(t)?{changeType:"update",data:t}:null,oa=(e,t)=>{let r={},n=oo(ro(e),ro(t)),o=oo(no(e),no(t));return n&&(r.resource=n),o&&(r.color=o),Object.keys(r).length>0?r:null},kr=(e={},t={})=>{let r={},n=["sfx","voice"],o=c=>{let a=e[c],l=t[c];l&&!a?r[c]={changeType:"add",data:l}:a&&!l?n.includes(c)||(r[c]={changeType:"delete",data:a}):a&&l&&JSON.stringify(a)!==JSON.stringify(l)&&(r[c]={changeType:"update",data:l})},i=oa(e.background,t.background);i&&(r.background=i),o("screen"),o("bgm"),o("voice");let s=na(e.dialogue,t.dialogue);return s&&(r.dialogue=s),o("choice"),o("form"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),r},Tr=(e={})=>{let t=structuredClone(e);t.background&&(t.background.animations?.playback?.continuity!=="persistent"&&delete t.background.animations,!t.background.resourceId&&!t.background.colorId&&delete t.background);let r=o=>{t[o]&&(delete t[o].animations,Object.keys(t[o]).length===0&&delete t[o])};r("layout"),r("choice"),r("form"),r("screen"),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 n=(o,i)=>{let s=t[o]?.items;Array.isArray(s)&&(t[o].items=s.map(c=>{let a={...c};return delete a.animations,i(a)?a:null}).filter(Boolean),t[o].items.length===0&&delete t[o])};return n("character",o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId),n("visual",o=>o.resourceId||o.transformId),t},ia=(e,t)=>{if(!e||!t)return;let r=e;for(let n of t.split(".")){if(r==null||!(n in Object(r)))return;r=r[n]}return r},sa=(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 r=e.slice(7),n=ia(t,r);if(n===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return n},aa={conditional:new Set(["branches"]),updateProjectData:new Set(["projectData"]),showConfirmDialog:new Set(["confirmActions","cancelActions"]),form:new Set(["submitActions","cancelActions"]),submitForm:new Set(["actions"]),cancelForm:new Set(["actions"])},lo=(e,t)=>{let r=e[e.length-1];return r?aa[r]?.has(t)===!0:!1},Or=(e,t,r=[])=>Array.isArray(e)?e.map(n=>Or(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,lo(r,n)?o:Or(o,t,[...r,n])])):sa(e,t),Lr=(e,t,r=[])=>Array.isArray(e)?e.map(n=>Lr(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,lo(r,n)?o:Lr(o,t,[...r,n])])):typeof e=="string"?ue(e,t):e,Dr=(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 r=Or(e,t._event);return Lr(r,t)};var Z=e=>structuredClone(fe(e)?Be(e):e),U=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),uo=e=>e?.animations?.playback?.continuity==="persistent",$=(e,t)=>U(e??{},t)&&e[t]!==void 0,mt=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:Z(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},ca=e=>$(e,"opacity")||$(e,"blur"),mo=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],go=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],Pr=["animationName","animationSpeed","loop"],la=e=>mo.some(t=>$(e,t)),yo=e=>e?.text&&$(e.text,"content")&&$(e.text,"textStyleId"),bo=e=>$(e,"text"),ua=(e,t)=>e.resourceId?!0:yo(e)?!t?.text:!1,da=(e,t)=>{let r={...Z(e),...t};return t.text&&e.text&&(r.text={...Z(e.text),...Z(t.text)}),r},fa=(e,t)=>{if(bo(e)){if(e.resourceId)throw new Error(`Visual item "${e.id}" cannot define both resourceId and text`);if(!yo(e)&&!t?.text)throw new Error(`Visual item "${e.id}" text requires content and textStyleId`)}},fo=e=>go.some(t=>$(e,t)),po=e=>Pr.some(t=>$(e,t)),pa=(e,t,{hasAuthoredTransformId:r=!1}={})=>{if(!t)return e;for(let n of go)!r&&!$(e,n)&&$(t,n)&&(e[n]=t[n]),U(e,n)&&e[n]===void 0&&delete e[n];return e},Io=(e,t,r)=>{let n=e[r];return n?.id===t?.id?n:e.find(o=>o.id===t?.id)},ha=(e,t)=>{if(!t)return e;for(let r of mo)!$(e,r)&&$(t,r)&&(e[r]=t[r]),U(e,r)&&e[r]===void 0&&delete e[r];return e},ma=(e,t)=>(t&&(!$(e,"opacity")&&$(t,"opacity")&&(e.opacity=t.opacity),!$(e,"blur")&&$(t,"blur")&&(e.blur=Z(t.blur)),U(e,"opacity")&&e.opacity===void 0&&delete e.opacity,U(e,"blur")&&e.blur===void 0&&delete e.blur),e),Ao=(e,t,r=[],{hasPatchFn:n=()=>!1,mergeItemFn:o}={})=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let i=e.map((s,c)=>{let a=Io(r,s,c),l=t(s,a),d=ca(s),u=la(s),f=n(s),p=U(s,"animations"),h=Z(s);return!l&&(d||u||f)&&a&&(h=o?o(a,h):{...Z(a),...h},p||delete h.animations),ma(ha(h,a),a)}).filter(s=>t(s)||s.animations);return{hasValidItems:i.length>0,processedItems:i}},ga=e=>{if(e){if(e.character&&U(e.character,"name"))return e.character.name;if(U(e,"characterName"))return e.characterName}},wo=e=>!!e?.character&&U(e.character,"sprite"),ya=e=>{let t={},r=!1,n=ga(e);return n!==void 0&&(t.name=n,r=!0),wo(e)&&(t.sprite=Z(e.character.sprite),r=!0),r?t:void 0},ho=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},ba=({dialogueState:e,content:t,append:r=!1})=>{if(!r||!Array.isArray(t)){e.content=t,delete e.initialRevealedContent;return}let n=Array.isArray(e.content)?e.content:[];n.length>0?e.initialRevealedContent=n.map(o=>Z(o)):delete e.initialRevealedContent,e.content=[...n,...t]},Ia=()=>({}),Aa=(e,t)=>{if(!t.screen)return;let r=$(t.screen,"opacity"),n=$(t.screen,"blur"),o=U(t.screen,"animations");if(!r&&!n){o||delete e.screen;return}let i=e.screen,s={};if(r?s.opacity=t.screen.opacity:$(i,"opacity")&&(s.opacity=i.opacity),n?s.blur=Z(t.screen.blur):$(i,"blur")&&(s.blur=Z(i.blur)),U(s,"opacity")&&s.opacity===void 0&&delete s.opacity,U(s,"blur")&&s.blur===void 0&&delete s.blur,Object.keys(s).length===0){delete e.screen;return}e.screen=s},wa=(e,t)=>{if(t.background){let r=$(t.background,"resourceId"),n=$(t.background,"colorId"),o=$(t.background,"opacity"),i=$(t.background,"blur"),s=$(t.background,"transformId"),c=fo(t.background),a=po(t.background),{animationsOnly:l,state:d}=mt(t.background,p=>$(p,"resourceId")||$(p,"colorId")||$(p,"opacity")||$(p,"blur")||$(p,"transformId")||fo(p)||po(p));if(l){e.background=e.background?{...Z(e.background),...d}:d;return}if(!r&&!n&&!o&&!i&&!s&&!c&&!a){delete e.background;return}let u=e.background,f=Z(t.background);if(!r&&u?.resourceId){f.resourceId=u.resourceId,!U(f,"transformId")&&u.transformId&&(f.transformId=u.transformId);for(let p of Pr)!$(f,p)&&$(u,p)&&(f[p]=u[p])}pa(f,u,{hasAuthoredTransformId:s}),!n&&u?.colorId&&(f.colorId=u.colorId),!o&&$(u,"opacity")&&(f.opacity=u.opacity),!i&&$(u,"blur")&&(f.blur=Z(u.blur)),U(f,"resourceId")&&f.resourceId===void 0&&delete f.resourceId,U(f,"colorId")&&f.colorId===void 0&&delete f.colorId,U(f,"animations")&&f.animations===void 0&&delete f.animations,U(f,"transformId")&&f.transformId===void 0&&delete f.transformId,U(f,"opacity")&&f.opacity===void 0&&delete f.opacity,U(f,"blur")&&f.blur===void 0&&delete f.blur;for(let p of Pr)U(f,p)&&f[p]===void 0&&delete f[p];if(!f.resourceId&&!f.colorId){delete e.background;return}u?.resourceId===f.resourceId&&u?.transformId===f.transformId&&!U(f,"animations")&&uo(u)&&(f.animations=Z(u.animations)),e.background=f}else e.background?.animations&&!uo(e.background)&&(e.background.animations={})},Ea=(e,t)=>{if(!t.dialogue){e.dialogue&&(ho(e.dialogue),e.dialogue.mode==="adv"&&(e.dialogue.content=void 0,delete e.dialogue.initialRevealedContent,delete e.dialogue.textSpeed,e.dialogue.persistCharacter!==!0&&(delete e.dialogue.characterId,delete e.dialogue.character)));return}e.dialogue||(e.dialogue={});let r=e.dialogue.mode;if(t.dialogue.ui){let{animationsOnly:l,state:d}=mt(t.dialogue.ui,u=>!!u.resourceId);l?e.dialogue.ui={...e.dialogue.ui,...d}: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 n=t.dialogue.append===!0&&r!=="nvl"&&e.dialogue?.mode!=="nvl"&&Array.isArray(t.dialogue.content);t.dialogue.content!==void 0&&ba({dialogueState:e.dialogue,content:t.dialogue.content,append:n}),U(t.dialogue,"textSpeed")?e.dialogue.textSpeed=t.dialogue.textSpeed:delete e.dialogue.textSpeed;let o=U(t.dialogue,"persistCharacter")?t.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;o?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let i=U(t.dialogue,"characterId"),s=ya(t.dialogue),c=s!==void 0,a=wo(t.dialogue);if(i?t.dialogue.characterId?e.dialogue.characterId=t.dialogue.characterId:delete e.dialogue.characterId:!o&&!n&&delete e.dialogue.characterId,c?e.dialogue.character=!i&&o&&e.dialogue.character?{...Z(e.dialogue.character),...s}:s:(i||!o&&!n)&&delete e.dialogue.character,a||ho(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.textSpeed!==void 0&&(l.textSpeed=e.dialogue.textSpeed),e.dialogue.character&&(l.character=Z(e.dialogue.character)),e.dialogue.lines.push(l)}},va=(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},xa=(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}}},Ca=(e,t)=>{if(t.visual){let r=e.visual?.items||[];t.visual.items?.forEach((i,s)=>{fa(i,Io(r,i,s))});let{hasValidItems:n,processedItems:o}=Ao(t.visual.items,ua,r,{hasPatchFn:bo,mergeItemFn:da});n?e.visual={items:o}:delete e.visual}else e.visual?.items&&(e.visual.items=e.visual.items.map(r=>r.animations?{...r,animations:{}}:r))},Sa=(e,t)=>{if(!t.character){e.character?.items&&(e.character.items=e.character.items.map(o=>o.animations?{...o,animations:{}}:o));return}let{hasValidItems:r,processedItems:n}=Ao(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId,e.character?.items||[]);r?e.character={items:n}:delete e.character},_a=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},Ra=(e,t)=>{if(t.layout){let{animationsOnly:r,state:n}=mt(t.layout,o=>!!o.resourceId);if(r){e.layout=n;return}if(!t.layout.resourceId){delete e.layout;return}e.layout=t.layout}else e.layout&&delete e.layout},Oa=(e,t)=>{if(t.choice){let{animationsOnly:r,state:n}=mt(t.choice,o=>!!o.resourceId);if(r){e.choice={...e.choice,...n};return}if(!t.choice.resourceId){delete e.choice;return}e.choice=t.choice}else e.choice&&delete e.choice},La=(e,t)=>{if(t.form){let{animationsOnly:r,state:n}=mt(t.form,o=>!!o.resourceId);if(r){e.form={...e.form,...n};return}if(!t.form.resourceId){delete e.form;return}e.form=Z(t.form)}else e.form&&delete e.form},$a=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},ka=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},Ta=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(r=>{delete e[r]})},We=e=>Vt(Ia,[Ta,Aa,wa,va,xa,Ca,Ea,Sa,_a,Ra,Oa,La,$a,ka])(e);var Da=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"}}),Ne=Object.freeze({dialogueTextSpeed:50,autoForwardDelay:1e3,skipUnseenText:!1,skipTransitionsAndAnimations:!1,soundVolume:50,musicVolume:50,muteAll:!1,autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isLineCompleted:!1}),gt=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),Eo=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"}),Nr=Object.freeze(["dialogueTextSpeed","autoForwardDelay","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),Vr=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),Pa=(e,t)=>{if(t.startsWith("global.")){let r=t.slice(7);return e?.global?.[r]}if(t.startsWith("context.runtime.")){let r=t.slice(16),n=Array.isArray(e?.contexts)?e.contexts:[];return n[n.length-1]?.runtime?.[r]}},qe=e=>Object.fromEntries(Object.entries(Da).map(([t,r])=>{let n=Pa(e,r.source),o=n!==void 0?n:Ne[t]??gt[t];return[t,o]})),_e=(e,t)=>qe(e)[t],vo=(e={})=>Object.fromEntries(Nr.map(t=>[t,e[t]??Ne[t]]));var rt=Object.freeze({VISUAL_BEHIND_BACKGROUND:10,BACKGROUND:20,VISUAL_BEHIND_CHARACTER:30,CHARACTER:40,VISUAL_BEHIND_DIALOGUE:50,DIALOGUE:60,VISUAL_BEHIND_CHOICE:70,CHOICE:80,VISUAL_FOREGROUND:90}),Re=Object.freeze({BEHIND_BACKGROUND:rt.VISUAL_BEHIND_BACKGROUND,BEHIND_CHARACTER:rt.VISUAL_BEHIND_CHARACTER,BEHIND_DIALOGUE:rt.VISUAL_BEHIND_DIALOGUE,BEHIND_CHOICE:rt.VISUAL_BEHIND_CHOICE,FOREGROUND:rt.VISUAL_FOREGROUND}),jr=Re.BEHIND_DIALOGUE,Mr=Object.freeze(Object.values(Re).sort((e,t)=>e-t));var Oe={objectValues:e=>Object.entries(e).map(([t,r])=>({id:t,...r})),formatDate:co},Na=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,Va=(e,t)=>{let r=String(t||"").trim();if(!r)return;let n=r.match(/[A-Za-z_][A-Za-z0-9_]*|\[\d+\]/g)||[],o=e;for(let i of n){if(i.startsWith("[")){let s=Number(i.slice(1,-1));o=Array.isArray(o)?o[s]:void 0;continue}o=o?.[i]}return o},qt=(e,t,r)=>{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),c=Na.exec(s);if(c){let[,a,l,d]=c,u=Va(t,d);if(!Array.isArray(u))continue;let f=Array.isArray(i[s])?i[s]:[];u.forEach((p,h)=>{let g={...t,[a]:p};l&&(g[l]=h),f.forEach(y=>{let b=qt(y,g,r),A=ue(b,g,r);Array.isArray(A)?o.push(...A):o.push(A)})});continue}}o.push(qt(i,t,r))}return o}if(!e||typeof e!="object")return e;let n={};return Object.entries(e).forEach(([o,i])=>{n[o]=qt(i,t,r)}),n},tn=({animationType:e,animationId:t,animationPath:r})=>{if(e!==void 0&&!(e==="update"||e==="transition"))throw new Error(`[${r}] Animation "${t}" has unsupported type "${e}". Use "update" or "transition".`)},ja=({id:e,targetId:t,animation:r,playback:n,animationPath:o="animation"})=>{let i=structuredClone(r);if(tn({animationType:i.type,animationId:e,animationPath:o}),delete i.name,delete i.playback,i.id=e,i.targetId=t,n!==void 0){let s=Ba(n,`${o}.playback`);s!==void 0&&(i.playback=s)}return i},Ma=(e,{animationId:t="animation",animationPath:r="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return tn({animationType:e.type,animationId:t,animationPath:r}),e.type},Fa=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},Ua=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},Ba=(e,t="animation.playback")=>{if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`[${t}] playback must be an object.`);if(e.continuity!==void 0&&e.continuity!=="render"&&e.continuity!=="persistent")throw new Error(`[${t}] playback.continuity must be "render" or "persistent".`);if(e.speed!==void 0&&(typeof e.speed!="number"||!Number.isFinite(e.speed)||e.speed<=0))throw new Error(`[${t}] playback.speed must be a finite number greater than 0.`);let r={};return e.continuity!==void 0&&(r.continuity=e.continuity),e.speed!==void 0&&e.speed!==1&&(r.speed=e.speed),Object.keys(r).length>0?r:void 0},za=e=>{let t=e?.playback?.speed;return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1},He=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Vo=e=>e?.playback?.continuity==="persistent",qr=e=>Array.isArray(e)?e.map(qr):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((t,r)=>(t[r]=qr(e[r]),t),{}),Yt=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let t=structuredClone(e);return t.playback&&(delete t.playback.continuity,t.playback.speed===1&&delete t.playback.speed,Object.keys(t.playback).length===0&&delete t.playback),JSON.stringify(qr(t))},jo=(e=[])=>e.filter(t=>Vo(t)).map(t=>structuredClone(t)),Mo=e=>Array.isArray(e?.keyframes)?e.keyframes.reduce((t,r)=>{let n=typeof r?.duration=="number"&&Number.isFinite(r.duration)?r.duration:0;return t+n},0):0,Fr=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((t,r)=>Math.max(t,Mo(r)),0),Fo=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max(Fr(e.tween),Fr(e.prev?.tween),Fr(e.next?.tween),Mo(e.mask?.progress))/za(e),xo=({animationInstances:e,activePersistentAnimations:t})=>{if(!Array.isArray(e)||e.length===0||!Array.isArray(t)||t.length===0)return!1;let r=new Set(t.map(Yt).filter(Boolean));return e.some(n=>{if(!Vo(n))return!1;let o=Yt(n);return o?r.has(o):!1})},we=({animationInstances:e,isLineCompleted:t,skipTransitionsAndAnimations:r,activePersistentAnimations:n,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||r?!1:i&&!t||xo({animationInstances:e,activePersistentAnimations:n})?!0:i?!1:xo({animationInstances:e,activePersistentAnimations:o}),Wa=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),qa=(e,t)=>{if(Wa(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},Ha=({resources:e,animationId:t,playback:r,instanceId:n,targetId:o,animationPath:i="animation"})=>{if(!t||!o)return!1;let s=e?.animations?.[t];return s?ja({id:n,targetId:o,animation:s,playback:r,animationPath:i}):null},Ya=(e,{defaultTargetId:t,defaultId:r,animationPath:n="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return tn({animationType:o.type,animationId:o.id??r,animationPath:n}),o.id??=r,o.targetId??=t,o},rn=({animations:e,transitions:t,defaultTargetId:r,idPrefix:n,animationPathPrefix:o=n})=>{t.forEach((i,s)=>{e.push(Ya(i,{defaultTargetId:r,defaultId:`${n}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},Hr=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let r=ue(e,t);return r&&typeof r=="object"?e:r},Yr=(e,t)=>{if(e===void 0)return[];if(!Array.isArray(e)||e.some(r=>r===null||typeof r!="object"||Array.isArray(r)))throw new Error(`${t} must be an array of objects`);return e},Ka=({content:e,path:t,variables:r})=>Yr(e,t).reduce((n,o)=>{let i=Hr(o.text,{variables:r});return n+`${i??""}`.length},0),Co=(e=[])=>{let t=new Map;for(let r of e)r?.id&&t.set(r.id,(t.get(r.id)??0)+1);return new Set(Array.from(t.entries()).filter(([,r])=>r>1).map(([r])=>r))},zt=(e,t=0,r=new Set)=>{if(!r.has(e?.id))return`character-container-${e.id}`;let n=e?.sprites?.map(({resourceId:o})=>o)||[];return n.length===0?`character-container-${e.id}`:`character-container-${e.id}-${t}-${n.join("-")}`},Wt=(e,t)=>{if(!t.transformId)throw new Error(`Visual item "${t.id}" requires transformId`);let r=e.transforms?.[t.transformId];if(!r)throw new Error(`Transform "${t.transformId}" not found for visual item "${t.id}"`);return r},Ga=(e,t={})=>{if(!t?.transformId)return;let r=e.transforms?.[t.transformId];if(!r)throw new Error(`Transform "${t.transformId}" not found for background`);return r},Ja=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],Xa=(e={})=>Ja.some(t=>He(e,t)),Uo=(e={},t)=>{if(t){if(e.images?.[t])return"sprite";if(e.videos?.[t])return"video";if(e.spritesheets?.[t])return"spritesheet-animation";if(e.layouts?.[t])return"container"}},Ht=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},Qa=(e={})=>e.textStyles||{},Za=(e={})=>e.images||{},ec=.5,tc=(e={},t,r)=>{if(t){if(!e.animations?.[t])throw new Error(`Animation '${t}' not found in spritesheet resource '${r}'`);return t}return Object.keys(e.animations??{})[0]},Bo=({id:e,resourceId:t,spritesheet:r,animationName:n,animationSpeed:o,loop:i,transform:s={}}={})=>{let c=tc(r,n,t),a=c?r.animations?.[c]:void 0;if(!a){console.warn(`Spritesheet animation not found: ${t}`);return}return{id:e,type:"spritesheet-animation",...s,width:r.width,height:r.height,src:r.fileId,atlas:r.jsonData,playback:{frames:a.frames,animationSpeed:o??a.animationSpeed??ec,loop:i??a.loop??!0}}},zo=({id:e,item:t,resources:r={}}={})=>{let n=r.images?.[t.resourceId];if(n)return{type:"sprite",id:e,src:n.fileId,width:n.width,height:n.height,x:0,y:0};let o=r.spritesheets?.[t.resourceId];if(o)return Bo({id:e,resourceId:t.resourceId,spritesheet:o,animationName:t.animationName,animationSpeed:t.animationSpeed,loop:t.loop,transform:{x:0,y:0}});console.warn(`Character sprite resource not found: ${t.resourceId}`)},rc=(e={})=>e.colors||{},nc=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,bt=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,ot=(e,t,r)=>{if(typeof e!="string"||e.length===0)throw new Error(`${r} at "${t}" must resolve to a non-empty string`)},So=(e,t,r)=>{if(e===void 0)return 1;if(typeof e!="number"||!Number.isFinite(e))throw new Error(`${t} for text style "${r}" must be a number between 0 and 1`);if(e<0||e>1)throw new Error(`${t} for text style "${r}" must be a number between 0 and 1`);return e},nn=(e,t)=>{if(typeof e!="string"||!nc.test(e))throw new Error(`${t} must resolve to a hex color`);return e.length===4?`#${e.slice(1).split("").map(r=>r.repeat(2)).join("")}`:e},_o=(e,t,r)=>{let n=nn(e,r);if(t===1)return n;let o=Number.parseInt(n.slice(1,3),16),i=Number.parseInt(n.slice(3,5),16),s=Number.parseInt(n.slice(5,7),16);return`rgba(${o}, ${i}, ${s}, ${t})`},oc=(e={},t)=>{let r=Qa(e)?.[t];if(!r)throw new Error(`Text style "${t}" not found`);let n=e.fonts?.[r.fontId];if(!n)throw new Error(`Font "${r.fontId}" not found for text style "${t}"`);let o=e.colors?.[r.colorId];if(!o)throw new Error(`Color "${r.colorId}" not found for text style "${t}"`);let i=So(r.colorAlpha,"colorAlpha",t),s={fontFamily:n.fileId,fontSize:r.fontSize??16,fontWeight:r.fontWeight??"400",fontStyle:r.fontStyle??"normal",lineHeight:r.lineHeight??1.2,fill:_o(o.hex,i,`Color "${r.colorId}" for text style "${t}"`)};if(r.align!==void 0&&(s.align=r.align),r.wordWrap!==void 0&&(s.wordWrap=r.wordWrap),r.breakWords!==void 0&&(s.breakWords=r.breakWords),r.wordWrapWidth!==void 0&&(s.wordWrapWidth=r.wordWrapWidth),r.strokeColorId){let c=e.colors?.[r.strokeColorId];if(!c)throw new Error(`Stroke color "${r.strokeColorId}" not found for text style "${t}"`);let a=So(r.strokeAlpha,"strokeAlpha",t);s.strokeColor=_o(c.hex,a,`Stroke color "${r.strokeColorId}" for text style "${t}"`)}else if(r.strokeAlpha!==void 0)throw new Error(`strokeAlpha for text style "${t}" requires strokeColorId`);return r.strokeWidth!==void 0&&(s.strokeWidth=r.strokeWidth),s},Kr=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>Kr(o,t,`${r}[${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 "${r}". Use textStyleId instead`);let n={};for(let[o,i]of Object.entries(e))o!=="textStyleId"&&(n[o]=Kr(i,t,bt(r,o)));return e.textStyleId!==void 0&&(ot(e.textStyleId,r,"textStyleId"),n.textStyle=oc(t,e.textStyleId)),n},on=(e={},t)=>{let r=rc(e)?.[t];if(!r)throw new Error(`Color "${t}" not found`);return nn(r.hex,`Color "${t}"`)},Wo=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",Ur=(e,t,r)=>{let n=e?.[t];if(!(!n||typeof n!="object"||Array.isArray(n))&&Object.prototype.hasOwnProperty.call(n,"fill"))throw new Error(`Inline ${t}.fill is not allowed in rect layout elements at "${r}". Use ${Wo(`${t}.fill`)} instead`)},ic=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>It(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;let n={};for(let[o,i]of Object.entries(e))o!=="colorId"&&(n[o]=It(i,t,bt(r,o)));return e.colorId!==void 0&&(ot(e.colorId,r,"colorId"),n.fill=on(t,e.colorId)),n},It=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>It(o,t,`${r}[${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 "${r}". Use ${Wo("fill")} instead`);Ur(e,"hover",r),Ur(e,"click",r),Ur(e,"rightClick",r)}let n={};for(let[o,i]of Object.entries(e))if(!(e.type==="rect"&&o==="colorId")){if(e.type==="rect"&&(o==="hover"||o==="click"||o==="rightClick")){n[o]=ic(i,t,bt(r,o));continue}n[o]=It(i,t,bt(r,o))}return e.type==="rect"&&e.colorId!==void 0&&(ot(e.colorId,r,"colorId"),n.fill=on(t,e.colorId)),n},Br=(e={},t)=>{let r=Za(e)?.[t];return r||null},qo=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",Ro=(e,t,r,n)=>{let o=e?.[t];if(!(!o||typeof o!="object"||Array.isArray(o))&&Object.prototype.hasOwnProperty.call(o,n))throw new Error(`Inline ${t}.${n} is not allowed in sprite layout elements at "${r}". Use ${qo(`${t}.${n}`)} instead`)},Oo=(e,t,r)=>{let n=e[t];e[t]={...n&&typeof n=="object"&&!Array.isArray(n)?n:{},src:r}},Gr=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>Gr(o,t,`${r}[${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 "${r}". Use ${qo(o)} instead`);Ro(e,"hover",r,"src"),Ro(e,"click",r,"src")}let n={};for(let[o,i]of Object.entries(e))e.type==="sprite"&&(o==="imageId"||o==="hoverImageId"||o==="clickImageId")||(n[o]=Gr(i,t,bt(r,o)));if(e.type==="sprite"&&e.imageId!==void 0){ot(e.imageId,r,"imageId");let o=Br(t,e.imageId),i=o?.fileId??e.imageId;n.src=i,n.width===void 0&&o?.width!==void 0&&(n.width=o.width),n.height===void 0&&o?.height!==void 0&&(n.height=o.height)}return e.type==="sprite"&&e.hoverImageId!==void 0&&(ot(e.hoverImageId,r,"hoverImageId"),Oo(n,"hover",Br(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(ot(e.clickImageId,r,"clickImageId"),Oo(n,"click",Br(t,e.clickImageId)?.fileId??e.clickImageId)),n},sn=(e,t={},r="root")=>Gr(It(Kr(e,t,r),t,r),t,r),Le=sn,Ye=(e=[])=>e.find(t=>t.id==="story"),sc="#000000",Jr="bg-cg-background-color",ac=({resources:e={},background:t={},screen:r})=>t?.colorId===void 0?nn(r?.backgroundColor??sc,"screen.backgroundColor"):on(e,t.colorId),Ho=(e={})=>{if(He(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},cc=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},Lo=(e={},{includeDefaultAlpha:t=!1}={})=>{let r=Ho(e),n=cc(e),o={};return(t||r!==void 0)&&(o.alpha=r??1),n&&(o.blur=n),o},lc=(e={})=>{if(He(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},uc=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},Yo=(e={})=>{let t=lc(e),r=uc(e),n={};return t!==void 0&&(n.alpha=t),r&&(n.blur=r),n},yt=(e={})=>Yo(e),Ve=(e={},t={})=>{let r={x:t.x??e.x,y:t.y??e.y,anchorX:t.anchorX??e.anchorX,anchorY:t.anchorY??e.anchorY,rotation:t.rotation??e.rotation,scaleX:t.scaleX??e.scaleX,scaleY:t.scaleY??e.scaleY},n=t.originX??e.originX,o=t.originY??e.originY;return n!==void 0&&(r.originX=n),o!==void 0&&(r.originY=o),r},dc=["id","type","resourceId","transformId","x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY","layer","opacity","blur","animations"],an=(e={})=>e.text&&He(e.text,"content")&&He(e.text,"textStyleId"),$o=(e={})=>{if(e.resourceId)return e.resourceId;if(an(e))return"text"},fc=e=>{if(e.text){if(e.resourceId)throw new Error(`Visual item "${e.id}" cannot define both resourceId and text`);if(!an(e))throw new Error(`Visual item "${e.id}" text requires content and textStyleId`);for(let t of dc)if(He(e.text,t))throw new Error(`Visual item "${e.id}" text.${t} is reserved for the visual item`)}},pc=({resources:e,background:t,screen:r={width:1920,height:1080},includeOpacity:n=!1})=>{let o={id:Jr,type:"rect",x:0,y:0,width:r?.width??1920,height:r?.height??1080,fill:ac({resources:e,background:t,screen:r})};if(n){let i=Ho(t);i!==void 0&&(o.alpha=i)}return o},hc=(e={},t)=>t?!!(e.images?.[t]||e.videos?.[t]||e.spritesheets?.[t]||e.layouts?.[t]):!1,ko=({resources:e={},resourceId:t,colorId:r})=>{let n=Uo(e,t);return t&&(n||r===void 0)?{resourceId:t,targetId:Ht({resourceId:t,kind:n})}:r!==void 0?{resourceId:Jr,targetId:Jr}:{resourceId:void 0,targetId:void 0}},Ko=100,Gt=Ko,Go=(e,t)=>e*t/Ko,mc=(e={},t=Gt)=>e?.muteAll?0:Go(t,e?.soundVolume??Ne.soundVolume),gc=(e={},t=Gt)=>e?.muteAll?0:Go(t,e?.musicVolume??Ne.musicVolume),yc=({item:e,index:t}={})=>`sfx:${t}:${e?.resourceId}`,Ee=({variables:e,runtime:t,saveSlots:r=[],dialogueState:n,includeInactiveAdvDialogue:o=!1,isLineCompleted:i,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:d,confirmDialog:u,form:f,historyDialogue:p=[],characters:h={},dialogueUIHidden:g,skipOnlyViewedLines:y,skipTransitionsAndAnimations:b}={})=>{let A={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??c??!1,dialogueUIHidden:t?.dialogueUIHidden??g??!1,isLineCompleted:t?.isLineCompleted??i??!1},v=Ec({dialogueState:n,includeInactiveAdvDialogue:o,characters:h,variables:e,runtime:A}),S={variables:e,runtime:A,saveSlots:r,isChoiceVisible:a,isFormVisible:l,canRollback:d,confirmDialog:u,form:f,historyDialogue:p,characters:h};return v&&(S.dialogue=v,S.dialogueLines=v.lines),S},To=100,Kt=(e,t)=>{if(Array.isArray(e))return e.map(n=>Kt(n,t));if(!e||typeof e!="object")return e;let r={...e};return Object.keys(r).forEach(n=>{r[n]=Kt(r[n],t)}),r.type==="text-revealing"?t(r):r},bc=e=>Kt(e,t=>({...t,revealEffect:"none"})),Ic=e=>Kt(e,t=>{let r=Number(t.speed??t.displaySpeed),n=Number.isFinite(r)?Math.max(r,To):To;return{...t,speed:n,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:n}:{}}}),je=(e,{isLineCompleted:t=!1,skipMode:r=!1,skipTransitionsAndAnimations:n=!1}={})=>t||n?bc(e):r?Ic(e):e,Jo=({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:{}}}}),Xr=e=>{if(Array.isArray(e))return e.map(Xr);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=Xr(s);let r=t.click?.payload;if(!r||typeof r!="object"||Array.isArray(r))return t;let n=r.actions,o=n&&typeof n=="object"&&!Array.isArray(n)&&Object.prototype.hasOwnProperty.call(n,"nextLine")?{...n.nextLine,bypassChoice:!0}:void 0;return{...t,click:{...t.click,payload:{...r,bypassChoice:!0,...o?{actions:{...n,nextLine:o}}:{}}}}},Ac=new Set(["click","change","submit","focusEvent","blurEvent","selectionChange","compositionStart","compositionUpdate","compositionEnd"]),Do="submit",zr=(e,t,r={})=>{let n=e?.payload&&typeof e.payload=="object"&&!Array.isArray(e.payload)?e.payload:{},o=n.actions&&typeof n.actions=="object"?n.actions:{},i=r.replaceActions===!0?t:{...o,...t};return{...e||{},payload:{...n,actions:i}}},Qr=(e,t,r={})=>{if(Array.isArray(e))return e.map(l=>Qr(l,t,r));if(!e||typeof e!="object")return e;let n=typeof e.type=="string",o=n&&e.formRole===Do,i=n&&r.submitRoleAncestor,s=o||i?{submitRoleAncestor:!0}:{},c={};for(let[l,d]of Object.entries(e))c[l]=Qr(d,t,l==="children"?s:{});let a=c;if(a.type==="input"&&typeof a.field=="string"){let l=t?.fields?.[a.field];if(l){let d={updateFormField:{formKey:t.key,field:l.id,value:"_event.value"}};a={...a,value:l.value,placeholder:a.placeholder===void 0?l.placeholder:a.placeholder,multiline:a.multiline===void 0?l.multiline:a.multiline,...a.maxLength===void 0&&l.maxLength!==void 0?{maxLength:l.maxLength}:{},change:zr(a.change,d),submit:zr(a.submit,t.submitActions)}}}return a.formRole===Do||i?{...a,click:zr(a.click,t.submitActions,{replaceActions:!0})}:a},Zr=(e,t)=>{if(Array.isArray(e))return e.map(n=>Zr(n,t));if(!e||typeof e!="object")return e;let r={};for(let[n,o]of Object.entries(e))r[n]=Zr(o,t);for(let n of Ac){let o=r[n]?.payload;!o||typeof o!="object"||Array.isArray(o)||(r[n]={...r[n],payload:{...o,_interactionSource:"form"}})}return r},en=({characterId:e,character:t,characterName:r,characters:n={},variables:o={}}={})=>{let i=e?n?.[e]:void 0,s=jt({characterId:e,character:t,characterName:r,characters:n,variables:o});return{...i||{},...t||{},name:s}},Xo=(e=[],t={},r={})=>e.map(n=>{let o=en({characterId:n.characterId,character:n.character,characterName:n.characterName,characters:t,variables:r}),i=typeof n.text=="string"?n.text:Array.isArray(n.content)?n.content.map(s=>s?.text??"").join(""):"";return{...n,text:i,character:o,characterName:o.name}}),wc=e=>!(!e||e.mode==="adv"&&e.content===void 0),Ec=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:r={},variables:n,runtime:o}={})=>{if(!t&&!wc(e))return;let i=e.content===void 0?[{text:""}]:Yr(e.content,"dialogue.content"),s=e.content===void 0?0:Ka({content:e.initialRevealedContent,path:"dialogue.initialRevealedContent",variables:n}),c=o?.dialogueTextSpeed??Ne.dialogueTextSpeed,a=e.textSpeed??c,l=(e.lines||[]).map((u,f)=>{let p=Yr(u.content,`dialogue.lines[${f}].content`),h=en({characterId:u.characterId,character:u.character,characterName:u.characterName,characters:r,variables:n});return{...u,textSpeed:u.textSpeed??c,content:p.map(g=>({...g,text:Hr(g.text,{variables:n})})),character:h,characterName:h.name}}),d=en({characterId:e.characterId,character:e.character,characters:r,variables:n});return{characterId:e.characterId,persistCharacter:e.persistCharacter,character:d,textSpeed:a,content:i.map(u=>({...u,text:Hr(u.text,{variables:n})})),initialRevealedCharacters:s,lines:l}},Qo=({container:e,resources:t,templateData:r,isLineCompleted:n=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=ue(e,r,{functions:Oe});return Le(je(s,{isLineCompleted:n,skipMode:o,skipTransitionsAndAnimations:i}),t)},Wr=(e,t={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(t),Po=({renderStateKeyboard:e,keyboard:t,phase:r})=>{!t||typeof t!="object"||Array.isArray(t)||Object.entries(t).forEach(([n,o])=>{let i=e[n]??{},s=r==="keydown"?o?.keydown:o?.keyup;if(r==="keydown"&&s&&typeof s=="object"){e[n]={...i,keydown:{payload:Wr(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[n].keyup={payload:Wr(o.keyup)});return}e[n]={...i,[r]:{payload:Wr(o)}}})},vc=(e={},t={})=>{let r={};return Po({renderStateKeyboard:r,keyboard:e,phase:"keydown"}),Po({renderStateKeyboard:r,keyboard:t,phase:"keyup"}),Object.keys(r).length>0?r:void 0},$e=({animationsDef:e,resources:t,previousResourceId:r,currentResourceId:n,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:c})=>{if(!e)return[];let a=[],l=({instanceId:b,targetId:A})=>{let v=Ha({resources:t,animationId:p,playback:h,instanceId:b,targetId:A,animationPath:s});v&&a.push(v)},d=r!=null&&r!==!1,u=n!=null&&n!==!1,f=o&&i&&o===i;qa(e,s);let p=Fa(e),h=Ua(e),g=t?.animations?.[p],y=Ma(g,{animationId:p,animationPath:s});if(y==="update")return u&&i?l({instanceId:`${c}-animation-update`,targetId:i}):d&&o&&l({instanceId:`${c}-animation-update`,targetId:o}),a;if(y==="transition"){let b=`${c}-animation-transition`,A=h?.continuity==="persistent"?b:`${c}-animation-in`;if(d&&u&&f)return l({instanceId:b,targetId:i}),a;d&&l({instanceId:`${c}-animation-out`,targetId:o}),u&&l({instanceId:A,targetId:i})}return a},xc=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),Cc=(e,{presentationState:t,previousPresentationState:r,currentLineActions:n,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:c,variables:a,runtime:l,activePersistentAnimations:d,restoredPersistentAnimations:u,autoMode:f,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:b,saveSlots:A=[]})=>{let{elements:v,animations:S}=e;if(t.background){let P=n===void 0?!0:He(n?.background??{},"animations"),k=v.find(oe=>oe.id==="story");if(!k)return e;let w=Ga(o,t.background),j=w||Xa(t.background),F=r?.background?.resourceId,ee=r?.background?.colorId,N=t.background.resourceId??(t.background.animations?F:void 0),W=t.background.colorId??(t.background.animations?ee:void 0),q=hc(o,N),te={...t.background,colorId:W};if((W!==void 0||q)&&k.children.push(pc({resources:o,background:te,screen:i,includeOpacity:!q})),N){let{images:oe={},videos:re={},spritesheets:G={}}=o,ie=Uo(o,N),se;if(ie==="sprite"?se=oe[N]:ie==="video"?se=re[N]:ie==="spritesheet-animation"&&(se=G[N]),se){let x=ie==="video",_=ie==="spritesheet-animation",V={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...w},J={...Lo(t.background,{includeDefaultAlpha:!0}),...Ve(V,t.background)},z;_?z=Bo({id:Ht({resourceId:N,kind:ie}),resourceId:N,spritesheet:se,animationName:t.background.animationName,animationSpeed:t.background.animationSpeed,loop:t.background.loop,transform:J}):z={id:Ht({resourceId:N,kind:ie}),type:x?"video":"sprite",src:se.fileId,width:se.width,height:se.height,...J},x&&(z.loop=t.background.loop??!1,z.volume=se.volume??50),z&&k.children.push(z)}}if(N){let{layouts:oe={}}=o,re=oe[N];if(re){let G={id:Ht({resourceId:N,kind:"container"}),type:"container",children:re.elements,...Lo(t.background)};j&&Object.assign(G,Ve({x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...w},t.background));let ie=ue(G,Ee({variables:a,runtime:l,saveSlots:A,dialogueState:t.dialogue,isLineCompleted:s,autoMode:f,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:b,characters:o.characters||{},skipTransitionsAndAnimations:c}),{functions:Oe});k.children.push(Le(je(ie,{isLineCompleted:s,skipMode:p,skipTransitionsAndAnimations:c}),o))}}let ve=ko({resources:o,resourceId:F,colorId:ee}),Y=ko({resources:o,resourceId:N,colorId:W}),K=$e({animationsDef:t.background.animations,resources:o,previousResourceId:ve.resourceId,currentResourceId:Y.resourceId,previousTargetId:ve.targetId,currentTargetId:Y.targetId,animationPath:"background.animations",idPrefix:"bg-cg"});we({animationInstances:K,isLineCompleted:s,skipTransitionsAndAnimations:c,activePersistentAnimations:d,restoredPersistentAnimations:u,isAuthoredOnCurrentLine:P})&&S.push(...K)}return e},Sc=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:c,animations:a}=e;if(t.character&&n){let l=c.find(h=>h.id==="story");if(!l)return e;let d=t.character.items||[],u=r?.character?.items||[],f=Co(d),p=Co(u);for(let h=0;h<d.length;h++){let g=d[h],{transformId:y,sprites:b}=g,A=u.find(N=>N.id===g.id),v=u.findIndex(N=>N.id===g.id),S=A?.sprites&&A.sprites.length>0,P=b&&b.length>0,k=v>=0?zt(A,v,p):void 0,w=$e({animationsDef:g.animations,resources:n,previousResourceId:k,currentResourceId:P?zt(g,h,f):void 0,previousTargetId:k,currentTargetId:P?zt(g,h,f):void 0,animationPath:`character.items[${h}].animations`,idPrefix:"character"});if(g.animations&&!b&&!y&&S&&we({animationInstances:w,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){a.push(...w);continue}if(g.animations&&!b&&!y)continue;if(!b||b.length===0||!y){console.warn("Character item missing sprites or transformId:",g);continue}let j=zt(g,h,f),F=n.transforms[y];if(!F){console.warn("Transform not found:",y);continue}let ee={type:"container",id:j,...Ve(F,g),...yt(g),children:[]};for(let N of b){let W=zo({id:`${j}-${N.id}`,item:N,resources:n});W&&ee.children.push(W)}l.children.push(ee),we({animationInstances:w,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...w)}}return e},Zo=(e,t)=>{if(!Mr.includes(e))throw new Error(`${t} must be one of: ${Mr.join(", ")}.`)},_c=(e,t)=>{let r=!!e.resourceId||an(e),n=e.layer??(r?void 0:t?.layer)??jr;return Zo(n,`Visual item "${e.id}" layer`),n},Rc=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,runtime:c,activePersistentAnimations:a,autoMode:l,skipMode:d,isChoiceVisible:u,isFormVisible:f,canRollback:p,form:h,saveSlots:g=[],visualLayer:y})=>{let{elements:b,animations:A}=e;if(t.visual&&n){let v=b.find(w=>w.id==="story");if(!v)return e;let S=t.visual.items,P=r?.visual?.items||[],k=Ee({variables:s,runtime:c,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:o,autoMode:l,skipMode:d,isChoiceVisible:u,isFormVisible:f,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:i});y!==void 0&&Zo(y,"visualLayer");for(let w of S){let j=P.find(q=>q.id===w.id),F=_c(w,j);if(y!==void 0&&F!==y)continue;if(fc(w),w.text){let q=Wt(n,w),te={...structuredClone(w.text),id:`visual-${w.id}`,type:"text",...Ve(q,w)};Object.assign(te,yt(w)),v.children.push(Le(ue(te,k,{functions:Oe}),n))}if(w.resourceId){let{images:q={},videos:te={},spritesheets:ve={}}=n,Y=ve[w.resourceId];if(Y){let K=Wt(n,w),oe=w.animationName;if(oe){let re=Y.animations?.[oe];if(!re)throw new Error(`Animation '${oe}' not found in spritesheet resource '${w.resourceId}'`);let G=yt(w),ie={id:`visual-${w.id}`,type:"spritesheet-animation",...Ve(K,w),width:w.width??Y.width,height:w.height??Y.height,alpha:G.alpha??w.alpha??1,src:Y.fileId,atlas:Y.jsonData,playback:{frames:re.frames,animationSpeed:w.animationSpeed??re.animationSpeed??.5,loop:w.loop??re.loop??!0}};G.blur&&(ie.blur=G.blur),v.children.push(structuredClone(ie))}}else{let K=q[w.resourceId]||te[w.resourceId];if(K){let oe=te[w.resourceId]!==void 0,re=Wt(n,w),G={id:`visual-${w.id}`,type:oe?"video":"sprite",src:K.fileId,width:K.width,height:K.height,...Ve(re,w)};Object.assign(G,yt(w)),oe&&(G.loop=K.loop??!1,G.volume=K.volume??50),v.children.push(G)}}}if(w.resourceId){let{layouts:q={}}=n,te=q[w.resourceId];if(te){let ve=Wt(n,w),Y={id:`visual-${w.id}`,type:"container",children:structuredClone(te.elements),...Ve(ve,w)};Object.assign(Y,yt(w));let K=ue(Y,k,{functions:Oe});v.children.push(Le(je(K,{isLineCompleted:o,skipMode:d,skipTransitionsAndAnimations:i}),n))}}let ee=$o(j),N=$o(w),W=$e({animationsDef:w.animations,resources:n,previousResourceId:ee,currentResourceId:N,previousTargetId:ee?`visual-${w.id}`:void 0,currentTargetId:N?`visual-${w.id}`:void 0,animationPath:`visual.items[${w.id}].animations`,idPrefix:w.id});we({animationInstances:W,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:a})&&A.push(...W)}}return e},nt="dialogue-character-sprite",No=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,Oc=(e,{presentationState:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:c}=e,a=Ye(e.elements);if(!a)return e;let l=t.dialogue?.character?.sprite,d=r?.dialogue?.character?.sprite,u=No(l),f=No(d),p=$e({animationsDef:l?.animations,resources:n,previousResourceId:f?nt:void 0,currentResourceId:u?nt:void 0,previousTargetId:f?nt:void 0,currentTargetId:u?nt:void 0,animationPath:"dialogue.character.sprite.animations",idPrefix:"dialogue-character-sprite"});if(!u)return l?.animations&&f&&we({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...p),e;let h=n.transforms?.[l.transformId];if(!h)return console.warn("Transform not found:",l.transformId),e;let g={type:"container",id:nt,...Ve(h),children:[]};for(let y of l.items){let b=zo({id:`${nt}-${y.id}`,item:y,resources:n});b&&g.children.push(b)}return a.children.push(g),we({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...p),e},Lc=(e,{presentationState:t,previousPresentationState:r,resources:n={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:c,isFormVisible:a,canRollback:l,form:d,skipOnlyViewedLines:u,isLineCompleted:f,skipTransitionsAndAnimations:p,variables:h,runtime:g,activePersistentAnimations:y,saveSlots:b=[]})=>{let{elements:A,animations:v}=e;if(!t.dialogue||o)return e;let S=A.find(k=>k.id==="story");if(!S)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:k={}}=n,w=k[t.dialogue.ui.resourceId];if(w){let j={elements:w.elements},F=Ee({variables:h,runtime:g,saveSlots:b,dialogueState:t.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:f,autoMode:i,skipMode:s,isChoiceVisible:c,isFormVisible:a,canRollback:l,form:d,characters:n.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:u,skipTransitionsAndAnimations:p}),ee={functions:Oe},N=qt(j,F,ee),W=ue(N,F,ee),q=Le(je(W?.elements,{isLineCompleted:f,skipMode:s,skipTransitionsAndAnimations:p}),n);if(Array.isArray(q))for(let te of q)S.children.push(te);else q&&S.children.push(q)}}Oc(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:f,skipTransitionsAndAnimations:p,activePersistentAnimations:y});let P=$e({animationsDef:t.dialogue.ui?.animations,resources:n,previousResourceId:r?.dialogue?.ui?.resourceId,currentResourceId:t.dialogue.ui?.resourceId,previousTargetId:r?.dialogue?.ui?.resourceId?"dialogue-container":void 0,currentTargetId:t.dialogue.ui?.resourceId?"dialogue-container":void 0,animationPath:"dialogue.ui.animations",idPrefix:"dialogue-ui"});return we({animationInstances:P,isLineCompleted:f,skipTransitionsAndAnimations:p,activePersistentAnimations:y})&&v.push(...P),e},$c=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:c,runtime:a,autoMode:l,skipMode:d,isChoiceVisible:u,isFormVisible:f,canRollback:p,form:h,activePersistentAnimations:g,saveSlots:y=[]})=>{let{elements:b,animations:A}=e;if(t.choice&&n){let v=Ye(b);if(!v)return e;let S=n?.layouts[t.choice.resourceId];if(S&&S.elements){let k={elements:S.elements},w=ue(k,{...Ee({variables:c,runtime:a,saveSlots:y,dialogueState:t.dialogue,isLineCompleted:i,autoMode:l,skipMode:d,isChoiceVisible:u??!!t.choice,isFormVisible:f,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}},{functions:Oe}),j=Xr(Le(je(w?.elements,{isLineCompleted:i,skipMode:d,skipTransitionsAndAnimations:s}),n));if(Array.isArray(j))for(let F of j)v.children.push(F);else j&&v.children.push(j)}let P=$e({animationsDef:t.choice.animations,resources:n,previousResourceId:r?.choice?.resourceId,currentResourceId:t.choice.resourceId,previousTargetId:r?.choice?.resourceId?"choice-container":void 0,currentTargetId:t.choice.resourceId?"choice-container":void 0,animationPath:"choice.animations",idPrefix:"choice"});we({animationInstances:P,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:g})&&A.push(...P)}return e},kc=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:c,runtime:a,autoMode:l,skipMode:d,isChoiceVisible:u,isFormVisible:f,canRollback:p,activePersistentAnimations:h,saveSlots:g=[],form:y})=>{let{elements:b,animations:A}=e;if(!y?.resourceId||!n)return e;let v=Ye(b);if(!v)return e;let S=n?.layouts?.[y.resourceId];if(!S)return console.warn(`Form layout not found: ${y.resourceId}`),e;let P={id:"form-container",type:"container",x:0,y:0,children:S.elements||[]},k={...Ee({variables:c,runtime:a,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:i,autoMode:l,skipMode:d,isChoiceVisible:u,isFormVisible:f,canRollback:p,characters:n.characters||{},skipTransitionsAndAnimations:s,form:y}),form:y},w=ue(P,k,{functions:Oe}),j=Zr(Le(je(Qr(w,y),{isLineCompleted:i,skipMode:d,skipTransitionsAndAnimations:s}),n),y);j&&v.children.push(j);let F=$e({animationsDef:y.animations,resources:n,previousResourceId:r?.form?.resourceId,currentResourceId:y.resourceId,previousTargetId:r?.form?.resourceId?"form-container":void 0,currentTargetId:y.resourceId?"form-container":void 0,animationPath:"form.animations",idPrefix:"form"});return we({animationInstances:F,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:h})&&A.push(...F),e},Tc=(e,{presentationState:t,resources:r={},variables:n,runtime:o,isLineCompleted:i,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:d,form:u,saveSlots:f=[],skipTransitionsAndAnimations:p})=>{if(!t.control?.resourceId)return e;let h=r.controls?.[t.control.resourceId];if(!h)return e;let g=vc(h.keyboard,h.keyup);if(g&&Object.keys(g).length>0&&(e.global.keyboard=g),!Array.isArray(h.elements)||h.elements.length===0)return e;let y=Ye(e.elements);if(!y)return e;let b={id:`control-${t.control.resourceId}`,type:"container",x:0,y:0,children:h.elements};return y.children.push(Qo({container:b,resources:r,templateData:Ee({variables:n,runtime:o,saveSlots:f,dialogueState:t.dialogue,isLineCompleted:i,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:d,form:u,characters:r.characters||{},skipTransitionsAndAnimations:p}),isLineCompleted:i,skipMode:c,skipTransitionsAndAnimations:p})),e},Dc=(e,{presentationState:t,resources:r,runtime:n,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&r){if(!Ye(i))return e;let a=r.sounds[t.bgm.resourceId];if(!a)return e;let l=Ee({variables:o,runtime:n}).runtime;s.push({id:"bgm",type:"sound",src:a.fileId,loop:t.bgm.loop??!0,volume:gc(l,t.bgm.volume??a.volume??Gt),startDelayMs:t.bgm.startDelayMs??null})}return e},Pc=(e,{presentationState:t,resources:r,runtime:n})=>{let{audio:o}=e;if(t.sfx&&r){let i=t.sfx.items;for(let[s,c]of i.entries()){let a=r.sounds?.[c.resourceId];a&&o.push({id:yc({item:c,index:s}),type:"sound",src:a.fileId,loop:c.loop??a.loop??!1,volume:mc(n,c.volume??a.volume??Gt),startDelayMs:c.startDelayMs??a.startDelayMs??null})}}return e},Nc=(e,t,r)=>{if(!(!t||!r))return e?.voices?.[t]?.[r]},Vc=(e={},t={})=>t.muteAll?0:e.volume??t.soundVolume??50,jc=(e,{presentationState:t,resources:r,currentSceneId:n,runtime:o,variables:i})=>{let{audio:s}=e;if(!t?.voice)return e;let c=t.voice,{resourceId:a,loop:l,startDelayMs:d}=c,u=Nc(r,n,a);if(!u)return e;let f=Ee({variables:i,runtime:o}).runtime;return s.push({id:`voice-${n}-${a}`,type:"sound",src:u.fileId,volume:Vc(c,f),loop:l??!1,startDelayMs:d??null}),e},Mc=(e,{presentationState:t,previousPresentationState:r,resources:n={},variables:o,runtime:i,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:d,form:u,saveSlots:f=[],isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})=>{let{elements:y,animations:b}=e;if(t.layout){let P=Ye(y);if(!P)return e;let k=n.layouts[t.layout.resourceId];if(!k)return e;Array.isArray(k.transitions)&&!p&&!h&&rn({animations:b,transitions:k.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let w={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:k.elements||[]};P.children.push(Qo({container:w,resources:n,templateData:Ee({variables:o,runtime:i,saveSlots:f,dialogueState:t.dialogue,isLineCompleted:p,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:d,form:u,characters:n.characters||{},skipTransitionsAndAnimations:h}),isLineCompleted:p,skipMode:c,skipTransitionsAndAnimations:h}))}let A=r?.layout?.resourceId,v=t.layout?.resourceId,S=$e({animationsDef:t.layout?.animations,resources:n,previousResourceId:A,currentResourceId:v,previousTargetId:A?`layout-${A}`:void 0,currentTargetId:v?`layout-${v}`:void 0,animationPath:"layout.animations",idPrefix:"layout"});return we({animationInstances:S,isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})&&b.push(...S),e},Fc=(e,{currentLineActions:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:c}=e,a=t?.screen?.animations;if(!a)return e;let l=r!=null,d=$e({animationsDef:a,resources:n,previousResourceId:l?"story":void 0,currentResourceId:"story",previousTargetId:l?"story":void 0,currentTargetId:"story",animationPath:"screen.animations",idPrefix:"screen"});return we({animationInstances:d,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...d),e},Uc=(e,{presentationState:t})=>{let r=Ye(e.elements);return!r||!t?.screen||Object.assign(r,Yo(t.screen)),e},Bc=(e,{presentationState:t,resources:r={},variables:n,runtime:o,autoMode:i,skipMode:s,isChoiceVisible:c,isFormVisible:a,canRollback:l,form:d,overlayStack:u=[],dialogueHistory:f=[],saveSlots:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:b,animations:A}=e;return u&&u.length>0&&u.forEach((v,S)=>{let P=r.layouts[v.resourceId];if(!P){console.warn(`Overlay layout not found: ${v.resourceId}`);return}Array.isArray(P.transitions)&&(y||rn({animations:A,transitions:P.transitions,defaultTargetId:`overlayStack-${S}`,idPrefix:`overlayStack-${S}`,animationPathPrefix:`overlayStack[${S}]`}));let k={id:`overlayStack-${S}`,type:"container",x:0,y:0,children:[Jo({id:`overlayStack-${S}-blocker`,screen:h}),...P.elements||[]]},w=Xo(f,r.characters,n),j=Ee({variables:n,runtime:o,saveSlots:p,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:i,skipMode:s,isChoiceVisible:c,isFormVisible:a,canRollback:l,form:d,historyDialogue:w,characters:r.characters||{},skipTransitionsAndAnimations:y}),F=ue(k,j,{functions:Oe}),[ee,...N]=F.children||[],W=Le(je({...F,children:N},{isLineCompleted:g,skipMode:s,skipTransitionsAndAnimations:y}),r);b.push({...W,children:ee?[ee,...W.children||[]]:W.children})}),e},zc=(e,{presentationState:t,resources:r={},variables:n,runtime:o,saveSlots:i=[],autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:d,form:u,confirmDialog:f,dialogueHistory:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:b,animations:A}=e;if(!f?.resourceId)return e;let v=r.layouts?.[f.resourceId];if(!v)return console.warn(`ConfirmDialog layout not found: ${f.resourceId}`),e;Array.isArray(v.transitions)&&!y&&rn({animations:A,transitions:v.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let S={id:"confirmDialog",type:"container",x:0,y:0,children:[Jo({id:"confirmDialog-blocker",screen:h}),...v.elements||[]]},P=Xo(p,r.characters,n),k=ue(S,Ee({variables:n,runtime:o,saveSlots:i,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:d,form:u,confirmDialog:f,historyDialogue:P,characters:r.characters||{},skipTransitionsAndAnimations:y}),{functions:Oe}),[w,...j]=k.children||[],F=Le(je({...k,children:j},{isLineCompleted:g,skipMode:c,skipTransitionsAndAnimations:y}),r);return b.push({...F,children:w?[w,...F.children||[]]:F.children}),e},At=e=>(t,r)=>Rc(t,{...r,visualLayer:e}),Wc=At(Re.BEHIND_BACKGROUND),qc=At(Re.BEHIND_CHARACTER),Hc=At(Re.BEHIND_DIALOGUE),Yc=At(Re.BEHIND_CHOICE),Kc=At(Re.FOREGROUND),ei=e=>Vt(xc,[Tc,Wc,Cc,qc,Sc,Hc,Lc,Yc,$c,kc,Mc,Kc,Uc,Fc,Dc,Pc,jc,Bc,zc])(e);var Jt={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},ii=1,er="choice",Xt="form",tr=()=>({manual:{...Jt.manual},auto:{...Jt.auto},applyMode:Jt.applyMode}),cn=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let r=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...tr()},r&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},D=e=>{let t=fe(e)?Be(e):e;return structuredClone(t)},T=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),rr=e=>String(e),si=()=>({sections:[],resources:[]}),Gc=e=>T(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):si(),Jc=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",Xc=({sectionId:e,lineId:t,content:r,dialogueState:n,characterName:o})=>({sectionId:e,lineId:t,content:r,text:Jc(r),characterId:n.characterId,character:{...n.character||{},name:o},characterName:o}),Qc=()=>({resourceId:void 0}),Zc=e=>{if(!T(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},ln=(e,t)=>{let r=e?.story?.scenes??{};for(let[n,o]of Object.entries(r))if(o?.sections?.[t])return{sceneId:n,section:o.sections[t]};return{sceneId:void 0,section:void 0}},ai=e=>{let t=e?.story?.scenes??{},r=new Map;for(let[n,o]of Object.entries(t)){let i=o?.sections??{};for(let s of Object.keys(i)){let c=r.get(s);if(c!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${c}" and "${n}". Section IDs must be globally unique.`);r.set(s,n)}}},ci=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},li=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==ii)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},el=(e,t={})=>{let r;try{r=li(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let n={...t,formatVersion:r,slotId:ci(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete n.slotKey,delete n.date,n},tl=(e={})=>Object.fromEntries(Object.entries(e).map(([t,r])=>[t,el(t,r)])),ui=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:r})=>Hu(r));return t.length>0?t:void 0},rl=e=>{!T(e)||!Array.isArray(e.timeline)||e.timeline.forEach(t=>{if(!T(t))return;let r=ui(t.executedActions);if(r){t.executedActions=r;return}delete t.executedActions})},ti=(e,t,r,n="viewedRegistry")=>{let o=t==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[o]:String(e)};if(!T(e))throw new Error(`Malformed ${n}.${t}[${r}] entry.`);if(typeof e[o]!="string"||e[o].length===0)throw new Error(`Malformed ${n}.${t}[${r}] 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 ${n}.sections[${r}] entry: invalid lastLineId.`);return typeof e.lastLineId=="string"&&e.lastLineId.length>0&&(i.lastLineId=e.lastLineId),i}return{resourceId:e.resourceId}},nl=(e,t="viewedRegistry")=>{if(e===void 0)return si();if(!T(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 r=e.sections??[],n=e.resources??[];return{sections:Object.values(Object.fromEntries(r.map((o,i)=>{let s=ti(o,"sections",i,t);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(n.map((o,i)=>{let s=ti(o,"resources",i,t);return[s.resourceId,s]})))}},di=(e,t,r)=>{if(!T(e))throw new Error(`Malformed save slot ${r}.`);let{sectionId:n,lineId:o}=e;if(typeof n!="string"||n.length===0)throw new Error(`Malformed save slot ${r}: missing sectionId.`);if(typeof o!="string"||o.length===0)throw new Error(`Malformed save slot ${r}: missing lineId.`);let{sceneId:i,section:s}=ln(t,n);if(!s)throw new Error(`Malformed save slot ${r}: section "${n}" does not exist in projectData.`);if(!s.lines?.some(a=>a.id===o))throw new Error(`Malformed save slot ${r}: line "${o}" does not exist in section "${n}".`);return{sceneId:i,sectionId:n,lineId:o}},ol=(e,t,r)=>{if(!T(e)||!Array.isArray(e.timeline))return wt({pointer:t,replayStartIndex:1});let n=e.timeline.flatMap((c,a)=>{if(!T(c))return[];try{let l=di(c,r,`rollback.timeline[${a}]`),d=Zt({sectionId:l.sectionId,lineId:l.lineId,rollbackPolicy:c.rollbackPolicy}),u=ui(D(c.executedActions));return u&&(d.executedActions=u),[d]}catch{return[]}});if(n.length===0)return wt({pointer:t,replayStartIndex:1});let o=typeof e.currentIndex=="number"?Math.trunc(e.currentIndex):n.length-1;(o<0||o>=n.length)&&(o=n.length-1);let i=n[o];if(i?.sectionId!==t.sectionId||i?.lineId!==t.lineId){let c=n.findLastIndex(a=>a.sectionId===t.sectionId&&a.lineId===t.lineId);c>=0?o=c:(n.push(Zt({sectionId:t.sectionId,lineId:t.lineId})),o=n.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:n}},il=(e,t,r)=>{if(!T(e))throw new Error(`Malformed save slot contexts[${r}] entry.`);let n=fn(t),o=di(e.pointers?.read,t,`contexts[${r}].pointers.read`);if(e.variables!==void 0&&!T(e.variables))throw new Error(`Malformed save slot contexts[${r}].variables entry.`);if(e.runtime!==void 0&&!T(e.runtime))throw new Error(`Malformed save slot contexts[${r}].runtime entry.`);let i=e.variables?tt(D(e.variables),t.resources?.variables??{}):{},s=bl({loadedContextRuntime:T(e.runtime)?D(e.runtime):{}}),c={currentPointerMode:"read",pointers:{read:o},configuration:T(e.configuration)?D(e.configuration):{},views:Array.isArray(e.views)?D(e.views):[],bgm:T(e.bgm)?D(e.bgm):{resourceId:void 0},variables:{...n,...i},rollback:ol(e.rollback,o,t)};return s&&(c.runtime=s),c},sl=(e,t)=>{if(!T(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((r,n)=>il(r,t,n))}},al=(e,t)=>{if(!T(e))throw new Error("Malformed save slot.");let r=li(e.formatVersion);return{...e,formatVersion:r,state:sl(e.state,t)}},ri=(e,t,{required:r=!1}={})=>{if(e===void 0){if(r)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 n=D(e);return Object.prototype.hasOwnProperty.call(n,"hideConfirmDialog")||(n.hideConfirmDialog={}),n},cl=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:ri(e.confirmActions,"confirmActions",{required:!0}),cancelActions:ri(e.cancelActions,"cancelActions")}},it=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},ll=e=>(T(e.global.formDrafts)||(e.global.formDrafts={}),e.global.formDrafts),st=e=>{Object.prototype.hasOwnProperty.call(e.global,"formDrafts")&&(e.global.formDrafts={})},fi=e=>{if(!(!T(e)||!e.animations))return{animations:D(e.animations)}},ul=(e,t)=>{let r=fi(t);if(r){e.global.pendingScreenTransition=r;return}delete e.global.pendingScreenTransition},dl=e=>{let t=e?.id??e?.resourceId;return typeof t=="string"&&t.length>0?t:void 0},fl=(e,t)=>{let r=e?.sectionId,n=e?.lineId;if(!(!r||!n||!t))return`${r}:${n}:${t}`},Qt=e=>String(e??""),pi=(e,t)=>{let r=Qt(t);return e?.trim===!0?r.trim():r},pl=e=>T(e?.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,t])=>T(t)).map(([t,r])=>[t,{id:t,...D(r)}])):{},hl=(e,t)=>{if(!t||!T(e.global.formDrafts))return;let r=e.global.formDrafts[t];return T(r)?r:void 0},hi=(e,t)=>{let r=ll(e);T(r[t])||(r[t]={values:{},touched:{},errors:{},submitted:!1});let n=r[t];return T(n.values)||(n.values={}),T(n.touched)||(n.touched={}),T(n.errors)||(n.errors={}),typeof n.submitted!="boolean"&&(n.submitted=!1),n},un=(e,t)=>{let r=pi(e,t);return e?.required===!0&&r.length===0?"required":null},ml=({state:e,pointer:t})=>{if(!t?.sectionId||!t?.lineId)return{};let n=ce({state:e},{sectionId:t.sectionId})?.lines||[],o=n.findIndex(i=>i.id===t.lineId);return o<0?{}:We(n.slice(0,o+1).map(i=>i.actions||{}))},gl=({state:e,form:t,pointer:r})=>{if(!t?.resourceId)return null;let n=dl(t),o=fl(r,n);if(!n||!o)return null;let i=hl(e,o),s=pl(t),c=gn({state:e}),a={},l=[],d={},u=!0;return Object.entries(s).forEach(([f,p])=>{let h=Qt(c?.[p.variableId]),g=Object.prototype.hasOwnProperty.call(i?.values??{},f)?Qt(i.values[f]):h,y=i?.touched?.[f]===!0,b=un(p,g),A=i?.submitted||y?b:null,v=typeof p.maxLength=="number"?Math.max(0,Math.round(p.maxLength)):void 0,S={id:f,variableId:p.variableId,value:g,initialValue:h,valid:!b,error:A,touched:y,required:p.required===!0,trim:p.trim===!0,placeholder:p.placeholder===void 0?"":String(p.placeholder),multiline:p.multiline===!0,...v!==void 0?{maxLength:v}:{}};b&&(u=!1),a[f]=S,l.push(S),d[f]=g}),{id:n,key:o,resourceId:t.resourceId,animations:t.animations,valid:u,submitted:i?.submitted===!0,fields:a,fieldList:l,values:d,submitActions:{submitForm:{formKey:o,actions:D(t.submitActions??{})}},cancelActions:{cancelForm:{formKey:o,actions:D(t.cancelActions??{})}}}},Ke=[],ni="line",dn="interaction",Zt=({sectionId:e,lineId:t,rollbackPolicy:r})=>({sectionId:e,lineId:t,rollbackPolicy:r??"free"}),fn=e=>{let{contextVariableDefaultValues:t}=Mt(e??{});return D(t)},mi=()=>({...D(gt)}),gi=({loadedRuntime:e,runtimeIds:t,defaults:r={},path:n})=>{if(e===void 0)return{runtimeState:D(r),hasLoadedValues:!1};if(!T(e))throw new Error(`Malformed ${n}.`);let o=D(r),i=!1;return t.forEach(s=>{e[s]!==void 0&&(o[s]=yi(s,D(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},yl=({loadedGlobalRuntime:e={}})=>gi({loadedRuntime:e,runtimeIds:Nr,defaults:Ne,path:"global.runtime"}).runtimeState,bl=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:r}=gi({loadedRuntime:e,runtimeIds:Vr,defaults:mi(),path:"context.runtime"});return r?t:void 0},nr=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},Il=e=>e.runtime?(Vr.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=D(gt[t]))}),e.runtime):(e.runtime=mi(),e.runtime),Al=e=>vo(e.global),wl=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:Al(e)}})},El=e=>Eo[e],vl=(e,t)=>{let r=El(e);if(r==="number"){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} requires a finite numeric value`);return}if(r==="boolean"){if(typeof t!="boolean")throw new Error(`${e} requires a boolean value`);return}if(r==="string"){if(typeof t!="string")throw new Error(`${e} requires a string value`);return}throw new Error(`Unsupported runtime field "${e}"`)},yi=(e,t)=>(vl(e,t),e==="saveLoadPagination"?Math.max(1,Math.trunc(t)):t),bi=(e,t,r)=>{let n=yi(t,r);if(t in gt){let o=nr(e);if(!o)return n;let i=Il(o);return i[t]=n,n}return e.global[t]=n,n},Ii=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:D(e)},configuration:{},views:[],bgm:Qc(),variables:fn(t),rollback:wt({pointer:e})}),at=e=>e?(e.currentPointerMode="read",T(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,xl=(e,{queueRender:t=!0}={})=>{let r=e.contexts?.[e.contexts.length-1],n=r?.pointers?.read;if(!r||!n?.sectionId||!n?.lineId)return null;let o=Ii({pointer:n,projectData:e.projectData});return e.contexts[e.contexts.length-1]=o,Cl(e,{queueRender:t}),o},Cl=(e,{queueRender:t=!0}={})=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,it(e),st(e),e.global.nextLineConfig=tr(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"}),t&&e.global.pendingEffects.push({name:"render"})},Ai=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},wt=({pointer:e,replayStartIndex:t=0})=>{let r=e?.sectionId&&e?.lineId;return{currentIndex:r?0:-1,isRestoring:!1,replayStartIndex:t,timeline:r?[Zt({sectionId:e.sectionId,lineId:e.lineId})]:[]}},Xe=(e,t={})=>{if(e?.rollback)return Ai(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 r=e?.pointers?.read;return e.rollback=wt({pointer:r,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},pn=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return;let n=Xe(r);if(n.isRestoring)return;n.currentIndex<n.timeline.length-1&&(n.timeline=n.timeline.slice(0,n.currentIndex+1));let o=n.timeline[n.timeline.length-1];if(o?.sectionId===t.sectionId&&o?.lineId===t.lineId&&(o?.rollbackPolicy??"free")===(t.rollbackPolicy??"free")){n.currentIndex=n.timeline.length-1;return}n.timeline.push(Zt(t)),n.currentIndex=n.timeline.length-1},Sl=e=>{let r=e.contexts?.[e.contexts.length-1]?.rollback;if(!r||r.isRestoring||!Array.isArray(r.timeline)||typeof r.currentIndex!="number")return null;let n=Ke[Ke.length-1],o=typeof n?.checkpointIndex=="number"?n.checkpointIndex:r.currentIndex;return o<0||o>=r.timeline.length?null:(typeof n?.checkpointIndex!="number"&&o<r.timeline.length-1&&(r.timeline=r.timeline.slice(0,o+1)),r.timeline[o]??null)},_l=({state:e},t={})=>{let r=t?.source===ni?ni:dn,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?(Ke.push({checkpointIndex:null,source:r}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),Ke.push({checkpointIndex:o.currentIndex,source:r}),e)},Rl=({state:e})=>(Ke.pop(),e),Se=(e,t,r)=>{let o=Ke[Ke.length-1]?.source??dn;if(!Yu(t,o))return;let i=Sl(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:D(r)}))},oi=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return;let n=t?.operations??[];for(let{variableId:o,op:i,value:s,roundTo:c}of n){let a=e.projectData.resources?.variables?.[o],l=a?.scope,d=a?.type;if(Pe(a))throw new Error(`Cannot update computed variable: ${o}`);if(a?.readonly===!0)throw new Error(`Cannot update readonly variable: ${o}`);Ft(l,o),Ut(d,i,o),$r(d,i,s,o,{roundTo:c}),l==="context"&&(r.variables[o]=Bt(r.variables[o],i,s,{roundTo:c}))}},Ol=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:r,payload:n})=>{Ku(e,r,n)})},Ll=(e,t)=>{let{sectionId:r,lineId:n}=t,s=ce({state:e},{sectionId:r})?.lines?.find(c=>c.id===n)?.actions;s&&Object.entries(s).forEach(([c,a])=>{Vi(e,c,a)})},wi=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let n=Xe(r),o=n.timeline[t];if(!o)return e;e.global.autoMode&&ir({state:e}),e.global.skipMode&&Ge({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),n.isRestoring=!0,n.currentIndex=t;try{r.variables=fn(e.projectData),delete r.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=D(Jt),e.global.overlayStack=[],it(e),st(e),e.global.isLineCompleted=!0;let i=n.replayStartIndex??0;for(let c=i;c<=t;c++)c>i&&cn(e),Ll(e,n.timeline[c]),Ol(e,n.timeline[c]);let s=at(r);s.read={sectionId:o.sectionId,lineId:o.lineId},e.global.pendingEffects=e.global.pendingEffects.filter(c=>c?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{n.isRestoring=!1}return e},$l=e=>{let{projectData:t}=e,r=e.global??{},{saveSlots:n={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=r;ai(t);let c=t.story.initialSceneId,a=t.story.scenes[c],l=a.initialSectionId,d=a.sections[l],u={sceneId:c,sectionId:l,lineId:d.initialLineId??d.lines[0].id},{globalVariablesDefaultValues:f}=Mt(t),p={...f,...tt(o,t.resources?.variables??{})};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,formDrafts:{},accountViewedRegistry:nl(s,"accountViewedRegistry"),nextLineConfig:tr(),saveSlots:tl(n),overlayStack:[],variables:p,...yl({loadedGlobalRuntime:i})},contexts:[Ii({pointer:u,projectData:t})]}},kl=({state:e})=>e.global.overlayStack||[],Tl=({state:e})=>e.global.pendingEffects,Ei=({state:e})=>e.global.skipMode,Dl=({state:e})=>e.global.autoMode,vi=({state:e})=>e.global.dialogueUIHidden,xi=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],r=t[t.length-1];if(!r)return[];let{sectionId:n,lineId:o}=r.pointers.read,i=ce({state:e},{sectionId:n});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(u=>u.id===o),c=i.lines.slice(0,s+1),a=[],l={},d=ht({variables:{...e.global?.variables??{},...nr(e)?.variables??{}},runtime:qe(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1});for(let u of c){let f=u.actions||{};if(l=We([l,f]),!f.dialogue)continue;let p=l.dialogue||{},h=jt({characterId:p.characterId,character:p.character,characters:e.projectData.resources?.characters??{},variables:d}),g=Xc({sectionId:n,lineId:u.id,content:f.dialogue.append===!0?p.content:f.dialogue.content,dialogueState:p,characterName:h});if(f.dialogue.append===!0&&a.length>0){a[a.length-1]={...a[a.length-1],content:g.content,text:g.text,characterId:g.characterId,character:g.character,characterName:g.characterName};continue}a.push(g)}return a},Pl=({state:e})=>e.global.confirmDialog??null,Et=({state:e},{pointer:t}={})=>{let r=t??ye({state:e})?.pointer,n=ml({state:e,pointer:r});return gl({state:e,form:n.form,pointer:r})},Nl=({state:e},{pointer:t}={})=>!!Et({state:e},{pointer:t}),be=({state:e},{pointer:t}={})=>{let r=Et({state:e},{pointer:t});if(r)return{source:Xt,formId:r.id,formKey:r.key};let n=Ci({state:e,pointer:t});return n?{source:er,resourceId:n}:null},Vl=({state:e,registry:t},r)=>{let{sectionId:n,lineId:o}=r,s=(Array.isArray(t?.sections)?t.sections:[]).find(d=>d.sectionId===n);if(!s)return!1;if(s.lastLineId===void 0||o===void 0)return!0;let c=ce({state:e},{sectionId:n});if(!c||!c.lines||!Array.isArray(c.lines))return s.lastLineId===o;let a=c.lines.findIndex(d=>d.id===s.lastLineId),l=c.lines.findIndex(d=>d.id===o);return a===-1||l===-1?s.lastLineId===o:l<=a},jl=({registry:e},t)=>{let{resourceId:r}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===r)},hn=({state:e},t)=>Vl({state:e,registry:e.global.accountViewedRegistry},t),Ml=({state:e},t)=>jl({registry:e.global.accountViewedRegistry},t),Fl=({state:e})=>e.global.nextLineConfig,Ci=({state:e,pointer:t}={})=>{let r=t??ye({state:e})?.pointer;if(!r)return;let n=r?.sectionId,o=r?.lineId,s=ce({state:e},{sectionId:n})?.lines||[],c=s.findIndex(l=>l.id===o);if(c<0)return;let a;for(let l of s.slice(0,c+1)){let d=l?.actions;if(d?.cleanAll&&(a=void 0),!d||!Object.prototype.hasOwnProperty.call(d,"choice")){a=void 0;continue}let u=d.choice;if(u?.resourceId){a=u.resourceId;continue}u?.animations||(a=void 0)}return a},Si=({state:e})=>!!Ci({state:e}),Ul=({state:e})=>structuredClone(e),_i=({state:e})=>e.global.saveSlots,Bl=({state:e},t)=>{let r=t?.slotId,n=rr(r);return e.global.saveSlots[n]},mn=({state:e})=>qe(e),zl=({state:e},t)=>_e(e,t?.runtimeId),gn=({state:e})=>{let t={...e.global?.variables??{},...nr(e)?.variables??{}};return ht({variables:t,runtime:qe(e),variableConfigs:e.projectData.resources?.variables??{}})},ye=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],r=t[t.length-1];if(r)return{currentPointerMode:"read",pointer:r.pointers?.read}},ce=({state:e},t)=>{let{sectionId:r}=t;return ln(e.projectData,r).section},yn=({state:e})=>{let t=ye({state:e});if(!t?.pointer)return;let{sectionId:r,lineId:n}=t.pointer,o=ce({state:e},{sectionId:r});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===n)},Ri=({state:e})=>{let{sectionId:t,lineId:r}=ye({state:e}).pointer,o=ce({state:e},{sectionId:t})?.lines||[],i=o.findIndex(l=>l.id===r),c=o.slice(0,i+1).map(l=>{let d=l.actions||{},u={};return Object.keys(d).forEach(f=>{u[f]=d[f]}),u});return We(c)},Wl=({state:e})=>{let t=Oi({state:e}),n=yn({state:e})?.actions??{},o=We([t??{},n]);return kr(t??{},o??{})},ql=({state:e},{sectionId:t})=>{let r=ce({state:e},{sectionId:t});if(!r?.lines)return[];let n=[],o={};for(let i of r.lines){let s=i.actions||{},c=We([o,s]),a=kr(o,c);n.push({id:i.id,changes:a,presentationState:c}),o=Tr(c)}return n},Hl=({state:e},{sectionId:t,includePresentationState:r=!1})=>{let n=ql({state:e},{sectionId:t});return r?{lines:n}:{lines:n.map(({presentationState:o,...i})=>i)}},Oi=({state:e})=>{let{sectionId:t,lineId:r}=ye({state:e}).pointer,o=ce({state:e},{sectionId:t})?.lines||[],i=o.findIndex(a=>a.id===r);if(i<=0)return null;let c=o.slice(0,i).map(a=>{let l=a.actions||{},d={};return Object.keys(l).forEach(u=>{d[u]=l[u]}),d});return Tr(We(c))},bn=({state:e},{slotsPerPage:t=6}={})=>{let o=((mn({state:e}).saveLoadPagination??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let c=o+s,a=e.global.saveSlots&&e.global.saveSlots[rr(c)]||{};i.push({...a,slotId:c})}return{saveSlots:i}},Yl=_i,Kl=bn,Gl=e=>{let r=e.contexts?.[e.contexts.length-1]?.rollback;return!r||!Array.isArray(r.timeline)||typeof r.currentIndex!="number"?!1:r.currentIndex>=0&&r.currentIndex<r.timeline.length-1},Jl=({state:e},t={})=>{let r=Ri({state:e}),n=Oi({state:e}),o=yn({state:e})?.actions??{},i=e.global.pendingScreenTransition,s=i?.animations?{...o,screen:D(i)}:o,c=i?.animations&&n===null?{}:n,{sectionId:a}=ye({state:e}).pointer,{sceneId:l}=ln(e.projectData,a),d=mn({state:e}),u=t?.activePersistentAnimations??[],f=t?.restoredPersistentAnimations??[],p=Et({state:e}),h=Si({state:e}),g=gn({state:e}),{saveSlots:y}=bn({state:e}),b=Gl(e);return ei({presentationState:r,previousPresentationState:c,currentLineActions:s,resources:e.projectData.resources,currentSceneId:l,screen:e.projectData.screen,dialogueUIHidden:d.dialogueUIHidden,autoMode:d.autoMode,skipMode:d.skipMode,isChoiceVisible:h,isFormVisible:!!p,canRollback:Mi({state:e}),skipOnlyViewedLines:!d.skipUnseenText,isLineCompleted:d.isLineCompleted,skipTransitionsAndAnimations:!!d.skipTransitionsAndAnimations||b,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,form:p,dialogueHistory:xi({state:e}),saveSlots:y,variables:g,runtime:d,activePersistentAnimations:u,restoredPersistentAnimations:f})},Xl=({state:e},t)=>(e.global.confirmDialog=cl(t),e.global.pendingEffects.push({name:"render"}),e),Ql=({state:e})=>(e.global.confirmDialog&&(it(e),e.global.pendingEffects.push({name:"render"})),e),Zl=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),Se(e,"pushOverlay",t),e),eu=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),Se(e,"popOverlay",void 0),e),tu=({state:e},t)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=t),e.global.pendingEffects.push({name:"render"}),Se(e,"replaceLastOverlay",t),e),ru=({state:e})=>(e.global.overlayStack=[],it(e),st(e),e.global.pendingEffects.push({name:"render"}),Se(e,"clearOverlays",void 0),e),nu=e=>{e.global.autoMode&&e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.skipMode&&e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.nextLineConfig?.auto?.enabled&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},or=(e,t,{screenTransition:r}={})=>{e.global.isLineCompleted=!1,ul(e,r),st(e);let n=be({state:e},{pointer:t}),o=n?.source===er,i=n?.source===Xt;return n&&nu(e),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:o,isFormVisible:i,activeInteraction:n}},In=(e,t,r)=>{t?.source!==er||r||!e.global.skipMode||e.global.pendingEffects.push({name:"startSkipNextTimer"})},Li=({state:e})=>(be({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:_e(e,"autoForwardDelay")}}),e.global.pendingEffects.push({name:"render"})),e),ir=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),ou=({state:e})=>{let t=e.global.autoMode;return be({state:e})&&!t||(t?ir({state:e}):Li({state:e})),e},$i=({state:e})=>(be({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),Ge=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),iu=({state:e})=>{let t=Ei({state:e});return be({state:e})&&!t||(t?Ge({state:e}):$i({state:e})),e},sr=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),Se(e,"showDialogueUI",void 0),e),ki=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),Se(e,"hideDialogueUI",void 0),e),su=({state:e})=>(vi({state:e})?sr({state:e}):ki({state:e}),e),Qe=(e,t,r)=>(bi(e,t,r),wl(e),e.global.pendingEffects.push({name:"render"}),e),vt=(e,t,r,n)=>{let o=bi(e,t,r);return e.global.pendingEffects.push({name:"render"}),Se(e,n,{value:o}),e},au=({state:e},t)=>Qe(e,"dialogueTextSpeed",t?.value),cu=({state:e},t)=>Qe(e,"autoForwardDelay",t?.value),lu=({state:e},t)=>Qe(e,"skipUnseenText",t?.value),uu=({state:e},t)=>Qe(e,"skipTransitionsAndAnimations",t?.value),du=({state:e},t)=>Qe(e,"soundVolume",t?.value),fu=({state:e},t)=>Qe(e,"musicVolume",t?.value),pu=({state:e},t)=>Qe(e,"muteAll",t?.value),hu=({state:e},t)=>vt(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),mu=({state:e})=>{let t=_e(e,"saveLoadPagination")+1;return vt(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},gu=({state:e})=>{let t=_e(e,"saveLoadPagination")-1;return vt(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},yu=({state:e},t)=>vt(e,"menuPage",t?.value,"setMenuPage"),bu=({state:e},t)=>vt(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),Iu=({state:e})=>(e.global.pendingEffects=[],e),Au=({state:e},t)=>(e.global.pendingEffects.push(t),e),Ti=(e,{sectionId:t,resetStoryState:r=!1,screen:n})=>{let o=!!fi(n),i=ce({state:e},{sectionId:t});if(!i)return console.warn(`Section not found: ${t}`),e;let s=i.lines?.[0];if(!s)return console.warn(`Section ${t} has no lines`),e;if(r&&!xl(e,{queueRender:!o}))return e;let c=be({state:e});r&&e.global.skipMode&&Ge({state:e});let a=e.contexts?.[e.contexts.length-1];if(a){let d=at(a),u=d.read;r||Je(e,{sectionId:u?.sectionId,lineId:u?.lineId}),a.rollback||Xe(a,{compatibilityAnchor:!0}),d.read={sectionId:t,lineId:s.id},r?a.rollback=wt({pointer:d.read}):pn(e,{sectionId:t,lineId:s.id})}let{activeInteraction:l}=or(e,a?.pointers?.read,{screenTransition:n});return In(e,c,l),!r&&e.global.autoMode&&!c&&!l&&e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e},wu=({state:e},t)=>Ti(e,{sectionId:t?.sectionId,resetStoryState:!0,screen:t?.screen}),Di=e=>(e.global.accountViewedRegistry=Gc(e.global.accountViewedRegistry),e.global.accountViewedRegistry),An=(e,t)=>{!Array.isArray(t)||t.length===0||e.global.pendingEffects.push({name:"applyScopedDataUpdates",payload:{updates:t.map(r=>({scope:r.scope,path:r.path,op:r.op,value:D(r.value)}))}})},Pi=(e,t)=>{An(e,[{scope:"account",path:"viewedRegistry",op:"markViewed",value:{sections:(Array.isArray(t?.sections)?t.sections:[]).map(r=>({sectionId:r.sectionId,...r.lastLineId===void 0?{}:{lineId:r.lastLineId}})),resources:Array.isArray(t?.resources)?t.resources:[]}}])},Eu=(e,t,{sectionId:r,lineId:n})=>{if(!r||!n)return!1;let o=T(t)?t:{};Array.isArray(o.sections)||(o.sections=[]);let i=o.sections.find(s=>s.sectionId===r);if(i){if(i.lastLineId===void 0)return!1;let s=ce({state:e},{sectionId:r});if(s?.lines){let c=s.lines.findIndex(l=>l.id===i.lastLineId),a=s.lines.findIndex(l=>l.id===n);if(c===-1||a>c)return i.lastLineId===n?!1:(i.lastLineId=n,!0)}else return i.lastLineId===n?!1:(i.lastLineId=n,!0);return!1}else return o.sections.push({sectionId:r,lastLineId:n}),!0},Je=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;Eu(e,Di(e),t)&&Pi(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},vu=({state:e},t)=>(Je(e,t),e.global.pendingEffects.push({name:"render"}),e),xu=({state:e},t)=>{let{resourceId:r}=t;if(e.global.accountViewedRegistry!==void 0){let n=Di(e);n.resources.find(i=>i.resourceId===r)||(n.resources.push({resourceId:r}),Pi(e,{sections:[],resources:[{resourceId:r}]}))}return e.global.pendingEffects.push({name:"render"}),e},Ni=({state:e},t)=>{let r=Zc(t.manual),{auto:n,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,c=e.contexts?.[e.contexts.length-1]?.rollback?.isRestoring===!0;r&&n?(e.global.nextLineConfig={manual:r,auto:n},o!==void 0?e.global.nextLineConfig.applyMode=o:s!==void 0&&(e.global.nextLineConfig.applyMode=s)):(r&&(e.global.nextLineConfig.manual=r),n&&(e.global.nextLineConfig.auto=n),o!==void 0&&(e.global.nextLineConfig.applyMode=o));let a=e.global.nextLineConfig.auto?.enabled,l=be({state:e});return!c&&!l&&a===!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}}):!c&&a===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),Se(e,"setNextLineConfig",t),e},Cu=({state:e},t)=>{let r=t?.slotId;if(r==null||r==="")throw new Error("saveSlot requires slotId");let{thumbnailImage:n}=t,o=t?.savedAt,i=rr(r),s=D(e.contexts);s?.forEach(l=>{at(l),Ai(l.rollback),rl(l.rollback)});let c={contexts:s},a={formatVersion:ii,slotId:ci(r),savedAt:typeof o=="number"?o:Date.now(),image:n,state:c};return e.global.saveSlots[i]=a,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},Su=({state:e},t)=>{let r=t?.slotId;if(r==null||r==="")throw new Error("loadSlot requires slotId");let n=rr(r),o=e.global.saveSlots[n];if(o){let i=al(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=tr(),e.global.overlayStack=[],e.global.isLineCompleted=!0,it(e),st(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},_u=({state:e},t)=>{let{projectData:r}=t;ai(r),e.projectData=r;let n=r?.resources?.variables??{},{contextVariableDefaultValues:o,globalVariablesDefaultValues:i}=Mt(r??{});return Object.prototype.hasOwnProperty.call(e.global??{},"variables")&&(e.global.variables={...i,...tt(e.global.variables,n)}),e.contexts?.forEach(s=>{Object.prototype.hasOwnProperty.call(s??{},"variables")&&(s.variables={...o,...tt(s.variables,n)})}),it(e),st(e),e.global.pendingEffects.push({name:"render"}),e},Ru=({state:e},t)=>{let{sectionId:r,lineId:n}=t;if(!n)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=r||o.pointers.read?.sectionId;if(r&&!ce({state:e},{sectionId:r}))return console.warn(`Section not found: ${r}`),e;let s=ce({state:e},{sectionId:i});if(!s?.lines||!Array.isArray(s.lines))return console.warn(`Section ${i} has no lines`),e;if(!s.lines.find(u=>u.id===n))return console.warn(`Line not found: ${n} in section ${i}`),e;let a=be({state:e}),l=at(o);l.read={sectionId:i,lineId:n};let{activeInteraction:d}=or(e,l.read);return In(e,a,d),e},Ou=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return sr({state:e}),e;let r=be({state:e});if(r?.source===er&&t?.bypassChoice!==!0||r?.source===Xt&&t?._interactionSource!==Xt)return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let d=ye({state:e})?.pointer,u=d?.sectionId,f=d?.lineId;u&&f&&Je(e,{sectionId:u,lineId:f}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&!r&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:_e(e,"autoForwardDelay")}});let p=e.global.nextLineConfig;return p?.auto?.enabled&&!r&&p.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:p.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e}let n=ye({state:e})?.pointer,o=n?.sectionId,i=ce({state:e},{sectionId:o}),s=e.contexts[e.contexts.length-1],c=i?.lines||[],l=c.findIndex(d=>d.id===n?.lineId)+1;if(l<c.length){let d=c[l],u=!_e(e,"skipUnseenText");if(e.global.skipMode&&u&&!hn({state:e},{sectionId:o,lineId:d.id}))return Ge({state:e}),e;if(s&&!s.rollback&&Xe(s,{compatibilityAnchor:!0}),s){let h=at(s),g=h.read?.lineId;g&&o&&Je(e,{sectionId:o,lineId:g}),h.read={sectionId:o,lineId:d.id}}pn(e,{sectionId:o,lineId:d.id}),cn(e);let{activeInteraction:f}=or(e,{sectionId:o,lineId:d.id});In(e,r,f);let p=e.global.nextLineConfig;p?.auto?.enabled&&!f&&p.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:p.auto.delay}})}else e.global.autoMode&&ir({state:e}),e.global.skipMode&&Ge({state:e});return e},Lu=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=be({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:_e(e,"autoForwardDelay")}});let r=ye({state:e})?.pointer,n=r?.sectionId,o=r?.lineId;n&&o&&Je(e,{sectionId:n,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},$u=({state:e},t)=>Ti(e,{sectionId:t?.sectionId,screen:t?.screen}),ku=({state:e})=>{if(e.global.dialogueUIHidden)return sr({state:e}),e;if(be({state:e}))return e;let t=ye({state:e})?.pointer,r=t?.sectionId,n=ce({state:e},{sectionId:r}),o=e.contexts[e.contexts.length-1],i=n?.lines||[],c=i.findIndex(a=>a.id===t?.lineId)+1;if(c<i.length){let a=i[c],l=!_e(e,"skipUnseenText");if(e.global.skipMode&&l&&!hn({state:e},{sectionId:r,lineId:a.id}))return Ge({state:e}),e;if(o&&!o.rollback&&Xe(o,{compatibilityAnchor:!0}),o){let u=at(o),f=u.read?.lineId;f&&r&&Je(e,{sectionId:r,lineId:f}),u.read={sectionId:r,lineId:a.id}}pn(e,{sectionId:r,lineId:a.id}),cn(e);let{activeInteraction:d}=or(e,{sectionId:r,lineId:a.id});e.global.nextLineConfig.auto?.enabled&&!d&&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},wn=(e,t={})=>{let r=Et({state:e});return!r||t.formKey&&t.formKey!==r.key||t.formId&&t.formId!==r.id?null:r},Tu=(e,t)=>{if(!t.variableId)throw new Error(`form field "${t.id}" requires variableId`);let r=e.projectData.resources?.variables?.[t.variableId],n=r?.scope,o=r?.type;if(Pe(r))throw new Error(`Cannot update computed variable: ${t.variableId}`);if(r?.readonly===!0)throw new Error(`Cannot update readonly variable: ${t.variableId}`);return Ft(n,t.variableId),Ut(o,"set",t.variableId),{variableConfig:r,scope:n}},Du=(e,t)=>({id:e.id,key:e.key,valid:!0,values:D(t),fields:D(e.fields),fieldList:D(e.fieldList)}),Pu=e=>{if(e.global.isLineCompleted)return;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=ye({state:e})?.pointer,r=t?.sectionId,n=t?.lineId;r&&n&&Je(e,{sectionId:r,lineId:n})},Nu=({state:e},t={})=>{let r=wn(e,t),n=t.field;if(!r?.fields?.[n])return e;let o=hi(e,r.key),i=Qt(t.value),s=r.fields[n],c=un(s,i);return o.values[n]=i,o.touched[n]=!0,c?o.errors[n]=c:delete o.errors[n],e.global.pendingEffects.push({name:"render"}),e},Vu=({state:e},t={})=>{let r=wn(e,t);if(!r)return{submitted:!1,valid:!1,reason:"inactive"};let n=hi(e,r.key);n.submitted=!0;let o={},i={};if(Object.entries(r.fields).forEach(([u,f])=>{let p=Object.prototype.hasOwnProperty.call(n.values,u)?n.values[u]:f.value,h=un(f,p);n.touched[u]=!0,h&&(i[u]=h),o[u]=pi(f,p)}),n.errors=i,Object.keys(i).length>0)return e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!1,errors:D(i),form:{id:r.id,key:r.key,values:D(o)}};let s=e.contexts[e.contexts.length-1];if(s?.rollback?.isRestoring)return{submitted:!1,valid:!1,reason:"restoring"};let c=!1,a=[],l=[];Object.entries(r.fields).forEach(([u,f])=>{let{scope:p}=Tu(e,f),h=p==="context"?s.variables:e.global.variables,g=o[u];h[f.variableId]=Bt(h[f.variableId],"set",g),p==="context"&&(c=!0,l.push({variableId:f.variableId,op:"set",value:g})),(p==="device"||p==="account")&&a.push({scope:p,path:`variables.${f.variableId}`,op:"set",value:D(h[f.variableId])})}),c&&Se(e,"updateVariable",{id:"submitForm",operations:l}),An(e,a);let d=Du(r,o);return Pu(e),delete e.global.formDrafts[r.key],e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!0,form:d}},ju=({state:e},t={})=>{let r=wn(e,t);return r?(delete e.global.formDrafts?.[r.key],e.global.pendingEffects.push({name:"render"}),{cancelled:!0,form:{id:r.id,key:r.key,values:D(r.values),fields:D(r.fields),fieldList:D(r.fieldList)}}):{cancelled:!1,reason:"inactive"}},Mu=({state:e},t)=>{let{id:r,operations:n=[]}=t;if(!r)throw new Error("updateVariable requires an id field");if(typeof r!="string"||!/^[a-zA-Z0-9]+$/.test(r))throw new Error(`updateVariable id must be alphanumeric, got: "${r}"`);let o=e.contexts[e.contexts.length-1];if(o?.rollback?.isRestoring)return e;let i=!1,s=[],c=[];return n.forEach(({variableId:a,op:l,value:d,roundTo:u})=>{let f=e.projectData.resources?.variables?.[a],p=f?.scope,h=f?.type;if(Pe(f))throw new Error(`Cannot update computed variable: ${a}`);if(f?.readonly===!0)throw new Error(`Cannot update readonly variable: ${a}`);Ft(p,a),Ut(h,l,a),$r(h,l,d,a,{roundTo:u});let g=p==="context"?o.variables:e.global.variables;if(p==="context"){i=!0;let y={variableId:a,op:l,value:d};u!==void 0&&(y.roundTo=u),c.push(y)}g[a]=Bt(g[a],l,d,{roundTo:u}),(p==="device"||p==="account")&&s.push({scope:p,path:`variables.${a}`,op:"set",value:D(g[a])})}),i&&Se(e,"updateVariable",{id:r,operations:c}),An(e,s),e.global.pendingEffects.push({name:"render"}),e},Fu=e=>(t,r)=>e({state:t},r),Uu=e=>({variables:ht({variables:{...e.global?.variables??{},...nr(e)?.variables??{}},runtime:qe(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1}),runtime:qe(e)}),Bu=e=>{if(!T(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")},zu=(e,t,r)=>{if(!T(e))throw new Error(`conditional branch at index ${t} must be an object`);if(!T(e.actions))throw new Error(`conditional branch at index ${t} requires actions object`);if(!Object.prototype.hasOwnProperty.call(e,"when")&&t!==r-1)throw new Error("conditional else branch must be the last branch")},Wu=(e,t)=>{Bu(t);for(let r=0;r<t.branches.length;r+=1){let n=t.branches[r];if(zu(n,r,t.branches.length),!(Object.prototype.hasOwnProperty.call(n,"when")&&!pt(n.when,Uu(e)))){Object.entries(n.actions).forEach(([i,s])=>{Vi(e,i,s)});return}}},qu={conditional:{replayLine:Wu},updateVariable:{recordSources:[dn],replayLine:oi,replayRecorded:oi,persistInSaveSlot:!0},setNextLineConfig:{replayLine:Fu(Ni)}},ar=e=>qu[e]??null,Hu=e=>ar(e)?.persistInSaveSlot===!0,Yu=(e,t)=>{let r=ar(e)?.recordSources;return Array.isArray(r)&&r.includes(t)},Ku=(e,t,r)=>{ar(t)?.replayRecorded?.(e,r)},Vi=(e,t,r)=>{ar(t)?.replayLine?.(e,r)},ji=({state:e},t)=>{let{offset:r}=t;if(r===void 0||typeof r!="number")return console.warn("selectLineIdByOffset requires a numeric offset"),null;let n=e.contexts[e.contexts.length-1];if(!n)return null;let o=n.rollback;if(!Array.isArray(o?.timeline)||typeof o?.currentIndex!="number")return null;let i=o.currentIndex+r;if(i<0||i>=o.timeline.length)return null;let s=o.timeline[i];return{sectionId:s.sectionId,lineId:s.lineId}},Mi=({state:e})=>ji({state:e},{offset:-1})!==null,Gu=({state:e},t)=>{let{offset:r=-1}=t;if(r>=0)throw new Error("rollbackByOffset requires a negative offset");let n=e.contexts?.[e.contexts.length-1];if(!n)return e;let o=Xe(n,{compatibilityAnchor:!n.rollback}),i=o.currentIndex+r;return i<0||i>=o.timeline.length?e:wi(e,i)},Ju=({state:e},t)=>{let{sectionId:r,lineId:n}=t,o=e.contexts[e.contexts.length-1];if(!o)throw new Error("No context available for rollbackToLine");let i=Xe(o,{compatibilityAnchor:!o.rollback}),c=i.timeline.slice(0,i.currentIndex+1).findLastIndex(a=>a.sectionId===r&&a.lineId===n);if(c===-1)throw new Error(`Line ${n} not found in section ${r} rollback timeline`);return c===i.currentIndex?e:wi(e,c)},Fi=e=>{let t=$l(e);return io(t,{selectPendingEffects:Tl,selectSkipMode:Ei,selectAutoMode:Dl,selectIsChoiceVisible:Si,selectIsFormVisible:Nl,selectActiveInteraction:be,selectActiveForm:Et,selectDialogueUIHidden:vi,selectDialogueHistory:xi,selectConfirmDialog:Pl,selectIsLineAccountViewed:hn,selectIsResourceAccountViewed:Ml,selectNextLineConfig:Fl,selectSystemState:Ul,selectSaveSlotMap:_i,selectSaveSlots:Yl,selectSaveSlot:Bl,selectRuntime:mn,selectRuntimeValue:zl,selectAllVariables:gn,selectCurrentPointer:ye,selectSection:ce,selectCurrentLine:yn,selectPresentationState:Ri,selectPresentationChanges:Wl,selectSectionLineChanges:Hl,selectSaveSlotPage:bn,selectCurrentPageSlots:Kl,selectRenderState:Jl,selectOverlayStack:kl,selectLineIdByOffset:ji,selectCanRollback:Mi,startAutoMode:Li,stopAutoMode:ir,toggleAutoMode:ou,startSkipMode:$i,stopSkipMode:Ge,toggleSkipMode:iu,showDialogueUI:sr,hideDialogueUI:ki,toggleDialogueUI:su,setDialogueTextSpeed:au,setAutoForwardDelay:cu,setSkipUnseenText:lu,setSkipTransitionsAndAnimations:uu,setSoundVolume:du,setMusicVolume:fu,setMuteAll:pu,setSaveLoadPagination:hu,incrementSaveLoadPagination:mu,decrementSaveLoadPagination:gu,setMenuPage:yu,setMenuEntryPoint:bu,showConfirmDialog:Xl,hideConfirmDialog:Ql,resetStoryAtSection:wu,clearPendingEffects:Iu,appendPendingEffect:Au,beginRollbackActionBatch:_l,endRollbackActionBatch:Rl,addViewedLine:vu,addViewedResource:xu,setNextLineConfig:Ni,saveSlot:Cu,loadSlot:Su,updateProjectData:_u,sectionTransition:$u,jumpToLine:Ru,nextLine:Ou,markLineCompleted:Lu,rollbackToLine:Ju,rollbackByOffset:Gu,pushOverlay:Zl,popOverlay:eu,replaceLastOverlay:tu,clearOverlays:ru,updateFormField:Nu,submitForm:Vu,cancelForm:ju,updateVariable:Mu,nextLineFromSystem:ku},{transformActionFirstArgument:n=>({state:n}),transformSelectorFirstArgument:n=>({state:n})})};var Xu="route-engine",Qu="projectPersistence";var Bi=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),ne=e=>Object.prototype.toString.call(e)==="[object Object]",Ui="variables.",Zu=(e={})=>{let t=ne(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!ne(r)||typeof r.sectionId!="string"||r.sectionId.length===0?null:{sectionId:r.sectionId,...typeof r.lineId=="string"?{lineId:r.lineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(r=>typeof r=="string"||typeof r=="number"?{resourceId:String(r)}:!ne(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},ed=(e={})=>{let t=ne(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!ne(r)||typeof r.sectionId!="string"||r.sectionId.length===0?null:{sectionId:r.sectionId,...typeof r.lastLineId=="string"?{lastLineId:r.lastLineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(r=>typeof r=="string"||typeof r=="number"?{resourceId:String(r)}:!ne(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},td=(e,t)=>{let r=ed(e),n=Zu(t),o=r.sections.map(s=>({...s})),i=r.resources.map(s=>({...s}));return n.sections.forEach(s=>{let c=o.find(a=>a.sectionId===s.sectionId);if(!c){o.push({sectionId:s.sectionId,...s.lineId===void 0?{}:{lastLineId:s.lineId}});return}if(c.lastLineId!==void 0){if(s.lineId===void 0){delete c.lastLineId;return}c.lastLineId=s.lineId}}),n.resources.forEach(s=>{i.find(a=>a.resourceId===s.resourceId)||i.push({...s})}),{sections:o,resources:i}},zi=(e={})=>{let t=ne(e)?e:{};return{saveSlots:ne(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:ne(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:ne(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:ne(t.globalRuntime)?t.globalRuntime:{},accountViewedRegistry:ne(t.accountViewedRegistry)?t.accountViewedRegistry:{}}},rd=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((t,r)=>{if(!ne(t))throw new Error(`Malformed applyScopedDataUpdates.updates[${r}] entry.`);let n=t.path?.startsWith(Ui)?t.path.slice(Ui.length):null;if(n!==null){if(!["device","account"].includes(t.scope))throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${r}].`);if(n.length===0)throw new Error(`Malformed applyScopedDataUpdates path "${t.path}" at updates[${r}].`);if(t.op!=="set")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${r}].`);return{scope:t.scope,path:t.path,op:t.op,value:t.value,variableId:n}}if(t.path==="viewedRegistry"){if(t.scope!=="account")throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${r}].`);if(t.op!=="markViewed")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${r}].`);return t}throw typeof t.path!="string"?new Error(`Malformed applyScopedDataUpdates path at updates[${r}].`):new Error(`Unsupported applyScopedDataUpdates path "${t.path}" at updates[${r}].`)})},nd=(e,t)=>{let r={};return rd(t).forEach(n=>{if(n.path==="viewedRegistry"){r.accountViewedRegistry=td(r.accountViewedRegistry??e.accountViewedRegistry,n.value);return}let o=n.scope==="device"?"globalDeviceVariables":"globalAccountVariables";r[o]={...e[o],...r[o],[n.variableId]:n.value}}),r},En=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},od=e=>{let t=En(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},id=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},sd=({indexedDB:e,databaseName:t,objectStoreName:r})=>new Promise((n,o)=>{let i=e.open(t,1);i.onupgradeneeded=()=>{let s=i.result;s.objectStoreNames.contains(r)||s.createObjectStore(r,{keyPath:"namespace"})},i.onsuccess=()=>{n(i.result)},i.onerror=()=>{o(i.error??new Error(`Failed to open IndexedDB database "${t}".`))}}),ad=async({databasePromise:e,objectStoreName:t,namespace:r})=>{let n=await e;return new Promise((o,i)=>{let a=n.transaction(t,"readonly").objectStore(t).get(r);a.onsuccess=()=>{o(a.result??null)},a.onerror=()=>{i(a.error??new Error(`Failed to read persisted namespace "${r}" from IndexedDB.`))}})},xt=async({databasePromise:e,objectStoreName:t,namespace:r,patch:n})=>{let o=await e;return new Promise((i,s)=>{let c=o.transaction(t,"readwrite"),a=c.objectStore(t),l=a.get(r),d=!1,u=p=>{d||(d=!0,s(p))},f=()=>{d||(d=!0,i())};l.onerror=()=>{u(l.error??new Error(`Failed to read persisted namespace "${r}" before updating IndexedDB.`))},l.onsuccess=()=>{let p=zi(l.result),h=typeof n=="function"?n(p):n,g={namespace:r,version:1,...Bi(),...p,...h},y=a.put(g);y.onerror=()=>{u(y.error??new Error(`Failed to persist namespace "${r}" to IndexedDB.`))}},c.oncomplete=()=>{f()},c.onerror=()=>{u(c.error??new Error(`IndexedDB transaction failed while updating namespace "${r}".`))},c.onabort=()=>{u(c.error??new Error(`IndexedDB transaction aborted while updating namespace "${r}".`))}})},cd=async({databasePromise:e,objectStoreName:t,namespace:r})=>{let n=await e;return new Promise((o,i)=>{let s=n.transaction(t,"readwrite"),a=s.objectStore(t).delete(r),l=!1,d=f=>{l||(l=!0,i(f))},u=()=>{l||(l=!0,o())};a.onerror=()=>{d(a.error??new Error(`Failed to clear persisted namespace "${r}" from IndexedDB.`))},s.oncomplete=()=>{u()},s.onerror=()=>{d(s.error??new Error(`IndexedDB transaction failed while clearing namespace "${r}".`))},s.onabort=()=>{d(s.error??new Error(`IndexedDB transaction aborted while clearing namespace "${r}".`))}})},vn=(e={})=>{let{indexedDB:t,databaseName:r=Xu,objectStoreName:n=Qu,namespace:o}=e,i=id(t),s=od(o),c=sd({indexedDB:i,databaseName:r,objectStoreName:n});return{namespace:s,load:async()=>{let a=await ad({databasePromise:c,objectStoreName:n,namespace:s});return{...Bi(),...zi(a)}},clear:async()=>cd({databasePromise:c,objectStoreName:n,namespace:s}),saveSlots:async a=>xt({databasePromise:c,objectStoreName:n,namespace:s,patch:{saveSlots:ne(a)?a:{}}}),saveGlobalDeviceVariables:async a=>xt({databasePromise:c,objectStoreName:n,namespace:s,patch:{globalDeviceVariables:ne(a)?a:{}}}),saveGlobalAccountVariables:async a=>xt({databasePromise:c,objectStoreName:n,namespace:s,patch:{globalAccountVariables:ne(a)?a:{}}}),saveGlobalRuntime:async a=>xt({databasePromise:c,objectStoreName:n,namespace:s,patch:{globalRuntime:ne(a)?a:{}}}),applyScopedDataUpdates:async a=>xt({databasePromise:c,objectStoreName:n,namespace:s,patch:l=>nd(l,a)})}},ld=vn;var ud=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),dd=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),Wi="conditional",xn="form",fd=new Set(["submitForm","cancelForm"]),Ct=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function Cn(e){let t,r=0,n=null,o=new Map,i=new Map,s=new Map,{handlePendingEffects:c}=e,a=(I=new Map,C=Date.now())=>new Map(Array.from(I.entries()).filter(([,R])=>C<R.expiresAt).map(([R,M])=>[R,{animation:structuredClone(M.animation),startedAt:M.startedAt,expiresAt:M.expiresAt}])),l=(I=new Map)=>Array.from(I.values()).map(C=>structuredClone(C.animation)),d=(I=Date.now())=>{o=new Map(Array.from(o.entries()).filter(([,C])=>I<C.expiresAt))},u=()=>{for(;t.selectPendingEffects().length>0;){let I=[...t.selectPendingEffects()];t.clearPendingEffects();try{c(I)}catch(C){throw t.clearPendingEffects(),I.forEach(R=>{t.appendPendingEffect(R)}),C}}},f=({initialState:I,namespace:C})=>{t=Fi(I),r=0,n=En(C),o=new Map,i=new Map,s=new Map,t.appendPendingEffect({name:"handleLineActions"}),u()},p=()=>n,h=()=>t.selectPresentationState(),g=()=>t.selectPresentationChanges(),y=I=>t.selectSectionLineChanges(I),b=(I={})=>{r+=1;let C=Date.now();d(C);let R=i.size>0,M=a(o,C),B=R?a(i,C):new Map,xe={...t.selectRenderState({activePersistentAnimations:l(M),restoredPersistentAnimations:l(B)}),id:`render-${r}`};return s.set(xe.id,{builtAt:C,persistentAnimationSessions:new Map([...B.entries(),...M.entries()]),usedRestoredPersistentAnimationSessions:R}),xe},A=(I={})=>b(I),v=(I={})=>b(I),S=I=>{let C=typeof I?.id=="string"&&I.id.length>0?I.id:null,R=C?s.get(C):null;C&&s.delete(C);let M=new Map;jo(I?.animations).forEach(B=>{let he=Yt(B);if(!he)return;let xe=R?.persistentAnimationSessions?.get(he)??o.get(he),St=Math.max(0,Fo(B)),_n=xe?.startedAt??R?.builtAt??Date.now();M.set(he,{animation:structuredClone(B),startedAt:_n,expiresAt:_n+St})}),o=M,R?.usedRestoredPersistentAnimationSessions&&(i=new Map)},P=()=>t.selectSystemState(),k=()=>t.selectSaveSlotMap(),w=I=>t.selectSaveSlot(I),j=I=>t.selectSaveSlotPage(I),F=()=>t.selectSkipMode(),ee=()=>t.selectAutoMode(),N=()=>t.selectRuntime(),W=()=>t.selectIsChoiceVisible(),q=()=>t.selectIsFormVisible(),te=()=>t.selectActiveInteraction(),ve=(I,C,R={})=>!Ct(C)||I!=="nextLine"?C:R.bypassChoice===!0?{...C,bypassChoice:!0}:R.interactionSource===xn?{...C,_interactionSource:xn}:C,Y=(I,C)=>{if(!t[I])return;ud.has(I)&&(dd.has(I)?i=a(o):i=new Map,o=new Map);let R=t[I](C);return u(),R},K=(I,C,R,M={})=>{if(I===Wi){let B=re(R),he=Dr({[I]:C},B);se(he[I],R,M);return}Y(I,C)},oe=(I,C)=>{K(I,C)},re=I=>{if(!I)return{variables:t.selectAllVariables?t.selectAllVariables():void 0,runtime:t.selectRuntime?t.selectRuntime():{}};if(Object.prototype.hasOwnProperty.call(I,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:C,...R}=I,M=t.selectAllVariables?t.selectAllVariables():void 0;return{...R,_event:C,variables:M,runtime:t.selectRuntime?t.selectRuntime():{}}},G=I=>{if(!Ct(I))throw new Error("conditional action payload must be an object");if(!Array.isArray(I.branches))throw new Error("conditional action requires branches array");if(I.branches.length===0)throw new Error("conditional action requires at least one branch")},ie=(I,C,R)=>{if(!Ct(I))throw new Error(`conditional branch at index ${C} must be an object`);if(!Ct(I.actions))throw new Error(`conditional branch at index ${C} requires actions object`);if(!Object.prototype.hasOwnProperty.call(I,"when")&&C!==R-1)throw new Error("conditional else branch must be the last branch")},se=(I,C,R)=>{G(I);for(let M=0;M<I.branches.length;M+=1){let B=I.branches[M];ie(B,M,I.branches.length);let he=re(C);if(!(Object.prototype.hasOwnProperty.call(B,"when")&&!pt(B.when,he))){J(B.actions,C,R);return}}},x=(I,C)=>({...I??{},_form:C}),_=(I,C,R,M)=>{let B=Y(I,C),he=B?.submitted===!0&&B.valid===!0,xe=B?.cancelled===!0;!he&&!xe||Ct(C.actions)&&J(C.actions,x(R,B.form),{...M,interactionSource:xn})},V=(I,C,R,M)=>{let B=re(R),xe=Dr({[I]:C},B)[I];if(I===Wi){se(xe,R,M);return}let St=ve(I,xe,M);if(fd.has(I)){_(I,St,R,M);return}Y(I,St)},J=(I,C,R)=>{Object.entries(I).forEach(([M,B])=>{V(M,B,C,R)})},z=(I,C,R={})=>{t.beginRollbackActionBatch({source:R.rollbackSource});try{J(I,C,R)}finally{t.endRollbackActionBatch({})}};return{init:f,handleAction:K,handleInternalAction:oe,handleActions:z,selectRenderState:A,prepareRenderState:v,commitRenderState:S,selectPresentationState:h,selectPresentationChanges:g,selectSectionLineChanges:y,selectSystemState:P,selectSaveSlotMap:k,selectSaveSlot:w,selectSaveSlotPage:j,selectSaveSlots:k,selectRuntime:N,selectIsChoiceVisible:W,selectIsFormVisible:q,selectActiveInteraction:te,handleLineActions:()=>{let I=t.selectCurrentLine();return I?.actions?(z(I.actions,void 0,{rollbackSource:"line"}),!0):!1},getNamespace:p}}var Sn=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:r=>{e=r},addElapsed:r=>{e+=r},getCallback:()=>t,setCallback:r=>{t=r}}},pd=80,Hi=({engine:e,routeGraphics:t,trackRenderDispatch:r},n)=>{let o=e.prepareRenderState?.(n)??e.selectRenderState(n);r?.(o),t.render(o),e.commitRenderState?.(o)},hd=({engine:e,routeGraphics:t,trackRenderDispatch:r,getRenderDispatchCount:n},o)=>{let i=n?.()??0,s=e.handleLineActions();(n?.()??0)===i&&Hi({engine:e,routeGraphics:t,trackRenderDispatch:r},o)},md=({engine:e,ticker:t,autoTimer:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let c=n.delay??1e3;r.getElapsed()>=c&&(t.remove(i),r.setCallback(null),r.setElapsed(0),cr(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},gd=({ticker:e,autoTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},yd=({engine:e,ticker:t,skipTimer:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let c=n?.delay??pd;r.getElapsed()>=c&&(r.setElapsed(0),cr(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},bd=({ticker:e,skipTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},Id=({engine:e,ticker:t,nextLineConfigTimerState:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let c=n.delay??1e3;r.getElapsed()>=c&&(r.setElapsed(0),cr(e,"nextLineFromSystem",{}),t.remove(i),r.setCallback(null))};r.setCallback(i),t.add(i)},Ad=({ticker:e,nextLineConfigTimerState:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},wd=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveSlots(t?.saveSlots))},Ed=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalDeviceVariables(t?.globalDeviceVariables))},vd=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalAccountVariables(t?.globalAccountVariables))},xd=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalRuntime(t?.globalRuntime))},Cd=({enqueuePersistenceWrite:e},t)=>{e(r=>{if(typeof r.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return r.applyScopedDataUpdates(t?.updates)})},qi={render:Hi,saveSlots:wd,saveGlobalDeviceVariables:Ed,saveGlobalAccountVariables:vd,saveGlobalRuntime:xd,applyScopedDataUpdates:Cd,handleLineActions:hd,startAutoNextTimer:md,clearAutoNextTimer:gd,startSkipNextTimer:yd,clearSkipNextTimer:bd,nextLineConfigTimer:Id,clearNextLineConfigTimer:Ad},Sd=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),cr=(e,t,r)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,r)},_d=(e=[])=>{let t=new Set,r=[];for(let n=e.length-1;n>=0;n-=1){let o=e[n];if(typeof o?.name!="string"||o.name.length===0)throw new Error("Pending effect is missing a valid name.");if(!Sd.has(o.name)){r.unshift(o);continue}t.has(o.name)||(t.add(o.name),r.unshift(o))}return r},Rd=({getEngine:e,routeGraphics:t,ticker:r,handleUnhandledEffect:n,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:c})=>{let a=Sn(),l=Sn(),d=Sn(),u=s??null,f=Promise.resolve(),p=null,h=null,g=!1,y=0,b=x=>{if(o){o(x);return}console.error("RouteEngine persistence write failed.",x)},A=()=>{if(u)return u;let x=e();return u=vn({indexedDB:i,namespace:c??x?.getNamespace?.()}),u},v=x=>{f=f.catch(()=>{}).then(()=>{let _=A();return x(_)}).catch(_=>{b(_)})},S=x=>{let _=typeof x?.id=="string"&&x.id.length>0?x.id:null;y+=1,p=_,g=!1},P=()=>y,k=(x={})=>{if(x?.aborted===!0)return!1;let _=typeof x?.id=="string"&&x.id.length>0?x.id:null;return _?_!==p||_===h?!1:(h=_,!0):p!==null||g?!1:(g=!0,!0)},w=(x,_={})=>{if(x!=="renderComplete"||!k(_))return!1;let V=e();return cr(V,"markLineCompleted",{}),!0},j=new Set(["updateFormField","submitForm","cancelForm"]),F=new Set(["updateVariable"]),ee=x=>typeof x?.selectActiveInteraction=="function"?x.selectActiveInteraction():typeof x?.selectIsChoiceVisible=="function"&&x.selectIsChoiceVisible()?{source:"choice"}:null,N=x=>x?._formKey??x?.formKey,W=(x,_)=>N(x)===_?.formKey,q=(x,_)=>!x||typeof x!="object"||Array.isArray(x)?!1:x._interactionSource===_?.source,te=(x,_)=>q(x,_)?_.source==="form"?W(x,_):!0:!1,ve=(x,_)=>!x||typeof x!="object"||Array.isArray(x)||_?.source!=="form"?!1:W(x,_),Y=(x={})=>Object.keys(x).some(_=>j.has(_)),K=(x={},_)=>Object.entries(x).some(([V,J])=>j.has(V)&&ve(J,_)),oe=(x={})=>Object.keys(x).length>0&&Object.keys(x).every(_=>F.has(_)),re=(x={},_)=>{let V=x?.actions;return _?.source==="form"?!V||typeof V!="object"||Array.isArray(V)?!1:K(V,_)?!0:Y(V)?!1:oe(V):te(x,_)?!0:!V||typeof V!="object"||Array.isArray(V)?!1:Object.values(V).some(J=>te(J,_))},G=(x,_={})=>{if(!_?.actions)return!1;let V=ee(x);return!V||V.source==="choice"?!1:!re(_,V)},ie=({preprocessPayload:x,onEvent:_}={})=>async(V,J={})=>{let z=e();if(G(z,J))return _?.(V,J);let X=await x?.(V,J)??J;if(G(z,X))return _?.(V,X);if(w(V,X),X?.actions){let I=X?._event?{_event:X._event}:X?.event?{_event:X.event}:void 0,C;X?.bypassChoice===!0?C={bypassChoice:!0}:X?._interactionSource&&(C={interactionSource:X._interactionSource}),C?z.handleActions(X.actions,I,C):z.handleActions(X.actions,I)}return _?.(V,X)},se=x=>{let _=e(),V=_d(x);V.forEach(z=>{if(!qi[z.name]&&!n)throw new Error(`Unhandled pending effect "${z.name}".`)});let J={engine:_,routeGraphics:t,ticker:r,autoTimer:a,skipTimer:l,nextLineConfigTimerState:d,trackRenderDispatch:S,getRenderDispatchCount:P,enqueuePersistenceWrite:v};for(let z of V){let X=qi[z.name];if(X){X(J,z.payload);continue}n(z,J)}};return se.handleRouteGraphicsEvent=w,se.createRouteGraphicsEventHandler=ie,se},Od=Rd;var Ld=(e,t={})=>{let{resources:r={}}=t;return sn(e,r)};var Gf=Cn;export{jr as DEFAULT_VISUAL_LAYER,rt as RENDER_LAYER,Re as VISUAL_LAYER,Od as createEffectsHandler,ld as createIndexedDbPersistence,Gf as default,ea as resolveComputedVariables,Ld as resolveLayoutReferences};
1
+ var ws=Object.defineProperty;var Es=(e,t)=>{for(var r in t)ws(e,r,{get:t[r],enumerable:!0})};var Bn=Symbol.for("immer-nothing"),Vn=Symbol.for("immer-draftable"),fe=Symbol.for("immer-state");function Ie(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var et=Object.getPrototypeOf;function de(e){return!!e&&!!e[fe]}function Me(e){return e?zn(e)||Array.isArray(e)||!!e[Vn]||!!e.constructor?.[Vn]||Tt(e)||Nt(e):!1}var xs=Object.prototype.constructor.toString();function zn(e){if(!e||typeof e!="object")return!1;let t=et(e);if(t===null)return!0;let r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return r===Object?!0:typeof r=="function"&&Function.toString.call(r)===xs}function Lt(e,t){Dt(e)===0?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,n)=>t(n,r,e))}function Dt(e){let t=e[fe];return t?t.type_:Array.isArray(e)?1:Tt(e)?2:Nt(e)?3:0}function Ir(e,t){return Dt(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function qn(e,t,r){let n=Dt(e);n===2?e.set(t,r):n===3?e.add(r):e[t]=r}function vs(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Tt(e){return e instanceof Map}function Nt(e){return e instanceof Set}function Fe(e){return e.copy_||e.base_}function Ar(e,t){if(Tt(e))return new Map(e);if(Nt(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=zn(e);if(t===!0||t==="class_only"&&!r){let n=Object.getOwnPropertyDescriptors(e);delete n[fe];let o=Reflect.ownKeys(n);for(let i=0;i<o.length;i++){let s=o[i],c=n[s];c.writable===!1&&(c.writable=!0,c.configurable=!0),(c.get||c.set)&&(n[s]={configurable:!0,writable:!0,enumerable:c.enumerable,value:e[s]})}return Object.create(et(e),n)}else{let n=et(e);if(n!==null&&r)return{...e};let o=Object.create(n);return Object.assign(o,e)}}function Sr(e,t=!1){return Pt(e)||de(e)||!Me(e)||(Dt(e)>1&&(e.set=e.add=e.clear=e.delete=Ss),Object.freeze(e),t&&Object.entries(e).forEach(([r,n])=>Sr(n,!0))),e}function Ss(){Ie(2)}function Pt(e){return Object.isFrozen(e)}var Cs={};function Ue(e){let t=Cs[e];return t||Ie(0,e),t}var ut;function Wn(){return ut}function _s(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function jn(e,t){t&&(Ue("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function wr(e){Er(e),e.drafts_.forEach(Rs),e.drafts_=null}function Er(e){e===ut&&(ut=e.parent_)}function Fn(e){return ut=_s(ut,e)}function Rs(e){let t=e[fe];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function Mn(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[fe].modified_&&(wr(t),Ie(4)),Me(e)&&(e=$t(t,e),t.parent_||kt(t,e)),t.patches_&&Ue("Patches").generateReplacementPatches_(r[fe].base_,e,t.patches_,t.inversePatches_)):e=$t(t,r,[]),wr(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Bn?e:void 0}function $t(e,t,r){if(Pt(t))return t;let n=t[fe];if(!n)return Lt(t,(o,i)=>Un(e,n,t,o,i,r)),t;if(n.scope_!==e)return t;if(!n.modified_)return kt(e,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;let o=n.copy_,i=o,s=!1;n.type_===3&&(i=new Set(o),o.clear(),s=!0),Lt(i,(c,a)=>Un(e,n,o,c,a,r,s)),kt(e,o,!1),r&&e.patches_&&Ue("Patches").generatePatches_(n,r,e.patches_,e.inversePatches_)}return n.copy_}function Un(e,t,r,n,o,i,s){if(de(o)){let c=i&&t&&t.type_!==3&&!Ir(t.assigned_,n)?i.concat(n):void 0,a=$t(e,o,c);if(qn(r,n,a),de(a))e.canAutoFreeze_=!1;else return}else s&&r.add(o);if(Me(o)&&!Pt(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;$t(e,o),(!t||!t.scope_.parent_)&&typeof n!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,n)&&kt(e,o)}}function kt(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&Sr(t,r)}function Os(e,t){let r=Array.isArray(e),n={type_:r?1:0,scope_:t?t.scope_:Wn(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=n,i=Cr;r&&(o=[n],i=ft);let{revoke:s,proxy:c}=Proxy.revocable(o,i);return n.draft_=c,n.revoke_=s,c}var Cr={get(e,t){if(t===fe)return e;let r=Fe(e);if(!Ir(r,t))return Ls(e,r,t);let n=r[t];return e.finalized_||!Me(n)?n:n===yr(e.base_,t)?(br(e),e.copy_[t]=vr(n,e)):n},has(e,t){return t in Fe(e)},ownKeys(e){return Reflect.ownKeys(Fe(e))},set(e,t,r){let n=Hn(Fe(e),t);if(n?.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){let o=yr(Fe(e),t),i=o?.[fe];if(i&&i.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(vs(r,o)&&(r!==void 0||Ir(e.base_,t)))return!0;br(e),xr(e)}return e.copy_[t]===r&&(r!==void 0||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_[t]=!0),!0},deleteProperty(e,t){return yr(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,br(e),xr(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=Fe(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:n.enumerable,value:r[t]}},defineProperty(){Ie(11)},getPrototypeOf(e){return et(e.base_)},setPrototypeOf(){Ie(12)}},ft={};Lt(Cr,(e,t)=>{ft[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});ft.deleteProperty=function(e,t){return ft.set.call(this,e,t,void 0)};ft.set=function(e,t,r){return Cr.set.call(this,e[0],t,r,e[0])};function yr(e,t){let r=e[fe];return(r?Fe(r):e)[t]}function Ls(e,t,r){let n=Hn(t,r);return n?"value"in n?n.value:n.get?.call(e.draft_):void 0}function Hn(e,t){if(!(t in e))return;let r=et(e);for(;r;){let n=Object.getOwnPropertyDescriptor(r,t);if(n)return n;r=et(r)}}function xr(e){e.modified_||(e.modified_=!0,e.parent_&&xr(e.parent_))}function br(e){e.copy_||(e.copy_=Ar(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var $s=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,r,n)=>{if(typeof t=="function"&&typeof r!="function"){let i=r;r=t;let s=this;return function(a=i,...l){return s.produce(a,u=>r.call(this,u,...l))}}typeof r!="function"&&Ie(6),n!==void 0&&typeof n!="function"&&Ie(7);let o;if(Me(t)){let i=Fn(this),s=vr(t,void 0),c=!0;try{o=r(s),c=!1}finally{c?wr(i):Er(i)}return jn(i,n),Mn(o,i)}else if(!t||typeof t!="object"){if(o=r(t),o===void 0&&(o=t),o===Bn&&(o=void 0),this.autoFreeze_&&Sr(o,!0),n){let i=[],s=[];Ue("Patches").generateReplacementPatches_(t,o,i,s),n(i,s)}return o}else Ie(1,t)},this.produceWithPatches=(t,r)=>{if(typeof t=="function")return(s,...c)=>this.produceWithPatches(s,a=>t(a,...c));let n,o;return[this.produce(t,r,(s,c)=>{n=s,o=c}),n,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){Me(e)||Ie(8),de(e)&&(e=Be(e));let t=Fn(this),r=vr(e,void 0);return r[fe].isManual_=!0,Er(t),r}finishDraft(e,t){let r=e&&e[fe];(!r||!r.isManual_)&&Ie(9);let{scope_:n}=r;return jn(n,t),Mn(void 0,n)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){let o=t[r];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}r>-1&&(t=t.slice(r+1));let n=Ue("Patches").applyPatches_;return de(e)?n(e,t):this.produce(e,o=>n(o,t))}};function vr(e,t){let r=Tt(e)?Ue("MapSet").proxyMap_(e,t):Nt(e)?Ue("MapSet").proxySet_(e,t):Os(e,t);return(t?t.scope_:Wn()).drafts_.push(r),r}function Be(e){return de(e)||Ie(10,e),Yn(e)}function Yn(e){if(!Me(e)||Pt(e))return e;let t=e[fe],r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=Ar(e,t.scope_.immer_.useStrictShallowCopy_)}else r=Ar(e,!0);return Lt(r,(n,o)=>{qn(r,n,Yn(o))}),t&&(t.finalized_=!1),r}var pe=new $s,_r=pe.produce,wd=pe.produceWithPatches.bind(pe),Ed=pe.setAutoFreeze.bind(pe),xd=pe.setUseStrictShallowCopy.bind(pe),vd=pe.applyPatches.bind(pe),Sd=pe.createDraft.bind(pe),Cd=pe.finishDraft.bind(pe);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},O={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},tt={NOT:0};var E=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},ue=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var Rr=e=>{if(!e||e.trim()==="")throw new E("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let r=e.includes("===")?"==":"!=";throw new E(`Invalid comparison operator '${e.includes("===")?"===":"!=="}' - did you mean '${r}'? (got: '${e}')`)}let t=["<",">","<=",">=","==","!="];for(let r of t)if(e.trim().endsWith(r))throw new E(`Incomplete comparison expression - missing right operand (got: '${e}')`)},Gn=e=>{if(e.trim().endsWith(" in"))throw new E(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new E(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,r]=e.split(" in ");if(!r||r.trim()==="")throw new E(`Missing iterable expression after 'in' (got: '$for ${e}')`);let n=t.includes(",")?t.split(",").map(o=>o.trim()):[t.trim()];for(let o of n){if(!o)throw new E(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new E(`Invalid loop syntax (got: '$for ${e}')`)}};var Kn=(e,t,r=!1)=>{if(t===null)return new ue(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new ue(`Cannot iterate over undefined value at '$for ${e}'`);let n=typeof t;return r?new ue(`Cannot iterate over non-array value in loop '${e}' - got ${n} instead`):new ue(`Cannot iterate over non-array value (got: ${n}) at '$for ${e}'`)},Jn=(e,t)=>{let r=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new ue(`Unknown function '${e}' (${r})`)};var ks=(e,t,r={})=>{let n={},o={};r&&typeof r=="object"&&(r.functions!==void 0||r.partials!==void 0?(n=r.functions||{},o=r.partials||{}):typeof r=="object"&&(n=r));let s=L(e,{functions:n,partials:o},t,{});return s===void 0?{}:s},L=(e,t,r,n)=>{let o=t.functions||t;if(e.var&&!e.type)return Y(e.var,r,n);if(e.type===m.LITERAL)return e.value;if(e.type===m.VARIABLE)return Y(e.path,r,n);if(e.type===m.INTERPOLATION)return Ts(e.parts,t,r,n);switch(e.type){case m.FUNCTION:return Qn(e,t,r,n);case m.BINARY:return Zn(e,t,r,n);case m.UNARY:return eo(e,t,r,n);case m.CONDITIONAL:return Ps(e,t,r,n);case m.LOOP:return Us(e,t,r,n);case m.OBJECT:return zs(e,t,r,n);case m.ARRAY:return qs(e,t,r,n);case m.PARTIAL:return Ws(e,t,r,n);case m.PATH_REFERENCE:return Hs(e,t,r,n);default:throw new Error(`Unknown node type: ${e.type}`)}},Xn=new Map,Ds=e=>{let t=[],r="",n=!1;for(let o=0;o<e.length;o++){let i=e[o];if(i==="[")r&&(t.push({type:"property",value:r}),r=""),n=!0;else if(i==="]"){if(n&&r){let s=r.trim();if(/^\d+$/.test(s))t.push({type:"index",value:parseInt(s,10)});else if(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'")){let c=s.slice(1,-1);t.push({type:"property",value:c})}else t.push({type:"property",value:s});r=""}n=!1}else r+=i}return r&&t.push({type:"property",value:r}),t},Y=(e,t,r)=>{if(!e)return;if(e in r)return r[e];let n=Xn.get(e);if(!n){let i=[],s="",c=0;for(let a=0;a<e.length;a++){let l=e[a];l==="["?(c++,s+=l):l==="]"?(c--,s+=l):l==="."&&c===0?s&&(i.push(s),s=""):s+=l}s&&i.push(s),n=[];for(let a of i){let l=Ds(a.trim());n.push(...l)}Xn.set(e,n)}let o=t;for(let i=0;i<n.length;i++){let s=n[i];if(s.type==="property"&&s.value in r){o=r[s.value];continue}if(o==null)return;(s.type==="property"||s.type==="index")&&(o=o[s.value])}return o},Ts=(e,t,r,n)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=L(i,t,r,n);o.push(s!=null?String(s):"")}return o.join("")},Qn=(e,t,r,n)=>{let o=t.functions||t,i=o[e.name];if(!i)throw Jn(e.name,o);let s=e.args.map(c=>L(c,t,r,n));return i(...s)},$e=(e,t,r,n)=>{if(e.var&&!e.type)return Y(e.var,r,n);switch(e.type){case m.VARIABLE:return Y(e.path,r,n);case m.LITERAL:return e.value;case m.BINARY:return Zn(e,t,r,n);case m.UNARY:return eo(e,t,r,n);case m.FUNCTION:return Qn(e,t,r,n);default:return L(e,t,r,n)}},Zn=(e,t,r,n)=>{if(e.op===O.AND||e.op===O.OR){let s=$e(e.left,t,r,n),c=$e(e.right,t,r,n);switch(e.op){case O.AND:return s&&c;case O.OR:return s||c}}let o=L(e.left,t,r,n),i=L(e.right,t,r,n);switch(e.op){case O.EQ:return o==i;case O.NEQ:return o!=i;case O.GT:return o>i;case O.LT:return o<i;case O.GTE:return o>=i;case O.LTE:return o<=i;case O.IN:return Array.isArray(i)?i.includes(o):!1;case O.ADD:if(typeof o!="number"||typeof i!="number")throw new ue(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case O.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new ue(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},eo=(e,t,r,n)=>{let o=e.op===tt.NOT?$e(e.operand,t,r,n):L(e.operand,t,r,n);if(e.op===tt.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},Ns=(e,t,r,n)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===m.VARIABLE)if(Y(o.path,r,n)){let s=e.bodies[0];if(s.type===m.OBJECT&&s.properties.length<=5){let c={};for(let a of s.properties){let l=a.parsedKey?L(a.parsedKey,t,r,n):a.key,u=a.value;if(u.type===m.LITERAL)c[l]=u.value;else if(u.type===m.VARIABLE)c[l]=Y(u.path,r,n);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=Y(d.path,r,n);f.push(p!=null?String(p):"")}else{let p=L(d,t,r,n);f.push(p!=null?String(p):"")}c[l]=f.join("")}else c[l]=L(u,t,r,n)}return c}}else{let s=e.bodies[1];if(s.type===m.OBJECT&&s.properties.length<=5){let c={};for(let a of s.properties){let l=a.parsedKey?L(a.parsedKey,t,r,n):a.key,u=a.value;if(u.type===m.LITERAL)c[l]=u.value;else if(u.type===m.VARIABLE)c[l]=Y(u.path,r,n);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=Y(d.path,r,n);f.push(p!=null?String(p):"")}else{let p=L(d,t,r,n);f.push(p!=null?String(p):"")}c[l]=f.join("")}else c[l]=L(u,t,r,n)}return c}}}return null},Ps=(e,t,r,n)=>{let o=Ns(e,t,r,n);if(o!==null)return o;for(let i=0;i<e.conditions.length;i++){let s=e.conditions[i];if(s===null||$e(s,t,r,n))return L(e.bodies[i],t,r,n)}return to},Vs=(e,t)=>{let r=e.body,n=e.itemVar;if(r.type===m.CONDITIONAL&&r.conditions.length===1&&r.conditions[0].type===m.VARIABLE){let o=r.conditions[0].path,i=r.bodies[0];if(o.startsWith(n+".")){let s=o.substring(n.length+1);if(i.type===m.OBJECT&&i.properties.length<=5){for(let a of i.properties)if(a.parsedKey)return null;let c=[];for(let a=0;a<t.length;a++){let l=t[a];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===n)u[d]=l;else if(h.startsWith(n+".")){let g=h.substring(n.length+1);u[d]=l[g]}else return null}else if(p.type===m.INTERPOLATION){let h=[],g=!0;for(let y of p.parts)if(typeof y=="string")h.push(y);else if(y.type===m.VARIABLE){let b=y.path;if(b===n)h.push(l!=null?String(l):"");else if(b.startsWith(n+".")){let A=b.substring(n.length+1),x=l[A];h.push(x!=null?String(x):"")}else{g=!1;break}}else{g=!1;break}if(!g)return null;u[d]=h.join("")}else return null}c.push(u)}}return c}}}return null},js=(e,t)=>{let r=e.body,n=e.itemVar,o=Vs(e,t);if(o!==null)return o;if(r.type===m.OBJECT&&r.properties.length<=5&&!r.whenCondition){for(let c of r.properties)if(c.parsedKey)return null;let i=[],s=!0;for(let c of r.properties){let a=c.key,l=c.value;if(l.type===m.LITERAL)i.push({key:a,type:"literal",value:l.value});else if(l.type===m.VARIABLE){let u=l.path;if(u===n)i.push({key:a,type:"item"});else if(u.startsWith(n+".")){let f=u.substring(n.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:a,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===n)i.push({key:a,type:"item_string"});else if(f.startsWith(n+".")){let d=f.substring(n.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:a,type:"prop_string",prop:d});else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}if(s){let c=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 a=0;a<t.length;a++){let l=t[a];c[a]={id:l.id,title:l.title!=null?String(l.title):"",completed:l.completed}}else for(let a=0;a<t.length;a++){let l=t[a],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):""}c[a]=u}return c}}return null},Fs=(e,t,r,n,o)=>{let i=[],s=e.body;if(s.type===m.OBJECT&&s.fast!==!1){let c=e.itemVar,a=e.indexVar;for(let l=0;l<o.length;l++){let u=o[l],f={},d={...n,[c]:u,...a&&{[a]:l}};d.__paths__||(d.__paths__=n.__paths__||{});let p=e.iterable.path||"";if(n&&n.__paths__&&p){let h=p.split("."),g=h[0];g in n.__paths__&&(p=n.__paths__[g],h.length>1&&(p+="."+h.slice(1).join(".")))}d.__paths__={...d.__paths__,[c]:`${p}[${l}]`,...a&&{[a]:l}};for(let h of s.properties){let g=h.parsedKey?L(h.parsedKey,t,r,d):h.key,y=h.value;if(y.type===m.LITERAL)f[g]=y.value;else if(y.type===m.VARIABLE){let b=y.path;if(b===c)f[g]=u;else if(b===a)f[g]=l;else if(b.startsWith(c+".")){let A=b.substring(c.length+1);!A.includes(".")&&!A.includes("[")?f[g]=u[A]:f[g]=Y(b,r,{...n,[c]:u,...a&&{[a]:l}})}else f[g]=Y(b,r,{...n,[c]:u,...a&&{[a]:l}})}else if(y.type===m.INTERPOLATION){let b=[];for(let A of y.parts)if(typeof A=="string")b.push(A);else if(A.type===m.VARIABLE){let x=A.path,C;if(x===c)C=u;else if(x===a)C=l;else if(x.startsWith(c+".")){let N=x.substring(c.length+1);!N.includes(".")&&!N.includes("[")?C=u[N]:C=Y(x,r,{...n,[c]:u,...a&&{[a]:l}})}else C=Y(x,r,{...n,[c]:u,...a&&{[a]:l}});b.push(C!=null?String(C):"")}else{let x={...n,[c]:u,...a&&{[a]:l}},C=L(A,t,r,x);b.push(C!=null?String(C):"")}f[g]=b.join("")}else{let b={...n,[c]:u,...a&&{[a]:l}};f[g]=L(y,t,r,b)}}i.push(f)}return i}return null},Ms=(e,t,r)=>{let n=e.body;if(n.type===m.OBJECT&&n.properties.length===1&&n.properties[0].key==="$if item.visible"){let i=n.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 c=s.properties[0],a=s.properties[1];if(c.key==="id"&&c.value.type===m.VARIABLE&&c.value.path==="item.id"&&a.key==="$if item.highlighted"&&a.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},Us=(e,t,r,n)=>{let o=L(e.iterable,t,r,n);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 Kn(f,o,u)}if(!e.indexVar){let l=Ms(e,o,e.itemVar);if(l!==null)return l}if(!e.indexVar){let l=js(e,o);if(l!==null)return l}let i=Fs(e,t,r,n,o);if(i!==null)return i;let s=[],c=e.iterable.path||"";if(n&&n.__paths__&&c){let l=c.split("."),u=l[0];u in n.__paths__&&(c=n.__paths__[u],l.length>1&&(c+="."+l.slice(1).join(".")))}let a=!1;e.body.type===m.ARRAY&&(e.body.items.length<=1?a=!1:a=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?{...n,[e.itemVar]:o[l],[e.indexVar]:l}:{...n,[e.itemVar]:o[l]};u.__paths__||(u.__paths__=n.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${c}[${l}]`},e.indexVar&&(u.__paths__[e.indexVar]=l);let f=L(e.body,t,r,u);if(Array.isArray(f)&&f.length===1&&!a){let d=f[0];s.push(d===void 0?{}:d)}else s.push(f===void 0?{}:f)}return s},Bs=(e,t,r,n)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?L(o.parsedKey,t,r,n):o.key,s=o.value;if(s.type===m.OBJECT&&s.properties.length<=10&&!s.whenCondition){let c={},a={},l=!0;for(let u of s.properties){let f=u.parsedKey?L(u.parsedKey,t,r,n):u.key,d=u.value;if(d.type===m.LITERAL)a[f]=d.value;else if(d.type===m.VARIABLE)a[f]=Y(d.path,r,n);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 g=Y(h.path,r,n);p.push(g!=null?String(g):"")}else{l=!1;break}if(!l)break;a[f]=p.join("")}else if(d.type===m.OBJECT&&d.properties.length<=5){let p={};for(let h of d.properties){let g=h.key,y=h.value;if(y.type===m.LITERAL)p[g]=y.value;else if(y.type===m.VARIABLE)p[g]=Y(y.path,r,n);else if(y.type===m.INTERPOLATION){let b=[];for(let A of y.parts)if(typeof A=="string")b.push(A);else if(A.type===m.VARIABLE){let x=Y(A.path,r,n);b.push(x!=null?String(x):"")}else{l=!1;break}if(!l)break;p[g]=b.join("")}else{l=!1;break}}if(!l)break;a[f]=p}else{l=!1;break}}if(l)return c[i]=a,c}}return null},zs=(e,t,r,n)=>{let o=t.functions||t;if(e.whenCondition&&!$e(e.whenCondition,o,r,n))return;let i=Bs(e,t,r,n);if(i!==null)return i;if(e.fast){let l={};for(let u of e.properties){let f=u.parsedKey?L(u.parsedKey,t,r,n):u.key,d=u.value;if(d.type===m.LITERAL)l[f]=d.value;else if(d.type===m.VARIABLE)l[f]=Y(d.path,r,n);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 g=Y(h.path,r,n);p.push(g!=null?String(g):"")}else{let g=L(h,t,r,n);p.push(g!=null?String(g):"")}l[f]=p.join("")}else l[f]=L(d,t,r,n)}return l}let s={},c=null,a=!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 ")){a=!0;break}for(let l of e.properties)if(l.key.startsWith("$if ")||l.key.match(/^\$if\s+\w+.*:?$/)){let u=L(l.value,t,r,n);if(!a&&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 L(l.value,t,r,n)}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=L(f.value,t,r,n);d!==void 0&&(s[l.key]=d)}else{let d=L(l.value,t,r,n);d!==void 0&&(s[l.key]=d)}}else{let f=l.parsedKey?L(l.parsedKey,t,r,n):l.key,d=L(l.value,t,r,n);d!==void 0&&(s[f]=d)}}return s},to={},qs=(e,t,r,n)=>{let o=[];for(let i of e.items)if(i.type===m.LOOP){let s=L(i,t,r,n);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=L(i,t,r,n);s!==to&&s!==void 0&&o.push(s)}return o},Ws=(e,t,r,n)=>{let{name:o,data:i,whenCondition:s}=e,c=t.partials||{},a=t.functions||t;if(s&&!$e(s,a,r,n))return;if(!c[o])throw new ue(`Partial '${o}' is not defined`);let l=n._partialStack||[];if(l.includes(o))throw new ue(`Circular partial reference detected: ${o}`);let u=c[o],f=r,d={...n,_partialStack:[...l,o]};if(n){f={...r};for(let p of Object.keys(n))p.startsWith("_")||(f[p]=n[p])}if(i){let p=L(i,t,r,n);f={...f,...p}}return L(u,t,f,d)},Hs=(e,t,r,n)=>{let{path:o}=e,i=o.split("."),s=i[0],c=i.slice(1);if(!n||!(s in n))throw new ue(`Path reference '#{${o}}' refers to '${s}' which is not a loop variable in the current scope`);if(n.__paths__||(n.__paths__={}),!(s in n.__paths__))throw new ue(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let a=n.__paths__[s];if(typeof a=="number"){if(c.length>0)throw new ue(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(a)}return c.length>0&&(a+="."+c.join(".")),a};var Or=ks;var Ys=/\$\{([^}]*)\}/g,Gs=/#\{([^}]*)\}/g,no=(e,t={})=>{let r=e.match(/^(\w+)\((.*)\)$/);if(!r)return{isFunction:!1};let[,n,o]=r,i=Ks(o,t);return{isFunction:!0,type:m.FUNCTION,name:n,args:i}},Ks=(e,t={})=>e.trim()?Js(e).map(n=>Xs(n.trim(),t)):[],Js=e=>{let t=[],r="",n=0,o=!1,i="";for(let s=0;s<e.length;s++){let c=e[s],a=s>0?e[s-1]:"";!o&&(c==='"'||c==="'")?(o=!0,i=c,r+=c):o&&c===i&&a!=="\\"?(o=!1,i="",r+=c):!o&&c==="("?(n++,r+=c):!o&&c===")"?(n--,r+=c):!o&&c===","&&n===0?(t.push(r),r=""):r+=c}return r&&t.push(r),t},Xs=(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 r=no(e,t);if(r.isFunction)return{type:r.type,name:r.name,args:r.args};let n=e.trim(),o=[{op:" + ",type:"ADD"},{op:" - ",type:"SUBTRACT"}],i=-1,s=null;for(let{op:c,type:a}of o){let l=0;for(;l<n.length;){let u=ze(n.substring(l),c);if(u===-1)break;let f=l+u;f>i&&(i=f,s={op:c,type:a}),l=f+c.length}}if(i!==-1)try{return Z(n,t)}catch{return{type:m.VARIABLE,path:n}}return{type:m.VARIABLE,path:n}},oo=/^\w+\(.*\)$/,Qs=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,Zs=e=>{if(!(!e||e.trim()===""||oo.test(e))&&Qs.test(e))throw e.includes("?")&&e.includes(":")?new E(`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 E(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new E(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},ro=e=>{let t=e.trim();if(oo.test(t))throw new E(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new E(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new E(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new E(`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 E(`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}},dt=(e,t={})=>{let r=e.trim();Zs(r);let n=no(r,t);if(n.isFunction)return{type:n.type,name:n.name,args:n.args};if(r.includes("[")&&!/[\s+\-*/%|&?:]/.test(r)){let o=0;for(let i of r)i==="["?o++:i==="]"&&o--;if(o!==0)throw new Error("Invalid array index syntax")}return{type:m.VARIABLE,path:r}},Lr=(e,t={})=>{let r=e,n=[];(e.includes("\\${")||e.includes("\\#{"))&&(r=e.replace(/\\\\(\$\{[^}]*\})/g,"\\DOUBLE_ESC_VAR$1"),r=r.replace(/\\\\(#\{[^}]*\})/g,"\\DOUBLE_ESC_PATH$1"),r=r.replace(/\\(\$\{[^}]*\})/g,(l,u)=>{let f=`__ESCAPED_${n.length}__`;return n.push(u),f}),r=r.replace(/\\(#\{[^}]*\})/g,(l,u)=>{let f=`__ESCAPED_${n.length}__`;return n.push(u),f}),r=r.replace(/\\DOUBLE_ESC_VAR/g,"\\"),r=r.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...r.matchAll(Ys)],i=[...r.matchAll(Gs)],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=r;for(let u=0;u<n.length;u++)l=l.replace(`__ESCAPED_${u}__`,n[u]);return{type:m.LITERAL,value:l}}if(s.length===1&&s[0].match[0]===r&&n.length===0){let{match:l,type:u}=s[0];try{return u==="variable"?dt(l[1],t):ro(l[1])}catch(f){if(f.message==="Invalid array index syntax")return{type:m.LITERAL,value:r};throw f}}let c=[],a=0;for(let{match:l,type:u}of s){let[f,d]=l,p=l.index;if(p>a){let h=r.substring(a,p);for(let g=0;g<n.length;g++)h=h.replace(`__ESCAPED_${g}__`,n[g]);h&&c.push(h)}try{let h;u==="variable"?h=dt(d.trim(),t):h=ro(d.trim()),c.push(h)}catch(h){if(h.message==="Invalid array index syntax")c.push(f);else throw h}a=p+f.length}if(a<r.length){let l=r.substring(a);for(let u=0;u<n.length;u++)l=l.replace(`__ESCAPED_${u}__`,n[u]);l&&c.push(l)}return{type:m.INTERPOLATION,parts:c}};var Dr=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),ao=e=>Object.keys(e),ae=e=>e.join("."),ke=(e,t,r)=>{let n=ao(e).filter(o=>!t.has(o));if(n.length>0)throw new E(`Unexpected key '${n[0]}' in condition JSON at '${ae(r)}'`)},De=(e,t)=>typeof e=="string"?Lr(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?ta(e,t):ra(e,t):{type:m.LITERAL,value:e},ea=e=>{let{$each:t,...r}=e;if(typeof t!="string")throw new E("$each value must be a non-empty string");let n=t.trim();if(n==="")throw new E("$each value must be a non-empty string");if(Object.keys(r).length===0)throw new E("Empty $each body not allowed");if(r.$partial!==void 0)throw new E("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${n}`]:r}},ta=(e,t)=>{let r=[],n=!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 a=ea(i),l=Object.keys(a);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let u=so(l[0],a[l[0]],t,!0);r.push(u),n=!0;continue}}catch(a){throw a instanceof E?a:new E(a.message)}let c=Object.keys(i);if(c.length===1&&/^\$for(?::\w+)?\s/.test(c[0])){let a=so(c[0],i[c[0]],t);r.push(a),n=!0;continue}}let s=De(i,t);r.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)&&(n=!0)}return{type:m.ARRAY,items:r,fast:!n}},ra=(e,t)=>{let r=[],n=!1,o=null,i=Object.entries(e),s=0;if(e.$partial!==void 0){if(typeof e.$partial!="string")throw new E("$partial value must be a string");if(e.$partial.trim()==="")throw new E("$partial value cannot be an empty string");let a=["$if","$elif","$else","$for"],l=[];for(let[b]of i)for(let A of a)if(b===A||b.startsWith(A+" ")||b.startsWith(A+"#")){l.push(A);break}if(l.length>0)throw new E(`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,A]of Object.entries(d)){let x=b;(b.startsWith("\\$")||b.startsWith("$$"))&&(x=b.slice(1)),p[x]=A,h=!0}let g=null;if(h&&(g=De(p,t),g.type===m.OBJECT)){let b=!1;for(let A of g.properties)if(A.value.type===m.VARIABLE||A.value.type===m.INTERPOLATION||A.value.type===m.FUNCTION||A.value.type===m.CONDITIONAL||A.value.type===m.OBJECT&&!A.value.fast||A.value.type===m.ARRAY&&!A.value.fast){b=!0;break}b&&(g.fast=!1)}let y={type:m.PARTIAL,name:u,data:g};return f!==void 0&&(y.whenCondition=io(f,t)),y}for(let[a,l]of i)if(a==="$when"){if(o!==null)throw new E("Multiple '$when' directives on the same object are not allowed");if(l==null)throw new E("Missing condition expression after '$when'");o=io(l,t),n=!0}else if(a.startsWith("$when#")||a.startsWith("$when "))throw new E("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<i.length;){let[a,l]=i[s];if(a==="$when"){s++;continue}if(a==="$each")throw new E("$each can only be used inside arrays");if(a.startsWith("$if ")||a.match(/^\$if#\w+\s/)||a.match(/^\$if\s+\w+.*:$/)){let u=na(i,s,t);r.push({key:a,value:u.node}),n=!0,s=u.nextIndex}else if(/^\$for(?::\w+)?\s/.test(a)){let u=a.match(/^\$for(?::(\w+))?\s/)?.[1]||"",f=u?`:${u}`:"";throw new E(`$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(a.startsWith("$elif ")||a.startsWith("$else"))throw new E(`'${a.split(" ")[0]}' without matching '$if'`);if(a==="$if"||a==="$if:")throw new E("Missing condition expression after '$if'");{let u=De(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)&&(n=!0);let f=Lr(a,t),d={key:a,value:u};(f.type!==m.LITERAL||f.value!==a)&&(d.parsedKey=f),r.push(d),s++}}}let c={type:m.OBJECT,properties:r,fast:!n};return o&&(c.whenCondition=o),c},na=(e,t,r={})=>{let n=[],o=[],i=t,[s,c]=e[i],a=null,l;if(s.startsWith("$if#")){let f=s.match(/^\$if#(\w+)\s+(.+)$/);if(f)a=f[1],l=f[2];else throw new E(`Invalid conditional syntax: ${s}`)}else l=s.substring(4),l.endsWith(":")&&(l=l.slice(0,-1).trim());Rr(l);let u=Z(l,r);for(n.push(u),o.push(De(c,r)),i++;i<e.length;){let[f,d]=e[i],p=!1,h;if(a?f.startsWith(`$elif#${a} `)?(h=f.substring(`$elif#${a} `.length),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(f===`$else#${a}`||f===`$else#${a}:`)&&(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)n.push(null);else{Rr(h);let g=Z(h,r);n.push(g)}if(o.push(De(d,r)),i++,h===null)break}else break}return{node:{type:m.CONDITIONAL,conditions:n,bodies:o,id:a},nextIndex:i}},$r={eq:O.EQ,neq:O.NEQ,gt:O.GT,gte:O.GTE,lt:O.LT,lte:O.LTE,in:O.IN,add:O.ADD,sub:O.SUBTRACT},kr={all:O.AND,any:O.OR},oa=new Set(["var","literal","call","not",...Object.keys($r),...Object.keys(kr)]),ia=(e,t,r)=>{if(!Array.isArray(e))throw new E(`Condition JSON operator '${t}' at '${ae(r)}' requires an array`);if(e.length!==2)throw new E(`Condition JSON operator '${t}' at '${ae(r)}' requires exactly 2 operands`);return e},sa=(e,t,r,n,o)=>{if(!Array.isArray(e))throw new E(`Condition JSON operator '${t}' at '${ae(o)}' requires an array`);if(e.length===0)throw new E(`Condition JSON operator '${t}' at '${ae(o)}' requires at least 1 condition`);return e.map((s,c)=>Se(s,n,[...o,c])).reduce((s,c)=>({type:m.BINARY,op:r,left:s,right:c}))},aa=(e,t,r)=>{let n,o;if(typeof e.call=="string")n=e.call,o=e.args??[],ke(e,new Set(["call","args"]),r);else if(Dr(e.call))n=e.call.name,o=e.call.args??[],ke(e,new Set(["call"]),r),ke(e.call,new Set(["name","args"]),[...r,"call"]);else throw new E(`Condition JSON call at '${ae(r)}' requires a function name`);if(typeof n!="string"||n.trim()==="")throw new E(`Condition JSON call at '${ae(r)}' requires a non-empty function name`);if(!/^\w+$/.test(n))throw new E(`Invalid condition JSON function name '${n}' at '${ae(r)}'`);if(!Array.isArray(o))throw new E(`Condition JSON call '${n}' at '${ae(r)}' requires args to be an array`);return{type:m.FUNCTION,name:n,args:o.map((i,s)=>Se(i,t,[...r,"args",s]))}},Se=(e,t={},r=["$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 E(`Condition JSON array at '${ae(r)}' must be wrapped in an operator or { literal: [...] }`);if(!Dr(e))throw new E(`Invalid condition JSON value at '${ae(r)}'`);let n=ao(e);if(n.length===0)throw new E(`Condition JSON object at '${ae(r)}' must contain an operator`);let o=n.filter(s=>oa.has(s));if(o.length===0)throw new E(`Unknown condition JSON operator '${n[0]}' at '${ae(r)}'`);if(o.length>1)throw new E(`Condition JSON at '${ae(r)}' must contain exactly one operator`);let i=o.includes("call")?"call":o[0];if(i==="var"){if(ke(e,new Set(["var"]),r),typeof e.var!="string"||e.var.trim()==="")throw new E(`Condition JSON var at '${ae(r)}' requires a non-empty path`);return{type:m.VARIABLE,path:e.var}}if(i==="literal")return ke(e,new Set(["literal"]),r),{type:m.LITERAL,value:e.literal};if(i==="call")return aa(e,t,r);if(i==="not")return ke(e,new Set(["not"]),r),{type:m.UNARY,op:tt.NOT,operand:Se(e.not,t,[...r,"not"])};if(i in kr)return ke(e,new Set([i]),r),sa(e[i],i,kr[i],t,[...r,i]);if(i in $r){ke(e,new Set([i]),r);let s=ia(e[i],i,[...r,i]);return{type:m.BINARY,op:$r[i],left:Se(s[0],t,[...r,i,0]),right:Se(s[1],t,[...r,i,1])}}throw new E(`Unknown condition JSON operator '${i}' at '${ae(r)}'`)},io=(e,t={})=>{if(e==null)throw new E("Missing condition expression after '$when'");if(typeof e=="string"){if(e.trim()==="")throw new E("Empty condition expression after '$when'");return Z(e,t)}return Dr(e)||Array.isArray(e)?Se(e,t):{type:m.LITERAL,value:e}},Z=(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 Z(l,t)}let r=ze(e,"||");if(r!==-1)return{type:m.BINARY,op:O.OR,left:Z(e.substring(0,r).trim(),t),right:Z(e.substring(r+2).trim(),t)};let n=ze(e,"&&");if(n!==-1)return{type:m.BINARY,op:O.AND,left:Z(e.substring(0,n).trim(),t),right:Z(e.substring(n+2).trim(),t)};let o=[{op:">=",type:O.GTE},{op:"<=",type:O.LTE},{op:"==",type:O.EQ},{op:"!=",type:O.NEQ},{op:">",type:O.GT},{op:"<",type:O.LT},{op:" in ",type:O.IN}];for(let{op:l,type:u}of o){let f=ze(e,l);if(f!==-1)return{type:m.BINARY,op:u,left:Z(e.substring(0,f).trim(),t),right:Z(e.substring(f+l.length).trim(),t)}}let i=-1,s=null,c=[{op:" + ",type:O.ADD},{op:" - ",type:O.SUBTRACT}];for(let{op:l,type:u}of c){let f=0;for(;f<e.length;){let d=ze(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:Z(e.substring(0,i).trim(),t),right:Z(e.substring(i+s.op.length).trim(),t)};let a=[" * "," / "," % "];for(let l of a)if(ze(e,l)!==-1)throw new E(`Arithmetic operations are not allowed in conditionals: "${l}"`);return e.startsWith("!")?{type:m.UNARY,op:tt.NOT,operand:Z(e.substring(1).trim(),t)}:co(e,t)},ze=(e,t)=>{let r=0,n=0;for(;n<=e.length-t.length;){if(e[n]==="(")r++;else if(e[n]===")")r--;else if(r===0&&e.substring(n,n+t.length)===t)return n;n++}return-1},ca=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}},co=(e,t)=>{let r=e.trim();if(r.match(/^(\w+)\((.*)\)$/))return dt(r,t);let o=ca(r);if(o.type===m.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(r))return{type:m.VARIABLE,path:r};try{return dt(r,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},la=(e,t=!1)=>{let r=t?"$each":"$for";try{Gn(e)}catch(n){if(n instanceof E&&t){let o=n.message.replace(/\$for/g,"$each");throw new E(o.replace("Parse Error: ",""))}throw n}},so=(e,t,r,n=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let y=n?"$each":"$for";throw new E(`Invalid loop syntax (got: '${e.replace("$for",y)}')`)}let s=i[1],c=i[2].trim();la(c,n);let a=c.match(/^(.+?)\s+in\s+(.+)$/);if(!a){let y=n?"$each":"$for";throw new E(`Invalid loop syntax - missing 'in' keyword (got: '${y} ${c}')`)}let l=a[1].trim(),u=a[2].trim(),f,d=null;if(l.includes(",")){let y=l.split(",").map(b=>b.trim());if(y.length!==2)throw new E(`Invalid loop variables: ${l}. Expected format: "item" or "item, index"`);f=y[0],d=y[1]}else f=l;let p=["this","undefined","null","true","false"];if(p.includes(f))throw new E(`Reserved variable name: ${f}`);if(d&&p.includes(d))throw new E(`Reserved variable name: ${d}`);let h=co(u,r),g=De(t,r);return{type:m.LOOP,itemVar:f,indexVar:d,iterable:h,body:g,flatten:s!=="nested"}};var ua=(e,t={})=>{let{functions:r={}}=t;return De(e,r)},Vt=ua;var pt={};Es(pt,{now:()=>fa});var fa=()=>Date.now();var da=(e,t,r={})=>{let{functions:n={},partials:o={}}=r,i={...pt,...n},s=Vt(e,{functions:i}),c={};for(let[a,l]of Object.entries(o))c[a]=Vt(l,{functions:i});return Or(s,t,{functions:i,partials:c})},ce=da;var pa=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",ha=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,ma=(e,t)=>{if(pa(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new E("Empty condition expression");return Z(e,t)}return Se(e,t)},ga=(e,t={},r={})=>{let n=ha(r),o={...pt,...n},i=ma(e,o);return!!$e(i,{functions:o,partials:{}},t,{})},Tr=ga;var mt=(e,t={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return Tr(e,t)},mo=(e,t,r={})=>{let n=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=a=>a,transformActionFirstArgument:c=a=>a}=r;for(let[a,l]of Object.entries(t))a!=="createInitialState"&&(a.startsWith("select")?o[a]=(...u)=>l(s(n),...u):i[a]=(...u)=>{let f;return n=_r(n,p=>{let h=l(c(p),...u);f=h!==void 0&&!de(h)?h:void 0}),f});return{...o,...i}},Mt=(e,t)=>r=>{let n=e(),o=Array.isArray(r)?r:[r];return _r(n,i=>{o.forEach(s=>{t.forEach(c=>{c(i,s)})})})};var ya=(e,t)=>{if(e.default!==void 0)return e.default;let r=["number","boolean","string","object"];if(!r.includes(e.type))throw new Error(`Invalid variable type: ${e.type} for variable ${t}. Expected one of: ${r.join(", ")}`);switch(e.type){case"number":return 0;case"boolean":return!1;case"string":return"";case"object":return{}}},ge=(e,t)=>Object.prototype.hasOwnProperty.call(e??{},t),ht=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),go=e=>{let t=de(e)?Be(e):e;return structuredClone(t)},ba=({characterId:e,resourceCharacter:t,variables:r={}}={})=>{if(!ge(t,"nameVariableId"))return;let n=t.nameVariableId,o=r?.[n];if(typeof o!="string")throw new Error(`Character "${e}" nameVariableId "${n}" must resolve to a string variable`);return o},Ut=({characterId:e,character:t,characterName:r,characters:n={},variables:o={}}={})=>{let i=e?n?.[e]:void 0;if(t?.name!==void 0)return t.name;if(r!==void 0)return r;let s=ba({characterId:e,resourceCharacter:i,variables:o});return s!==void 0?s:i?.name||""},Te=e=>ge(e,"computed"),rt=(e={},t={})=>Object.fromEntries(Object.entries(e??{}).filter(([r])=>!Te(t[r]))),Ia=e=>String(e).replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean),Nr=(e,t)=>{let r=e;for(let n of t){if(r==null)return;r=r[n]}return r},Aa=(e,t={})=>{if(typeof e!="string"||e.trim()==="")throw new Error("Computed expression var requires a non-empty string path");let r=Ia(e),[n,o,...i]=r;if(n==="variables"){if(!o)return t.variables;let s=typeof t.resolveVariable=="function"?t.resolveVariable(o):t.variables?.[o];return Nr(s,i)}return n==="runtime"?Nr(t.runtime,r.slice(1)):Nr(t,r)},wa=(e,t,r)=>{if(!Array.isArray(t))throw new Error(`Computed expression operator "${e}" requires an array`);if(r!==void 0&&t.length!==r)throw new Error(`Computed expression operator "${e}" requires ${r} operand(s)`)},lo=(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`)},Ea=(e,t)=>{if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Computed expression operator "${e}" requires finite numeric operands`)},Ae=(e,t,r,n)=>(wa(e,t,n),t.map(o=>Ft(o,r))),me=(e,t,r,n)=>{let o=Ae(e,t,r,n);return o.forEach(i=>Ea(e,i)),o},xa=(e,t,r)=>{switch(e){case"var":return Aa(t,r);case"add":{let[n,o]=me(e,t,r,2);return n+o}case"sub":{let[n,o]=me(e,t,r,2);return n-o}case"mul":{let[n,o]=me(e,t,r,2);return n*o}case"div":{let[n,o]=me(e,t,r,2);return n/o}case"mod":{let[n,o]=me(e,t,r,2);return n%o}case"neg":{let[n]=me(e,t,r,1);return-n}case"round":{let[n]=me(e,t,r,1);return Math.round(n)}case"floor":{let[n]=me(e,t,r,1);return Math.floor(n)}case"ceil":{let[n]=me(e,t,r,1);return Math.ceil(n)}case"min":{let[n,o]=me(e,t,r,2);return Math.min(n,o)}case"max":{let[n,o]=me(e,t,r,2);return Math.max(n,o)}case"clamp":{let[n,o,i]=me(e,t,r,3);return Math.min(i,Math.max(o,n))}case"eq":{let[n,o]=Ae(e,t,r,2);return n==o}case"neq":{let[n,o]=Ae(e,t,r,2);return n!=o}case"gt":{let[n,o]=Ae(e,t,r,2);return n>o}case"gte":{let[n,o]=Ae(e,t,r,2);return n>=o}case"lt":{let[n,o]=Ae(e,t,r,2);return n<o}case"lte":{let[n,o]=Ae(e,t,r,2);return n<=o}case"in":{let[n,o]=Ae(e,t,r,2);return Array.isArray(o)?o.includes(n):!1}case"and":case"all":return lo(e,t),t.every(n=>!!Ft(n,r));case"or":case"any":return lo(e,t),t.some(n=>!!Ft(n,r));case"not":{let[n]=Ae(e,t,r,1);return!n}case"length":{let[n]=Ae(e,t,r,1);return typeof n=="string"||Array.isArray(n)?n.length:ht(n)?Object.keys(n).length:0}case"includes":{let[n,o]=Ae(e,t,r,2);return typeof n=="string"||Array.isArray(n)?n.includes(o):!1}case"literal":return go(t);default:throw new Error(`Unknown computed expression operator: ${e}`)}},Ft=(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 r=Object.entries(e);if(r.length!==1)throw new Error("Computed expression objects must contain exactly one operator");let[[n,o]]=r;return xa(n,o,t)},va=(e,t={})=>mt(e,{variables:t.variables,runtime:t.runtime}),Sa=(e,t)=>{if(!ht(e))throw new Error(`${t} must be an object`);let r=ge(e,"expr"),n=ge(e,"value");if(r===n)throw new Error(`${t} must contain exactly one of expr or value`)},Pr=(e,t,r)=>(Sa(e,t),ge(e,"value")?go(e.value):Ft(e.expr,r)),Ca=(e,t={},r="unknown")=>{if(!ht(e))throw new Error(`Computed variable "${r}" computed must be an object`);let n=ge(e,"expr"),o=ge(e,"value");if(ge(e,"branches")){if(n||o)throw new Error(`Computed variable "${r}" cannot combine branches with expr or value`);if(!Array.isArray(e.branches))throw new Error(`Computed variable "${r}" branches must be an array`);if(e.branches.length===0)throw new Error(`Computed variable "${r}" branches must not be empty`);if(!ht(e.default))throw new Error(`Computed variable "${r}" requires default`);for(let s=0;s<e.branches.length;s+=1){let c=e.branches[s];if(!ht(c))throw new Error(`Computed variable "${r}" branch ${s} must be an object`);if(!ge(c,"when"))throw new Error(`Computed variable "${r}" branch ${s} requires when`);if(va(c.when,t))return Pr(c,`Computed variable "${r}" branch ${s}`,t)}return Pr(e.default,`Computed variable "${r}" default`,t)}if(n===o)throw new Error(`Computed variable "${r}" must contain exactly one of expr, value, or branches`);return Pr(e,`Computed variable "${r}"`,t)},_a=(e,t,r)=>{switch(t){case"number":if(typeof r!="number"||!Number.isFinite(r))throw new Error(`Computed variable "${e}" expected type number, got ${Array.isArray(r)?"array":typeof r}`);return;case"boolean":if(typeof r!="boolean")throw new Error(`Computed variable "${e}" expected type boolean, got ${Array.isArray(r)?"array":typeof r}`);return;case"string":if(typeof r!="string")throw new Error(`Computed variable "${e}" expected type string, got ${Array.isArray(r)?"array":typeof r}`);return;case"object":if(r===null||typeof r!="object")throw new Error(`Computed variable "${e}" expected type object, got ${typeof r}`);return;default:throw new Error(`Invalid variable type: ${t} for computed variable ${e}`)}},gt=({variables:e={},runtime:t={},variableConfigs:r={},eager:n=!0}={})=>{let o=rt(e,r),i=Object.entries(r).filter(([,f])=>Te(f)).map(([f])=>f),s={},c=[],a=f=>{if(ge(s,f))return s[f];let d=r[f];if(!Te(d))return o[f];let p=c.indexOf(f);if(p>=0){let h=[...c.slice(p),f].join(" -> ");throw new Error(`Computed variable cycle detected: ${h}`)}c.push(f);try{let h=Ca(d.computed,u,f);return _a(f,d.type,h),s[f]=h,h}finally{c.pop()}},l=new Proxy({},{get:(f,d)=>{if(typeof d=="string")return a(d)},has:(f,d)=>typeof d=="string"&&(ge(o,d)||i.includes(d)),ownKeys:()=>[...new Set([...Object.keys(o),...i])],getOwnPropertyDescriptor:(f,d)=>{if(!(typeof d!="string"||!ge(o,d)&&!i.includes(d)))return{enumerable:!0,configurable:!0}}}),u={variables:l,runtime:t,resolveVariable:a};return n?(i.forEach(f=>{a(f)}),{...o,...s}):l},Ra=({variables:e={},runtime:t={},variableConfigs:r,projectData:n}={})=>gt({variables:e,runtime:t,variableConfigs:r??n?.resources?.variables??{},eager:!0}),Bt=e=>{let t={},r={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([n,o])=>{if(Te(o))return;let i=ya(o,n);o.scope==="context"?t[n]=i:r[n]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}},zt=(e,t)=>{let r=["context","device","account"];if(!e)throw new Error(`Variable scope is required for variable: ${t}`);if(!r.includes(e))throw new Error(`Invalid variable scope: ${e} for variable ${t}. Expected one of: ${r.join(", ")}`)},qt=(e,t,r)=>{let n={number:["set","increment","decrement","multiply","divide"],boolean:["set","toggle"],string:["set"],object:["set"]},o=n[e];if(!o)throw new Error(`Unknown variable type: ${e} for variable ${r}`);if(!Object.values(n).flat().includes(t))throw new Error(`Unknown operation: ${t}`);if(!o.includes(t))throw new Error(`Operation "${t}" is not valid for variable "${r}" of type "${e}". Valid operations: ${o.join(", ")}`)},Oa=2,uo=12,yo=(e=Oa)=>{if(!Number.isInteger(e)||e<0||e>uo)throw new Error(`Operation "divide" requires roundTo to be an integer between 0 and ${uo}.`);return e},La=(e,t)=>{let r=10**t;return Math.round((e+Number.EPSILON)*r)/r},jt=e=>typeof e=="number"&&Number.isFinite(e),Fr=(e,t,r,n,o={})=>{if(e==="number"){if(t==="set"&&!jt(r))throw new Error(`Operation "set" requires value to be a number for variable "${n}".`);if(t==="multiply"&&!jt(r))throw new Error(`Operation "multiply" requires value to be a number for variable "${n}".`);if(t==="divide"&&!jt(r))throw new Error(`Operation "divide" requires value to be a number for variable "${n}".`);if(t==="divide"){if(r===0)throw new Error(`Operation "divide" requires value to be a non-zero number for variable "${n}".`);yo(o.roundTo)}}},Wt=(e,t,r,n={})=>{let o=(s,c,a)=>{let l=s??c;if(!jt(l))throw new Error(`Operation "${t}" requires ${a} to be a number.`);return l},i=s=>{let c=o(s,void 0,"value");if(c===0)throw new Error(`Operation "${t}" requires value to be a non-zero number.`);return c};switch(t){case"set":return r;case"multiply":return o(e,1,"current value")*o(r,void 0,"value");case"divide":return La(o(e,0,"current value")/i(r),yo(n.roundTo));case"increment":return o(e,0,"current value")+o(r,1,"value");case"decrement":return o(e,0,"current value")-o(r,1,"value");case"toggle":return!e;default:throw new Error(`Unknown operation: ${t}`)}};var bo=(e,t="DD/MM/YYYY - HH:mm")=>{if(!e)return"";let r=new Date(e),n=o=>String(o).padStart(2,"0");return t.replace("DD",n(r.getDate())).replace("MM",n(r.getMonth()+1)).replace("YYYY",r.getFullYear()).replace("YY",String(r.getFullYear()).slice(-2)).replace("HH",n(r.getHours())).replace("mm",n(r.getMinutes())).replace("ss",n(r.getSeconds()))},$a=(e,t)=>{let r=i=>{if(!i)return;let s={};i.ui&&(s.ui=i.ui);let c=i.character?.sprite;return c&&Object.keys(c).length>0&&(s.sprite=c),Object.keys(s).length>0?s:void 0},n=r(e),o=r(t);return JSON.stringify(n)===JSON.stringify(o)?null:n&&!o?{changeType:"delete",data:e}:o&&!n?{changeType:"add",data:t}:o&&n?{changeType:"update",data:t}:null},fo=e=>{if(e?.resourceId===void 0)return;let t={resourceId:e.resourceId};e.transformId!==void 0&&(t.transformId=e.transformId);for(let r of["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"])e[r]!==void 0&&(t[r]=e[r]);for(let r of["animationName","animationSpeed","loop"])e[r]!==void 0&&(t[r]=e[r]);return t},po=e=>{if(e?.colorId!==void 0)return{colorId:e.colorId}},ho=(e,t)=>t&&!e?{changeType:"add",data:t}:e&&!t?{changeType:"delete",data:e}:e&&t&&JSON.stringify(e)!==JSON.stringify(t)?{changeType:"update",data:t}:null,ka=(e,t)=>{let r={},n=ho(fo(e),fo(t)),o=ho(po(e),po(t));return n&&(r.resource=n),o&&(r.color=o),Object.keys(r).length>0?r:null},Mr=(e={},t={})=>{let r={},n=["sfx","voice"],o=c=>{let a=e[c],l=t[c];l&&!a?r[c]={changeType:"add",data:l}:a&&!l?n.includes(c)||(r[c]={changeType:"delete",data:a}):a&&l&&JSON.stringify(a)!==JSON.stringify(l)&&(r[c]={changeType:"update",data:l})},i=ka(e.background,t.background);i&&(r.background=i),o("screen"),o("bgm"),o("voice");let s=$a(e.dialogue,t.dialogue);return s&&(r.dialogue=s),o("choice"),o("form"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),r},Ur=(e={})=>{let t=structuredClone(e);t.background&&(t.background.animations?.playback?.continuity!=="persistent"&&delete t.background.animations,!t.background.resourceId&&!t.background.colorId&&delete t.background);let r=o=>{t[o]&&(delete t[o].animations,Object.keys(t[o]).length===0&&delete t[o])};r("layout"),r("choice"),r("form"),r("screen"),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 n=(o,i)=>{let s=t[o]?.items;Array.isArray(s)&&(t[o].items=s.map(c=>{let a={...c};return delete a.animations,i(a)?a:null}).filter(Boolean),t[o].items.length===0&&delete t[o])};return n("character",o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId),n("visual",o=>o.resourceId||o.transformId),t},Da=(e,t)=>{if(!e||!t)return;let r=e;for(let n of t.split(".")){if(r==null||!(n in Object(r)))return;r=r[n]}return r},Ta=(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 r=e.slice(7),n=Da(t,r);if(n===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return n},Na={conditional:new Set(["branches"]),updateProjectData:new Set(["projectData"]),showConfirmDialog:new Set(["confirmActions","cancelActions"]),form:new Set(["submitActions","cancelActions"]),submitForm:new Set(["actions"]),cancelForm:new Set(["actions"])},Io=(e,t)=>{let r=e[e.length-1];return r?Na[r]?.has(t)===!0:!1},Vr=(e,t,r=[])=>Array.isArray(e)?e.map(n=>Vr(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,Io(r,n)?o:Vr(o,t,[...r,n])])):Ta(e,t),jr=(e,t,r=[])=>Array.isArray(e)?e.map(n=>jr(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,Io(r,n)?o:jr(o,t,[...r,n])])):typeof e=="string"?ce(e,t):e,Br=(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 r=Vr(e,t._event);return jr(r,t)};var q=e=>structuredClone(de(e)?Be(e):e),U=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Ao=e=>e?.animations?.playback?.continuity==="persistent",$=(e,t)=>U(e??{},t)&&e[t]!==void 0,yt=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:q(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},Pa=e=>$(e,"opacity")||$(e,"blur"),vo=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],So=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],zr=["animationName","animationSpeed","loop"],Va=e=>vo.some(t=>$(e,t)),Co=e=>e?.text&&$(e.text,"content")&&$(e.text,"textStyleId"),_o=e=>$(e,"text"),ja=(e,t)=>e.resourceId?!0:Co(e)?!t?.text:!1,Fa=(e,t)=>{let r={...q(e),...t};return t.text&&e.text&&(r.text={...q(e.text),...q(t.text)}),r},Ma=(e,t)=>{if(_o(e)){if(e.resourceId)throw new Error(`Visual item "${e.id}" cannot define both resourceId and text`);if(!Co(e)&&!t?.text)throw new Error(`Visual item "${e.id}" text requires content and textStyleId`)}},wo=e=>So.some(t=>$(e,t)),Eo=e=>zr.some(t=>$(e,t)),Ua=(e,t,{hasAuthoredTransformId:r=!1}={})=>{if(!t)return e;for(let n of So)!r&&!$(e,n)&&$(t,n)&&(e[n]=t[n]),U(e,n)&&e[n]===void 0&&delete e[n];return e},Ro=(e,t,r)=>{let n=e[r];return n?.id===t?.id?n:e.find(o=>o.id===t?.id)},Ba=(e,t)=>{if(!t)return e;for(let r of vo)!$(e,r)&&$(t,r)&&(e[r]=t[r]),U(e,r)&&e[r]===void 0&&delete e[r];return e},za=(e,t)=>(t&&(!$(e,"opacity")&&$(t,"opacity")&&(e.opacity=t.opacity),!$(e,"blur")&&$(t,"blur")&&(e.blur=q(t.blur)),U(e,"opacity")&&e.opacity===void 0&&delete e.opacity,U(e,"blur")&&e.blur===void 0&&delete e.blur),e),Oo=(e,t,r=[],{hasPatchFn:n=()=>!1,mergeItemFn:o}={})=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let i=e.map((s,c)=>{let a=Ro(r,s,c),l=t(s,a),u=Pa(s),f=Va(s),d=n(s),p=U(s,"animations"),h=q(s);return!l&&(u||f||d)&&a&&(h=o?o(a,h):{...q(a),...h},p||delete h.animations),za(Ba(h,a),a)}).filter(s=>t(s)||s.animations);return{hasValidItems:i.length>0,processedItems:i}},qa=e=>{if(e){if(e.character&&U(e.character,"name"))return e.character.name;if(U(e,"characterName"))return e.characterName}},Lo=e=>!!e?.character&&U(e.character,"sprite"),Wa=e=>{let t={},r=!1,n=qa(e);return n!==void 0&&(t.name=n,r=!0),Lo(e)&&(t.sprite=q(e.character.sprite),r=!0),r?t:void 0},xo=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},Ha=({dialogueState:e,content:t,append:r=!1})=>{if(!r||!Array.isArray(t)){e.content=t,delete e.initialRevealedContent;return}let n=Array.isArray(e.content)?e.content:[];n.length>0?e.initialRevealedContent=n.map(o=>q(o)):delete e.initialRevealedContent,e.content=[...n,...t]},Ya=()=>({}),Ga=(e,t)=>{if(!t.screen)return;let r=$(t.screen,"opacity"),n=$(t.screen,"blur"),o=U(t.screen,"animations");if(!r&&!n){o||delete e.screen;return}let i=e.screen,s={};if(r?s.opacity=t.screen.opacity:$(i,"opacity")&&(s.opacity=i.opacity),n?s.blur=q(t.screen.blur):$(i,"blur")&&(s.blur=q(i.blur)),U(s,"opacity")&&s.opacity===void 0&&delete s.opacity,U(s,"blur")&&s.blur===void 0&&delete s.blur,Object.keys(s).length===0){delete e.screen;return}e.screen=s},Ka=(e,t)=>{if(t.background){let r=$(t.background,"resourceId"),n=$(t.background,"colorId"),o=$(t.background,"opacity"),i=$(t.background,"blur"),s=$(t.background,"transformId"),c=wo(t.background),a=Eo(t.background),{animationsOnly:l,state:u}=yt(t.background,p=>$(p,"resourceId")||$(p,"colorId")||$(p,"opacity")||$(p,"blur")||$(p,"transformId")||wo(p)||Eo(p));if(l){e.background=e.background?{...q(e.background),...u}:u;return}if(!r&&!n&&!o&&!i&&!s&&!c&&!a){delete e.background;return}let f=e.background,d=q(t.background);if(!r&&f?.resourceId){d.resourceId=f.resourceId,!U(d,"transformId")&&f.transformId&&(d.transformId=f.transformId);for(let p of zr)!$(d,p)&&$(f,p)&&(d[p]=f[p])}Ua(d,f,{hasAuthoredTransformId:s}),!n&&f?.colorId&&(d.colorId=f.colorId),!o&&$(f,"opacity")&&(d.opacity=f.opacity),!i&&$(f,"blur")&&(d.blur=q(f.blur)),U(d,"resourceId")&&d.resourceId===void 0&&delete d.resourceId,U(d,"colorId")&&d.colorId===void 0&&delete d.colorId,U(d,"animations")&&d.animations===void 0&&delete d.animations,U(d,"transformId")&&d.transformId===void 0&&delete d.transformId,U(d,"opacity")&&d.opacity===void 0&&delete d.opacity,U(d,"blur")&&d.blur===void 0&&delete d.blur;for(let p of zr)U(d,p)&&d[p]===void 0&&delete d[p];if(!d.resourceId&&!d.colorId){delete e.background;return}f?.resourceId===d.resourceId&&f?.transformId===d.transformId&&!U(d,"animations")&&Ao(f)&&(d.animations=q(f.animations)),e.background=d}else e.background?.animations&&!Ao(e.background)&&(e.background.animations={})},Ja=(e,t)=>{if(!t.dialogue){e.dialogue&&(xo(e.dialogue),e.dialogue.mode==="adv"&&(e.dialogue.content=void 0,delete e.dialogue.initialRevealedContent,delete e.dialogue.textSpeed,e.dialogue.persistCharacter!==!0&&(delete e.dialogue.characterId,delete e.dialogue.character)));return}e.dialogue||(e.dialogue={});let r=e.dialogue.mode;if(t.dialogue.ui){let{animationsOnly:l,state:u}=yt(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 n=t.dialogue.append===!0&&r!=="nvl"&&e.dialogue?.mode!=="nvl"&&Array.isArray(t.dialogue.content);t.dialogue.content!==void 0&&Ha({dialogueState:e.dialogue,content:t.dialogue.content,append:n}),U(t.dialogue,"textSpeed")?e.dialogue.textSpeed=t.dialogue.textSpeed:delete e.dialogue.textSpeed;let o=U(t.dialogue,"persistCharacter")?t.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;o?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let i=U(t.dialogue,"characterId"),s=Wa(t.dialogue),c=s!==void 0,a=Lo(t.dialogue);if(i?t.dialogue.characterId?e.dialogue.characterId=t.dialogue.characterId:delete e.dialogue.characterId:!o&&!n&&delete e.dialogue.characterId,c?e.dialogue.character=!i&&o&&e.dialogue.character?{...q(e.dialogue.character),...s}:s:(i||!o&&!n)&&delete e.dialogue.character,a||xo(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.textSpeed!==void 0&&(l.textSpeed=e.dialogue.textSpeed),e.dialogue.character&&(l.character=q(e.dialogue.character)),e.dialogue.lines.push(l)}},Xa=(e,t)=>{if(t.sfx){let r=Array.isArray(t.sfx.items)&&t.sfx.items.length>0,n=Array.isArray(t.sfx.channels)&&t.sfx.channels.length>0;if(!r&&!n){delete e.sfx;return}e.sfx=q(t.sfx)}else e.sfx&&delete e.sfx},Qa=(e,t)=>{if(t.bgm){let r=Array.isArray(t.bgm.sounds);if(!t.bgm.resourceId&&!r||r&&t.bgm.sounds.length===0){e.bgm=void 0;return}e.bgm=q(t.bgm),t.bgm.resourceId&&(e.bgm.loop=t.bgm.loop??!0)}},Za=(e,t)=>{if(t.visual){let r=e.visual?.items||[];t.visual.items?.forEach((i,s)=>{Ma(i,Ro(r,i,s))});let{hasValidItems:n,processedItems:o}=Oo(t.visual.items,ja,r,{hasPatchFn:_o,mergeItemFn:Fa});n?e.visual={items:o}:delete e.visual}else e.visual?.items&&(e.visual.items=e.visual.items.map(r=>r.animations?{...r,animations:{}}:r))},ec=(e,t)=>{if(!t.character){e.character?.items&&(e.character.items=e.character.items.map(o=>o.animations?{...o,animations:{}}:o));return}let{hasValidItems:r,processedItems:n}=Oo(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId,e.character?.items||[]);r?e.character={items:n}:delete e.character},tc=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},rc=(e,t)=>{if(t.layout){let{animationsOnly:r,state:n}=yt(t.layout,o=>!!o.resourceId);if(r){e.layout=n;return}if(!t.layout.resourceId){delete e.layout;return}e.layout=t.layout}else e.layout&&delete e.layout},nc=(e,t)=>{if(t.choice){let{animationsOnly:r,state:n}=yt(t.choice,o=>!!o.resourceId);if(r){e.choice={...e.choice,...n};return}if(!t.choice.resourceId){delete e.choice;return}e.choice=t.choice}else e.choice&&delete e.choice},oc=(e,t)=>{if(t.form){let{animationsOnly:r,state:n}=yt(t.form,o=>!!o.resourceId);if(r){e.form={...e.form,...n};return}if(!t.form.resourceId){delete e.form;return}e.form=q(t.form)}else e.form&&delete e.form},ic=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},sc=(e,t)=>{if(t.voice){let r=Array.isArray(t.voice.sounds);if(!t.voice.resourceId&&!r||r&&t.voice.sounds.length===0){delete e.voice;return}e.voice=q(t.voice)}else e.voice&&delete e.voice},ac=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(r=>{delete e[r]})},qe=e=>Mt(Ya,[ac,Ga,Ka,Xa,Qa,Za,Ja,ec,tc,rc,nc,oc,ic,sc])(e);var nt=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let r=ce(e,t);return r&&typeof r=="object"?e:r};var cc=Object.freeze({dialogueTextSpeed:{source:"global.dialogueTextSpeed"},autoForwardDelay:{source:"global.autoForwardDelay"},autoForwardSpeed:{source:"global.autoForwardSpeed"},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"}}),We=Object.freeze({dialogueTextSpeed:50,autoForwardDelay:1e3,autoForwardSpeed:1,skipUnseenText:!1,skipTransitionsAndAnimations:!1,soundVolume:50,musicVolume:50,muteAll:!1,autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isLineCompleted:!1}),bt=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),$o=Object.freeze({dialogueTextSpeed:"number",autoForwardDelay:"number",autoForwardSpeed:"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"}),qr=Object.freeze(["dialogueTextSpeed","autoForwardDelay","autoForwardSpeed","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),Wr=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),lc=(e,t)=>{if(t.startsWith("global.")){let r=t.slice(7);return e?.global?.[r]}if(t.startsWith("context.runtime.")){let r=t.slice(16),n=Array.isArray(e?.contexts)?e.contexts:[];return n[n.length-1]?.runtime?.[r]}},He=e=>Object.fromEntries(Object.entries(cc).map(([t,r])=>{let n=lc(e,r.source),o=n!==void 0?n:We[t]??bt[t];return[t,o]})),Ne=(e,t)=>He(e)[t],ko=(e={})=>Object.fromEntries(qr.map(t=>[t,e[t]??We[t]]));var ot=Object.freeze({VISUAL_BEHIND_BACKGROUND:10,BACKGROUND:20,VISUAL_BEHIND_CHARACTER:30,CHARACTER:40,VISUAL_BEHIND_DIALOGUE:50,DIALOGUE:60,VISUAL_BEHIND_CHOICE:70,CHOICE:80,VISUAL_FOREGROUND:90}),_e=Object.freeze({BEHIND_BACKGROUND:ot.VISUAL_BEHIND_BACKGROUND,BEHIND_CHARACTER:ot.VISUAL_BEHIND_CHARACTER,BEHIND_DIALOGUE:ot.VISUAL_BEHIND_DIALOGUE,BEHIND_CHOICE:ot.VISUAL_BEHIND_CHOICE,FOREGROUND:ot.VISUAL_FOREGROUND}),Hr=_e.BEHIND_DIALOGUE,Yr=Object.freeze(Object.values(_e).sort((e,t)=>e-t));var Re={objectValues:e=>Object.entries(e).map(([t,r])=>({id:t,...r})),formatDate:bo},uc=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,fc=(e,t)=>{let r=String(t||"").trim();if(!r)return;let n=r.match(/[A-Za-z_][A-Za-z0-9_]*|\[\d+\]/g)||[],o=e;for(let i of n){if(i.startsWith("[")){let s=Number(i.slice(1,-1));o=Array.isArray(o)?o[s]:void 0;continue}o=o?.[i]}return o},Kt=(e,t,r)=>{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),c=uc.exec(s);if(c){let[,a,l,u]=c,f=fc(t,u);if(!Array.isArray(f))continue;let d=Array.isArray(i[s])?i[s]:[];f.forEach((p,h)=>{let g={...t,[a]:p};l&&(g[l]=h),d.forEach(y=>{let b=Kt(y,g,r),A=ce(b,g,r);Array.isArray(A)?o.push(...A):o.push(A)})});continue}}o.push(Kt(i,t,r))}return o}if(!e||typeof e!="object")return e;let n={};return Object.entries(e).forEach(([o,i])=>{n[o]=Kt(i,t,r)}),n},ln=({animationType:e,animationId:t,animationPath:r})=>{if(e!==void 0&&!(e==="update"||e==="transition"))throw new Error(`[${r}] Animation "${t}" has unsupported type "${e}". Use "update" or "transition".`)},dc=({id:e,targetId:t,animation:r,playback:n,animationPath:o="animation"})=>{let i=structuredClone(r);if(ln({animationType:i.type,animationId:e,animationPath:o}),delete i.name,delete i.playback,i.id=e,i.targetId=t,n!==void 0){let s=gc(n,`${o}.playback`);s!==void 0&&(i.playback=s)}return i},pc=(e,{animationId:t="animation",animationPath:r="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return ln({animationType:e.type,animationId:t,animationPath:r}),e.type},hc=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},mc=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},gc=(e,t="animation.playback")=>{if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`[${t}] playback must be an object.`);if(e.continuity!==void 0&&e.continuity!=="render"&&e.continuity!=="persistent")throw new Error(`[${t}] playback.continuity must be "render" or "persistent".`);if(e.speed!==void 0&&(typeof e.speed!="number"||!Number.isFinite(e.speed)||e.speed<=0))throw new Error(`[${t}] playback.speed must be a finite number greater than 0.`);let r={};return e.continuity!==void 0&&(r.continuity=e.continuity),e.speed!==void 0&&e.speed!==1&&(r.speed=e.speed),Object.keys(r).length>0?r:void 0},yc=e=>{let t=e?.playback?.speed;return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1},Ye=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Ho=e=>e?.playback?.continuity==="persistent",Zr=e=>Array.isArray(e)?e.map(Zr):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((t,r)=>(t[r]=Zr(e[r]),t),{}),Xt=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let t=structuredClone(e);return t.playback&&(delete t.playback.continuity,t.playback.speed===1&&delete t.playback.speed,Object.keys(t.playback).length===0&&delete t.playback),JSON.stringify(Zr(t))},Yo=(e=[])=>e.filter(t=>Ho(t)).map(t=>structuredClone(t)),Go=e=>Array.isArray(e?.keyframes)?e.keyframes.reduce((t,r)=>{let n=typeof r?.duration=="number"&&Number.isFinite(r.duration)?r.duration:0;return t+n},0):0,Gr=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((t,r)=>Math.max(t,Go(r)),0),Ko=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max(Gr(e.tween),Gr(e.prev?.tween),Gr(e.next?.tween),Go(e.mask?.progress))/yc(e),Do=({animationInstances:e,activePersistentAnimations:t})=>{if(!Array.isArray(e)||e.length===0||!Array.isArray(t)||t.length===0)return!1;let r=new Set(t.map(Xt).filter(Boolean));return e.some(n=>{if(!Ho(n))return!1;let o=Xt(n);return o?r.has(o):!1})},we=({animationInstances:e,isLineCompleted:t,skipTransitionsAndAnimations:r,activePersistentAnimations:n,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||r?!1:i&&!t||Do({animationInstances:e,activePersistentAnimations:n})?!0:i?!1:Do({animationInstances:e,activePersistentAnimations:o}),bc=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),Ic=(e,t)=>{if(bc(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},Ac=({resources:e,animationId:t,playback:r,instanceId:n,targetId:o,animationPath:i="animation"})=>{if(!t||!o)return!1;let s=e?.animations?.[t];return s?dc({id:n,targetId:o,animation:s,playback:r,animationPath:i}):null},wc=(e,{defaultTargetId:t,defaultId:r,animationPath:n="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return ln({animationType:o.type,animationId:o.id??r,animationPath:n}),o.id??=r,o.targetId??=t,o},un=({animations:e,transitions:t,defaultTargetId:r,idPrefix:n,animationPathPrefix:o=n})=>{t.forEach((i,s)=>{e.push(wc(i,{defaultTargetId:r,defaultId:`${n}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},en=(e,t)=>{if(e===void 0)return[];if(!Array.isArray(e)||e.some(r=>r===null||typeof r!="object"||Array.isArray(r)))throw new Error(`${t} must be an array of objects`);return e},Ec=({content:e,path:t,variables:r})=>en(e,t).reduce((n,o)=>{let i=nt(o.text,{variables:r});return n+`${i??""}`.length},0),To=(e=[])=>{let t=new Map;for(let r of e)r?.id&&t.set(r.id,(t.get(r.id)??0)+1);return new Set(Array.from(t.entries()).filter(([,r])=>r>1).map(([r])=>r))},Ht=(e,t=0,r=new Set)=>{if(!r.has(e?.id))return`character-container-${e.id}`;let n=e?.sprites?.map(({resourceId:o})=>o)||[];return n.length===0?`character-container-${e.id}`:`character-container-${e.id}-${t}-${n.join("-")}`},Yt=(e,t)=>{if(!t.transformId)throw new Error(`Visual item "${t.id}" requires transformId`);let r=e.transforms?.[t.transformId];if(!r)throw new Error(`Transform "${t.transformId}" not found for visual item "${t.id}"`);return r},xc=(e,t={})=>{if(!t?.transformId)return;let r=e.transforms?.[t.transformId];if(!r)throw new Error(`Transform "${t.transformId}" not found for background`);return r},vc=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],Sc=(e={})=>vc.some(t=>Ye(e,t)),Jo=(e={},t)=>{if(t){if(e.images?.[t])return"sprite";if(e.videos?.[t])return"video";if(e.spritesheets?.[t])return"spritesheet-animation";if(e.layouts?.[t])return"container"}},Jt=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},Cc=(e={})=>e.textStyles||{},_c=(e={})=>e.images||{},Rc=.5,Oc=(e={},t,r)=>{if(t){if(!e.animations?.[t])throw new Error(`Animation '${t}' not found in spritesheet resource '${r}'`);return t}return Object.keys(e.animations??{})[0]},Xo=({id:e,resourceId:t,spritesheet:r,animationName:n,animationSpeed:o,loop:i,transform:s={}}={})=>{let c=Oc(r,n,t),a=c?r.animations?.[c]:void 0;if(!a){console.warn(`Spritesheet animation not found: ${t}`);return}return{id:e,type:"spritesheet-animation",...s,width:r.width,height:r.height,src:r.fileId,atlas:r.jsonData,playback:{frames:a.frames,animationSpeed:o??a.animationSpeed??Rc,loop:i??a.loop??!0}}},Qo=({id:e,item:t,resources:r={}}={})=>{let n=r.images?.[t.resourceId];if(n)return{type:"sprite",id:e,src:n.fileId,width:n.width,height:n.height,x:0,y:0};let o=r.spritesheets?.[t.resourceId];if(o)return Xo({id:e,resourceId:t.resourceId,spritesheet:o,animationName:t.animationName,animationSpeed:t.animationSpeed,loop:t.loop,transform:{x:0,y:0}});console.warn(`Character sprite resource not found: ${t.resourceId}`)},Lc=(e={})=>e.colors||{},$c=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,wt=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,st=(e,t,r)=>{if(typeof e!="string"||e.length===0)throw new Error(`${r} at "${t}" must resolve to a non-empty string`)},No=(e,t,r)=>{if(e===void 0)return 1;if(typeof e!="number"||!Number.isFinite(e))throw new Error(`${t} for text style "${r}" must be a number between 0 and 1`);if(e<0||e>1)throw new Error(`${t} for text style "${r}" must be a number between 0 and 1`);return e},fn=(e,t)=>{if(typeof e!="string"||!$c.test(e))throw new Error(`${t} must resolve to a hex color`);return e.length===4?`#${e.slice(1).split("").map(r=>r.repeat(2)).join("")}`:e},Po=(e,t,r)=>{let n=fn(e,r);if(t===1)return n;let o=Number.parseInt(n.slice(1,3),16),i=Number.parseInt(n.slice(3,5),16),s=Number.parseInt(n.slice(5,7),16);return`rgba(${o}, ${i}, ${s}, ${t})`},kc=(e={},t)=>{let r=Cc(e)?.[t];if(!r)throw new Error(`Text style "${t}" not found`);let n=e.fonts?.[r.fontId];if(!n)throw new Error(`Font "${r.fontId}" not found for text style "${t}"`);let o=e.colors?.[r.colorId];if(!o)throw new Error(`Color "${r.colorId}" not found for text style "${t}"`);let i=No(r.colorAlpha,"colorAlpha",t),s={fontFamily:n.fileId,fontSize:r.fontSize??16,fontWeight:r.fontWeight??"400",fontStyle:r.fontStyle??"normal",lineHeight:r.lineHeight??1.2,fill:Po(o.hex,i,`Color "${r.colorId}" for text style "${t}"`)};if(r.align!==void 0&&(s.align=r.align),r.wordWrap!==void 0&&(s.wordWrap=r.wordWrap),r.breakWords!==void 0&&(s.breakWords=r.breakWords),r.wordWrapWidth!==void 0&&(s.wordWrapWidth=r.wordWrapWidth),r.strokeColorId){let c=e.colors?.[r.strokeColorId];if(!c)throw new Error(`Stroke color "${r.strokeColorId}" not found for text style "${t}"`);let a=No(r.strokeAlpha,"strokeAlpha",t);s.strokeColor=Po(c.hex,a,`Stroke color "${r.strokeColorId}" for text style "${t}"`)}else if(r.strokeAlpha!==void 0)throw new Error(`strokeAlpha for text style "${t}" requires strokeColorId`);return r.strokeWidth!==void 0&&(s.strokeWidth=r.strokeWidth),s},tn=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>tn(o,t,`${r}[${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 "${r}". Use textStyleId instead`);let n={};for(let[o,i]of Object.entries(e))o!=="textStyleId"&&(n[o]=tn(i,t,wt(r,o)));return e.textStyleId!==void 0&&(st(e.textStyleId,r,"textStyleId"),n.textStyle=kc(t,e.textStyleId)),n},dn=(e={},t)=>{let r=Lc(e)?.[t];if(!r)throw new Error(`Color "${t}" not found`);return fn(r.hex,`Color "${t}"`)},Zo=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",Kr=(e,t,r)=>{let n=e?.[t];if(!(!n||typeof n!="object"||Array.isArray(n))&&Object.prototype.hasOwnProperty.call(n,"fill"))throw new Error(`Inline ${t}.fill is not allowed in rect layout elements at "${r}". Use ${Zo(`${t}.fill`)} instead`)},Dc=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>Et(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;let n={};for(let[o,i]of Object.entries(e))o!=="colorId"&&(n[o]=Et(i,t,wt(r,o)));return e.colorId!==void 0&&(st(e.colorId,r,"colorId"),n.fill=dn(t,e.colorId)),n},Et=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>Et(o,t,`${r}[${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 "${r}". Use ${Zo("fill")} instead`);Kr(e,"hover",r),Kr(e,"click",r),Kr(e,"rightClick",r)}let n={};for(let[o,i]of Object.entries(e))if(!(e.type==="rect"&&o==="colorId")){if(e.type==="rect"&&(o==="hover"||o==="click"||o==="rightClick")){n[o]=Dc(i,t,wt(r,o));continue}n[o]=Et(i,t,wt(r,o))}return e.type==="rect"&&e.colorId!==void 0&&(st(e.colorId,r,"colorId"),n.fill=dn(t,e.colorId)),n},Jr=(e={},t)=>{let r=_c(e)?.[t];return r||null},ei=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",Vo=(e,t,r,n)=>{let o=e?.[t];if(!(!o||typeof o!="object"||Array.isArray(o))&&Object.prototype.hasOwnProperty.call(o,n))throw new Error(`Inline ${t}.${n} is not allowed in sprite layout elements at "${r}". Use ${ei(`${t}.${n}`)} instead`)},jo=(e,t,r)=>{let n=e[t];e[t]={...n&&typeof n=="object"&&!Array.isArray(n)?n:{},src:r}},rn=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>rn(o,t,`${r}[${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 "${r}". Use ${ei(o)} instead`);Vo(e,"hover",r,"src"),Vo(e,"click",r,"src")}let n={};for(let[o,i]of Object.entries(e))e.type==="sprite"&&(o==="imageId"||o==="hoverImageId"||o==="clickImageId")||(n[o]=rn(i,t,wt(r,o)));if(e.type==="sprite"&&e.imageId!==void 0){st(e.imageId,r,"imageId");let o=Jr(t,e.imageId),i=o?.fileId??e.imageId;n.src=i,n.width===void 0&&o?.width!==void 0&&(n.width=o.width),n.height===void 0&&o?.height!==void 0&&(n.height=o.height)}return e.type==="sprite"&&e.hoverImageId!==void 0&&(st(e.hoverImageId,r,"hoverImageId"),jo(n,"hover",Jr(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(st(e.clickImageId,r,"clickImageId"),jo(n,"click",Jr(t,e.clickImageId)?.fileId??e.clickImageId)),n},pn=(e,t={},r="root")=>rn(Et(tn(e,t,r),t,r),t,r),Oe=pn,Ke=(e=[])=>e.find(t=>t.id==="story"),Tc="#000000",nn="bg-cg-background-color",Nc=({resources:e={},background:t={},screen:r})=>t?.colorId===void 0?fn(r?.backgroundColor??Tc,"screen.backgroundColor"):dn(e,t.colorId),ti=(e={})=>{if(Ye(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},Pc=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},Fo=(e={},{includeDefaultAlpha:t=!1}={})=>{let r=ti(e),n=Pc(e),o={};return(t||r!==void 0)&&(o.alpha=r??1),n&&(o.blur=n),o},Vc=(e={})=>{if(Ye(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},jc=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},ri=(e={})=>{let t=Vc(e),r=jc(e),n={};return t!==void 0&&(n.alpha=t),r&&(n.blur=r),n},It=(e={})=>ri(e),Pe=(e={},t={})=>{let r={x:t.x??e.x,y:t.y??e.y,anchorX:t.anchorX??e.anchorX,anchorY:t.anchorY??e.anchorY,rotation:t.rotation??e.rotation,scaleX:t.scaleX??e.scaleX,scaleY:t.scaleY??e.scaleY},n=t.originX??e.originX,o=t.originY??e.originY;return n!==void 0&&(r.originX=n),o!==void 0&&(r.originY=o),r},Fc=["id","type","resourceId","transformId","x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY","layer","opacity","blur","animations"],hn=(e={})=>e.text&&Ye(e.text,"content")&&Ye(e.text,"textStyleId"),Mo=(e={})=>{if(e.resourceId)return e.resourceId;if(hn(e))return"text"},Mc=e=>{if(e.text){if(e.resourceId)throw new Error(`Visual item "${e.id}" cannot define both resourceId and text`);if(!hn(e))throw new Error(`Visual item "${e.id}" text requires content and textStyleId`);for(let t of Fc)if(Ye(e.text,t))throw new Error(`Visual item "${e.id}" text.${t} is reserved for the visual item`)}},Uc=({resources:e,background:t,screen:r={width:1920,height:1080},includeOpacity:n=!1})=>{let o={id:nn,type:"rect",x:0,y:0,width:r?.width??1920,height:r?.height??1080,fill:Nc({resources:e,background:t,screen:r})};if(n){let i=ti(t);i!==void 0&&(o.alpha=i)}return o},Bc=(e={},t)=>t?!!(e.images?.[t]||e.videos?.[t]||e.spritesheets?.[t]||e.layouts?.[t]):!1,Uo=({resources:e={},resourceId:t,colorId:r})=>{let n=Jo(e,t);return t&&(n||r===void 0)?{resourceId:t,targetId:Jt({resourceId:t,kind:n})}:r!==void 0?{resourceId:nn,targetId:nn}:{resourceId:void 0,targetId:void 0}},ni=100,Ge=ni,zc="channel:bgm",qc="channel:voice",Wc="default",Hc=e=>String(e).replaceAll("%","%25").replaceAll(":","%3A"),At=(...e)=>e.map(Hc).join(":"),Qt=(e,t,r)=>{let n=new Set;e.forEach(({id:o})=>{if(n.has(o)){let i=r?` in ${r}`:"";throw new Error(`Duplicate ${t} id "${o}"${i}.`)}n.add(o)})},Yc=(e,t)=>e*t/ni,oi=(e={},t)=>e?.[t]??We[t],mn=(e={},t,r=Ge)=>Yc(r,oi(e,t)),gn=({id:e,volume:t,muted:r,pan:n,children:o,runtime:i})=>({id:e,type:"audio-channel",volume:t,muted:!!i?.muteAll||(r??!1),pan:n??0,children:o}),Gt=(e,t,r,n)=>e[r]!==void 0?e[r]:t[r]!==void 0?t[r]:n,Gc=["muted","pan","playbackRate","startAt","endAt"],yn=({id:e,sound:t,resource:r,defaultLoop:n=!1})=>{let o={id:e,type:"sound",src:r.fileId,loop:Gt(t,r,"loop",n),volume:Gt(t,r,"volume",Ge),startDelayMs:Gt(t,r,"startDelayMs",0)};Gc.forEach(s=>{let c=Gt(t,r,s,void 0);c!==void 0&&(o[s]=c)});let i=o.startAt??0;if(o.endAt!==void 0&&o.endAt!==null&&o.endAt<i)throw new Error(`Sound "${e}" endAt (${o.endAt}) must be greater than or equal to startAt (${i}).`);return o},Ee=({variables:e,runtime:t,saveSlots:r=[],dialogueState:n,includeInactiveAdvDialogue:o=!1,isLineCompleted:i,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:u,confirmDialog:f,form:d,historyDialogue:p=[],characters:h={},dialogueUIHidden:g,skipOnlyViewedLines:y,skipTransitionsAndAnimations:b}={})=>{let A={dialogueTextSpeed:t?.dialogueTextSpeed??50,autoForwardDelay:t?.autoForwardDelay??1e3,autoForwardSpeed:t?.autoForwardSpeed??1,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??c??!1,dialogueUIHidden:t?.dialogueUIHidden??g??!1,isLineCompleted:t?.isLineCompleted??i??!1},x=Zc({dialogueState:n,includeInactiveAdvDialogue:o,characters:h,variables:e,runtime:A}),C={variables:e,runtime:A,saveSlots:r,isChoiceVisible:a,isFormVisible:l,canRollback:u,confirmDialog:f,form:d,historyDialogue:p,characters:h};return x&&(C.dialogue=x,C.dialogueLines=x.lines),C},Bo=100,Zt=(e,t)=>{if(Array.isArray(e))return e.map(n=>Zt(n,t));if(!e||typeof e!="object")return e;let r={...e};return Object.keys(r).forEach(n=>{r[n]=Zt(r[n],t)}),r.type==="text-revealing"?t(r):r},Kc=e=>Zt(e,t=>({...t,revealEffect:"none"})),Jc=e=>Zt(e,t=>{let r=Number(t.speed??t.displaySpeed),n=Number.isFinite(r)?Math.max(r,Bo):Bo;return{...t,speed:n,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:n}:{}}}),Ve=(e,{isLineCompleted:t=!1,skipMode:r=!1,skipTransitionsAndAnimations:n=!1}={})=>t||n?Kc(e):r?Jc(e):e,ii=({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:{}}}}),on=e=>{if(Array.isArray(e))return e.map(on);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=on(s);let r=t.click?.payload;if(!r||typeof r!="object"||Array.isArray(r))return t;let n=r.actions,o=n&&typeof n=="object"&&!Array.isArray(n)&&Object.prototype.hasOwnProperty.call(n,"nextLine")?{...n.nextLine,bypassChoice:!0}:void 0;return{...t,click:{...t.click,payload:{...r,bypassChoice:!0,...o?{actions:{...n,nextLine:o}}:{}}}}},Xc=new Set(["click","change","submit","focusEvent","blurEvent","selectionChange","compositionStart","compositionUpdate","compositionEnd"]),zo="submit",Xr=(e,t,r={})=>{let n=e?.payload&&typeof e.payload=="object"&&!Array.isArray(e.payload)?e.payload:{},o=n.actions&&typeof n.actions=="object"?n.actions:{},i=r.replaceActions===!0?t:{...o,...t};return{...e||{},payload:{...n,actions:i}}},sn=(e,t,r={})=>{if(Array.isArray(e))return e.map(l=>sn(l,t,r));if(!e||typeof e!="object")return e;let n=typeof e.type=="string",o=n&&e.formRole===zo,i=n&&r.submitRoleAncestor,s=o||i?{submitRoleAncestor:!0}:{},c={};for(let[l,u]of Object.entries(e))c[l]=sn(u,t,l==="children"?s:{});let a=c;if(a.type==="input"&&typeof a.field=="string"){let l=t?.fields?.[a.field];if(l){let u={updateFormField:{formKey:t.key,field:l.id,value:"_event.value"}};a={...a,value:l.value,placeholder:a.placeholder===void 0?l.placeholder:a.placeholder,multiline:a.multiline===void 0?l.multiline:a.multiline,...a.maxLength===void 0&&l.maxLength!==void 0?{maxLength:l.maxLength}:{},change:Xr(a.change,u),submit:Xr(a.submit,t.submitActions)}}}return a.formRole===zo||i?{...a,click:Xr(a.click,t.submitActions,{replaceActions:!0})}:a},an=(e,t)=>{if(Array.isArray(e))return e.map(n=>an(n,t));if(!e||typeof e!="object")return e;let r={};for(let[n,o]of Object.entries(e))r[n]=an(o,t);for(let n of Xc){let o=r[n]?.payload;!o||typeof o!="object"||Array.isArray(o)||(r[n]={...r[n],payload:{...o,_interactionSource:"form"}})}return r},cn=({characterId:e,character:t,characterName:r,characters:n={},variables:o={}}={})=>{let i=e?n?.[e]:void 0,s=Ut({characterId:e,character:t,characterName:r,characters:n,variables:o});return{...i||{},...t||{},name:s}},si=(e=[],t={},r={})=>e.map(n=>{let o=cn({characterId:n.characterId,character:n.character,characterName:n.characterName,characters:t,variables:r}),i=typeof n.text=="string"?n.text:Array.isArray(n.content)?n.content.map(s=>s?.text??"").join(""):"";return{...n,text:i,character:o,characterName:o.name}}),Qc=e=>!(!e||e.mode==="adv"&&e.content===void 0),Zc=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:r={},variables:n,runtime:o}={})=>{if(!t&&!Qc(e))return;let i=e.content===void 0?[{text:""}]:en(e.content,"dialogue.content"),s=e.content===void 0?0:Ec({content:e.initialRevealedContent,path:"dialogue.initialRevealedContent",variables:n}),c=o?.dialogueTextSpeed??We.dialogueTextSpeed,a=e.textSpeed??c,l=(e.lines||[]).map((f,d)=>{let p=en(f.content,`dialogue.lines[${d}].content`),h=cn({characterId:f.characterId,character:f.character,characterName:f.characterName,characters:r,variables:n});return{...f,textSpeed:f.textSpeed??c,content:p.map(g=>({...g,text:nt(g.text,{variables:n})})),character:h,characterName:h.name}}),u=cn({characterId:e.characterId,character:e.character,characters:r,variables:n});return{characterId:e.characterId,persistCharacter:e.persistCharacter,character:u,textSpeed:a,content:i.map(f=>({...f,text:nt(f.text,{variables:n})})),initialRevealedCharacters:s,lines:l}},ai=({container:e,resources:t,templateData:r,isLineCompleted:n=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=ce(e,r,{functions:Re});return Oe(Ve(s,{isLineCompleted:n,skipMode:o,skipTransitionsAndAnimations:i}),t)},Qr=(e,t={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(t),qo=({renderStateKeyboard:e,keyboard:t,phase:r})=>{!t||typeof t!="object"||Array.isArray(t)||Object.entries(t).forEach(([n,o])=>{let i=e[n]??{},s=r==="keydown"?o?.keydown:o?.keyup;if(r==="keydown"&&s&&typeof s=="object"){e[n]={...i,keydown:{payload:Qr(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[n].keyup={payload:Qr(o.keyup)});return}e[n]={...i,[r]:{payload:Qr(o)}}})},el=(e={},t={})=>{let r={};return qo({renderStateKeyboard:r,keyboard:e,phase:"keydown"}),qo({renderStateKeyboard:r,keyboard:t,phase:"keyup"}),Object.keys(r).length>0?r:void 0},Le=({animationsDef:e,resources:t,previousResourceId:r,currentResourceId:n,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:c})=>{if(!e)return[];let a=[],l=({instanceId:b,targetId:A})=>{let x=Ac({resources:t,animationId:p,playback:h,instanceId:b,targetId:A,animationPath:s});x&&a.push(x)},u=r!=null&&r!==!1,f=n!=null&&n!==!1,d=o&&i&&o===i;Ic(e,s);let p=hc(e),h=mc(e),g=t?.animations?.[p],y=pc(g,{animationId:p,animationPath:s});if(y==="update")return f&&i?l({instanceId:`${c}-animation-update`,targetId:i}):u&&o&&l({instanceId:`${c}-animation-update`,targetId:o}),a;if(y==="transition"){let b=`${c}-animation-transition`,A=h?.continuity==="persistent"?b:`${c}-animation-in`;if(u&&f&&d)return l({instanceId:b,targetId:i}),a;u&&l({instanceId:`${c}-animation-out`,targetId:o}),f&&l({instanceId:A,targetId:i})}return a},tl=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),rl=(e,{presentationState:t,previousPresentationState:r,currentLineActions:n,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:c,variables:a,runtime:l,activePersistentAnimations:u,restoredPersistentAnimations:f,autoMode:d,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:b,saveSlots:A=[]})=>{let{elements:x,animations:C}=e;if(t.background){let N=n===void 0?!0:Ye(n?.background??{},"animations"),k=x.find(oe=>oe.id==="story");if(!k)return e;let w=xc(o,t.background),j=w||Sc(t.background),M=r?.background?.resourceId,ee=r?.background?.colorId,P=t.background.resourceId??(t.background.animations?M:void 0),W=t.background.colorId??(t.background.animations?ee:void 0),H=Bc(o,P),te={...t.background,colorId:W};if((W!==void 0||H)&&k.children.push(Uc({resources:o,background:te,screen:i,includeOpacity:!H})),P){let{images:oe={},videos:re={},spritesheets:J={}}=o,ie=Jo(o,P),se;if(ie==="sprite"?se=oe[P]:ie==="video"?se=re[P]:ie==="spritesheet-animation"&&(se=J[P]),se){let v=ie==="video",_=ie==="spritesheet-animation",V={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...w},X={...Fo(t.background,{includeDefaultAlpha:!0}),...Pe(V,t.background)},z;_?z=Xo({id:Jt({resourceId:P,kind:ie}),resourceId:P,spritesheet:se,animationName:t.background.animationName,animationSpeed:t.background.animationSpeed,loop:t.background.loop,transform:X}):z={id:Jt({resourceId:P,kind:ie}),type:v?"video":"sprite",src:se.fileId,width:se.width,height:se.height,...X},v&&(z.loop=t.background.loop??!1,z.volume=se.volume??50),z&&k.children.push(z)}}if(P){let{layouts:oe={}}=o,re=oe[P];if(re){let J={id:Jt({resourceId:P,kind:"container"}),type:"container",children:re.elements,...Fo(t.background)};j&&Object.assign(J,Pe({x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...w},t.background));let ie=ce(J,Ee({variables:a,runtime:l,saveSlots:A,dialogueState:t.dialogue,isLineCompleted:s,autoMode:d,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:b,characters:o.characters||{},skipTransitionsAndAnimations:c}),{functions:Re});k.children.push(Oe(Ve(ie,{isLineCompleted:s,skipMode:p,skipTransitionsAndAnimations:c}),o))}}let xe=Uo({resources:o,resourceId:M,colorId:ee}),G=Uo({resources:o,resourceId:P,colorId:W}),K=Le({animationsDef:t.background.animations,resources:o,previousResourceId:xe.resourceId,currentResourceId:G.resourceId,previousTargetId:xe.targetId,currentTargetId:G.targetId,animationPath:"background.animations",idPrefix:"bg-cg"});we({animationInstances:K,isLineCompleted:s,skipTransitionsAndAnimations:c,activePersistentAnimations:u,restoredPersistentAnimations:f,isAuthoredOnCurrentLine:N})&&C.push(...K)}return e},nl=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:c,animations:a}=e;if(t.character&&n){let l=c.find(h=>h.id==="story");if(!l)return e;let u=t.character.items||[],f=r?.character?.items||[],d=To(u),p=To(f);for(let h=0;h<u.length;h++){let g=u[h],{transformId:y,sprites:b}=g,A=f.find(P=>P.id===g.id),x=f.findIndex(P=>P.id===g.id),C=A?.sprites&&A.sprites.length>0,N=b&&b.length>0,k=x>=0?Ht(A,x,p):void 0,w=Le({animationsDef:g.animations,resources:n,previousResourceId:k,currentResourceId:N?Ht(g,h,d):void 0,previousTargetId:k,currentTargetId:N?Ht(g,h,d):void 0,animationPath:`character.items[${h}].animations`,idPrefix:"character"});if(g.animations&&!b&&!y&&C&&we({animationInstances:w,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){a.push(...w);continue}if(g.animations&&!b&&!y)continue;if(!b||b.length===0||!y){console.warn("Character item missing sprites or transformId:",g);continue}let j=Ht(g,h,d),M=n.transforms[y];if(!M){console.warn("Transform not found:",y);continue}let ee={type:"container",id:j,...Pe(M,g),...It(g),children:[]};for(let P of b){let W=Qo({id:`${j}-${P.id}`,item:P,resources:n});W&&ee.children.push(W)}l.children.push(ee),we({animationInstances:w,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...w)}}return e},ci=(e,t)=>{if(!Yr.includes(e))throw new Error(`${t} must be one of: ${Yr.join(", ")}.`)},ol=(e,t)=>{let r=!!e.resourceId||hn(e),n=e.layer??(r?void 0:t?.layer)??Hr;return ci(n,`Visual item "${e.id}" layer`),n},il=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,runtime:c,activePersistentAnimations:a,autoMode:l,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,form:h,saveSlots:g=[],visualLayer:y})=>{let{elements:b,animations:A}=e;if(t.visual&&n){let x=b.find(w=>w.id==="story");if(!x)return e;let C=t.visual.items,N=r?.visual?.items||[],k=Ee({variables:s,runtime:c,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:o,autoMode:l,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:i});y!==void 0&&ci(y,"visualLayer");for(let w of C){let j=N.find(H=>H.id===w.id),M=ol(w,j);if(y!==void 0&&M!==y)continue;if(Mc(w),w.text){let H=Yt(n,w),te={...structuredClone(w.text),id:`visual-${w.id}`,type:"text",...Pe(H,w)};Object.assign(te,It(w)),x.children.push(Oe(ce(te,k,{functions:Re}),n))}if(w.resourceId){let{images:H={},videos:te={},spritesheets:xe={}}=n,G=xe[w.resourceId];if(G){let K=Yt(n,w),oe=w.animationName;if(oe){let re=G.animations?.[oe];if(!re)throw new Error(`Animation '${oe}' not found in spritesheet resource '${w.resourceId}'`);let J=It(w),ie={id:`visual-${w.id}`,type:"spritesheet-animation",...Pe(K,w),width:w.width??G.width,height:w.height??G.height,alpha:J.alpha??w.alpha??1,src:G.fileId,atlas:G.jsonData,playback:{frames:re.frames,animationSpeed:w.animationSpeed??re.animationSpeed??.5,loop:w.loop??re.loop??!0}};J.blur&&(ie.blur=J.blur),x.children.push(structuredClone(ie))}}else{let K=H[w.resourceId]||te[w.resourceId];if(K){let oe=te[w.resourceId]!==void 0,re=Yt(n,w),J={id:`visual-${w.id}`,type:oe?"video":"sprite",src:K.fileId,width:K.width,height:K.height,...Pe(re,w)};Object.assign(J,It(w)),oe&&(J.loop=K.loop??!1,J.volume=K.volume??50),x.children.push(J)}}}if(w.resourceId){let{layouts:H={}}=n,te=H[w.resourceId];if(te){let xe=Yt(n,w),G={id:`visual-${w.id}`,type:"container",children:structuredClone(te.elements),...Pe(xe,w)};Object.assign(G,It(w));let K=ce(G,k,{functions:Re});x.children.push(Oe(Ve(K,{isLineCompleted:o,skipMode:u,skipTransitionsAndAnimations:i}),n))}}let ee=Mo(j),P=Mo(w),W=Le({animationsDef:w.animations,resources:n,previousResourceId:ee,currentResourceId:P,previousTargetId:ee?`visual-${w.id}`:void 0,currentTargetId:P?`visual-${w.id}`:void 0,animationPath:`visual.items[${w.id}].animations`,idPrefix:w.id});we({animationInstances:W,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:a})&&A.push(...W)}}return e},it="dialogue-character-sprite",Wo=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,sl=(e,{presentationState:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:c}=e,a=Ke(e.elements);if(!a)return e;let l=t.dialogue?.character?.sprite,u=r?.dialogue?.character?.sprite,f=Wo(l),d=Wo(u),p=Le({animationsDef:l?.animations,resources:n,previousResourceId:d?it:void 0,currentResourceId:f?it:void 0,previousTargetId:d?it:void 0,currentTargetId:f?it:void 0,animationPath:"dialogue.character.sprite.animations",idPrefix:"dialogue-character-sprite"});if(!f)return l?.animations&&d&&we({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...p),e;let h=n.transforms?.[l.transformId];if(!h)return console.warn("Transform not found:",l.transformId),e;let g={type:"container",id:it,...Pe(h),children:[]};for(let y of l.items){let b=Qo({id:`${it}-${y.id}`,item:y,resources:n});b&&g.children.push(b)}return a.children.push(g),we({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...p),e},al=(e,{presentationState:t,previousPresentationState:r,resources:n={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:c,isFormVisible:a,canRollback:l,form:u,skipOnlyViewedLines:f,isLineCompleted:d,skipTransitionsAndAnimations:p,variables:h,runtime:g,activePersistentAnimations:y,saveSlots:b=[]})=>{let{elements:A,animations:x}=e;if(!t.dialogue||o)return e;let C=A.find(k=>k.id==="story");if(!C)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:k={}}=n,w=k[t.dialogue.ui.resourceId];if(w){let j={elements:w.elements},M=Ee({variables:h,runtime:g,saveSlots:b,dialogueState:t.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:d,autoMode:i,skipMode:s,isChoiceVisible:c,isFormVisible:a,canRollback:l,form:u,characters:n.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:f,skipTransitionsAndAnimations:p}),ee={functions:Re},P=Kt(j,M,ee),W=ce(P,M,ee),H=Oe(Ve(W?.elements,{isLineCompleted:d,skipMode:s,skipTransitionsAndAnimations:p}),n);if(Array.isArray(H))for(let te of H)C.children.push(te);else H&&C.children.push(H)}}sl(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:d,skipTransitionsAndAnimations:p,activePersistentAnimations:y});let N=Le({animationsDef:t.dialogue.ui?.animations,resources:n,previousResourceId:r?.dialogue?.ui?.resourceId,currentResourceId:t.dialogue.ui?.resourceId,previousTargetId:r?.dialogue?.ui?.resourceId?"dialogue-container":void 0,currentTargetId:t.dialogue.ui?.resourceId?"dialogue-container":void 0,animationPath:"dialogue.ui.animations",idPrefix:"dialogue-ui"});return we({animationInstances:N,isLineCompleted:d,skipTransitionsAndAnimations:p,activePersistentAnimations:y})&&x.push(...N),e},cl=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:c,runtime:a,autoMode:l,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,form:h,activePersistentAnimations:g,saveSlots:y=[]})=>{let{elements:b,animations:A}=e;if(t.choice&&n){let x=Ke(b);if(!x)return e;let C=n?.layouts[t.choice.resourceId];if(C&&C.elements){let k={elements:C.elements},w=ce(k,{...Ee({variables:c,runtime:a,saveSlots:y,dialogueState:t.dialogue,isLineCompleted:i,autoMode:l,skipMode:u,isChoiceVisible:f??!!t.choice,isFormVisible:d,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}},{functions:Re}),j=on(Oe(Ve(w?.elements,{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),n));if(Array.isArray(j))for(let M of j)x.children.push(M);else j&&x.children.push(j)}let N=Le({animationsDef:t.choice.animations,resources:n,previousResourceId:r?.choice?.resourceId,currentResourceId:t.choice.resourceId,previousTargetId:r?.choice?.resourceId?"choice-container":void 0,currentTargetId:t.choice.resourceId?"choice-container":void 0,animationPath:"choice.animations",idPrefix:"choice"});we({animationInstances:N,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:g})&&A.push(...N)}return e},ll=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:c,runtime:a,autoMode:l,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,activePersistentAnimations:h,saveSlots:g=[],form:y})=>{let{elements:b,animations:A}=e;if(!y?.resourceId||!n)return e;let x=Ke(b);if(!x)return e;let C=n?.layouts?.[y.resourceId];if(!C)return console.warn(`Form layout not found: ${y.resourceId}`),e;let N={id:"form-container",type:"container",x:0,y:0,children:C.elements||[]},k={...Ee({variables:c,runtime:a,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:i,autoMode:l,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,characters:n.characters||{},skipTransitionsAndAnimations:s,form:y}),form:y},w=ce(N,k,{functions:Re}),j=an(Oe(Ve(sn(w,y),{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),n),y);j&&x.children.push(j);let M=Le({animationsDef:y.animations,resources:n,previousResourceId:r?.form?.resourceId,currentResourceId:y.resourceId,previousTargetId:r?.form?.resourceId?"form-container":void 0,currentTargetId:y.resourceId?"form-container":void 0,animationPath:"form.animations",idPrefix:"form"});return we({animationInstances:M,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:h})&&A.push(...M),e},ul=(e,{presentationState:t,resources:r={},variables:n,runtime:o,isLineCompleted:i,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:u,form:f,saveSlots:d=[],skipTransitionsAndAnimations:p})=>{if(!t.control?.resourceId)return e;let h=r.controls?.[t.control.resourceId];if(!h)return e;let g=el(h.keyboard,h.keyup);if(g&&Object.keys(g).length>0&&(e.global.keyboard=g),!Array.isArray(h.elements)||h.elements.length===0)return e;let y=Ke(e.elements);if(!y)return e;let b={id:`control-${t.control.resourceId}`,type:"container",x:0,y:0,children:h.elements};return y.children.push(ai({container:b,resources:r,templateData:Ee({variables:n,runtime:o,saveSlots:d,dialogueState:t.dialogue,isLineCompleted:i,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:u,form:f,characters:r.characters||{},skipTransitionsAndAnimations:p}),isLineCompleted:i,skipMode:c,skipTransitionsAndAnimations:p})),e},fl=(e,{presentationState:t,resources:r,runtime:n,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&r){if(!Ke(i))return e;let a=t.bgm,l=!Array.isArray(a.sounds),u=l?a.resourceId?[{id:"default",resourceId:a.resourceId,loop:a.loop??!0,volume:a.volume,startDelayMs:a.startDelayMs??0}]:[]:a.sounds,f=[];if(l||Qt(u,"BGM sound"),u.forEach(p=>{let h=r.sounds?.[p.resourceId];h&&f.push(yn({id:At("bgm",l?"default":p.id),sound:p,resource:h,defaultLoop:!0}))}),f.length===0)return e;let d=Ee({variables:o,runtime:n}).runtime;s.push(gn({id:zc,volume:mn(d,"musicVolume",l?Ge:a.volume??Ge),muted:a.muted,pan:a.pan,children:f,runtime:d}))}return e},dl=(e,{presentationState:t,resources:r,runtime:n})=>{let{audio:o}=e;if(t.sfx&&r){let i=t.sfx,s=!Array.isArray(i.channels),c=s?[{id:Wc,sounds:i.items??[]}]:i.channels;s||Qt(c,"SFX channel"),c.forEach(a=>{let l=[];s||Qt(a.sounds,"SFX sound",`SFX channel "${a.id}"`),a.sounds.forEach((u,f)=>{let d=r.sounds?.[u.resourceId];d&&l.push(yn({id:s?At("sfx","default",f,u.id):At("sfx",a.id,u.id),sound:u,resource:d}))}),l.length!==0&&o.push(gn({id:At("channel","sfx",a.id),volume:mn(n,"soundVolume",a.volume??Ge),muted:a.muted,pan:a.pan,children:l,runtime:n}))})}return e},pl=(e,t,r)=>{if(!(!t||!r))return e?.voices?.[t]?.[r]},hl=(e,{presentationState:t,resources:r,currentSceneId:n,runtime:o,variables:i})=>{let{audio:s}=e;if(!t?.voice)return e;let c=t.voice,a=!Array.isArray(c.sounds),l=a?c.resourceId?[{id:"default",resourceId:c.resourceId,loop:c.loop??!1,volume:Ge,startDelayMs:c.startDelayMs??0}]:[]:c.sounds,u=[];if(a||Qt(l,"Voice sound"),l.forEach(d=>{let p=pl(r,n,d.resourceId);p&&u.push(yn({id:At("voice",n,a?"default":d.id),sound:d,resource:p}))}),u.length===0)return e;let f=Ee({variables:i,runtime:o}).runtime;return s.push(gn({id:qc,volume:a?c.volume??oi(f,"soundVolume"):mn(f,"soundVolume",c.volume??Ge),muted:c.muted,pan:c.pan,children:u,runtime:f})),e},ml=(e,{presentationState:t,previousPresentationState:r,resources:n={},variables:o,runtime:i,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:u,form:f,saveSlots:d=[],isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})=>{let{elements:y,animations:b}=e;if(t.layout){let N=Ke(y);if(!N)return e;let k=n.layouts[t.layout.resourceId];if(!k)return e;Array.isArray(k.transitions)&&!p&&!h&&un({animations:b,transitions:k.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let w={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:k.elements||[]};N.children.push(ai({container:w,resources:n,templateData:Ee({variables:o,runtime:i,saveSlots:d,dialogueState:t.dialogue,isLineCompleted:p,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:u,form:f,characters:n.characters||{},skipTransitionsAndAnimations:h}),isLineCompleted:p,skipMode:c,skipTransitionsAndAnimations:h}))}let A=r?.layout?.resourceId,x=t.layout?.resourceId,C=Le({animationsDef:t.layout?.animations,resources:n,previousResourceId:A,currentResourceId:x,previousTargetId:A?`layout-${A}`:void 0,currentTargetId:x?`layout-${x}`:void 0,animationPath:"layout.animations",idPrefix:"layout"});return we({animationInstances:C,isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})&&b.push(...C),e},gl=(e,{currentLineActions:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:c}=e,a=t?.screen?.animations;if(!a)return e;let l=r!=null,u=Le({animationsDef:a,resources:n,previousResourceId:l?"story":void 0,currentResourceId:"story",previousTargetId:l?"story":void 0,currentTargetId:"story",animationPath:"screen.animations",idPrefix:"screen"});return we({animationInstances:u,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...u),e},yl=(e,{presentationState:t})=>{let r=Ke(e.elements);return!r||!t?.screen||Object.assign(r,ri(t.screen)),e},bl=(e,{presentationState:t,resources:r={},variables:n,runtime:o,autoMode:i,skipMode:s,isChoiceVisible:c,isFormVisible:a,canRollback:l,form:u,overlayStack:f=[],dialogueHistory:d=[],saveSlots:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:b,animations:A}=e;return f&&f.length>0&&f.forEach((x,C)=>{let N=r.layouts[x.resourceId];if(!N){console.warn(`Overlay layout not found: ${x.resourceId}`);return}Array.isArray(N.transitions)&&(y||un({animations:A,transitions:N.transitions,defaultTargetId:`overlayStack-${C}`,idPrefix:`overlayStack-${C}`,animationPathPrefix:`overlayStack[${C}]`}));let k={id:`overlayStack-${C}`,type:"container",x:0,y:0,children:[ii({id:`overlayStack-${C}-blocker`,screen:h}),...N.elements||[]]},w=si(d,r.characters,n),j=Ee({variables:n,runtime:o,saveSlots:p,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:i,skipMode:s,isChoiceVisible:c,isFormVisible:a,canRollback:l,form:u,historyDialogue:w,characters:r.characters||{},skipTransitionsAndAnimations:y}),M=ce(k,j,{functions:Re}),[ee,...P]=M.children||[],W=Oe(Ve({...M,children:P},{isLineCompleted:g,skipMode:s,skipTransitionsAndAnimations:y}),r);b.push({...W,children:ee?[ee,...W.children||[]]:W.children})}),e},Il=(e,{presentationState:t,resources:r={},variables:n,runtime:o,saveSlots:i=[],autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:u,form:f,confirmDialog:d,dialogueHistory:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:b,animations:A}=e;if(!d?.resourceId)return e;let x=r.layouts?.[d.resourceId];if(!x)return console.warn(`ConfirmDialog layout not found: ${d.resourceId}`),e;Array.isArray(x.transitions)&&!y&&un({animations:A,transitions:x.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let C={id:"confirmDialog",type:"container",x:0,y:0,children:[ii({id:"confirmDialog-blocker",screen:h}),...x.elements||[]]},N=si(p,r.characters,n),k=ce(C,Ee({variables:n,runtime:o,saveSlots:i,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:u,form:f,confirmDialog:d,historyDialogue:N,characters:r.characters||{},skipTransitionsAndAnimations:y}),{functions:Re}),[w,...j]=k.children||[],M=Oe(Ve({...k,children:j},{isLineCompleted:g,skipMode:c,skipTransitionsAndAnimations:y}),r);return b.push({...M,children:w?[w,...M.children||[]]:M.children}),e},xt=e=>(t,r)=>il(t,{...r,visualLayer:e}),Al=xt(_e.BEHIND_BACKGROUND),wl=xt(_e.BEHIND_CHARACTER),El=xt(_e.BEHIND_DIALOGUE),xl=xt(_e.BEHIND_CHOICE),vl=xt(_e.FOREGROUND),li=e=>Mt(tl,[ul,Al,rl,wl,nl,El,al,xl,cl,ll,ml,vl,yl,gl,fl,dl,hl,bl,Il])(e);function ui(e,t=""){let r=[],n=e.length,o=0,i=0,s=-1,c=()=>{let a=0,l=0,u;do u=parseInt(e[o++],36),a+=(u&15)<<l,l+=4;while(u&16);return a};for(;o<n;){let a=s+1+c();s=a+c(),r.push([a,s,t?parseInt(t[i++],36):0])}return r}function fi(e,t,r){let n=0,o=t.length-1;for(;n<=o;){let i=n+o>>>1,s=r[i];if(e<t[i])o=i-1;else if(e>s>>>5)n=i+1;else return s&31}return 0}var di="090001000h1v5g2903000hl2v6jh16ng1s210111110o35aa10u2k1g10l6600152113h2010u1q1r5aq3890o13181214r22k3158q2n1000v100h1k20000001207030001160721k171001h1j11610332010010321210090411021c1c02100o301201412230u1130b100h1j116111420120411001100k11l10051001h1j11611142011000321210072411021d0g10r3000000132120090o200200g1j11f2012031213711271t1001o301001000001121371b1f0c101h1l2011001031212000080a1t1001m40400102101600i11t301006c7i601008b6p41r10101041h3d0004115a1j290p3q223000511010100g1501010302003172030c0010016000e0i6v50n40n5tl12ir33s12t11u11cj30100060700010a90t220000l71i20m7203010241000502rd101004k300000006101027050920g3t22bk1300616g209030207u18c1000t10003010501b2o20000102000004g37070101o921c000640602001mcv3rg20000001o16d0c0m1fg6g2h30m10q55f1vm11c0ma0p1a42nc0ne1a090q3314902021204020112030318250105bb1201110i1021i15101131502141b15120511011k1155132040202510201010603060a1f02040104210b1g3290e0e0kn11vs12j11j3040pp12t80g6v1vmo7319g21g51gh103040n11010040j51i3f01q1h1d0m27p1a0000cs13200523j200010301010100v140018a4q2501010101c08000i1f12601011g3012215110u1a0001015000pcq181000100011000iji5fvc0u91g5bhg20ie0l94lo6002115303121s12240la1tj23h44tj11t45m4ah33q700000l3ep2021a200t220301012040a0i320j2040007f00100r20c100g3208000011531000s520201036020t900207l1101n311000000321210090a12634b910201l22001051020120011020000e1i520701020000n10h5001050000010000010001re0010323010001r11i520701000001q6000000107l600000230004gg12080001lc62027111n1000411230000000000t820321030030r10090n205001380800501020n2050c0001mc00002000000nc006150000i5l1100600010001q753011160000i441111000000rl11019100000c1h201043102n10ltk1f006eoss2b0202gs94r36si2033ku101m373h50b1rqs4113sli1t22m1uh2435070726u13k92rr7m34h380e0m141egl561g1261114k60ga6nn10t33sv13uf1jf0207150qt16t66pr60n23k6bf1f0e1l29g71c1e029j1n30p11ea0k1028139m16rb2v621122i52213040tf1u3b51n17127c0232041d120819052c28220104060306l5g3l4572g130152cqdl2c3o37a5o27u11c32d9m2cu2191obo57eh9gg1tv3",pi="262122424333333393233393339333333333393393bf3b3b3b3b3f3f3bffff33b3bb33ff3f33b3b3333333bffff3b33bb33f33bffff33b3bb33ff3f33b3bbb333b3ff33b333f33b3b3b3b3333b3bf33b3bb39333b33b33b3b3b333b333333b3b33333f3b33b3ffb3f3fff3f3b33f35dc33333f3b3b3b33323333b3bb3b33b3fb3b3333b33333bff3b3f33bfb3b3ff3b3b3b3b3b333b333b3323e22442344444444444444444444444444444444444444444444444444444444444444444444444444444443333333333b3b3bb33333b353bff3b3b3b3f3ff3b3b333bfff3f33333fb3bb3fb3b3bb33232333f333fff333333333b3b3333bb3b39393f3b3fbf33bb3b393b3b3b3333b33b33b3bbb33b33ffff3b3333bb3933b3b3b333b3b3b3b3b33b3b3b33b3b3b33b3b33b33b3b3b3fffff3bb39b9b3b33b3bf3f3b33f3b3f93b33b3b3bb33b33b3b3b3333393b3b3b33b39bffb3b332333b333dd3b3333233332333333333333333333333333333444444444444a4444444444444344444444444444444444444444444444444444444444",hi="0001000000010010000000100000000000000000000000000001000000010014000100000001001000010101100101100000000000000000000100000001111000010000000110101001110111111111000100000021001000010000000100100001000000011010000100000001111000013000000100140001000000010010";var mi=65535,bn=40960,er=126976,bi=new Uint8Array(12288),Ii=new Uint8Array(3072),Ai=new Uint8Array(2816),wi,Ei;{let e=(o,i,s,c,a)=>{let l=i+o.length-1;for(let u=s<i?i:s,f=c>l?l:c;u<=f;u++)o[u-i]=a},t=new Uint32Array(320),r=new Uint32Array(320),n=0;for(let[o,i,s]of ui(di,pi))e(bi,0,o,i,s),e(Ii,bn,o,i,s),e(Ai,er,o,i,s),i>=65040&&!(o>=er&&i<=129791)&&(t[n]=o,r[n++]=i<<5|s);wi=t.slice(0,n),Ei=r.slice(0,n)}function gi(e){return e<12288?bi[e]:e<bn?e<12336?e>=12330?3:0:e<12443?e===12336||e===12349?4:e>=12441?3:0:e===12951||e===12953?4:0:e<44032?Ii[e-bn]:e<55204?(e-44032)%28?8:7:e<57344?e<=55238?e>=55216?13:0:e>=55243&&e<=55291?12:0:e<65024?e===64286?3:0:e<65040?3:e>=er&&e<129792?Ai[e-er]:e>=917504?e>921599?0:e>=917536&&e<917632||e>=917760&&e<918e3?3:2:fi(e,wi,Ei)}var xi=Uint8Array.from(hi,Number);function Sl(e){return e===2381||e===2509||e===2637||e===2765||e===2893||e===3149||e===3405||e===4153||e===6098||e===6752||e===6980||e===7083||e===43456||e===43766||e===68159||e===69939||e===70608||e===71998||e===72263||e===72345||e===73538}function yi(e,t,r){switch(t){case 3:return e&24?r===8204?e&6:(e&24)===16||Sl(r)?e&6|16:e&6|8:e&6;case 4:return 2;case 10:return e&1^1;case 14:return(e&2)<<1|e&24;default:return 8}}function*vi(e){let t=e.length;if(t===0)return;let r=e.codePointAt(0),n=r>mi?2:1,o=gi(r),i=50200>>o&1?yi(0,o,r):0,s=0,c=r,a=o;for(;n<t;){r=e.codePointAt(n);let l=r>mi?2:1,u=gi(r),f=xi[o<<4|u],d;f===0?d=!0:f===1?d=!1:f===2?d=!(i&1):f===3?d=!(i&4):d=(i&24)!==16,i=50200>>u&1&&(i!==0||u!==3)?yi(i,u,r):0,d&&(yield{segment:e.slice(s,n),index:s,input:e,_hd:c,_catBegin:a===15?0:a,_catEnd:o===15?0:o},s=n,c=r,a=u),n+=l,o=u}yield{segment:e.slice(s),index:s,input:e,_hd:c,_catBegin:a===15?0:a,_catEnd:o===15?0:o}}function*Si(e){for(let t of vi(e))yield t.segment}{let e=vi("_");xi._keep=[e,e.next()]}var Ci=1e3,Cl=1,_l=60,Rl=3,Ol=.5,Ll=2e4,$l=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,kl=/^\s+$/u,_i,Dl=e=>{let t=`${e??""}`.normalize("NFC"),r=globalThis.Intl?.Segmenter;return typeof r!="function"?Array.from(Si(t)):(_i??=new r(void 0,{granularity:"grapheme"}),Array.from(_i.segment(t),({segment:n})=>n))},Tl=e=>Dl(e).reduce((t,r)=>kl.test(r)?t+Ol:$l.test(r)?t+Rl:t+1,0),Ri=({text:e="",baseDelay:t=Ci,speed:r=Cl}={})=>{let n=Number.isFinite(t)?Math.max(0,t):Ci,o=Number.isFinite(r)&&r>0?r:1,i=Tl(e)*_l/o,s=Math.max(n,Ll);return Math.min(n+i,s)};var tr={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},Di=1,ir="choice",rr="form",sr=()=>({manual:{...tr.manual},auto:{...tr.auto},applyMode:tr.applyMode}),In=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let r=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...sr()},r&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},T=e=>{let t=de(e)?Be(e):e;return structuredClone(t)},D=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),ar=e=>String(e),Ti=()=>({sections:[],resources:[]}),Nl=e=>D(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):Ti(),Pl=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",Vl=({sectionId:e,lineId:t,content:r,dialogueState:n,characterName:o})=>({sectionId:e,lineId:t,content:r,text:Pl(r),characterId:n.characterId,character:{...n.character||{},name:o},characterName:o}),jl=()=>({resourceId:void 0}),Fl=e=>{if(!D(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},An=(e,t)=>{let r=e?.story?.scenes??{};for(let[n,o]of Object.entries(r))if(o?.sections?.[t])return{sceneId:n,section:o.sections[t]};return{sceneId:void 0,section:void 0}},Ni=e=>{let t=e?.story?.scenes??{},r=new Map;for(let[n,o]of Object.entries(t)){let i=o?.sections??{};for(let s of Object.keys(i)){let c=r.get(s);if(c!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${c}" and "${n}". Section IDs must be globally unique.`);r.set(s,n)}}},Pi=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},Vi=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==Di)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},Ml=(e,t={})=>{let r;try{r=Vi(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let n={...t,formatVersion:r,slotId:Pi(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete n.slotKey,delete n.date,n},Ul=(e={})=>Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Ml(t,r)])),ji=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:r})=>Nf(r));return t.length>0?t:void 0},Bl=e=>{!D(e)||!Array.isArray(e.timeline)||e.timeline.forEach(t=>{if(!D(t))return;let r=ji(t.executedActions);if(r){t.executedActions=r;return}delete t.executedActions})},Oi=(e,t,r,n="viewedRegistry")=>{let o=t==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[o]:String(e)};if(!D(e))throw new Error(`Malformed ${n}.${t}[${r}] entry.`);if(typeof e[o]!="string"||e[o].length===0)throw new Error(`Malformed ${n}.${t}[${r}] 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 ${n}.sections[${r}] entry: invalid lastLineId.`);return typeof e.lastLineId=="string"&&e.lastLineId.length>0&&(i.lastLineId=e.lastLineId),i}return{resourceId:e.resourceId}},zl=(e,t="viewedRegistry")=>{if(e===void 0)return Ti();if(!D(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 r=e.sections??[],n=e.resources??[];return{sections:Object.values(Object.fromEntries(r.map((o,i)=>{let s=Oi(o,"sections",i,t);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(n.map((o,i)=>{let s=Oi(o,"resources",i,t);return[s.resourceId,s]})))}},Fi=(e,t,r)=>{if(!D(e))throw new Error(`Malformed save slot ${r}.`);let{sectionId:n,lineId:o}=e;if(typeof n!="string"||n.length===0)throw new Error(`Malformed save slot ${r}: missing sectionId.`);if(typeof o!="string"||o.length===0)throw new Error(`Malformed save slot ${r}: missing lineId.`);let{sceneId:i,section:s}=An(t,n);if(!s)throw new Error(`Malformed save slot ${r}: section "${n}" does not exist in projectData.`);if(!s.lines?.some(a=>a.id===o))throw new Error(`Malformed save slot ${r}: line "${o}" does not exist in section "${n}".`);return{sceneId:i,sectionId:n,lineId:o}},ql=(e,t,r)=>{if(!D(e)||!Array.isArray(e.timeline))return vt({pointer:t,replayStartIndex:1});let n=e.timeline.flatMap((c,a)=>{if(!D(c))return[];try{let l=Fi(c,r,`rollback.timeline[${a}]`),u=or({sectionId:l.sectionId,lineId:l.lineId,rollbackPolicy:c.rollbackPolicy}),f=ji(T(c.executedActions));return f&&(u.executedActions=f),[u]}catch{return[]}});if(n.length===0)return vt({pointer:t,replayStartIndex:1});let o=typeof e.currentIndex=="number"?Math.trunc(e.currentIndex):n.length-1;(o<0||o>=n.length)&&(o=n.length-1);let i=n[o];if(i?.sectionId!==t.sectionId||i?.lineId!==t.lineId){let c=n.findLastIndex(a=>a.sectionId===t.sectionId&&a.lineId===t.lineId);c>=0?o=c:(n.push(or({sectionId:t.sectionId,lineId:t.lineId})),o=n.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:n}},Wl=(e,t,r)=>{if(!D(e))throw new Error(`Malformed save slot contexts[${r}] entry.`);let n=xn(t),o=Fi(e.pointers?.read,t,`contexts[${r}].pointers.read`);if(e.variables!==void 0&&!D(e.variables))throw new Error(`Malformed save slot contexts[${r}].variables entry.`);if(e.runtime!==void 0&&!D(e.runtime))throw new Error(`Malformed save slot contexts[${r}].runtime entry.`);let i=e.variables?rt(T(e.variables),t.resources?.variables??{}):{},s=ou({loadedContextRuntime:D(e.runtime)?T(e.runtime):{}}),c={currentPointerMode:"read",pointers:{read:o},configuration:D(e.configuration)?T(e.configuration):{},views:Array.isArray(e.views)?T(e.views):[],bgm:D(e.bgm)?T(e.bgm):{resourceId:void 0},variables:{...n,...i},rollback:ql(e.rollback,o,t)};return s&&(c.runtime=s),c},Hl=(e,t)=>{if(!D(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((r,n)=>Wl(r,t,n))}},Yl=(e,t)=>{if(!D(e))throw new Error("Malformed save slot.");let r=Vi(e.formatVersion);return{...e,formatVersion:r,state:Hl(e.state,t)}},Li=(e,t,{required:r=!1}={})=>{if(e===void 0){if(r)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 n=T(e);return Object.prototype.hasOwnProperty.call(n,"hideConfirmDialog")||(n.hideConfirmDialog={}),n},Gl=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:Li(e.confirmActions,"confirmActions",{required:!0}),cancelActions:Li(e.cancelActions,"cancelActions")}},at=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},Kl=e=>(D(e.global.formDrafts)||(e.global.formDrafts={}),e.global.formDrafts),ct=e=>{Object.prototype.hasOwnProperty.call(e.global,"formDrafts")&&(e.global.formDrafts={})},Mi=e=>{if(!(!D(e)||!e.animations))return{animations:T(e.animations)}},Jl=(e,t)=>{let r=Mi(t);if(r){e.global.pendingScreenTransition=r;return}delete e.global.pendingScreenTransition},Xl=e=>{let t=e?.id??e?.resourceId;return typeof t=="string"&&t.length>0?t:void 0},Ql=(e,t)=>{let r=e?.sectionId,n=e?.lineId;if(!(!r||!n||!t))return`${r}:${n}:${t}`},nr=e=>String(e??""),Ui=(e,t)=>{let r=nr(t);return e?.trim===!0?r.trim():r},Zl=e=>D(e?.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,t])=>D(t)).map(([t,r])=>[t,{id:t,...T(r)}])):{},eu=(e,t)=>{if(!t||!D(e.global.formDrafts))return;let r=e.global.formDrafts[t];return D(r)?r:void 0},Bi=(e,t)=>{let r=Kl(e);D(r[t])||(r[t]={values:{},touched:{},errors:{},submitted:!1});let n=r[t];return D(n.values)||(n.values={}),D(n.touched)||(n.touched={}),D(n.errors)||(n.errors={}),typeof n.submitted!="boolean"&&(n.submitted=!1),n},wn=(e,t)=>{let r=Ui(e,t);return e?.required===!0&&r.length===0?"required":null},tu=({state:e,pointer:t})=>{if(!t?.sectionId||!t?.lineId)return{};let n=le({state:e},{sectionId:t.sectionId})?.lines||[],o=n.findIndex(i=>i.id===t.lineId);return o<0?{}:qe(n.slice(0,o+1).map(i=>i.actions||{}))},ru=({state:e,form:t,pointer:r})=>{if(!t?.resourceId)return null;let n=Xl(t),o=Ql(r,n);if(!n||!o)return null;let i=eu(e,o),s=Zl(t),c=lr({state:e}),a={},l=[],u={},f=!0;return Object.entries(s).forEach(([d,p])=>{let h=nr(c?.[p.variableId]),g=Object.prototype.hasOwnProperty.call(i?.values??{},d)?nr(i.values[d]):h,y=i?.touched?.[d]===!0,b=wn(p,g),A=i?.submitted||y?b:null,x=typeof p.maxLength=="number"?Math.max(0,Math.round(p.maxLength)):void 0,C={id:d,variableId:p.variableId,value:g,initialValue:h,valid:!b,error:A,touched:y,required:p.required===!0,trim:p.trim===!0,placeholder:p.placeholder===void 0?"":String(p.placeholder),multiline:p.multiline===!0,...x!==void 0?{maxLength:x}:{}};b&&(f=!1),a[d]=C,l.push(C),u[d]=g}),{id:n,key:o,resourceId:t.resourceId,animations:t.animations,valid:f,submitted:i?.submitted===!0,fields:a,fieldList:l,values:u,submitActions:{submitForm:{formKey:o,actions:T(t.submitActions??{})}},cancelActions:{cancelForm:{formKey:o,actions:T(t.cancelActions??{})}}}},Je=[],$i="line",En="interaction",or=({sectionId:e,lineId:t,rollbackPolicy:r})=>({sectionId:e,lineId:t,rollbackPolicy:r??"free"}),xn=e=>{let{contextVariableDefaultValues:t}=Bt(e??{});return T(t)},zi=()=>({...T(bt)}),qi=({loadedRuntime:e,runtimeIds:t,defaults:r={},path:n})=>{if(e===void 0)return{runtimeState:T(r),hasLoadedValues:!1};if(!D(e))throw new Error(`Malformed ${n}.`);let o=T(r),i=!1;return t.forEach(s=>{e[s]!==void 0&&(o[s]=Wi(s,T(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},nu=({loadedGlobalRuntime:e={}})=>qi({loadedRuntime:e,runtimeIds:qr,defaults:We,path:"global.runtime"}).runtimeState,ou=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:r}=qi({loadedRuntime:e,runtimeIds:Wr,defaults:zi(),path:"context.runtime"});return r?t:void 0},cr=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},iu=e=>e.runtime?(Wr.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=T(bt[t]))}),e.runtime):(e.runtime=zi(),e.runtime),su=e=>ko(e.global),au=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:su(e)}})},cu=e=>$o[e],lu=(e,t)=>{let r=cu(e);if(r==="number"){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} requires a finite numeric value`);return}if(r==="boolean"){if(typeof t!="boolean")throw new Error(`${e} requires a boolean value`);return}if(r==="string"){if(typeof t!="string")throw new Error(`${e} requires a string value`);return}throw new Error(`Unsupported runtime field "${e}"`)},Wi=(e,t)=>{if(lu(e,t),e==="autoForwardSpeed"&&t<=0)throw new Error("autoForwardSpeed requires a value greater than 0");return e==="saveLoadPagination"?Math.max(1,Math.trunc(t)):t},Hi=(e,t,r)=>{let n=Wi(t,r);if(t in bt){let o=cr(e);if(!o)return n;let i=iu(o);return i[t]=n,n}return e.global[t]=n,n},Yi=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:T(e)},configuration:{},views:[],bgm:jl(),variables:xn(t),rollback:vt({pointer:e})}),lt=e=>e?(e.currentPointerMode="read",D(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,uu=(e,{queueRender:t=!0}={})=>{let r=e.contexts?.[e.contexts.length-1],n=r?.pointers?.read;if(!r||!n?.sectionId||!n?.lineId)return null;let o=Yi({pointer:n,projectData:e.projectData});return e.contexts[e.contexts.length-1]=o,fu(e,{queueRender:t}),o},fu=(e,{queueRender:t=!0}={})=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,at(e),ct(e),e.global.nextLineConfig=sr(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"}),t&&e.global.pendingEffects.push({name:"render"})},Gi=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},vt=({pointer:e,replayStartIndex:t=0})=>{let r=e?.sectionId&&e?.lineId;return{currentIndex:r?0:-1,isRestoring:!1,replayStartIndex:t,timeline:r?[or({sectionId:e.sectionId,lineId:e.lineId})]:[]}},Ze=(e,t={})=>{if(e?.rollback)return Gi(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 r=e?.pointers?.read;return e.rollback=vt({pointer:r,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},vn=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return;let n=Ze(r);if(n.isRestoring)return;n.currentIndex<n.timeline.length-1&&(n.timeline=n.timeline.slice(0,n.currentIndex+1));let o=n.timeline[n.timeline.length-1];if(o?.sectionId===t.sectionId&&o?.lineId===t.lineId&&(o?.rollbackPolicy??"free")===(t.rollbackPolicy??"free")){n.currentIndex=n.timeline.length-1;return}n.timeline.push(or(t)),n.currentIndex=n.timeline.length-1},du=e=>{let r=e.contexts?.[e.contexts.length-1]?.rollback;if(!r||r.isRestoring||!Array.isArray(r.timeline)||typeof r.currentIndex!="number")return null;let n=Je[Je.length-1],o=typeof n?.checkpointIndex=="number"?n.checkpointIndex:r.currentIndex;return o<0||o>=r.timeline.length?null:(typeof n?.checkpointIndex!="number"&&o<r.timeline.length-1&&(r.timeline=r.timeline.slice(0,o+1)),r.timeline[o]??null)},pu=({state:e},t={})=>{let r=t?.source===$i?$i:En,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?(Je.push({checkpointIndex:null,source:r}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),Je.push({checkpointIndex:o.currentIndex,source:r}),e)},hu=({state:e})=>(Je.pop(),e),Ce=(e,t,r)=>{let o=Je[Je.length-1]?.source??En;if(!Pf(t,o))return;let i=du(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:T(r)}))},ki=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return;let n=t?.operations??[];for(let{variableId:o,op:i,value:s,roundTo:c}of n){let a=e.projectData.resources?.variables?.[o],l=a?.scope,u=a?.type;if(Te(a))throw new Error(`Cannot update computed variable: ${o}`);if(a?.readonly===!0)throw new Error(`Cannot update readonly variable: ${o}`);zt(l,o),qt(u,i,o),Fr(u,i,s,o,{roundTo:c}),l==="context"&&(r.variables[o]=Wt(r.variables[o],i,s,{roundTo:c}))}},mu=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:r,payload:n})=>{Vf(e,r,n)})},gu=(e,t)=>{let{sectionId:r,lineId:n}=t,s=le({state:e},{sectionId:r})?.lines?.find(c=>c.id===n)?.actions;s&&Object.entries(s).forEach(([c,a])=>{fs(e,c,a)})},Ki=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let n=Ze(r),o=n.timeline[t];if(!o)return e;e.global.autoMode&&pr({state:e}),e.global.skipMode&&Xe({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),n.isRestoring=!0,n.currentIndex=t;try{r.variables=xn(e.projectData),delete r.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=T(tr),e.global.overlayStack=[],at(e),ct(e),e.global.isLineCompleted=!0;let i=n.replayStartIndex??0;for(let c=i;c<=t;c++)c>i&&In(e),gu(e,n.timeline[c]),mu(e,n.timeline[c]);let s=lt(r);s.read={sectionId:o.sectionId,lineId:o.lineId},e.global.pendingEffects=e.global.pendingEffects.filter(c=>c?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{n.isRestoring=!1}return e},yu=e=>{let{projectData:t}=e,r=e.global??{},{saveSlots:n={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=r;Ni(t);let c=t.story.initialSceneId,a=t.story.scenes[c],l=a.initialSectionId,u=a.sections[l],f={sceneId:c,sectionId:l,lineId:u.initialLineId??u.lines[0].id},{globalVariablesDefaultValues:d}=Bt(t),p={...d,...rt(o,t.resources?.variables??{})};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,formDrafts:{},accountViewedRegistry:zl(s,"accountViewedRegistry"),nextLineConfig:sr(),saveSlots:Ul(n),overlayStack:[],variables:p,...nu({loadedGlobalRuntime:i})},contexts:[Yi({pointer:f,projectData:t})]}},bu=({state:e})=>e.global.overlayStack||[],Iu=({state:e})=>e.global.pendingEffects,Ji=({state:e})=>e.global.skipMode,Au=({state:e})=>e.global.autoMode,Xi=({state:e})=>e.global.dialogueUIHidden,Qi=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],r=t[t.length-1];if(!r)return[];let{sectionId:n,lineId:o}=r.pointers.read,i=le({state:e},{sectionId:n});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(f=>f.id===o),c=i.lines.slice(0,s+1),a=[],l={},u=gt({variables:{...e.global?.variables??{},...cr(e)?.variables??{}},runtime:He(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1});for(let f of c){let d=f.actions||{};if(l=qe([l,d]),!d.dialogue)continue;let p=l.dialogue||{},h=Ut({characterId:p.characterId,character:p.character,characters:e.projectData.resources?.characters??{},variables:u}),g=Vl({sectionId:n,lineId:f.id,content:d.dialogue.append===!0?p.content:d.dialogue.content,dialogueState:p,characterName:h});if(d.dialogue.append===!0&&a.length>0){a[a.length-1]={...a[a.length-1],content:g.content,text:g.text,characterId:g.characterId,character:g.character,characterName:g.characterName};continue}a.push(g)}return a},wu=({state:e})=>e.global.confirmDialog??null,St=({state:e},{pointer:t}={})=>{let r=t??ye({state:e})?.pointer,n=tu({state:e,pointer:r});return ru({state:e,form:n.form,pointer:r})},Eu=({state:e},{pointer:t}={})=>!!St({state:e},{pointer:t}),be=({state:e},{pointer:t}={})=>{let r=St({state:e},{pointer:t});if(r)return{source:rr,formId:r.id,formKey:r.key};let n=Zi({state:e,pointer:t});return n?{source:ir,resourceId:n}:null},xu=({state:e,registry:t},r)=>{let{sectionId:n,lineId:o}=r,s=(Array.isArray(t?.sections)?t.sections:[]).find(u=>u.sectionId===n);if(!s)return!1;if(s.lastLineId===void 0||o===void 0)return!0;let c=le({state:e},{sectionId:n});if(!c||!c.lines||!Array.isArray(c.lines))return s.lastLineId===o;let a=c.lines.findIndex(u=>u.id===s.lastLineId),l=c.lines.findIndex(u=>u.id===o);return a===-1||l===-1?s.lastLineId===o:l<=a},vu=({registry:e},t)=>{let{resourceId:r}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===r)},Sn=({state:e},t)=>xu({state:e,registry:e.global.accountViewedRegistry},t),Su=({state:e},t)=>vu({registry:e.global.accountViewedRegistry},t),Cu=({state:e})=>e.global.nextLineConfig,Zi=({state:e,pointer:t}={})=>{let r=t??ye({state:e})?.pointer;if(!r)return;let n=r?.sectionId,o=r?.lineId,s=le({state:e},{sectionId:n})?.lines||[],c=s.findIndex(l=>l.id===o);if(c<0)return;let a;for(let l of s.slice(0,c+1)){let u=l?.actions;if(u?.cleanAll&&(a=void 0),!u||!Object.prototype.hasOwnProperty.call(u,"choice")){a=void 0;continue}let f=u.choice;if(f?.resourceId){a=f.resourceId;continue}f?.animations||(a=void 0)}return a},es=({state:e})=>!!Zi({state:e}),_u=({state:e})=>structuredClone(e),ts=({state:e})=>e.global.saveSlots,Ru=({state:e},t)=>{let r=t?.slotId,n=ar(r);return e.global.saveSlots[n]},Cn=({state:e})=>He(e),Ou=({state:e},t)=>Ne(e,t?.runtimeId),lr=({state:e})=>{let t={...e.global?.variables??{},...cr(e)?.variables??{}};return gt({variables:t,runtime:He(e),variableConfigs:e.projectData.resources?.variables??{}})},ye=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],r=t[t.length-1];if(r)return{currentPointerMode:"read",pointer:r.pointers?.read}},le=({state:e},t)=>{let{sectionId:r}=t;return An(e.projectData,r).section},ur=({state:e})=>{let t=ye({state:e});if(!t?.pointer)return;let{sectionId:r,lineId:n}=t.pointer,o=le({state:e},{sectionId:r});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===n)},rs=({state:e})=>{let{sectionId:t,lineId:r}=ye({state:e}).pointer,o=le({state:e},{sectionId:t})?.lines||[],i=o.findIndex(l=>l.id===r),c=o.slice(0,i+1).map(l=>{let u=l.actions||{},f={};return Object.keys(u).forEach(d=>{f[d]=u[d]}),f});return qe(c)},Lu=e=>{let t=ur({state:e})?.actions?.dialogue;if(t?.clear===!0||!Array.isArray(t?.content))return"";let r=lr({state:e});return t.content.map(n=>`${nt(n?.text,{variables:r})??""}`).join("")},fr=({state:e})=>Ri({text:Lu(e),baseDelay:Ne(e,"autoForwardDelay"),speed:Ne(e,"autoForwardSpeed")}),$u=({state:e})=>{let t=ns({state:e}),n=ur({state:e})?.actions??{},o=qe([t??{},n]);return Mr(t??{},o??{})},ku=({state:e},{sectionId:t})=>{let r=le({state:e},{sectionId:t});if(!r?.lines)return[];let n=[],o={};for(let i of r.lines){let s=i.actions||{},c=qe([o,s]),a=Mr(o,c);n.push({id:i.id,changes:a,presentationState:c}),o=Ur(c)}return n},Du=({state:e},{sectionId:t,includePresentationState:r=!1})=>{let n=ku({state:e},{sectionId:t});return r?{lines:n}:{lines:n.map(({presentationState:o,...i})=>i)}},ns=({state:e})=>{let{sectionId:t,lineId:r}=ye({state:e}).pointer,o=le({state:e},{sectionId:t})?.lines||[],i=o.findIndex(a=>a.id===r);if(i<=0)return null;let c=o.slice(0,i).map(a=>{let l=a.actions||{},u={};return Object.keys(l).forEach(f=>{u[f]=l[f]}),u});return Ur(qe(c))},_n=({state:e},{slotsPerPage:t=6}={})=>{let o=((Cn({state:e}).saveLoadPagination??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let c=o+s,a=e.global.saveSlots&&e.global.saveSlots[ar(c)]||{};i.push({...a,slotId:c})}return{saveSlots:i}},Tu=ts,Nu=_n,Pu=e=>{let r=e.contexts?.[e.contexts.length-1]?.rollback;return!r||!Array.isArray(r.timeline)||typeof r.currentIndex!="number"?!1:r.currentIndex>=0&&r.currentIndex<r.timeline.length-1},Vu=({state:e},t={})=>{let r=rs({state:e}),n=ns({state:e}),o=ur({state:e})?.actions??{},i=e.global.pendingScreenTransition,s=i?.animations?{...o,screen:T(i)}:o,c=i?.animations&&n===null?{}:n,{sectionId:a}=ye({state:e}).pointer,{sceneId:l}=An(e.projectData,a),u=Cn({state:e}),f=t?.activePersistentAnimations??[],d=t?.restoredPersistentAnimations??[],p=St({state:e}),h=es({state:e}),g=lr({state:e}),{saveSlots:y}=_n({state:e}),b=Pu(e);return li({presentationState:r,previousPresentationState:c,currentLineActions:s,resources:e.projectData.resources,currentSceneId:l,screen:e.projectData.screen,dialogueUIHidden:u.dialogueUIHidden,autoMode:u.autoMode,skipMode:u.skipMode,isChoiceVisible:h,isFormVisible:!!p,canRollback:ps({state:e}),skipOnlyViewedLines:!u.skipUnseenText,isLineCompleted:u.isLineCompleted,skipTransitionsAndAnimations:!!u.skipTransitionsAndAnimations||b,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,form:p,dialogueHistory:Qi({state:e}),saveSlots:y,variables:g,runtime:u,activePersistentAnimations:f,restoredPersistentAnimations:d})},ju=({state:e},t)=>(e.global.confirmDialog=Gl(t),e.global.pendingEffects.push({name:"render"}),e),Fu=({state:e})=>(e.global.confirmDialog&&(at(e),e.global.pendingEffects.push({name:"render"})),e),Mu=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),Ce(e,"pushOverlay",t),e),Uu=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),Ce(e,"popOverlay",void 0),e),Bu=({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),zu=({state:e})=>(e.global.overlayStack=[],at(e),ct(e),e.global.pendingEffects.push({name:"render"}),Ce(e,"clearOverlays",void 0),e),qu=e=>{e.global.autoMode&&e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.skipMode&&e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.nextLineConfig?.auto?.enabled&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},dr=(e,t,{screenTransition:r}={})=>{e.global.isLineCompleted=!1,Jl(e,r),ct(e);let n=be({state:e},{pointer:t}),o=n?.source===ir,i=n?.source===rr;return n&&qu(e),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:o,isFormVisible:i,activeInteraction:n}},Rn=(e,t,r)=>{t?.source!==ir||r||!e.global.skipMode||e.global.pendingEffects.push({name:"startSkipNextTimer"})},os=({state:e})=>(be({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:fr({state:e})}}),e.global.pendingEffects.push({name:"render"})),e),pr=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Wu=({state:e})=>{let t=e.global.autoMode;return be({state:e})&&!t||(t?pr({state:e}):os({state:e})),e},is=({state:e})=>(be({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),Xe=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Hu=({state:e})=>{let t=Ji({state:e});return be({state:e})&&!t||(t?Xe({state:e}):is({state:e})),e},hr=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),Ce(e,"showDialogueUI",void 0),e),ss=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),Ce(e,"hideDialogueUI",void 0),e),Yu=({state:e})=>(Xi({state:e})?hr({state:e}):ss({state:e}),e),je=(e,t,r)=>(Hi(e,t,r),au(e),e.global.pendingEffects.push({name:"render"}),e),Ct=(e,t,r,n)=>{let o=Hi(e,t,r);return e.global.pendingEffects.push({name:"render"}),Ce(e,n,{value:o}),e},Gu=({state:e},t)=>je(e,"dialogueTextSpeed",t?.value),Ku=({state:e},t)=>je(e,"autoForwardDelay",t?.value),Ju=({state:e},t)=>je(e,"autoForwardSpeed",t?.value),Xu=({state:e},t)=>je(e,"skipUnseenText",t?.value),Qu=({state:e},t)=>je(e,"skipTransitionsAndAnimations",t?.value),Zu=({state:e},t)=>je(e,"soundVolume",t?.value),ef=({state:e},t)=>je(e,"musicVolume",t?.value),tf=({state:e},t)=>je(e,"muteAll",t?.value),rf=({state:e},t)=>Ct(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),nf=({state:e})=>{let t=Ne(e,"saveLoadPagination")+1;return Ct(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},of=({state:e})=>{let t=Ne(e,"saveLoadPagination")-1;return Ct(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},sf=({state:e},t)=>Ct(e,"menuPage",t?.value,"setMenuPage"),af=({state:e},t)=>Ct(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),cf=({state:e})=>(e.global.pendingEffects=[],e),lf=({state:e},t)=>(e.global.pendingEffects.push(t),e),as=(e,{sectionId:t,resetStoryState:r=!1,screen:n})=>{let o=!!Mi(n),i=le({state:e},{sectionId:t});if(!i)return console.warn(`Section not found: ${t}`),e;let s=i.lines?.[0];if(!s)return console.warn(`Section ${t} has no lines`),e;if(r&&!uu(e,{queueRender:!o}))return e;let c=be({state:e});r&&e.global.skipMode&&Xe({state:e});let a=e.contexts?.[e.contexts.length-1];if(a){let u=lt(a),f=u.read;r||Qe(e,{sectionId:f?.sectionId,lineId:f?.lineId}),a.rollback||Ze(a,{compatibilityAnchor:!0}),u.read={sectionId:t,lineId:s.id},r?a.rollback=vt({pointer:u.read}):vn(e,{sectionId:t,lineId:s.id})}let{activeInteraction:l}=dr(e,a?.pointers?.read,{screenTransition:n});return Rn(e,c,l),!r&&e.global.autoMode&&!c&&!l&&e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e},uf=({state:e},t)=>as(e,{sectionId:t?.sectionId,resetStoryState:!0,screen:t?.screen}),cs=e=>(e.global.accountViewedRegistry=Nl(e.global.accountViewedRegistry),e.global.accountViewedRegistry),On=(e,t)=>{!Array.isArray(t)||t.length===0||e.global.pendingEffects.push({name:"applyScopedDataUpdates",payload:{updates:t.map(r=>({scope:r.scope,path:r.path,op:r.op,value:T(r.value)}))}})},ls=(e,t)=>{On(e,[{scope:"account",path:"viewedRegistry",op:"markViewed",value:{sections:(Array.isArray(t?.sections)?t.sections:[]).map(r=>({sectionId:r.sectionId,...r.lastLineId===void 0?{}:{lineId:r.lastLineId}})),resources:Array.isArray(t?.resources)?t.resources:[]}}])},ff=(e,t,{sectionId:r,lineId:n})=>{if(!r||!n)return!1;let o=D(t)?t:{};Array.isArray(o.sections)||(o.sections=[]);let i=o.sections.find(s=>s.sectionId===r);if(i){if(i.lastLineId===void 0)return!1;let s=le({state:e},{sectionId:r});if(s?.lines){let c=s.lines.findIndex(l=>l.id===i.lastLineId),a=s.lines.findIndex(l=>l.id===n);if(c===-1||a>c)return i.lastLineId===n?!1:(i.lastLineId=n,!0)}else return i.lastLineId===n?!1:(i.lastLineId=n,!0);return!1}else return o.sections.push({sectionId:r,lastLineId:n}),!0},Qe=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;ff(e,cs(e),t)&&ls(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},df=({state:e},t)=>(Qe(e,t),e.global.pendingEffects.push({name:"render"}),e),pf=({state:e},t)=>{let{resourceId:r}=t;if(e.global.accountViewedRegistry!==void 0){let n=cs(e);n.resources.find(i=>i.resourceId===r)||(n.resources.push({resourceId:r}),ls(e,{sections:[],resources:[{resourceId:r}]}))}return e.global.pendingEffects.push({name:"render"}),e},us=({state:e},t)=>{let r=Fl(t.manual),{auto:n,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,c=e.contexts?.[e.contexts.length-1]?.rollback?.isRestoring===!0;r&&n?(e.global.nextLineConfig={manual:r,auto:n},o!==void 0?e.global.nextLineConfig.applyMode=o:s!==void 0&&(e.global.nextLineConfig.applyMode=s)):(r&&(e.global.nextLineConfig.manual=r),n&&(e.global.nextLineConfig.auto=n),o!==void 0&&(e.global.nextLineConfig.applyMode=o));let a=e.global.nextLineConfig.auto?.enabled,l=be({state:e});return!c&&!l&&a===!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}}):!c&&a===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),Ce(e,"setNextLineConfig",t),e},hf=({state:e},t)=>{let r=t?.slotId;if(r==null||r==="")throw new Error("saveSlot requires slotId");let{thumbnailImage:n}=t,o=t?.savedAt,i=ar(r),s=T(e.contexts);s?.forEach(l=>{lt(l),Gi(l.rollback),Bl(l.rollback)});let c={contexts:s},a={formatVersion:Di,slotId:Pi(r),savedAt:typeof o=="number"?o:Date.now(),image:n,state:c};return e.global.saveSlots[i]=a,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},mf=({state:e},t)=>{let r=t?.slotId;if(r==null||r==="")throw new Error("loadSlot requires slotId");let n=ar(r),o=e.global.saveSlots[n];if(o){let i=Yl(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=sr(),e.global.overlayStack=[],e.global.isLineCompleted=!0,at(e),ct(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},gf=({state:e},t)=>{let{projectData:r}=t;Ni(r),e.projectData=r;let n=r?.resources?.variables??{},{contextVariableDefaultValues:o,globalVariablesDefaultValues:i}=Bt(r??{});return Object.prototype.hasOwnProperty.call(e.global??{},"variables")&&(e.global.variables={...i,...rt(e.global.variables,n)}),e.contexts?.forEach(s=>{Object.prototype.hasOwnProperty.call(s??{},"variables")&&(s.variables={...o,...rt(s.variables,n)})}),at(e),ct(e),e.global.pendingEffects.push({name:"render"}),e},yf=({state:e},t)=>{let{sectionId:r,lineId:n}=t;if(!n)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=r||o.pointers.read?.sectionId;if(r&&!le({state:e},{sectionId:r}))return console.warn(`Section not found: ${r}`),e;let s=le({state:e},{sectionId:i});if(!s?.lines||!Array.isArray(s.lines))return console.warn(`Section ${i} has no lines`),e;if(!s.lines.find(f=>f.id===n))return console.warn(`Line not found: ${n} in section ${i}`),e;let a=be({state:e}),l=lt(o);l.read={sectionId:i,lineId:n};let{activeInteraction:u}=dr(e,l.read);return Rn(e,a,u),e},bf=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return hr({state:e}),e;let r=be({state:e});if(r?.source===ir&&t?.bypassChoice!==!0||r?.source===rr&&t?._interactionSource!==rr)return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let u=ye({state:e})?.pointer,f=u?.sectionId,d=u?.lineId;f&&d&&Qe(e,{sectionId:f,lineId:d}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&!r&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:fr({state:e})}});let p=e.global.nextLineConfig;return p?.auto?.enabled&&!r&&p.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:p.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e}let n=ye({state:e})?.pointer,o=n?.sectionId,i=le({state:e},{sectionId:o}),s=e.contexts[e.contexts.length-1],c=i?.lines||[],l=c.findIndex(u=>u.id===n?.lineId)+1;if(l<c.length){let u=c[l],f=!Ne(e,"skipUnseenText");if(e.global.skipMode&&f&&!Sn({state:e},{sectionId:o,lineId:u.id}))return Xe({state:e}),e;if(s&&!s.rollback&&Ze(s,{compatibilityAnchor:!0}),s){let h=lt(s),g=h.read?.lineId;g&&o&&Qe(e,{sectionId:o,lineId:g}),h.read={sectionId:o,lineId:u.id}}vn(e,{sectionId:o,lineId:u.id}),In(e);let{activeInteraction:d}=dr(e,{sectionId:o,lineId:u.id});Rn(e,r,d);let p=e.global.nextLineConfig;p?.auto?.enabled&&!d&&p.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:p.auto.delay}})}else e.global.autoMode&&pr({state:e}),e.global.skipMode&&Xe({state:e});return e},If=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=be({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:fr({state:e})}});let r=ye({state:e})?.pointer,n=r?.sectionId,o=r?.lineId;n&&o&&Qe(e,{sectionId:n,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},Af=({state:e},t)=>as(e,{sectionId:t?.sectionId,screen:t?.screen}),wf=({state:e})=>{if(e.global.dialogueUIHidden)return hr({state:e}),e;if(be({state:e}))return e;let t=ye({state:e})?.pointer,r=t?.sectionId,n=le({state:e},{sectionId:r}),o=e.contexts[e.contexts.length-1],i=n?.lines||[],c=i.findIndex(a=>a.id===t?.lineId)+1;if(c<i.length){let a=i[c],l=!Ne(e,"skipUnseenText");if(e.global.skipMode&&l&&!Sn({state:e},{sectionId:r,lineId:a.id}))return Xe({state:e}),e;if(o&&!o.rollback&&Ze(o,{compatibilityAnchor:!0}),o){let f=lt(o),d=f.read?.lineId;d&&r&&Qe(e,{sectionId:r,lineId:d}),f.read={sectionId:r,lineId:a.id}}vn(e,{sectionId:r,lineId:a.id}),In(e);let{activeInteraction:u}=dr(e,{sectionId:r,lineId:a.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},Ln=(e,t={})=>{let r=St({state:e});return!r||t.formKey&&t.formKey!==r.key||t.formId&&t.formId!==r.id?null:r},Ef=(e,t)=>{if(!t.variableId)throw new Error(`form field "${t.id}" requires variableId`);let r=e.projectData.resources?.variables?.[t.variableId],n=r?.scope,o=r?.type;if(Te(r))throw new Error(`Cannot update computed variable: ${t.variableId}`);if(r?.readonly===!0)throw new Error(`Cannot update readonly variable: ${t.variableId}`);return zt(n,t.variableId),qt(o,"set",t.variableId),{variableConfig:r,scope:n}},xf=(e,t)=>({id:e.id,key:e.key,valid:!0,values:T(t),fields:T(e.fields),fieldList:T(e.fieldList)}),vf=e=>{if(e.global.isLineCompleted)return;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=ye({state:e})?.pointer,r=t?.sectionId,n=t?.lineId;r&&n&&Qe(e,{sectionId:r,lineId:n})},Sf=({state:e},t={})=>{let r=Ln(e,t),n=t.field;if(!r?.fields?.[n])return e;let o=Bi(e,r.key),i=nr(t.value),s=r.fields[n],c=wn(s,i);return o.values[n]=i,o.touched[n]=!0,c?o.errors[n]=c:delete o.errors[n],e.global.pendingEffects.push({name:"render"}),e},Cf=({state:e},t={})=>{let r=Ln(e,t);if(!r)return{submitted:!1,valid:!1,reason:"inactive"};let n=Bi(e,r.key);n.submitted=!0;let o={},i={};if(Object.entries(r.fields).forEach(([f,d])=>{let p=Object.prototype.hasOwnProperty.call(n.values,f)?n.values[f]:d.value,h=wn(d,p);n.touched[f]=!0,h&&(i[f]=h),o[f]=Ui(d,p)}),n.errors=i,Object.keys(i).length>0)return e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!1,errors:T(i),form:{id:r.id,key:r.key,values:T(o)}};let s=e.contexts[e.contexts.length-1];if(s?.rollback?.isRestoring)return{submitted:!1,valid:!1,reason:"restoring"};let c=!1,a=[],l=[];Object.entries(r.fields).forEach(([f,d])=>{let{scope:p}=Ef(e,d),h=p==="context"?s.variables:e.global.variables,g=o[f];h[d.variableId]=Wt(h[d.variableId],"set",g),p==="context"&&(c=!0,l.push({variableId:d.variableId,op:"set",value:g})),(p==="device"||p==="account")&&a.push({scope:p,path:`variables.${d.variableId}`,op:"set",value:T(h[d.variableId])})}),c&&Ce(e,"updateVariable",{id:"submitForm",operations:l}),On(e,a);let u=xf(r,o);return vf(e),delete e.global.formDrafts[r.key],e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!0,form:u}},_f=({state:e},t={})=>{let r=Ln(e,t);return r?(delete e.global.formDrafts?.[r.key],e.global.pendingEffects.push({name:"render"}),{cancelled:!0,form:{id:r.id,key:r.key,values:T(r.values),fields:T(r.fields),fieldList:T(r.fieldList)}}):{cancelled:!1,reason:"inactive"}},Rf=({state:e},t)=>{let{id:r,operations:n=[]}=t;if(!r)throw new Error("updateVariable requires an id field");if(typeof r!="string"||!/^[a-zA-Z0-9]+$/.test(r))throw new Error(`updateVariable id must be alphanumeric, got: "${r}"`);let o=e.contexts[e.contexts.length-1];if(o?.rollback?.isRestoring)return e;let i=!1,s=[],c=[];return n.forEach(({variableId:a,op:l,value:u,roundTo:f})=>{let d=e.projectData.resources?.variables?.[a],p=d?.scope,h=d?.type;if(Te(d))throw new Error(`Cannot update computed variable: ${a}`);if(d?.readonly===!0)throw new Error(`Cannot update readonly variable: ${a}`);zt(p,a),qt(h,l,a),Fr(h,l,u,a,{roundTo:f});let g=p==="context"?o.variables:e.global.variables;if(p==="context"){i=!0;let y={variableId:a,op:l,value:u};f!==void 0&&(y.roundTo=f),c.push(y)}g[a]=Wt(g[a],l,u,{roundTo:f}),(p==="device"||p==="account")&&s.push({scope:p,path:`variables.${a}`,op:"set",value:T(g[a])})}),i&&Ce(e,"updateVariable",{id:r,operations:c}),On(e,s),e.global.pendingEffects.push({name:"render"}),e},Of=e=>(t,r)=>e({state:t},r),Lf=e=>({variables:gt({variables:{...e.global?.variables??{},...cr(e)?.variables??{}},runtime:He(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1}),runtime:He(e)}),$f=e=>{if(!D(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")},kf=(e,t,r)=>{if(!D(e))throw new Error(`conditional branch at index ${t} must be an object`);if(!D(e.actions))throw new Error(`conditional branch at index ${t} requires actions object`);if(!Object.prototype.hasOwnProperty.call(e,"when")&&t!==r-1)throw new Error("conditional else branch must be the last branch")},Df=(e,t)=>{$f(t);for(let r=0;r<t.branches.length;r+=1){let n=t.branches[r];if(kf(n,r,t.branches.length),!(Object.prototype.hasOwnProperty.call(n,"when")&&!mt(n.when,Lf(e)))){Object.entries(n.actions).forEach(([i,s])=>{fs(e,i,s)});return}}},Tf={conditional:{replayLine:Df},updateVariable:{recordSources:[En],replayLine:ki,replayRecorded:ki,persistInSaveSlot:!0},setNextLineConfig:{replayLine:Of(us)}},mr=e=>Tf[e]??null,Nf=e=>mr(e)?.persistInSaveSlot===!0,Pf=(e,t)=>{let r=mr(e)?.recordSources;return Array.isArray(r)&&r.includes(t)},Vf=(e,t,r)=>{mr(t)?.replayRecorded?.(e,r)},fs=(e,t,r)=>{mr(t)?.replayLine?.(e,r)},ds=({state:e},t)=>{let{offset:r}=t;if(r===void 0||typeof r!="number")return console.warn("selectLineIdByOffset requires a numeric offset"),null;let n=e.contexts[e.contexts.length-1];if(!n)return null;let o=n.rollback;if(!Array.isArray(o?.timeline)||typeof o?.currentIndex!="number")return null;let i=o.currentIndex+r;if(i<0||i>=o.timeline.length)return null;let s=o.timeline[i];return{sectionId:s.sectionId,lineId:s.lineId}},ps=({state:e})=>ds({state:e},{offset:-1})!==null,jf=({state:e},t)=>{let{offset:r=-1}=t;if(r>=0)throw new Error("rollbackByOffset requires a negative offset");let n=e.contexts?.[e.contexts.length-1];if(!n)return e;let o=Ze(n,{compatibilityAnchor:!n.rollback}),i=o.currentIndex+r;return i<0||i>=o.timeline.length?e:Ki(e,i)},Ff=({state:e},t)=>{let{sectionId:r,lineId:n}=t,o=e.contexts[e.contexts.length-1];if(!o)throw new Error("No context available for rollbackToLine");let i=Ze(o,{compatibilityAnchor:!o.rollback}),c=i.timeline.slice(0,i.currentIndex+1).findLastIndex(a=>a.sectionId===r&&a.lineId===n);if(c===-1)throw new Error(`Line ${n} not found in section ${r} rollback timeline`);return c===i.currentIndex?e:Ki(e,c)},hs=e=>{let t=yu(e);return mo(t,{selectPendingEffects:Iu,selectSkipMode:Ji,selectAutoMode:Au,selectIsChoiceVisible:es,selectIsFormVisible:Eu,selectActiveInteraction:be,selectActiveForm:St,selectDialogueUIHidden:Xi,selectDialogueHistory:Qi,selectConfirmDialog:wu,selectIsLineAccountViewed:Sn,selectIsResourceAccountViewed:Su,selectNextLineConfig:Cu,selectSystemState:_u,selectSaveSlotMap:ts,selectSaveSlots:Tu,selectSaveSlot:Ru,selectRuntime:Cn,selectRuntimeValue:Ou,selectAllVariables:lr,selectCurrentPointer:ye,selectSection:le,selectCurrentLine:ur,selectPresentationState:rs,selectAutoForwardTimerDelay:fr,selectPresentationChanges:$u,selectSectionLineChanges:Du,selectSaveSlotPage:_n,selectCurrentPageSlots:Nu,selectRenderState:Vu,selectOverlayStack:bu,selectLineIdByOffset:ds,selectCanRollback:ps,startAutoMode:os,stopAutoMode:pr,toggleAutoMode:Wu,startSkipMode:is,stopSkipMode:Xe,toggleSkipMode:Hu,showDialogueUI:hr,hideDialogueUI:ss,toggleDialogueUI:Yu,setDialogueTextSpeed:Gu,setAutoForwardDelay:Ku,setAutoForwardSpeed:Ju,setSkipUnseenText:Xu,setSkipTransitionsAndAnimations:Qu,setSoundVolume:Zu,setMusicVolume:ef,setMuteAll:tf,setSaveLoadPagination:rf,incrementSaveLoadPagination:nf,decrementSaveLoadPagination:of,setMenuPage:sf,setMenuEntryPoint:af,showConfirmDialog:ju,hideConfirmDialog:Fu,resetStoryAtSection:uf,clearPendingEffects:cf,appendPendingEffect:lf,beginRollbackActionBatch:pu,endRollbackActionBatch:hu,addViewedLine:df,addViewedResource:pf,setNextLineConfig:us,saveSlot:hf,loadSlot:mf,updateProjectData:gf,sectionTransition:Af,jumpToLine:yf,nextLine:bf,markLineCompleted:If,rollbackToLine:Ff,rollbackByOffset:jf,pushOverlay:Mu,popOverlay:Uu,replaceLastOverlay:Bu,clearOverlays:zu,updateFormField:Sf,submitForm:Cf,cancelForm:_f,updateVariable:Rf,nextLineFromSystem:wf},{transformActionFirstArgument:n=>({state:n}),transformSelectorFirstArgument:n=>({state:n})})};var Mf="route-engine",Uf="projectPersistence";var gs=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),ne=e=>Object.prototype.toString.call(e)==="[object Object]",ms="variables.",Bf=(e={})=>{let t=ne(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!ne(r)||typeof r.sectionId!="string"||r.sectionId.length===0?null:{sectionId:r.sectionId,...typeof r.lineId=="string"?{lineId:r.lineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(r=>typeof r=="string"||typeof r=="number"?{resourceId:String(r)}:!ne(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},zf=(e={})=>{let t=ne(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!ne(r)||typeof r.sectionId!="string"||r.sectionId.length===0?null:{sectionId:r.sectionId,...typeof r.lastLineId=="string"?{lastLineId:r.lastLineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(r=>typeof r=="string"||typeof r=="number"?{resourceId:String(r)}:!ne(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},qf=(e,t)=>{let r=zf(e),n=Bf(t),o=r.sections.map(s=>({...s})),i=r.resources.map(s=>({...s}));return n.sections.forEach(s=>{let c=o.find(a=>a.sectionId===s.sectionId);if(!c){o.push({sectionId:s.sectionId,...s.lineId===void 0?{}:{lastLineId:s.lineId}});return}if(c.lastLineId!==void 0){if(s.lineId===void 0){delete c.lastLineId;return}c.lastLineId=s.lineId}}),n.resources.forEach(s=>{i.find(a=>a.resourceId===s.resourceId)||i.push({...s})}),{sections:o,resources:i}},ys=(e={})=>{let t=ne(e)?e:{};return{saveSlots:ne(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:ne(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:ne(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:ne(t.globalRuntime)?t.globalRuntime:{},accountViewedRegistry:ne(t.accountViewedRegistry)?t.accountViewedRegistry:{}}},Wf=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((t,r)=>{if(!ne(t))throw new Error(`Malformed applyScopedDataUpdates.updates[${r}] entry.`);let n=t.path?.startsWith(ms)?t.path.slice(ms.length):null;if(n!==null){if(!["device","account"].includes(t.scope))throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${r}].`);if(n.length===0)throw new Error(`Malformed applyScopedDataUpdates path "${t.path}" at updates[${r}].`);if(t.op!=="set")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${r}].`);return{scope:t.scope,path:t.path,op:t.op,value:t.value,variableId:n}}if(t.path==="viewedRegistry"){if(t.scope!=="account")throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${r}].`);if(t.op!=="markViewed")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${r}].`);return t}throw typeof t.path!="string"?new Error(`Malformed applyScopedDataUpdates path at updates[${r}].`):new Error(`Unsupported applyScopedDataUpdates path "${t.path}" at updates[${r}].`)})},Hf=(e,t)=>{let r={};return Wf(t).forEach(n=>{if(n.path==="viewedRegistry"){r.accountViewedRegistry=qf(r.accountViewedRegistry??e.accountViewedRegistry,n.value);return}let o=n.scope==="device"?"globalDeviceVariables":"globalAccountVariables";r[o]={...e[o],...r[o],[n.variableId]:n.value}}),r},$n=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},Yf=e=>{let t=$n(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},Gf=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},Kf=({indexedDB:e,databaseName:t,objectStoreName:r})=>new Promise((n,o)=>{let i=e.open(t,1);i.onupgradeneeded=()=>{let s=i.result;s.objectStoreNames.contains(r)||s.createObjectStore(r,{keyPath:"namespace"})},i.onsuccess=()=>{n(i.result)},i.onerror=()=>{o(i.error??new Error(`Failed to open IndexedDB database "${t}".`))}}),Jf=async({databasePromise:e,objectStoreName:t,namespace:r})=>{let n=await e;return new Promise((o,i)=>{let a=n.transaction(t,"readonly").objectStore(t).get(r);a.onsuccess=()=>{o(a.result??null)},a.onerror=()=>{i(a.error??new Error(`Failed to read persisted namespace "${r}" from IndexedDB.`))}})},_t=async({databasePromise:e,objectStoreName:t,namespace:r,patch:n})=>{let o=await e;return new Promise((i,s)=>{let c=o.transaction(t,"readwrite"),a=c.objectStore(t),l=a.get(r),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 "${r}" before updating IndexedDB.`))},l.onsuccess=()=>{let p=ys(l.result),h=typeof n=="function"?n(p):n,g={namespace:r,version:1,...gs(),...p,...h},y=a.put(g);y.onerror=()=>{f(y.error??new Error(`Failed to persist namespace "${r}" to IndexedDB.`))}},c.oncomplete=()=>{d()},c.onerror=()=>{f(c.error??new Error(`IndexedDB transaction failed while updating namespace "${r}".`))},c.onabort=()=>{f(c.error??new Error(`IndexedDB transaction aborted while updating namespace "${r}".`))}})},Xf=async({databasePromise:e,objectStoreName:t,namespace:r})=>{let n=await e;return new Promise((o,i)=>{let s=n.transaction(t,"readwrite"),a=s.objectStore(t).delete(r),l=!1,u=d=>{l||(l=!0,i(d))},f=()=>{l||(l=!0,o())};a.onerror=()=>{u(a.error??new Error(`Failed to clear persisted namespace "${r}" from IndexedDB.`))},s.oncomplete=()=>{f()},s.onerror=()=>{u(s.error??new Error(`IndexedDB transaction failed while clearing namespace "${r}".`))},s.onabort=()=>{u(s.error??new Error(`IndexedDB transaction aborted while clearing namespace "${r}".`))}})},kn=(e={})=>{let{indexedDB:t,databaseName:r=Mf,objectStoreName:n=Uf,namespace:o}=e,i=Gf(t),s=Yf(o),c=Kf({indexedDB:i,databaseName:r,objectStoreName:n});return{namespace:s,load:async()=>{let a=await Jf({databasePromise:c,objectStoreName:n,namespace:s});return{...gs(),...ys(a)}},clear:async()=>Xf({databasePromise:c,objectStoreName:n,namespace:s}),saveSlots:async a=>_t({databasePromise:c,objectStoreName:n,namespace:s,patch:{saveSlots:ne(a)?a:{}}}),saveGlobalDeviceVariables:async a=>_t({databasePromise:c,objectStoreName:n,namespace:s,patch:{globalDeviceVariables:ne(a)?a:{}}}),saveGlobalAccountVariables:async a=>_t({databasePromise:c,objectStoreName:n,namespace:s,patch:{globalAccountVariables:ne(a)?a:{}}}),saveGlobalRuntime:async a=>_t({databasePromise:c,objectStoreName:n,namespace:s,patch:{globalRuntime:ne(a)?a:{}}}),applyScopedDataUpdates:async a=>_t({databasePromise:c,objectStoreName:n,namespace:s,patch:l=>Hf(l,a)})}},Qf=kn;var Zf=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),ed=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),bs="conditional",Dn="form",td=new Set(["submitForm","cancelForm"]),Rt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function Tn(e){let t,r=0,n=null,o=new Map,i=new Map,s=new Map,{handlePendingEffects:c}=e,a=(I=new Map,S=Date.now())=>new Map(Array.from(I.entries()).filter(([,R])=>S<R.expiresAt).map(([R,F])=>[R,{animation:structuredClone(F.animation),startedAt:F.startedAt,expiresAt:F.expiresAt}])),l=(I=new Map)=>Array.from(I.values()).map(S=>structuredClone(S.animation)),u=(I=Date.now())=>{o=new Map(Array.from(o.entries()).filter(([,S])=>I<S.expiresAt))},f=()=>{for(;t.selectPendingEffects().length>0;){let I=[...t.selectPendingEffects()];t.clearPendingEffects();try{c(I)}catch(S){throw t.clearPendingEffects(),I.forEach(R=>{t.appendPendingEffect(R)}),S}}},d=({initialState:I,namespace:S})=>{t=hs(I),r=0,n=$n(S),o=new Map,i=new Map,s=new Map,t.appendPendingEffect({name:"handleLineActions"}),f()},p=()=>n,h=()=>t.selectPresentationState(),g=()=>t.selectPresentationChanges(),y=I=>t.selectSectionLineChanges(I),b=(I={})=>{r+=1;let S=Date.now();u(S);let R=i.size>0,F=a(o,S),B=R?a(i,S):new Map,ve={...t.selectRenderState({activePersistentAnimations:l(F),restoredPersistentAnimations:l(B)}),id:`render-${r}`};return s.set(ve.id,{builtAt:S,persistentAnimationSessions:new Map([...B.entries(),...F.entries()]),usedRestoredPersistentAnimationSessions:R}),ve},A=(I={})=>b(I),x=(I={})=>b(I),C=I=>{let S=typeof I?.id=="string"&&I.id.length>0?I.id:null,R=S?s.get(S):null;S&&s.delete(S);let F=new Map;Yo(I?.animations).forEach(B=>{let he=Xt(B);if(!he)return;let ve=R?.persistentAnimationSessions?.get(he)??o.get(he),Ot=Math.max(0,Ko(B)),Pn=ve?.startedAt??R?.builtAt??Date.now();F.set(he,{animation:structuredClone(B),startedAt:Pn,expiresAt:Pn+Ot})}),o=F,R?.usedRestoredPersistentAnimationSessions&&(i=new Map)},N=()=>t.selectSystemState(),k=()=>t.selectSaveSlotMap(),w=I=>t.selectSaveSlot(I),j=I=>t.selectSaveSlotPage(I),M=()=>t.selectSkipMode(),ee=()=>t.selectAutoMode(),P=()=>t.selectRuntime(),W=()=>t.selectIsChoiceVisible(),H=()=>t.selectIsFormVisible(),te=()=>t.selectActiveInteraction(),xe=(I,S,R={})=>!Rt(S)||I!=="nextLine"?S:R.bypassChoice===!0?{...S,bypassChoice:!0}:R.interactionSource===Dn?{...S,_interactionSource:Dn}:S,G=(I,S)=>{if(!t[I])return;Zf.has(I)&&(ed.has(I)?i=a(o):i=new Map,o=new Map);let R=t[I](S);return f(),R},K=(I,S,R,F={})=>{if(I===bs){let B=re(R),he=Br({[I]:S},B);se(he[I],R,F);return}G(I,S)},oe=(I,S)=>{K(I,S)},re=I=>{if(!I)return{variables:t.selectAllVariables?t.selectAllVariables():void 0,runtime:t.selectRuntime?t.selectRuntime():{}};if(Object.prototype.hasOwnProperty.call(I,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:S,...R}=I,F=t.selectAllVariables?t.selectAllVariables():void 0;return{...R,_event:S,variables:F,runtime:t.selectRuntime?t.selectRuntime():{}}},J=I=>{if(!Rt(I))throw new Error("conditional action payload must be an object");if(!Array.isArray(I.branches))throw new Error("conditional action requires branches array");if(I.branches.length===0)throw new Error("conditional action requires at least one branch")},ie=(I,S,R)=>{if(!Rt(I))throw new Error(`conditional branch at index ${S} must be an object`);if(!Rt(I.actions))throw new Error(`conditional branch at index ${S} requires actions object`);if(!Object.prototype.hasOwnProperty.call(I,"when")&&S!==R-1)throw new Error("conditional else branch must be the last branch")},se=(I,S,R)=>{J(I);for(let F=0;F<I.branches.length;F+=1){let B=I.branches[F];ie(B,F,I.branches.length);let he=re(S);if(!(Object.prototype.hasOwnProperty.call(B,"when")&&!mt(B.when,he))){X(B.actions,S,R);return}}},v=(I,S)=>({...I??{},_form:S}),_=(I,S,R,F)=>{let B=G(I,S),he=B?.submitted===!0&&B.valid===!0,ve=B?.cancelled===!0;!he&&!ve||Rt(S.actions)&&X(S.actions,v(R,B.form),{...F,interactionSource:Dn})},V=(I,S,R,F)=>{let B=re(R),ve=Br({[I]:S},B)[I];if(I===bs){se(ve,R,F);return}let Ot=xe(I,ve,F);if(td.has(I)){_(I,Ot,R,F);return}G(I,Ot)},X=(I,S,R)=>{Object.entries(I).forEach(([F,B])=>{V(F,B,S,R)})},z=(I,S,R={})=>{t.beginRollbackActionBatch({source:R.rollbackSource});try{X(I,S,R)}finally{t.endRollbackActionBatch({})}};return{init:d,handleAction:K,handleInternalAction:oe,handleActions:z,selectRenderState:A,prepareRenderState:x,commitRenderState:C,selectPresentationState:h,selectPresentationChanges:g,selectSectionLineChanges:y,selectSystemState:N,selectSaveSlotMap:k,selectSaveSlot:w,selectSaveSlotPage:j,selectSaveSlots:k,selectRuntime:P,selectIsChoiceVisible:W,selectIsFormVisible:H,selectActiveInteraction:te,handleLineActions:()=>{let I=t.selectCurrentLine();return I?.actions?(z(I.actions,void 0,{rollbackSource:"line"}),!0):!1},getNamespace:p}}var Nn=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:r=>{e=r},addElapsed:r=>{e+=r},getCallback:()=>t,setCallback:r=>{t=r}}},rd=80,As=({engine:e,routeGraphics:t,trackRenderDispatch:r},n)=>{let o=e.prepareRenderState?.(n)??e.selectRenderState(n);r?.(o),t.render(o),e.commitRenderState?.(o)},nd=({engine:e,routeGraphics:t,trackRenderDispatch:r,getRenderDispatchCount:n},o)=>{let i=n?.()??0,s=e.handleLineActions();(n?.()??0)===i&&As({engine:e,routeGraphics:t,trackRenderDispatch:r},o)},od=({engine:e,ticker:t,autoTimer:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let c=n.delay??1e3;r.getElapsed()>=c&&(t.remove(i),r.setCallback(null),r.setElapsed(0),gr(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},id=({ticker:e,autoTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},sd=({engine:e,ticker:t,skipTimer:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let c=n?.delay??rd;r.getElapsed()>=c&&(r.setElapsed(0),gr(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},ad=({ticker:e,skipTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},cd=({engine:e,ticker:t,nextLineConfigTimerState:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let c=n.delay??1e3;r.getElapsed()>=c&&(r.setElapsed(0),gr(e,"nextLineFromSystem",{}),t.remove(i),r.setCallback(null))};r.setCallback(i),t.add(i)},ld=({ticker:e,nextLineConfigTimerState:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},ud=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveSlots(t?.saveSlots))},fd=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalDeviceVariables(t?.globalDeviceVariables))},dd=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalAccountVariables(t?.globalAccountVariables))},pd=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalRuntime(t?.globalRuntime))},hd=({enqueuePersistenceWrite:e},t)=>{e(r=>{if(typeof r.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return r.applyScopedDataUpdates(t?.updates)})},Is={render:As,saveSlots:ud,saveGlobalDeviceVariables:fd,saveGlobalAccountVariables:dd,saveGlobalRuntime:pd,applyScopedDataUpdates:hd,handleLineActions:nd,startAutoNextTimer:od,clearAutoNextTimer:id,startSkipNextTimer:sd,clearSkipNextTimer:ad,nextLineConfigTimer:cd,clearNextLineConfigTimer:ld},md=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),gr=(e,t,r)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,r)},gd=(e=[])=>{let t=new Set,r=[];for(let n=e.length-1;n>=0;n-=1){let o=e[n];if(typeof o?.name!="string"||o.name.length===0)throw new Error("Pending effect is missing a valid name.");if(!md.has(o.name)){r.unshift(o);continue}t.has(o.name)||(t.add(o.name),r.unshift(o))}return r},yd=({getEngine:e,routeGraphics:t,ticker:r,handleUnhandledEffect:n,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:c})=>{let a=Nn(),l=Nn(),u=Nn(),f=s??null,d=Promise.resolve(),p=null,h=null,g=!1,y=0,b=v=>{if(o){o(v);return}console.error("RouteEngine persistence write failed.",v)},A=()=>{if(f)return f;let v=e();return f=kn({indexedDB:i,namespace:c??v?.getNamespace?.()}),f},x=v=>{d=d.catch(()=>{}).then(()=>{let _=A();return v(_)}).catch(_=>{b(_)})},C=v=>{let _=typeof v?.id=="string"&&v.id.length>0?v.id:null;y+=1,p=_,g=!1},N=()=>y,k=(v={})=>{if(v?.aborted===!0)return!1;let _=typeof v?.id=="string"&&v.id.length>0?v.id:null;return _?_!==p||_===h?!1:(h=_,!0):p!==null||g?!1:(g=!0,!0)},w=(v,_={})=>{if(v!=="renderComplete"||!k(_))return!1;let V=e();return gr(V,"markLineCompleted",{}),!0},j=new Set(["updateFormField","submitForm","cancelForm"]),M=new Set(["updateVariable"]),ee=v=>typeof v?.selectActiveInteraction=="function"?v.selectActiveInteraction():typeof v?.selectIsChoiceVisible=="function"&&v.selectIsChoiceVisible()?{source:"choice"}:null,P=v=>v?._formKey??v?.formKey,W=(v,_)=>P(v)===_?.formKey,H=(v,_)=>!v||typeof v!="object"||Array.isArray(v)?!1:v._interactionSource===_?.source,te=(v,_)=>H(v,_)?_.source==="form"?W(v,_):!0:!1,xe=(v,_)=>!v||typeof v!="object"||Array.isArray(v)||_?.source!=="form"?!1:W(v,_),G=(v={})=>Object.keys(v).some(_=>j.has(_)),K=(v={},_)=>Object.entries(v).some(([V,X])=>j.has(V)&&xe(X,_)),oe=(v={})=>Object.keys(v).length>0&&Object.keys(v).every(_=>M.has(_)),re=(v={},_)=>{let V=v?.actions;return _?.source==="form"?!V||typeof V!="object"||Array.isArray(V)?!1:K(V,_)?!0:G(V)?!1:oe(V):te(v,_)?!0:!V||typeof V!="object"||Array.isArray(V)?!1:Object.values(V).some(X=>te(X,_))},J=(v,_={})=>{if(!_?.actions)return!1;let V=ee(v);return!V||V.source==="choice"?!1:!re(_,V)},ie=({preprocessPayload:v,onEvent:_}={})=>async(V,X={})=>{let z=e();if(J(z,X))return _?.(V,X);let Q=await v?.(V,X)??X;if(J(z,Q))return _?.(V,Q);if(w(V,Q),Q?.actions){let I=Q?._event?{_event:Q._event}:Q?.event?{_event:Q.event}:void 0,S;Q?.bypassChoice===!0?S={bypassChoice:!0}:Q?._interactionSource&&(S={interactionSource:Q._interactionSource}),S?z.handleActions(Q.actions,I,S):z.handleActions(Q.actions,I)}return _?.(V,Q)},se=v=>{let _=e(),V=gd(v);V.forEach(z=>{if(!Is[z.name]&&!n)throw new Error(`Unhandled pending effect "${z.name}".`)});let X={engine:_,routeGraphics:t,ticker:r,autoTimer:a,skipTimer:l,nextLineConfigTimerState:u,trackRenderDispatch:C,getRenderDispatchCount:N,enqueuePersistenceWrite:x};for(let z of V){let Q=Is[z.name];if(Q){Q(X,z.payload);continue}n(z,X)}};return se.handleRouteGraphicsEvent=w,se.createRouteGraphicsEventHandler=ie,se},bd=yd;var Id=(e,t={})=>{let{resources:r={}}=t;return pn(e,r)};var Jp=Tn;export{Hr as DEFAULT_VISUAL_LAYER,ot as RENDER_LAYER,_e as VISUAL_LAYER,bd as createEffectsHandler,Qf as createIndexedDbPersistence,Jp as default,Ra as resolveComputedVariables,Id as resolveLayoutReferences};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "route-engine-js",
3
- "version": "1.27.0",
3
+ "version": "1.29.0",
4
4
  "description": "A lightweight Visual Novel engine built in JavaScript for creating interactive narrative games with branching storylines",
5
5
  "repository": {
6
6
  "type": "git",
@@ -50,7 +50,8 @@
50
50
  "immer": "^10.1.1",
51
51
  "jempl": "1.1.1",
52
52
  "js-yaml": "^4.1.0",
53
- "puty": "^0.1.1"
53
+ "puty": "^0.1.1",
54
+ "unicode-segmenter": "^0.17.0"
54
55
  },
55
56
  "devDependencies": {
56
57
  "@vitest/coverage-v8": "4.0.16",