route-engine-js 0.6.0 → 0.7.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 Gn=Object.defineProperty;var Xn=(e,t)=>{for(var n in t)Gn(e,n,{get:t[n],enumerable:!0})};var Mt=Symbol.for("immer-nothing"),Tt=Symbol.for("immer-draftable"),O=Symbol.for("immer-state");function D(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var oe=Object.getPrototypeOf;function B(e){return!!e&&!!e[O]}function H(e){return e?jt(e)||Array.isArray(e)||!!e[Tt]||!!e.constructor?.[Tt]||ve(e)||Ee(e):!1}var Zn=Object.prototype.constructor.toString();function jt(e){if(!e||typeof e!="object")return!1;let t=oe(e);if(t===null)return!0;let n=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return n===Object?!0:typeof n=="function"&&Function.toString.call(n)===Zn}function Ie(e,t){xe(e)===0?Reflect.ownKeys(e).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function xe(e){let t=e[O];return t?t.type_:Array.isArray(e)?1:ve(e)?2:Ee(e)?3:0}function Ue(e,t){return xe(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function zt(e,t,n){let r=xe(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function Qn(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function ve(e){return e instanceof Map}function Ee(e){return e instanceof Set}function Y(e){return e.copy_||e.base_}function We(e,t){if(ve(e))return new Map(e);if(Ee(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let n=jt(e);if(t===!0||t==="class_only"&&!n){let r=Object.getOwnPropertyDescriptors(e);delete r[O];let o=Reflect.ownKeys(r);for(let i=0;i<o.length;i++){let s=o[i],a=r[s];a.writable===!1&&(a.writable=!0,a.configurable=!0),(a.get||a.set)&&(r[s]={configurable:!0,writable:!0,enumerable:a.enumerable,value:e[s]})}return Object.create(oe(e),r)}else{let r=oe(e);if(r!==null&&n)return{...e};let o=Object.create(r);return Object.assign(o,e)}}function Ke(e,t=!1){return _e(e)||B(e)||!H(e)||(xe(e)>1&&(e.set=e.add=e.clear=e.delete=er),Object.freeze(e),t&&Object.entries(e).forEach(([n,r])=>Ke(r,!0))),e}function er(){D(2)}function _e(e){return Object.isFrozen(e)}var tr={};function J(e){let t=tr[e];return t||D(0,e),t}var ce;function Bt(){return ce}function nr(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function Pt(e,t){t&&(J("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Ye(e){He(e),e.drafts_.forEach(rr),e.drafts_=null}function He(e){e===ce&&(ce=e.parent_)}function Nt(e){return ce=nr(ce,e)}function rr(e){let t=e[O];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function Vt(e,t){t.unfinalizedDrafts_=t.drafts_.length;let n=t.drafts_[0];return e!==void 0&&e!==n?(n[O].modified_&&(Ye(t),D(4)),H(e)&&(e=we(t,e),t.parent_||Ae(t,e)),t.patches_&&J("Patches").generateReplacementPatches_(n[O].base_,e,t.patches_,t.inversePatches_)):e=we(t,n,[]),Ye(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Mt?e:void 0}function we(e,t,n){if(_e(t))return t;let r=t[O];if(!r)return Ie(t,(o,i)=>Dt(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Ae(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;let o=r.copy_,i=o,s=!1;r.type_===3&&(i=new Set(o),o.clear(),s=!0),Ie(i,(a,c)=>Dt(e,r,o,a,c,n,s)),Ae(e,o,!1),n&&e.patches_&&J("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function Dt(e,t,n,r,o,i,s){if(B(o)){let a=i&&t&&t.type_!==3&&!Ue(t.assigned_,r)?i.concat(r):void 0,c=we(e,o,a);if(zt(n,r,c),B(c))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if(H(o)&&!_e(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;we(e,o),(!t||!t.scope_.parent_)&&typeof r!="symbol"&&Object.prototype.propertyIsEnumerable.call(n,r)&&Ae(e,o)}}function Ae(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&Ke(t,n)}function or(e,t){let n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:Bt(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=r,i=Ge;n&&(o=[r],i=ae);let{revoke:s,proxy:a}=Proxy.revocable(o,i);return r.draft_=a,r.revoke_=s,a}var Ge={get(e,t){if(t===O)return e;let n=Y(e);if(!Ue(n,t))return ir(e,n,t);let r=n[t];return e.finalized_||!H(r)?r:r===Be(e.base_,t)?(Fe(e),e.copy_[t]=qe(r,e)):r},has(e,t){return t in Y(e)},ownKeys(e){return Reflect.ownKeys(Y(e))},set(e,t,n){let r=Ft(Y(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){let o=Be(Y(e),t),i=o?.[O];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(Qn(n,o)&&(n!==void 0||Ue(e.base_,t)))return!0;Fe(e),Je(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return Be(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,Fe(e),Je(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let n=Y(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){D(11)},getPrototypeOf(e){return oe(e.base_)},setPrototypeOf(){D(12)}},ae={};Ie(Ge,(e,t)=>{ae[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});ae.deleteProperty=function(e,t){return ae.set.call(this,e,t,void 0)};ae.set=function(e,t,n){return Ge.set.call(this,e[0],t,n,e[0])};function Be(e,t){let n=e[O];return(n?Y(n):e)[t]}function ir(e,t,n){let r=Ft(t,n);return r?"value"in r?r.value:r.get?.call(e.draft_):void 0}function Ft(e,t){if(!(t in e))return;let n=oe(e);for(;n;){let r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=oe(n)}}function Je(e){e.modified_||(e.modified_=!0,e.parent_&&Je(e.parent_))}function Fe(e){e.copy_||(e.copy_=We(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var sr=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){let i=n;n=t;let s=this;return function(c=i,...l){return s.produce(c,u=>n.call(this,u,...l))}}typeof n!="function"&&D(6),r!==void 0&&typeof r!="function"&&D(7);let o;if(H(t)){let i=Nt(this),s=qe(t,void 0),a=!0;try{o=n(s),a=!1}finally{a?Ye(i):He(i)}return Pt(i,r),Vt(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===Mt&&(o=void 0),this.autoFreeze_&&Ke(o,!0),r){let i=[],s=[];J("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else D(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...a)=>this.produceWithPatches(s,c=>t(c,...a));let r,o;return[this.produce(t,n,(s,a)=>{r=s,o=a}),r,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){H(e)||D(8),B(e)&&(e=Xe(e));let t=Nt(this),n=qe(e,void 0);return n[O].isManual_=!0,He(t),n}finishDraft(e,t){let n=e&&e[O];(!n||!n.isManual_)&&D(9);let{scope_:r}=n;return Pt(r,t),Vt(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){let o=t[n];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}n>-1&&(t=t.slice(n+1));let r=J("Patches").applyPatches_;return B(e)?r(e,t):this.produce(e,o=>r(o,t))}};function qe(e,t){let n=ve(e)?J("MapSet").proxyMap_(e,t):Ee(e)?J("MapSet").proxySet_(e,t):or(e,t);return(t?t.scope_:Bt()).drafts_.push(n),n}function Xe(e){return B(e)||D(10,e),Ut(e)}function Ut(e){if(!H(e)||_e(e))return e;let t=e[O],n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=We(e,t.scope_.immer_.useStrictShallowCopy_)}else n=We(e,!0);return Ie(n,(r,o)=>{zt(n,r,Ut(o))}),t&&(t.finalized_=!1),n}var T=new sr,Ze=T.produce,Hi=T.produceWithPatches.bind(T),Ji=T.setAutoFreeze.bind(T),qi=T.setUseStrictShallowCopy.bind(T),Ki=T.applyPatches.bind(T),Gi=T.createDraft.bind(T),Xi=T.finishDraft.bind(T);var p={LITERAL:0,VARIABLE:1,INTERPOLATION:2,FUNCTION:3,BINARY:4,UNARY:5,CONDITIONAL:6,LOOP:7,OBJECT:8,ARRAY:9,PARTIAL:10,PATH_REFERENCE:11},L={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},ue={NOT:0};var v=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},S=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var Qe=e=>{if(!e||e.trim()==="")throw new v("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let n=e.includes("===")?"==":"!=";throw new v(`Invalid comparison operator '${e.includes("===")?"===":"!=="}' - did you mean '${n}'? (got: '${e}')`)}let t=["<",">","<=",">=","==","!="];for(let n of t)if(e.trim().endsWith(n))throw new v(`Incomplete comparison expression - missing right operand (got: '${e}')`)},Wt=e=>{if(e.trim().endsWith(" in"))throw new v(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new v(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,n]=e.split(" in ");if(!n||n.trim()==="")throw new v(`Missing iterable expression after 'in' (got: '$for ${e}')`);let r=t.includes(",")?t.split(",").map(o=>o.trim()):[t.trim()];for(let o of r){if(!o)throw new v(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new v(`Invalid loop syntax (got: '$for ${e}')`)}};var Yt=(e,t,n=!1)=>{if(t===null)return new S(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new S(`Cannot iterate over undefined value at '$for ${e}'`);let r=typeof t;return n?new S(`Cannot iterate over non-array value in loop '${e}' - got ${r} instead`):new S(`Cannot iterate over non-array value (got: ${r}) at '$for ${e}'`)},Ht=(e,t)=>{let n=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new S(`Unknown function '${e}' (${n})`)};var lr=(e,t,n={})=>{let r={},o={};n&&typeof n=="object"&&(n.functions!==void 0||n.partials!==void 0?(r=n.functions||{},o=n.partials||{}):typeof n=="object"&&(r=n));let s=_(e,{functions:r,partials:o},t,{});return s===void 0?{}:s},_=(e,t,n,r)=>{let o=t.functions||t;if(e.var&&!e.type)return C(e.var,n,r);if(e.type===p.LITERAL)return e.value;if(e.type===p.VARIABLE)return C(e.path,n,r);if(e.type===p.INTERPOLATION)return ar(e.parts,t,n,r);switch(e.type){case p.FUNCTION:return qt(e,t,n,r);case p.BINARY:return Kt(e,t,n,r);case p.UNARY:return Gt(e,t,n,r);case p.CONDITIONAL:return fr(e,t,n,r);case p.LOOP:return yr(e,t,n,r);case p.OBJECT:return br(e,t,n,r);case p.ARRAY:return Ir(e,t,n,r);case p.PARTIAL:return wr(e,t,n,r);case p.PATH_REFERENCE:return Ar(e,t,n,r);default:throw new Error(`Unknown node type: ${e.type}`)}},Jt=new Map,cr=e=>{let t=[],n="",r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(i==="[")n&&(t.push({type:"property",value:n}),n=""),r=!0;else if(i==="]"){if(r&&n){let s=n.trim();if(/^\d+$/.test(s))t.push({type:"index",value:parseInt(s,10)});else if(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'")){let a=s.slice(1,-1);t.push({type:"property",value:a})}else t.push({type:"property",value:s});n=""}r=!1}else n+=i}return n&&t.push({type:"property",value:n}),t},C=(e,t,n)=>{if(!e)return;if(e in n)return n[e];let r=Jt.get(e);if(!r){let i=[],s="",a=0;for(let c=0;c<e.length;c++){let l=e[c];l==="["?(a++,s+=l):l==="]"?(a--,s+=l):l==="."&&a===0?s&&(i.push(s),s=""):s+=l}s&&i.push(s),r=[];for(let c of i){let l=cr(c.trim());r.push(...l)}Jt.set(e,r)}let o=t;for(let i=0;i<r.length;i++){let s=r[i];if(s.type==="property"&&s.value in n){o=n[s.value];continue}if(o==null)return;(s.type==="property"||s.type==="index")&&(o=o[s.value])}return o},ar=(e,t,n,r)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=_(i,t,n,r);o.push(s!=null?String(s):"")}return o.join("")},qt=(e,t,n,r)=>{let o=t.functions||t,i=o[e.name];if(!i)throw Ht(e.name,o);let s=e.args.map(a=>_(a,t,n,r));return i(...s)},ie=(e,t,n,r)=>{if(e.var&&!e.type)return C(e.var,n,r);switch(e.type){case p.VARIABLE:return C(e.path,n,r);case p.LITERAL:return e.value;case p.BINARY:return Kt(e,t,n,r);case p.UNARY:return Gt(e,t,n,r);case p.FUNCTION:return qt(e,t,n,r);default:return _(e,t,n,r)}},Kt=(e,t,n,r)=>{if(e.op===L.AND||e.op===L.OR){let s=ie(e.left,t,n,r),a=ie(e.right,t,n,r);switch(e.op){case L.AND:return s&&a;case L.OR:return s||a}}let o=_(e.left,t,n,r),i=_(e.right,t,n,r);switch(e.op){case L.EQ:return o==i;case L.NEQ:return o!=i;case L.GT:return o>i;case L.LT:return o<i;case L.GTE:return o>=i;case L.LTE:return o<=i;case L.IN:return Array.isArray(i)?i.includes(o):!1;case L.ADD:if(typeof o!="number"||typeof i!="number")throw new S(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case L.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new S(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},Gt=(e,t,n,r)=>{let o=e.op===ue.NOT?ie(e.operand,t,n,r):_(e.operand,t,n,r);if(e.op===ue.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},ur=(e,t,n,r)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===p.VARIABLE)if(C(o.path,n,r)){let s=e.bodies[0];if(s.type===p.OBJECT&&s.properties.length<=5){let a={};for(let c of s.properties){let l=c.parsedKey?_(c.parsedKey,t,n,r):c.key,u=c.value;if(u.type===p.LITERAL)a[l]=u.value;else if(u.type===p.VARIABLE)a[l]=C(u.path,n,r);else if(u.type===p.INTERPOLATION){let f=[];for(let d of u.parts)if(typeof d=="string")f.push(d);else if(d.type===p.VARIABLE){let h=C(d.path,n,r);f.push(h!=null?String(h):"")}else{let h=_(d,t,n,r);f.push(h!=null?String(h):"")}a[l]=f.join("")}else a[l]=_(u,t,n,r)}return a}}else{let s=e.bodies[1];if(s.type===p.OBJECT&&s.properties.length<=5){let a={};for(let c of s.properties){let l=c.parsedKey?_(c.parsedKey,t,n,r):c.key,u=c.value;if(u.type===p.LITERAL)a[l]=u.value;else if(u.type===p.VARIABLE)a[l]=C(u.path,n,r);else if(u.type===p.INTERPOLATION){let f=[];for(let d of u.parts)if(typeof d=="string")f.push(d);else if(d.type===p.VARIABLE){let h=C(d.path,n,r);f.push(h!=null?String(h):"")}else{let h=_(d,t,n,r);f.push(h!=null?String(h):"")}a[l]=f.join("")}else a[l]=_(u,t,n,r)}return a}}}return null},fr=(e,t,n,r)=>{let o=ur(e,t,n,r);if(o!==null)return o;for(let i=0;i<e.conditions.length;i++){let s=e.conditions[i];if(s===null||ie(s,t,n,r))return _(e.bodies[i],t,n,r)}return Xt},dr=(e,t)=>{let n=e.body,r=e.itemVar;if(n.type===p.CONDITIONAL&&n.conditions.length===1&&n.conditions[0].type===p.VARIABLE){let o=n.conditions[0].path,i=n.bodies[0];if(o.startsWith(r+".")){let s=o.substring(r.length+1);if(i.type===p.OBJECT&&i.properties.length<=5){for(let c of i.properties)if(c.parsedKey)return null;let a=[];for(let c=0;c<t.length;c++){let l=t[c];if(l[s]){let u={};for(let f of i.properties){let d=f.key,h=f.value;if(h.type===p.LITERAL)u[d]=h.value;else if(h.type===p.VARIABLE){let y=h.path;if(y===r)u[d]=l;else if(y.startsWith(r+".")){let g=y.substring(r.length+1);u[d]=l[g]}else return null}else if(h.type===p.INTERPOLATION){let y=[],g=!0;for(let I of h.parts)if(typeof I=="string")y.push(I);else if(I.type===p.VARIABLE){let m=I.path;if(m===r)y.push(l!=null?String(l):"");else if(m.startsWith(r+".")){let b=m.substring(r.length+1),A=l[b];y.push(A!=null?String(A):"")}else{g=!1;break}}else{g=!1;break}if(!g)return null;u[d]=y.join("")}else return null}a.push(u)}}return a}}}return null},pr=(e,t)=>{let n=e.body,r=e.itemVar,o=dr(e,t);if(o!==null)return o;if(n.type===p.OBJECT&&n.properties.length<=5&&!n.whenCondition){for(let a of n.properties)if(a.parsedKey)return null;let i=[],s=!0;for(let a of n.properties){let c=a.key,l=a.value;if(l.type===p.LITERAL)i.push({key:c,type:"literal",value:l.value});else if(l.type===p.VARIABLE){let u=l.path;if(u===r)i.push({key:c,type:"item"});else if(u.startsWith(r+".")){let f=u.substring(r.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:c,type:"prop",prop:f});else{s=!1;break}}else{s=!1;break}}else if(l.type===p.INTERPOLATION&&l.parts.length===1){let u=l.parts[0];if(u.type===p.VARIABLE){let f=u.path;if(f===r)i.push({key:c,type:"item_string"});else if(f.startsWith(r+".")){let d=f.substring(r.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:c,type:"prop_string",prop:d});else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}if(s){let a=new Array(t.length);if(i.length===3&&i[0].type==="prop"&&i[0].key==="id"&&i[1].type==="prop_string"&&i[1].key==="title"&&i[2].type==="prop"&&i[2].key==="completed")for(let c=0;c<t.length;c++){let l=t[c];a[c]={id:l.id,title:l.title!=null?String(l.title):"",completed:l.completed}}else for(let c=0;c<t.length;c++){let l=t[c],u={};for(let f of i)if(f.type==="literal")u[f.key]=f.value;else if(f.type==="item")u[f.key]=l;else if(f.type==="prop")u[f.key]=l[f.prop];else if(f.type==="item_string")u[f.key]=l!=null?String(l):"";else if(f.type==="prop_string"){let d=l[f.prop];u[f.key]=d!=null?String(d):""}a[c]=u}return a}}return null},hr=(e,t,n,r,o)=>{let i=[],s=e.body;if(s.type===p.OBJECT&&s.fast!==!1){let a=e.itemVar,c=e.indexVar;for(let l=0;l<o.length;l++){let u=o[l],f={},d={...r,[a]:u,...c&&{[c]:l}};d.__paths__||(d.__paths__=r.__paths__||{});let h=e.iterable.path||"";if(r&&r.__paths__&&h){let y=h.split("."),g=y[0];g in r.__paths__&&(h=r.__paths__[g],y.length>1&&(h+="."+y.slice(1).join(".")))}d.__paths__={...d.__paths__,[a]:`${h}[${l}]`,...c&&{[c]:l}};for(let y of s.properties){let g=y.parsedKey?_(y.parsedKey,t,n,d):y.key,I=y.value;if(I.type===p.LITERAL)f[g]=I.value;else if(I.type===p.VARIABLE){let m=I.path;if(m===a)f[g]=u;else if(m===c)f[g]=l;else if(m.startsWith(a+".")){let b=m.substring(a.length+1);!b.includes(".")&&!b.includes("[")?f[g]=u[b]:f[g]=C(m,n,{...r,[a]:u,...c&&{[c]:l}})}else f[g]=C(m,n,{...r,[a]:u,...c&&{[c]:l}})}else if(I.type===p.INTERPOLATION){let m=[];for(let b of I.parts)if(typeof b=="string")m.push(b);else if(b.type===p.VARIABLE){let A=b.path,x;if(A===a)x=u;else if(A===c)x=l;else if(A.startsWith(a+".")){let w=A.substring(a.length+1);!w.includes(".")&&!w.includes("[")?x=u[w]:x=C(A,n,{...r,[a]:u,...c&&{[c]:l}})}else x=C(A,n,{...r,[a]:u,...c&&{[c]:l}});m.push(x!=null?String(x):"")}else{let A={...r,[a]:u,...c&&{[c]:l}},x=_(b,t,n,A);m.push(x!=null?String(x):"")}f[g]=m.join("")}else{let m={...r,[a]:u,...c&&{[c]:l}};f[g]=_(I,t,n,m)}}i.push(f)}return i}return null},gr=(e,t,n)=>{let r=e.body;if(r.type===p.OBJECT&&r.properties.length===1&&r.properties[0].key==="$if item.visible"){let i=r.properties[0].value;if(i.type===p.CONDITIONAL&&i.conditions.length===1&&i.conditions[0].type===p.VARIABLE&&i.conditions[0].path==="item.visible"){let s=i.bodies[0];if(s.type===p.OBJECT&&s.properties.length===2){let a=s.properties[0],c=s.properties[1];if(a.key==="id"&&a.value.type===p.VARIABLE&&a.value.path==="item.id"&&c.key==="$if item.highlighted"&&c.value.type===p.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},yr=(e,t,n,r)=>{let o=_(e.iterable,t,n,r);if(!Array.isArray(o)){let l,u=!1;if(e.iterable.type===p.FUNCTION){u=!0;let d=e.iterable.args.map(h=>h.type===p.LITERAL?typeof h.value=="string"?`'${h.value}'`:String(h.value):h.type===p.VARIABLE?h.path:h.type===p.FUNCTION?`${h.name}(...)`:"?").join(", ");l=`${e.iterable.name}(${d})`}else l=e.iterable.path||"undefined";let f=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${l}`;throw Yt(f,o,u)}if(!e.indexVar){let l=gr(e,o,e.itemVar);if(l!==null)return l}if(!e.indexVar){let l=pr(e,o);if(l!==null)return l}let i=hr(e,t,n,r,o);if(i!==null)return i;let s=[],a=e.iterable.path||"";if(r&&r.__paths__&&a){let l=a.split("."),u=l[0];u in r.__paths__&&(a=r.__paths__[u],l.length>1&&(a+="."+l.slice(1).join(".")))}let c=!1;e.body.type===p.ARRAY&&(e.body.items.length<=1?c=!1:c=e.body._shouldPreserveArray??=e.body.items.some(l=>l.type===p.OBJECT&&l.properties.some(u=>u.key.startsWith("$if ")||u.key.startsWith("$when "))));for(let l=0;l<o.length;l++){let u=e.indexVar?{...r,[e.itemVar]:o[l],[e.indexVar]:l}:{...r,[e.itemVar]:o[l]};u.__paths__||(u.__paths__=r.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${a}[${l}]`},e.indexVar&&(u.__paths__[e.indexVar]=l);let f=_(e.body,t,n,u);if(Array.isArray(f)&&f.length===1&&!c){let d=f[0];s.push(d===void 0?{}:d)}else s.push(f===void 0?{}:f)}return s},mr=(e,t,n,r)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?_(o.parsedKey,t,n,r):o.key,s=o.value;if(s.type===p.OBJECT&&s.properties.length<=10&&!s.whenCondition){let a={},c={},l=!0;for(let u of s.properties){let f=u.parsedKey?_(u.parsedKey,t,n,r):u.key,d=u.value;if(d.type===p.LITERAL)c[f]=d.value;else if(d.type===p.VARIABLE)c[f]=C(d.path,n,r);else if(d.type===p.INTERPOLATION){let h=[];for(let y of d.parts)if(typeof y=="string")h.push(y);else if(y.type===p.VARIABLE){let g=C(y.path,n,r);h.push(g!=null?String(g):"")}else{l=!1;break}if(!l)break;c[f]=h.join("")}else if(d.type===p.OBJECT&&d.properties.length<=5){let h={};for(let y of d.properties){let g=y.key,I=y.value;if(I.type===p.LITERAL)h[g]=I.value;else if(I.type===p.VARIABLE)h[g]=C(I.path,n,r);else if(I.type===p.INTERPOLATION){let m=[];for(let b of I.parts)if(typeof b=="string")m.push(b);else if(b.type===p.VARIABLE){let A=C(b.path,n,r);m.push(A!=null?String(A):"")}else{l=!1;break}if(!l)break;h[g]=m.join("")}else{l=!1;break}}if(!l)break;c[f]=h}else{l=!1;break}}if(l)return a[i]=c,a}}return null},br=(e,t,n,r)=>{let o=t.functions||t;if(e.whenCondition&&!ie(e.whenCondition,o,n,r))return;let i=mr(e,t,n,r);if(i!==null)return i;if(e.fast){let l={};for(let u of e.properties){let f=u.parsedKey?_(u.parsedKey,t,n,r):u.key,d=u.value;if(d.type===p.LITERAL)l[f]=d.value;else if(d.type===p.VARIABLE)l[f]=C(d.path,n,r);else if(d.type===p.INTERPOLATION){let h=[];for(let y of d.parts)if(typeof y=="string")h.push(y);else if(y.type===p.VARIABLE){let g=C(y.path,n,r);h.push(g!=null?String(g):"")}else{let g=_(y,t,n,r);h.push(g!=null?String(g):"")}l[f]=h.join("")}else l[f]=_(d,t,n,r)}return l}let s={},a=null,c=!1;for(let l of e.properties)if(!l.key.startsWith("$if ")&&!l.key.match(/^\$if\s+\w+.*:?$/)&&!l.key.startsWith("$elif")&&!l.key.startsWith("$else")&&!l.key.startsWith("$for ")){c=!0;break}for(let l of e.properties)if(l.key.startsWith("$if ")||l.key.match(/^\$if\s+\w+.*:?$/)){let u=_(l.value,t,n,r);if(!c&&u!==null&&u!==void 0)return Array.isArray(u)&&u.length===1?u[0]:u;typeof u=="object"&&u!==null&&!Array.isArray(u)&&Object.assign(s,u)}else if(l.key.startsWith("$for ")){if(e.properties.length===1)return _(l.value,t,n,r)}else{let u=l.value;if(u&&u.type===p.OBJECT&&u.properties){let f=u.properties.find(d=>d.key.startsWith("$for "));if(f){let d=_(f.value,t,n,r);d!==void 0&&(s[l.key]=d)}else{let d=_(l.value,t,n,r);d!==void 0&&(s[l.key]=d)}}else{let f=l.parsedKey?_(l.parsedKey,t,n,r):l.key,d=_(l.value,t,n,r);d!==void 0&&(s[f]=d)}}return s},Xt={},Ir=(e,t,n,r)=>{let o=[];for(let i of e.items)if(i.type===p.LOOP){let s=_(i,t,n,r);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=_(i,t,n,r);s!==Xt&&s!==void 0&&o.push(s)}return o},wr=(e,t,n,r)=>{let{name:o,data:i,whenCondition:s}=e,a=t.partials||{},c=t.functions||t;if(s&&!ie(s,c,n,r))return;if(!a[o])throw new S(`Partial '${o}' is not defined`);let l=r._partialStack||[];if(l.includes(o))throw new S(`Circular partial reference detected: ${o}`);let u=a[o],f=n,d={...r,_partialStack:[...l,o]};if(r){f={...n};for(let h of Object.keys(r))h.startsWith("_")||(f[h]=r[h])}if(i){let h=_(i,t,n,r);f={...f,...h}}return _(u,t,f,d)},Ar=(e,t,n,r)=>{let{path:o}=e,i=o.split("."),s=i[0],a=i.slice(1);if(!r||!(s in r))throw new S(`Path reference '#{${o}}' refers to '${s}' which is not a loop variable in the current scope`);if(r.__paths__||(r.__paths__={}),!(s in r.__paths__))throw new S(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let c=r.__paths__[s];if(typeof c=="number"){if(a.length>0)throw new S(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(c)}return a.length>0&&(c+="."+a.join(".")),c},et=lr;var xr=/\$\{([^}]*)\}/g,vr=/#\{([^}]*)\}/g,Qt=(e,t={})=>{let n=e.match(/^(\w+)\((.*)\)$/);if(!n)return{isFunction:!1};let[,r,o]=n,i=Er(o,t);return{isFunction:!0,type:p.FUNCTION,name:r,args:i}},Er=(e,t={})=>e.trim()?_r(e).map(r=>$r(r.trim(),t)):[],_r=e=>{let t=[],n="",r=0,o=!1,i="";for(let s=0;s<e.length;s++){let a=e[s],c=s>0?e[s-1]:"";!o&&(a==='"'||a==="'")?(o=!0,i=a,n+=a):o&&a===i&&c!=="\\"?(o=!1,i="",n+=a):!o&&a==="("?(r++,n+=a):!o&&a===")"?(r--,n+=a):!o&&a===","&&r===0?(t.push(n),n=""):n+=a}return n&&t.push(n),t},$r=(e,t={})=>{if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:p.LITERAL,value:e.slice(1,-1)};if(/^-?\d+(\.\d+)?$/.test(e))return{type:p.LITERAL,value:parseFloat(e)};if(e==="true")return{type:p.LITERAL,value:!0};if(e==="false")return{type:p.LITERAL,value:!1};if(e==="null")return{type:p.LITERAL,value:null};let n=Qt(e,t);if(n.isFunction)return{type:n.type,name:n.name,args:n.args};let r=e.trim(),o=[{op:" + ",type:"ADD"},{op:" - ",type:"SUBTRACT"}],i=-1,s=null;for(let{op:a,type:c}of o){let l=0;for(;l<r.length;){let u=q(r.substring(l),a);if(u===-1)break;let f=l+u;f>i&&(i=f,s={op:a,type:c}),l=f+a.length}}if(i!==-1)try{return R(r,t)}catch{return{type:p.VARIABLE,path:r}}return{type:p.VARIABLE,path:r}},en=/^\w+\(.*\)$/,Lr=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,Cr=e=>{if(!(!e||e.trim()===""||en.test(e))&&Lr.test(e))throw e.includes("?")&&e.includes(":")?new v(`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 v(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new v(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},Zt=e=>{let t=e.trim();if(en.test(t))throw new v(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new v(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new v(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new v(`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 v(`Complex expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);return{type:p.PATH_REFERENCE,path:t}},fe=(e,t={})=>{let n=e.trim();Cr(n);let r=Qt(n,t);if(r.isFunction)return{type:r.type,name:r.name,args:r.args};if(n.includes("[")&&!/[\s+\-*/%|&?:]/.test(n)){let o=0;for(let i of n)i==="["?o++:i==="]"&&o--;if(o!==0)throw new Error("Invalid array index syntax")}return{type:p.VARIABLE,path:n}},tt=(e,t={})=>{let n=e,r=[];(e.includes("\\${")||e.includes("\\#{"))&&(n=e.replace(/\\\\(\$\{[^}]*\})/g,"\\DOUBLE_ESC_VAR$1"),n=n.replace(/\\\\(#\{[^}]*\})/g,"\\DOUBLE_ESC_PATH$1"),n=n.replace(/\\(\$\{[^}]*\})/g,(l,u)=>{let f=`__ESCAPED_${r.length}__`;return r.push(u),f}),n=n.replace(/\\(#\{[^}]*\})/g,(l,u)=>{let f=`__ESCAPED_${r.length}__`;return r.push(u),f}),n=n.replace(/\\DOUBLE_ESC_VAR/g,"\\"),n=n.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...n.matchAll(xr)],i=[...n.matchAll(vr)],s=[...o.map(l=>({match:l,type:"variable"})),...i.map(l=>({match:l,type:"pathref"}))].sort((l,u)=>l.match.index-u.match.index);if(s.length===0){let l=n;for(let u=0;u<r.length;u++)l=l.replace(`__ESCAPED_${u}__`,r[u]);return{type:p.LITERAL,value:l}}if(s.length===1&&s[0].match[0]===n&&r.length===0){let{match:l,type:u}=s[0];try{return u==="variable"?fe(l[1],t):Zt(l[1])}catch(f){if(f.message==="Invalid array index syntax")return{type:p.LITERAL,value:n};throw f}}let a=[],c=0;for(let{match:l,type:u}of s){let[f,d]=l,h=l.index;if(h>c){let y=n.substring(c,h);for(let g=0;g<r.length;g++)y=y.replace(`__ESCAPED_${g}__`,r[g]);y&&a.push(y)}try{let y;u==="variable"?y=fe(d.trim(),t):y=Zt(d.trim()),a.push(y)}catch(y){if(y.message==="Invalid array index syntax")a.push(f);else throw y}c=h+f.length}if(c<n.length){let l=n.substring(c);for(let u=0;u<r.length;u++)l=l.replace(`__ESCAPED_${u}__`,r[u]);l&&a.push(l)}return{type:p.INTERPOLATION,parts:a}};var F=(e,t)=>typeof e=="string"?tt(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?Rr(e,t):Sr(e,t):{type:p.LITERAL,value:e},kr=e=>{let{$each:t,...n}=e;if(typeof t!="string")throw new v("$each value must be a non-empty string");let r=t.trim();if(r==="")throw new v("$each value must be a non-empty string");if(Object.keys(n).length===0)throw new v("Empty $each body not allowed");if(n.$partial!==void 0)throw new v("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${r}`]:n}},Rr=(e,t)=>{let n=[],r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(typeof i=="object"&&i!==null&&!Array.isArray(i)){if(i.$each!==void 0)try{let c=kr(i),l=Object.keys(c);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let u=tn(l[0],c[l[0]],t,!0);n.push(u),r=!0;continue}}catch(c){throw c instanceof v?c:new v(c.message)}let a=Object.keys(i);if(a.length===1&&/^\$for(?::\w+)?\s/.test(a[0])){let c=tn(a[0],i[a[0]],t);n.push(c),r=!0;continue}}let s=F(i,t);n.push(s),(s.type===p.FUNCTION||s.type===p.CONDITIONAL||s.type===p.LOOP||s.type===p.PARTIAL||s.type===p.OBJECT&&!s.fast||s.type===p.ARRAY&&!s.fast)&&(r=!0)}return{type:p.ARRAY,items:n,fast:!r}},Sr=(e,t)=>{let n=[],r=!1,o=null,i=Object.entries(e),s=0;if(e.$partial!==void 0){if(typeof e.$partial!="string")throw new v("$partial value must be a string");if(e.$partial.trim()==="")throw new v("$partial value cannot be an empty string");let c=["$if","$elif","$else","$for"],l=[];for(let[m]of i)for(let b of c)if(m===b||m.startsWith(b+" ")||m.startsWith(b+"#")){l.push(b);break}if(l.length>0)throw new v(`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,h={},y=!1;for(let[m,b]of Object.entries(d)){let A=m;(m.startsWith("\\$")||m.startsWith("$$"))&&(A=m.slice(1)),h[A]=b,y=!0}let g=null;if(y&&(g=F(h,t),g.type===p.OBJECT)){let m=!1;for(let b of g.properties)if(b.value.type===p.VARIABLE||b.value.type===p.INTERPOLATION||b.value.type===p.FUNCTION||b.value.type===p.CONDITIONAL||b.value.type===p.OBJECT&&!b.value.fast||b.value.type===p.ARRAY&&!b.value.fast){m=!0;break}m&&(g.fast=!1)}let I={type:p.PARTIAL,name:u,data:g};if(f!==void 0){let m;if(typeof f=="string"){if(f.trim()==="")throw new v("Empty condition expression after '$when'");m=R(f,t)}else m={type:p.LITERAL,value:f};I.whenCondition=m}return I}for(let[c,l]of i)if(c==="$when"){if(o!==null)throw new v("Multiple '$when' directives on the same object are not allowed");if(l==null)throw new v("Missing condition expression after '$when'");let u=typeof l=="string"?l:JSON.stringify(l);if(u.trim()==="")throw new v("Empty condition expression after '$when'");o=R(u,t),r=!0}else if(c.startsWith("$when#")||c.startsWith("$when "))throw new v("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<i.length;){let[c,l]=i[s];if(c==="$when"){s++;continue}if(c==="$each")throw new v("$each can only be used inside arrays");if(c.startsWith("$if ")||c.match(/^\$if#\w+\s/)||c.match(/^\$if\s+\w+.*:$/)){let u=Or(i,s,t);n.push({key:c,value:u.node}),r=!0,s=u.nextIndex}else if(/^\$for(?::\w+)?\s/.test(c)){let u=c.match(/^\$for(?::(\w+))?\s/)?.[1]||"",f=u?`:${u}`:"";throw new v(`$for loops must be inside arrays - use '- $for${f} item in items:' instead of '$for${f} item in items:'. For cleaner object generation syntax, consider using $each.`)}else{if(c.startsWith("$elif ")||c.startsWith("$else"))throw new v(`'${c.split(" ")[0]}' without matching '$if'`);if(c==="$if"||c==="$if:")throw new v("Missing condition expression after '$if'");{let u=F(l,t);(u.type===p.FUNCTION||u.type===p.CONDITIONAL||u.type===p.PARTIAL||u.type===p.OBJECT&&!u.fast||u.type===p.ARRAY&&!u.fast)&&(r=!0);let f=tt(c,t),d={key:c,value:u};(f.type!==p.LITERAL||f.value!==c)&&(d.parsedKey=f),n.push(d),s++}}}let a={type:p.OBJECT,properties:n,fast:!r};return o&&(a.whenCondition=o),a},Or=(e,t,n={})=>{let r=[],o=[],i=t,[s,a]=e[i],c=null,l;if(s.startsWith("$if#")){let f=s.match(/^\$if#(\w+)\s+(.+)$/);if(f)c=f[1],l=f[2];else throw new v(`Invalid conditional syntax: ${s}`)}else l=s.substring(4),l.endsWith(":")&&(l=l.slice(0,-1).trim());Qe(l);let u=R(l,n);for(r.push(u),o.push(F(a,n)),i++;i<e.length;){let[f,d]=e[i],h=!1,y;if(c?f.startsWith(`$elif#${c} `)?(y=f.substring(`$elif#${c} `.length),y.endsWith(":")&&(y=y.slice(0,-1).trim()),h=!0):(f===`$else#${c}`||f===`$else#${c}:`)&&(h=!0,y=null):f.startsWith("$elif ")?(y=f.substring(6),y.endsWith(":")&&(y=y.slice(0,-1).trim()),h=!0):(f==="$else"||f==="$else:")&&(h=!0,y=null),h){if(y===null)r.push(null);else{Qe(y);let g=R(y,n);r.push(g)}if(o.push(F(d,n)),i++,y===null)break}else break}return{node:{type:p.CONDITIONAL,conditions:r,bodies:o,id:c},nextIndex:i}},R=(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 R(l,t)}let n=q(e,"||");if(n!==-1)return{type:p.BINARY,op:L.OR,left:R(e.substring(0,n).trim(),t),right:R(e.substring(n+2).trim(),t)};let r=q(e,"&&");if(r!==-1)return{type:p.BINARY,op:L.AND,left:R(e.substring(0,r).trim(),t),right:R(e.substring(r+2).trim(),t)};let o=[{op:">=",type:L.GTE},{op:"<=",type:L.LTE},{op:"==",type:L.EQ},{op:"!=",type:L.NEQ},{op:">",type:L.GT},{op:"<",type:L.LT},{op:" in ",type:L.IN}];for(let{op:l,type:u}of o){let f=q(e,l);if(f!==-1)return{type:p.BINARY,op:u,left:R(e.substring(0,f).trim(),t),right:R(e.substring(f+l.length).trim(),t)}}let i=-1,s=null,a=[{op:" + ",type:L.ADD},{op:" - ",type:L.SUBTRACT}];for(let{op:l,type:u}of a){let f=0;for(;f<e.length;){let d=q(e.substring(f),l);if(d===-1)break;let h=f+d;h>i&&(i=h,s={op:l,type:u}),f=h+l.length}}if(i!==-1&&s)return{type:p.BINARY,op:s.type,left:R(e.substring(0,i).trim(),t),right:R(e.substring(i+s.op.length).trim(),t)};let c=[" * "," / "," % "];for(let l of c)if(q(e,l)!==-1)throw new v(`Arithmetic operations are not allowed in conditionals: "${l}"`);return e.startsWith("!")?{type:p.UNARY,op:ue.NOT,operand:R(e.substring(1).trim(),t)}:nn(e,t)},q=(e,t)=>{let n=0,r=0;for(;r<=e.length-t.length;){if(e[r]==="(")n++;else if(e[r]===")")n--;else if(n===0&&e.substring(r,r+t.length)===t)return r;r++}return-1},Tr=e=>{if(e=e.trim(),e==="true")return{type:p.LITERAL,value:!0};if(e==="false")return{type:p.LITERAL,value:!1};if(e==="null")return{type:p.LITERAL,value:null};if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:p.LITERAL,value:e.slice(1,-1)};if(e==='""'||e==="''")return{type:p.LITERAL,value:""};if(e==="{}")return{type:p.LITERAL,value:{}};if(e==="[]")return{type:p.LITERAL,value:[]};let t=Number(e);return!isNaN(t)&&isFinite(t)?{type:p.LITERAL,value:t}:{type:p.VARIABLE,path:e}},nn=(e,t)=>{let n=e.trim();if(n.match(/^(\w+)\((.*)\)$/))return fe(n,t);let o=Tr(n);if(o.type===p.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(n))return{type:p.VARIABLE,path:n};try{return fe(n,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},Pr=(e,t=!1)=>{let n=t?"$each":"$for";try{Wt(e)}catch(r){if(r instanceof v&&t){let o=r.message.replace(/\$for/g,"$each");throw new v(o.replace("Parse Error: ",""))}throw r}},tn=(e,t,n,r=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let I=r?"$each":"$for";throw new v(`Invalid loop syntax (got: '${e.replace("$for",I)}')`)}let s=i[1],a=i[2].trim();Pr(a,r);let c=a.match(/^(.+?)\s+in\s+(.+)$/);if(!c){let I=r?"$each":"$for";throw new v(`Invalid loop syntax - missing 'in' keyword (got: '${I} ${a}')`)}let l=c[1].trim(),u=c[2].trim(),f,d=null;if(l.includes(",")){let I=l.split(",").map(m=>m.trim());if(I.length!==2)throw new v(`Invalid loop variables: ${l}. Expected format: "item" or "item, index"`);f=I[0],d=I[1]}else f=l;let h=["this","undefined","null","true","false"];if(h.includes(f))throw new v(`Reserved variable name: ${f}`);if(d&&h.includes(d))throw new v(`Reserved variable name: ${d}`);let y=nn(u,n),g=F(t,n);return{type:p.LOOP,itemVar:f,indexVar:d,iterable:y,body:g,flatten:s!=="nested"}};var Nr=(e,t={})=>{let{functions:n={}}=t;return F(e,n)},$e=Nr;var nt={};Xn(nt,{now:()=>Vr});var Vr=()=>Date.now();var Dr=(e,t,n={})=>{let{functions:r={},partials:o={}}=n,i={...nt,...r},s=$e(e,{functions:i}),a={};for(let[c,l]of Object.entries(o))a[c]=$e(l,{functions:i});return et(s,t,{functions:i,partials:a})},P=Dr;var rn=(e,t,n={})=>{let r=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=c=>c,transformActionFirstArgument:a=c=>c}=n;for(let[c,l]of Object.entries(t))c!=="createInitialState"&&(c.startsWith("select")?o[c]=(...u)=>l(s(r),...u):i[c]=(...u)=>{r=Ze(r,d=>l(a(d),...u))});return{...o,...i}},Le=(e,t)=>n=>{let r=e(),o=Array.isArray(n)?n:[n];return Ze(r,i=>{o.forEach(s=>{t.forEach(a=>{a(i,s)})})})};var Mr=(e,t)=>{if(e.default!==void 0)return e.default;let n=["number","boolean","string","object"];if(!n.includes(e.type))throw new Error(`Invalid variable type: ${e.type} for variable ${t}. Expected one of: ${n.join(", ")}`);switch(e.type){case"number":return 0;case"boolean":return!1;case"string":return"";case"object":return{}}},ot=e=>{let t={},n={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([r,o])=>{let i=Mr(o,r);o.scope==="context"?t[r]=i:n[r]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}},Ce=(e,t)=>{let n=["context","global-device","global-account"];if(!e)throw new Error(`Variable scope is required for variable: ${t}`);if(!n.includes(e))throw new Error(`Invalid variable scope: ${e} for variable ${t}. Expected one of: ${n.join(", ")}`)},ke=(e,t,n)=>{let r={number:["set","increment","decrement","multiply","divide"],boolean:["set","toggle"],string:["set"],object:["set"]},o=r[e];if(!o)throw new Error(`Unknown variable type: ${e} for variable ${n}`);if(!Object.values(r).flat().includes(t))throw new Error(`Unknown operation: ${t}`);if(!o.includes(t))throw new Error(`Operation "${t}" is not valid for variable "${n}" of type "${e}". Valid operations: ${o.join(", ")}`)},Re=(e,t,n)=>{switch(t){case"set":return n;case"multiply":return(e??1)*n;case"divide":return(e??0)/n;case"increment":return(e??0)+(n??1);case"decrement":return(e??0)-(n??1);case"toggle":return!e;default:throw new Error(`Unknown operation: ${t}`)}},it=(e,t,n)=>Object.fromEntries(Object.entries(e).filter(([r])=>t?.[r]?.scope===n)),on=(e,t="DD/MM/YYYY - HH:mm")=>{if(!e)return"";let n=new Date(e),r=o=>String(o).padStart(2,"0");return t.replace("DD",r(n.getDate())).replace("MM",r(n.getMonth()+1)).replace("YYYY",n.getFullYear()).replace("YY",String(n.getFullYear()).slice(-2)).replace("HH",r(n.getHours())).replace("mm",r(n.getMinutes())).replace("ss",r(n.getSeconds()))},jr=(e,t)=>{let n=e?.ui,r=t?.ui;return JSON.stringify(n)===JSON.stringify(r)?null:n&&!r?{changeType:"delete",data:e}:r&&!e?{changeType:"add",data:t}:r&&e?{changeType:"update",data:t}:null},st=(e={},t={})=>{let n={},r=["sfx","voice"],o=s=>{let a=e[s],c=t[s];c&&!a?n[s]={changeType:"add",data:c}:a&&!c?r.includes(s)||(n[s]={changeType:"delete",data:a}):a&&c&&JSON.stringify(a)!==JSON.stringify(c)&&(n[s]={changeType:"update",data:c})};o("background"),o("bgm"),o("voice");let i=jr(e.dialogue,t.dialogue);return i&&(n.dialogue=i),o("choice"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),n},lt=(e={})=>{let t=structuredClone(e),n=o=>{t[o]&&(delete t[o].animations,Object.keys(t[o]).length===0&&delete t[o])};n("background"),n("layout"),n("choice"),t.dialogue?.ui&&(delete t.dialogue.ui.animations,Object.keys(t.dialogue.ui).length===0&&delete t.dialogue.ui,Object.keys(t.dialogue).length===0&&delete t.dialogue);let r=(o,i)=>{let s=t[o]?.items;Array.isArray(s)&&(t[o].items=s.map(a=>{let c={...a};return delete c.animations,i(c)?c:null}).filter(Boolean),t[o].items.length===0&&delete t[o])};return r("character",o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId),r("visual",o=>o.resourceId||o.transformId),t},zr=(e,t)=>{if(!e||!t)return;let n=e;for(let r of t.split(".")){if(n==null||!(r in Object(n)))return;n=n[r]}return n},Br=(e,t)=>{if(typeof e!="string")return e;if(e==="_event"){if(t==null)throw new Error('Action template binding "_event" requires event context "_event".');return t}if(!e.startsWith("_event."))return e;if(t==null)throw new Error(`Action template binding "${e}" requires event context "_event".`);let n=e.slice(7),r=zr(t,n);if(r===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return r},rt=(e,t)=>Array.isArray(e)?e.map(n=>rt(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,rt(r,t)])):Br(e,t),sn=(e,t)=>{if(!t)return e;if(Object.prototype.hasOwnProperty.call(t,"event"))throw new Error('Action template context key "event" is no longer supported. Use "_event".');let n=rt(e,t._event);return P(n,t)};var Se=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:structuredClone(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},ln=(e,t)=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let n=e.map(r=>structuredClone(r)).filter(r=>t(r)||r.animations);return{hasValidItems:n.length>0,processedItems:n}},Fr=()=>({}),Ur=(e,t)=>{if(t.background){let{animationsOnly:n,state:r}=Se(t.background,o=>!!o.resourceId);if(n){e.background=r;return}if(!t.background.resourceId){delete e.background;return}e.background=structuredClone(t.background)}else e.background?.animations&&(e.background.animations={})},Wr=(e,t)=>{if(!t.dialogue){e.dialogue&&e.dialogue.mode==="adv"&&(e.dialogue.content=void 0,e.dialogue.characterId=void 0);return}if(e.dialogue||(e.dialogue={}),t.dialogue.ui){let{animationsOnly:n,state:r}=Se(t.dialogue.ui,o=>!!o.resourceId);n?e.dialogue.ui={...e.dialogue.ui,...r}:e.dialogue.ui={...t.dialogue.ui}}else e.dialogue?.ui?.animations&&(e.dialogue.ui.animations={});if(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"),t.dialogue.content!==void 0&&(e.dialogue.content=t.dialogue.content),delete e.dialogue.characterId,t.dialogue.characterId&&(e.dialogue.characterId=t.dialogue.characterId),t.dialogue.character?e.dialogue.character={...t.dialogue.character}:delete e.dialogue.character,t.dialogue.clear){delete e.dialogue;return}t.dialogue?.clearPage&&e.dialogue?.mode==="nvl"&&(e.dialogue.lines=[]),e.dialogue?.mode==="nvl"&&t.dialogue.content!==void 0&&e.dialogue.lines.push({content:t.dialogue.content,characterId:t.dialogue.characterId||null})},Yr=(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},Hr=(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}}},Jr=(e,t)=>{if(t.visual){let{hasValidItems:n,processedItems:r}=ln(t.visual.items,o=>!!o.resourceId);n?e.visual={items:r}:delete e.visual}else e.visual?.items&&(e.visual.items=e.visual.items.map(n=>n.animations?{...n,animations:{}}:n))},qr=(e,t)=>{if(!t.character){e.character?.items&&(e.character.items=e.character.items.map(o=>o.animations?{...o,animations:{}}:o));return}let{hasValidItems:n,processedItems:r}=ln(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId);n?e.character={items:r}:delete e.character},Kr=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},Gr=(e,t)=>{if(t.layout){let{animationsOnly:n,state:r}=Se(t.layout,o=>!!o.resourceId);if(n){e.layout=r;return}if(!t.layout.resourceId){delete e.layout;return}e.layout=t.layout}else e.layout&&delete e.layout},Xr=(e,t)=>{if(t.choice){let{animationsOnly:n,state:r}=Se(t.choice,o=>!!o.resourceId);if(n){e.choice={...e.choice,...r};return}if(!t.choice.resourceId){delete e.choice;return}e.choice=t.choice}else e.choice&&delete e.choice},Zr=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},Qr=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},eo=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(n=>{delete e[n]})},de=e=>Le(Fr,[eo,Ur,Yr,Hr,Jr,Wr,qr,Kr,Gr,Xr,Zr,Qr])(e);var X={objectValues:e=>Object.entries(e).map(([t,n])=>({id:t,...n})),formatDate:on},to=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,no=(e,t)=>{let n=String(t||"").trim();if(!n)return;let r=n.match(/[A-Za-z_][A-Za-z0-9_]*|\[\d+\]/g)||[],o=e;for(let i of r){if(i.startsWith("[")){let s=Number(i.slice(1,-1));o=Array.isArray(o)?o[s]:void 0;continue}o=o?.[i]}return o},Te=(e,t,n)=>{if(Array.isArray(e)){let o=[];for(let i of e){if(i&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===1){let[s]=Object.keys(i),a=to.exec(s);if(a){let[,c,l,u]=a,f=no(t,u);if(!Array.isArray(f))continue;let d=Array.isArray(i[s])?i[s]:[];f.forEach((h,y)=>{let g={...t,[c]:h};l&&(g[l]=y),d.forEach(I=>{let m=Te(I,g,n),b=P(m,g,n);Array.isArray(b)?o.push(...b):o.push(b)})});continue}}o.push(Te(i,t,n))}return o}if(!e||typeof e!="object")return e;let r={};return Object.entries(e).forEach(([o,i])=>{r[o]=Te(i,t,n)}),r},gn={live:"update",replace:"transition"},yn=e=>{let t=structuredClone(e);return typeof t.type=="string"&&(t.type=gn[t.type]||t.type),t},ro=({id:e,targetId:t,animation:n})=>{let r=yn(n);return delete r.name,r.id=e,r.targetId=t,r},ct=e=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return gn[e.type]||e.type},Oe=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},oo=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),K=({animations:e,resources:t,animationId:n,instanceId:r,targetId:o})=>{if(!n||!o)return!1;let i=t?.animations?.[n];return i?(e.push(ro({id:r,targetId:o,animation:i})),!0):!1},io=({hasPrevious:e,hasCurrent:t,previousResourceId:n,currentResourceId:r,sharedTarget:o})=>!e&&t?"enter":e&&!t?"exit":e&&t?n===r&&o?"update":"replace":"none",at=({animationType:e,animationId:t,animationPath:n,lifecycle:r})=>{if(!(e!=="update"||r==="update"))throw new Error(`[${n}] Animation "${t}" has type "update", but update animations can only be used when the same target persists across the state change. Use type "transition" for enter, exit, and replace.`)},so=(e,{defaultTargetId:t,defaultId:n}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let r=yn(e);return r.id??=n,r.targetId??=t,r},yt=({animations:e,transitions:t,defaultTargetId:n,idPrefix:r})=>{t.forEach((o,i)=>{e.push(so(o,{defaultTargetId:n,defaultId:`${r}-transition-${i}`}))})},cn=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let n=P(e,t);return n&&typeof n=="object"?e:n},an=(e,t)=>{if(e===void 0)return[];if(!Array.isArray(e)||e.some(n=>n===null||typeof n!="object"||Array.isArray(n)))throw new Error(`${t} must be an array of objects`);return e},un=(e,t=0)=>{let n=e?.sprites?.map(({resourceId:r})=>r)||[];return n.length===0?`character-container-${e.id}`:`character-container-${e.id}-${t}-${n.join("-")}`},ut=(e,t)=>{if(!t.transformId)throw new Error(`Visual item "${t.id}" requires transformId`);let n=e.transforms?.[t.transformId];if(!n)throw new Error(`Transform "${t.transformId}" not found for visual item "${t.id}"`);return n},lo=(e={})=>e.textStyles||{},co=(e={})=>e.images||{},ao=(e={})=>e.colors||{},uo=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,pe=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,se=(e,t,n)=>{if(typeof e!="string"||e.length===0)throw new Error(`${n} at "${t}" must resolve to a non-empty string`)},fn=(e,t,n)=>{if(e===void 0)return 1;if(typeof e!="number"||!Number.isFinite(e))throw new Error(`${t} for text style "${n}" must be a number between 0 and 1`);if(e<0||e>1)throw new Error(`${t} for text style "${n}" must be a number between 0 and 1`);return e},mn=(e,t)=>{if(typeof e!="string"||!uo.test(e))throw new Error(`${t} must resolve to a hex color`);return e.length===4?`#${e.slice(1).split("").map(n=>n.repeat(2)).join("")}`:e},dn=(e,t,n)=>{let r=mn(e,n);if(t===1)return r;let o=Number.parseInt(r.slice(1,3),16),i=Number.parseInt(r.slice(3,5),16),s=Number.parseInt(r.slice(5,7),16);return`rgba(${o}, ${i}, ${s}, ${t})`},fo=(e={},t)=>{let n=lo(e)?.[t];if(!n)throw new Error(`Text style "${t}" not found`);let r=e.fonts?.[n.fontId];if(!r)throw new Error(`Font "${n.fontId}" not found for text style "${t}"`);let o=e.colors?.[n.colorId];if(!o)throw new Error(`Color "${n.colorId}" not found for text style "${t}"`);let i=fn(n.colorAlpha,"colorAlpha",t),s={fontFamily:r.fileId,fontSize:n.fontSize??16,fontWeight:n.fontWeight??"400",fontStyle:n.fontStyle??"normal",lineHeight:n.lineHeight??1.2,fill:dn(o.hex,i,`Color "${n.colorId}" for text style "${t}"`)};if(n.align!==void 0&&(s.align=n.align),n.wordWrap!==void 0&&(s.wordWrap=n.wordWrap),n.breakWords!==void 0&&(s.breakWords=n.breakWords),n.wordWrapWidth!==void 0&&(s.wordWrapWidth=n.wordWrapWidth),n.strokeColorId){let a=e.colors?.[n.strokeColorId];if(!a)throw new Error(`Stroke color "${n.strokeColorId}" not found for text style "${t}"`);let c=fn(n.strokeAlpha,"strokeAlpha",t);s.strokeColor=dn(a.hex,c,`Stroke color "${n.strokeColorId}" for text style "${t}"`)}else if(n.strokeAlpha!==void 0)throw new Error(`strokeAlpha for text style "${t}" requires strokeColorId`);return n.strokeWidth!==void 0&&(s.strokeWidth=n.strokeWidth),s},pt=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>pt(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(Object.prototype.hasOwnProperty.call(e,"textStyle"))throw new Error(`Inline textStyle is not allowed in layout elements at "${n}". Use textStyleId instead`);let r={};for(let[o,i]of Object.entries(e))o!=="textStyleId"&&(r[o]=pt(i,t,pe(n,o)));return e.textStyleId!==void 0&&(se(e.textStyleId,n,"textStyleId"),r.textStyle=fo(t,e.textStyleId)),r},bn=(e={},t)=>{let n=ao(e)?.[t];if(!n)throw new Error(`Color "${t}" not found`);return mn(n.hex,`Color "${t}"`)},In=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",ft=(e,t,n)=>{let r=e?.[t];if(!(!r||typeof r!="object"||Array.isArray(r))&&Object.prototype.hasOwnProperty.call(r,"fill"))throw new Error(`Inline ${t}.fill is not allowed in rect layout elements at "${n}". Use ${In(`${t}.fill`)} instead`)},po=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>he(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;let r={};for(let[o,i]of Object.entries(e))o!=="colorId"&&(r[o]=he(i,t,pe(n,o)));return e.colorId!==void 0&&(se(e.colorId,n,"colorId"),r.fill=bn(t,e.colorId)),r},he=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>he(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="rect"){if(Object.prototype.hasOwnProperty.call(e,"fill"))throw new Error(`Inline fill is not allowed in rect layout elements at "${n}". Use ${In("fill")} instead`);ft(e,"hover",n),ft(e,"click",n),ft(e,"rightClick",n)}let r={};for(let[o,i]of Object.entries(e))if(!(e.type==="rect"&&o==="colorId")){if(e.type==="rect"&&(o==="hover"||o==="click"||o==="rightClick")){r[o]=po(i,t,pe(n,o));continue}r[o]=he(i,t,pe(n,o))}return e.type==="rect"&&e.colorId!==void 0&&(se(e.colorId,n,"colorId"),r.fill=bn(t,e.colorId)),r},dt=(e={},t)=>{let n=co(e)?.[t];return n||null},wn=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",pn=(e,t,n,r)=>{let o=e?.[t];if(!(!o||typeof o!="object"||Array.isArray(o))&&Object.prototype.hasOwnProperty.call(o,r))throw new Error(`Inline ${t}.${r} is not allowed in sprite layout elements at "${n}". Use ${wn(`${t}.${r}`)} instead`)},hn=(e,t,n)=>{let r=e[t];e[t]={...r&&typeof r=="object"&&!Array.isArray(r)?r:{},src:n}},ht=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>ht(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="sprite"){for(let o of["url","src","hoverUrl","hoverSrc","clickUrl","clickSrc"])if(Object.prototype.hasOwnProperty.call(e,o))throw new Error(`Inline ${o} is not allowed in sprite layout elements at "${n}". Use ${wn(o)} instead`);pn(e,"hover",n,"src"),pn(e,"click",n,"src")}let r={};for(let[o,i]of Object.entries(e))e.type==="sprite"&&(o==="imageId"||o==="hoverImageId"||o==="clickImageId")||(r[o]=ht(i,t,pe(n,o)));if(e.type==="sprite"&&e.imageId!==void 0){se(e.imageId,n,"imageId");let o=dt(t,e.imageId),i=o?.fileId??e.imageId;r.src=i,r.width===void 0&&o?.width!==void 0&&(r.width=o.width),r.height===void 0&&o?.height!==void 0&&(r.height=o.height)}return e.type==="sprite"&&e.hoverImageId!==void 0&&(se(e.hoverImageId,n,"hoverImageId"),hn(r,"hover",dt(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(se(e.clickImageId,n,"clickImageId"),hn(r,"click",dt(t,e.clickImageId)?.fileId??e.clickImageId)),r},mt=(e,t={},n="root")=>ht(he(pt(e,t,n),t,n),t,n),Z=mt,Pe=(e=[])=>e.find(t=>t.id==="story"),Q=({variables:e,saveSlots:t=[],isLineCompleted:n,autoMode:r,skipMode:o,canRollback:i,confirmDialog:s,historyDialogue:a=[],characters:c={}}={})=>({variables:e,saveSlots:t,isLineCompleted:n,autoMode:r,skipMode:o,canRollback:i,confirmDialog:s,historyDialogue:a,characters:c,effectiveSoundVolume:e?._muteAll?0:e?._soundVolume??500,textSpeed:e?._textSpeed??50}),gt=e=>{if(Array.isArray(e))return e.map(n=>gt(n));if(!e||typeof e!="object")return e;let t={...e};return Object.keys(t).forEach(n=>{t[n]=gt(t[n])}),t.type==="text-revealing"&&(t.revealEffect="none"),t},ee=(e,{isLineCompleted:t=!1,skipTransitionsAndAnimations:n=!1}={})=>!t&&!n?e:gt(e),An=({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:{}}}}),xn=(e=[],t={})=>e.map(n=>{let r=t?.[n.characterId];return{...n,characterName:r?.name||""}}),vn=({container:e,resources:t,templateData:n,isLineCompleted:r=!1,skipTransitionsAndAnimations:o=!1})=>{let i=P(e,n,{functions:X});return Z(ee(i,{isLineCompleted:r,skipTransitionsAndAnimations:o}),t)},ho=(e={})=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,{payload:{actions:structuredClone(n?.actions||{})}}]))},G=({animations:e,animationsDef:t,resources:n,previousResourceId:r,currentResourceId:o,previousTargetId:i,currentTargetId:s,animationPath:a,idPrefix:c})=>{if(!t)return;let l=r!=null&&r!==!1,u=o!=null&&o!==!1,f=i&&s&&i===s,d=io({hasPrevious:l,hasCurrent:u,previousResourceId:r,currentResourceId:o,sharedTarget:f});if(oo(t)){if(t.in&&!l){let I=Oe(t.in);at({animationType:ct(n?.animations?.[I]),animationId:I,animationPath:`${a}.in`,lifecycle:"enter"}),K({animations:e,resources:n,animationId:I,instanceId:`${c}-animation-in`,targetId:s})}if(t.out&&l&&r!==o){let I=Oe(t.out);at({animationType:ct(n?.animations?.[I]),animationId:I,animationPath:`${a}.out`,lifecycle:"exit"}),K({animations:e,resources:n,animationId:I,instanceId:`${c}-animation-out`,targetId:i})}t.update&&l&&u&&r===o&&f&&K({animations:e,resources:n,animationId:Oe(t.update),instanceId:`${c}-animation-update`,targetId:s});return}let h=Oe(t),y=n?.animations?.[h],g=ct(y);if(at({animationType:g,animationId:h,animationPath:a,lifecycle:d}),g==="update"){l&&u&&r===o&&f&&K({animations:e,resources:n,animationId:h,instanceId:`${c}-animation-update`,targetId:s});return}if(g==="transition"){if(l&&u&&f){K({animations:e,resources:n,animationId:h,instanceId:`${c}-animation-transition`,targetId:s});return}l&&K({animations:e,resources:n,animationId:h,instanceId:`${c}-animation-out`,targetId:i}),u&&K({animations:e,resources:n,animationId:h,instanceId:`${c}-animation-in`,targetId:s})}},go=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),yo=(e,{presentationState:t,previousPresentationState:n,resources:r={},isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,autoMode:a,skipMode:c,canRollback:l,saveSlots:u=[]})=>{let{elements:f,animations:d}=e;if(t.background){let h=f.find(y=>y.id==="story");if(!h)return e;if(t.background.resourceId){let{images:y={},videos:g={}}=r,I=y[t.background.resourceId]||g[t.background.resourceId];if(I){let m=g[t.background.resourceId]!==void 0,b={id:`bg-cg-${t.background.resourceId}`,type:m?"video":"sprite",x:0,y:0,src:I.fileId,width:I.width,height:I.height,alpha:1,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1};m&&(b.loop=t.background.loop??!1,b.volume=I.volume??500),h.children.push(b)}}if(t.background.resourceId){let{layouts:y={}}=r,g=y[t.background.resourceId];if(g){let I={id:`bg-cg-${t.background.resourceId}`,type:"container",children:g.elements},m=P(I,Q({variables:s,saveSlots:u,isLineCompleted:o,autoMode:a,skipMode:c,canRollback:l}),{functions:X});h.children.push(Z(ee(m,{isLineCompleted:o,skipTransitionsAndAnimations:i}),r))}}if(t.background.animations&&!o&&!i){let y=n?.background?.resourceId,g=t.background.resourceId;G({animations:d,animationsDef:t.background.animations,resources:r,previousResourceId:y,currentResourceId:g,previousTargetId:y?`bg-cg-${y}`:void 0,currentTargetId:g?`bg-cg-${g}`:void 0,animationPath:"background.animations",idPrefix:"bg-cg"})}}return e},mo=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i})=>{let{elements:s,animations:a}=e;if(t.character&&r){let c=s.find(f=>f.id==="story");if(!c)return e;let l=t.character.items||[],u=n?.character?.items||[];for(let f=0;f<l.length;f++){let d=l[f],{transformId:h,sprites:y}=d,g=u.find($=>$.id===d.id),I=u.findIndex($=>$.id===d.id),m=g?.sprites&&g.sprites.length>0,b=y&&y.length>0,A=I>=0?un(g,I):void 0;if(d.animations&&!y&&!h&&m&&!o&&!i){G({animations:a,animationsDef:d.animations,resources:r,previousResourceId:A,currentResourceId:void 0,previousTargetId:A,currentTargetId:void 0,animationPath:`character.items[${f}].animations`,idPrefix:"character"});continue}if(d.animations&&!y&&!h)continue;if(!y||y.length===0||!h){console.warn("Character item missing sprites or transformId:",d);continue}let x=un(d,f),w=r.transforms[h];if(!w){console.warn("Transform not found:",h);continue}let E={type:"container",id:x,x:d.x??w.x,y:d.y??w.y,anchorX:w.anchorX,anchorY:w.anchorY,rotation:w.rotation,scaleX:w.scaleX,scaleY:w.scaleY,children:[]};for(let $ of y){let M=r.images[$.resourceId];if(!M){console.warn(`Image resource not found: ${$.resourceId}`);continue}E.children.push({type:"sprite",id:`${x}-${$.id}`,src:M.fileId,width:M.width,height:M.height,x:0,y:0})}c.children.push(E),d.animations&&!o&&!i&&G({animations:a,animationsDef:d.animations,resources:r,previousResourceId:A,currentResourceId:x,previousTargetId:A,currentTargetId:x,animationPath:`character.items[${f}].animations`,idPrefix:"character"})}}return e},bo=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,autoMode:a,skipMode:c,canRollback:l,saveSlots:u=[]})=>{let{elements:f,animations:d}=e;if(t.visual&&r){let h=f.find(g=>g.id==="story");if(!h)return e;let y=t.visual.items;for(let g of y){if(g.resourceId){let{images:I={},videos:m={},spritesheets:b={}}=r,A=b[g.resourceId];if(A){let x=ut(r,g),w=g.animationName;if(w){let E=A.animations?.[w];if(!E)throw new Error(`Animation '${w}' not found in spritesheet resource '${g.resourceId}'`);let $={id:`visual-${g.id}`,type:"animated-sprite",x:g.x??x.x,y:g.y??x.y,width:g.width??A.width,height:g.height??A.height,alpha:g.alpha??1,anchorX:x.anchorX,anchorY:x.anchorY,rotation:x.rotation,scaleX:x.scaleX,scaleY:x.scaleY,spritesheetSrc:A.fileId,spritesheetData:A.jsonData,animation:{frames:E.frames,animationSpeed:g.animationSpeed??E.animationSpeed??.5,loop:g.loop??E.loop??!0}};h.children.push(structuredClone($))}}else{let x=I[g.resourceId]||m[g.resourceId];if(x){let w=m[g.resourceId]!==void 0,E=ut(r,g),$={id:`visual-${g.id}`,type:w?"video":"sprite",src:x.fileId,width:x.width,height:x.height,x:E.x,y:E.y,anchorX:E.anchorX,anchorY:E.anchorY,rotation:E.rotation,scaleX:E.scaleX,scaleY:E.scaleY};w&&($.loop=x.loop??!1,$.volume=x.volume??500),h.children.push($)}}}if(g.resourceId){let{layouts:I={}}=r,m=I[g.resourceId];if(m){let b=ut(r,g),A={id:`visual-${g.id}`,type:"container",children:structuredClone(m.elements),x:b.x,y:b.y,anchorX:b.anchorX,anchorY:b.anchorY,rotation:b.rotation,scaleX:b.scaleX,scaleY:b.scaleY},x=P(A,Q({variables:s,saveSlots:u,isLineCompleted:o,autoMode:a,skipMode:c,canRollback:l}),{functions:X});h.children.push(Z(ee(x,{isLineCompleted:o,skipTransitionsAndAnimations:i}),r))}}if(g.animations&&!o&&!i){let m=(n?.visual?.items||[]).find(b=>b.id===g.id);G({animations:d,animationsDef:g.animations,resources:r,previousResourceId:m?.resourceId,currentResourceId:g.resourceId,previousTargetId:m?.resourceId?`visual-${g.id}`:void 0,currentTargetId:g.resourceId?`visual-${g.id}`:void 0,animationPath:`visual.items[${g.id}].animations`,idPrefix:g.id})}}}return e},Io=(e,{presentationState:t,previousPresentationState:n,resources:r={},dialogueUIHidden:o,autoMode:i,skipMode:s,canRollback:a,skipOnlyViewedLines:c,isLineCompleted:l,skipTransitionsAndAnimations:u,variables:f,saveSlots:d=[]})=>{let{elements:h,animations:y}=e;if(!t.dialogue||o)return e;let g=h.find(I=>I.id==="story");if(!g)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:I={}}=r,m=I[t.dialogue.ui.resourceId];if(m){let b;t.dialogue.characterId&&(b=r.characters[t.dialogue.characterId]),t.dialogue.character&&(b={...b,name:t.dialogue.character.name});let A={elements:m.elements},x=t.dialogue?.content===void 0?[{text:""}]:an(t.dialogue.content,"dialogue.content"),w=(t.dialogue?.lines||[]).map((z,Kn)=>({content:an(z.content,`dialogue.lines[${Kn}].content`).map(Ot=>({...Ot,text:cn(Ot.text,{variables:f})})),characterName:z.characterId&&r.characters?.[z.characterId]?.name||""})),E={variables:f,autoMode:i,skipMode:s,canRollback:a,skipOnlyViewedLines:c,isLineCompleted:l,saveSlots:d,effectiveSoundVolume:f?._muteAll?0:f?._soundVolume??500,textSpeed:f?._textSpeed??50,dialogueLines:w,dialogue:{character:{name:b?.name||""},content:x.map(z=>({...z,text:cn(z.text,{variables:f})})),lines:w}},$={functions:X},M=Te(A,E,$),ze=P(M,E,$),re=Z(ee(ze?.elements,{isLineCompleted:l,skipTransitionsAndAnimations:u}),r);if(Array.isArray(re))for(let z of re)g.children.push(z);else re&&g.children.push(re)}}return t.dialogue.ui?.animations&&!l&&!u&&G({animations:y,animationsDef:t.dialogue.ui.animations,resources:r,previousResourceId:n?.dialogue?.ui?.resourceId,currentResourceId:t.dialogue.ui?.resourceId,previousTargetId:n?.dialogue?.ui?.resourceId?"dialogue-container":void 0,currentTargetId:t.dialogue.ui?.resourceId?"dialogue-container":void 0,animationPath:"dialogue.ui.animations",idPrefix:"dialogue-ui"}),e},wo=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,screen:s,variables:a,autoMode:c,skipMode:l,canRollback:u,saveSlots:f=[]})=>{let{elements:d,animations:h}=e;if(t.choice&&r){let y=Pe(d);if(!y)return e;y.children.push({id:"choice-blocker",type:"rect",fill:"transparent",width:s.width,height:s.height,x:0,y:0,click:{payload:{actions:{}}}});let g=r?.layouts[t.choice.resourceId];if(g&&g.elements){let I={elements:g.elements},m=P(I,{...Q({variables:a,saveSlots:f,isLineCompleted:o,autoMode:c,skipMode:l,canRollback:u}),choice:{items:t.choice?.items??[]}},{functions:X}),b=Z(ee(m?.elements,{isLineCompleted:o,skipTransitionsAndAnimations:i}),r);if(Array.isArray(b))for(let A of b)y.children.push(A);else b&&y.children.push(b)}t.choice.animations&&!o&&!i&&G({animations:h,animationsDef:t.choice.animations,resources:r,previousResourceId:n?.choice?.resourceId,currentResourceId:t.choice.resourceId,previousTargetId:n?.choice?.resourceId?"choice-container":void 0,currentTargetId:t.choice.resourceId?"choice-container":void 0,animationPath:"choice.animations",idPrefix:"choice"})}return e},Ao=(e,{presentationState:t,resources:n={},variables:r,isLineCompleted:o,autoMode:i,skipMode:s,canRollback:a,saveSlots:c=[],skipTransitionsAndAnimations:l})=>{if(!t.control?.resourceId)return e;let u=n.controls?.[t.control.resourceId];if(!u)return e;let f=ho(u.keyboard);if(f&&Object.keys(f).length>0&&(e.global.keyboard=f),!Array.isArray(u.elements)||u.elements.length===0)return e;let d=Pe(e.elements);if(!d)return e;let h={id:`control-${t.control.resourceId}`,type:"container",x:0,y:0,children:u.elements};return d.children.push(vn({container:h,resources:n,templateData:Q({variables:r,saveSlots:c,isLineCompleted:o,autoMode:i,skipMode:s,canRollback:a}),isLineCompleted:o,skipTransitionsAndAnimations:l})),e},xo=(e,{presentationState:t,resources:n,variables:r})=>{let{elements:o,audio:i}=e;if(t.bgm&&n){if(!Pe(o))return e;let a=n.sounds[t.bgm.resourceId];if(!a)return e;let c=r?._muteAll?0:r?._musicVolume??500;i.push({id:"bgm",type:"sound",src:a.fileId,loop:t.bgm.loop??!0,volume:c,delay:t.bgm.delay??null})}return e},vo=(e,{presentationState:t,resources:n})=>{let{audio:r}=e;if(t.sfx&&n){let o=t.sfx.items;for(let i of o){let s=n.sounds?.[i.resourceId];s&&r.push({id:i.id,type:"sound",src:s.fileId,loop:i.loop??s.loop??!1,volume:i.volume??s.volume??500,delay:i.delay??s.delay??null})}}return e},Eo=(e,{presentationState:t,resources:n})=>{let{audio:r}=e;if(!t?.voice)return e;let{fileId:o,volume:i,loop:s}=t.voice;return r.push({id:`voice-${o}`,type:"sound",src:o,volume:i??500,loop:s??!1}),e},_o=(e,{presentationState:t,previousPresentationState:n,resources:r={},variables:o,autoMode:i,skipMode:s,canRollback:a,saveSlots:c=[],isLineCompleted:l,skipTransitionsAndAnimations:u})=>{let{elements:f,animations:d}=e;if(t.layout){let h=Pe(f);if(!h)return e;let y=r.layouts[t.layout.resourceId];if(!y)return e;Array.isArray(y.transitions)&&!l&&!u&&yt({animations:d,transitions:y.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`});let g={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:y.elements||[]};h.children.push(vn({container:g,resources:r,templateData:Q({variables:o,saveSlots:c,isLineCompleted:l,autoMode:i,skipMode:s,canRollback:a}),isLineCompleted:l,skipTransitionsAndAnimations:u}))}if(t.layout?.animations&&!l&&!u){let h=n?.layout?.resourceId,y=t.layout?.resourceId;G({animations:d,animationsDef:t.layout.animations,resources:r,previousResourceId:h,currentResourceId:y,previousTargetId:h?`layout-${h}`:void 0,currentTargetId:y?`layout-${y}`:void 0,animationPath:"layout.animations",idPrefix:"layout"})}return e},$o=(e,{resources:t={},variables:n,autoMode:r,skipMode:o,canRollback:i,layeredViews:s=[],dialogueHistory:a=[],saveSlots:c=[],screen:l,isLineCompleted:u,skipTransitionsAndAnimations:f})=>{let{elements:d,animations:h}=e;return s&&s.length>0&&s.forEach((y,g)=>{let I=t.layouts[y.resourceId];if(!I){console.warn(`LayeredView layout not found: ${y.resourceId}`);return}Array.isArray(I.transitions)&&(f||yt({animations:h,transitions:I.transitions,defaultTargetId:`layeredView-${g}`,idPrefix:`layeredView-${g}`}));let m={id:`layeredView-${g}`,type:"container",x:0,y:0,children:[An({id:`layeredView-${g}-blocker`,screen:l}),...I.elements||[]]},b=xn(a,t.characters),A=Q({variables:n,saveSlots:c,isLineCompleted:u,autoMode:r,skipMode:o,canRollback:i,historyDialogue:b,characters:t.characters||{}}),x=P(m,A,{functions:X}),[w,...E]=x.children||[],$=Z(ee({...x,children:E},{isLineCompleted:u,skipTransitionsAndAnimations:f}),t);d.push({...$,children:w?[w,...$.children||[]]:$.children})}),e},Lo=(e,{resources:t={},variables:n,saveSlots:r=[],autoMode:o,skipMode:i,canRollback:s,confirmDialog:a,dialogueHistory:c=[],screen:l,isLineCompleted:u,skipTransitionsAndAnimations:f})=>{let{elements:d,animations:h}=e;if(!a?.resourceId)return e;let y=t.layouts?.[a.resourceId];if(!y)return console.warn(`ConfirmDialog layout not found: ${a.resourceId}`),e;Array.isArray(y.transitions)&&!f&&yt({animations:h,transitions:y.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog"});let g={id:"confirmDialog",type:"container",x:0,y:0,children:[An({id:"confirmDialog-blocker",screen:l}),...y.elements||[]]},I=xn(c,t.characters),m=P(g,Q({variables:n,saveSlots:r,isLineCompleted:u,autoMode:o,skipMode:i,canRollback:s,confirmDialog:a,historyDialogue:I,characters:t.characters||{}}),{functions:X}),[b,...A]=m.children||[],x=Z(ee({...m,children:A},{isLineCompleted:u,skipTransitionsAndAnimations:f}),t);return d.push({...x,children:b?[b,...x.children||[]]:x.children}),e},En=e=>Le(go,[Ao,yo,mo,bo,Io,wo,_o,xo,vo,Eo,$o,Lo])(e);var U={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},Ln=1,It=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let n=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={manual:{...U.manual},auto:{...U.auto},applyMode:U.applyMode},n&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},V=e=>{let t=B(e)?Xe(e):e;return structuredClone(t)},N=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),De=e=>String(e),Co=()=>({sections:[],resources:[]}),bt=()=>({sectionId:void 0,lineId:void 0}),ko=e=>{if(!N(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},Cn=(e,t)=>{let n=e?.story?.scenes??{};for(let[r,o]of Object.entries(n))if(o?.sections?.[t])return{sceneId:r,section:o.sections[t]};return{sceneId:void 0,section:void 0}},kn=e=>{let t=e?.story?.scenes??{},n=new Map;for(let[r,o]of Object.entries(t)){let i=o?.sections??{};for(let s of Object.keys(i)){let a=n.get(s);if(a!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${a}" and "${r}". Section IDs must be globally unique.`);n.set(s,r)}}},Rn=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},Sn=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==Ln)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},Ro=(e,t={})=>{let n;try{n=Sn(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let r={...t,formatVersion:n,slotId:Rn(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete r.slotKey,delete r.date,r},So=(e={})=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Ro(t,n)])),_n=(e,t,n)=>{let r=t==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[r]:String(e)};if(!N(e))throw new Error(`Malformed save slot viewedRegistry.${t}[${n}] entry.`);if(typeof e[r]!="string"||e[r].length===0)throw new Error(`Malformed save slot viewedRegistry.${t}[${n}] entry: missing ${r}.`);if(t==="sections"){let o={sectionId:e.sectionId};if(e.lastLineId!==void 0&&e.lastLineId!==null&&typeof e.lastLineId!="string")throw new Error(`Malformed save slot viewedRegistry.sections[${n}] entry: invalid lastLineId.`);return typeof e.lastLineId=="string"&&e.lastLineId.length>0&&(o.lastLineId=e.lastLineId),o}return{resourceId:e.resourceId}},Oo=e=>{if(e===void 0)return Co();if(!N(e))throw new Error("Malformed save slot viewedRegistry.");if(e.sections!==void 0&&!Array.isArray(e.sections))throw new Error("Malformed save slot viewedRegistry.sections.");if(e.resources!==void 0&&!Array.isArray(e.resources))throw new Error("Malformed save slot viewedRegistry.resources.");let t=e.sections??[],n=e.resources??[];return{sections:Object.values(Object.fromEntries(t.map((r,o)=>{let i=_n(r,"sections",o);return[i.sectionId,i]}))),resources:Object.values(Object.fromEntries(n.map((r,o)=>{let i=_n(r,"resources",o);return[i.resourceId,i]})))}},wt=(e,t,n)=>{if(!N(e))throw new Error(`Malformed save slot ${n}.`);let{sectionId:r,lineId:o}=e;if(typeof r!="string"||r.length===0)throw new Error(`Malformed save slot ${n}: missing sectionId.`);if(typeof o!="string"||o.length===0)throw new Error(`Malformed save slot ${n}: missing lineId.`);let{sceneId:i,section:s}=Cn(t,r);if(!s)throw new Error(`Malformed save slot ${n}: section "${r}" does not exist in projectData.`);if(!s.lines?.some(c=>c.id===o))throw new Error(`Malformed save slot ${n}: line "${o}" does not exist in section "${r}".`);return{sceneId:i,sectionId:r,lineId:o}},To=(e,t)=>{if(!N(e)||typeof e.sectionId!="string"||e.sectionId.length===0||typeof e.lineId!="string"||e.lineId.length===0)return bt();try{let n=wt(e,t,"contexts[*].pointers.history");return{sectionId:n.sectionId,lineId:n.lineId}}catch{return bt()}},Po=(e,t,n)=>{if(!N(e)||!Array.isArray(e.timeline))return Ve({pointer:t,replayStartIndex:1});let r=e.timeline.flatMap((a,c)=>{if(!N(a))return[];try{let l=wt(a,n,`rollback.timeline[${c}]`),u=Ne({sectionId:l.sectionId,lineId:l.lineId,rollbackPolicy:a.rollbackPolicy});return Array.isArray(a.executedActions)&&(u.executedActions=V(a.executedActions)),[u]}catch{return[]}});if(r.length===0)return Ve({pointer:t,replayStartIndex:1});let o=typeof e.currentIndex=="number"?Math.trunc(e.currentIndex):r.length-1;(o<0||o>=r.length)&&(o=r.length-1);let i=r[o];if(i?.sectionId!==t.sectionId||i?.lineId!==t.lineId){let a=r.findLastIndex(c=>c.sectionId===t.sectionId&&c.lineId===t.lineId);a>=0?o=a:(r.push(Ne({sectionId:t.sectionId,lineId:t.lineId})),o=r.length-1)}let s=typeof e.replayStartIndex=="number"?Math.min(Math.max(Math.trunc(e.replayStartIndex),0),o):0;return{currentIndex:o,isRestoring:!1,replayStartIndex:s,timeline:r}},No=(e,t,n)=>{if(!N(e))throw new Error(`Malformed save slot contexts[${n}] entry.`);let r=On(t),o=wt(e.pointers?.read,t,`contexts[${n}].pointers.read`);if(e.variables!==void 0&&!N(e.variables))throw new Error(`Malformed save slot contexts[${n}].variables entry.`);let i=To(e.pointers?.history,t);return{currentPointerMode:e.currentPointerMode==="history"&&i.lineId?"history":"read",pointers:{read:o,history:i},configuration:N(e.configuration)?V(e.configuration):{},views:Array.isArray(e.views)?V(e.views):[],bgm:N(e.bgm)?V(e.bgm):{resourceId:void 0},variables:{...r,...e.variables?V(e.variables):{}},rollback:Po(e.rollback,o,t)}},Vo=(e,t)=>{if(!N(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{viewedRegistry:Oo(e.viewedRegistry),contexts:e.contexts.map((n,r)=>No(n,t,r))}},Do=(e,t)=>{if(!N(e))throw new Error("Malformed save slot.");let n=Sn(e.formatVersion);return{...e,formatVersion:n,state:Vo(e.state,t)}},$n=(e,t,{required:n=!1}={})=>{if(e===void 0){if(n)throw new Error(`showConfirmDialog requires ${t}`);return{hideConfirmDialog:{}}}if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`showConfirmDialog ${t} must be an action object`);let r=V(e);return Object.prototype.hasOwnProperty.call(r,"hideConfirmDialog")||(r.hideConfirmDialog={}),r},Mo=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:$n(e.confirmActions,"confirmActions",{required:!0}),cancelActions:$n(e.cancelActions,"cancelActions")}},me=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},ge=[],Ne=({sectionId:e,lineId:t,rollbackPolicy:n})=>({sectionId:e,lineId:t,rollbackPolicy:n??"free"}),On=e=>{let{contextVariableDefaultValues:t}=ot(e??{});return V(t)},Tn=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},Ve=({pointer:e,replayStartIndex:t=0})=>{let n=e?.sectionId&&e?.lineId;return{currentIndex:n?0:-1,isRestoring:!1,replayStartIndex:t,timeline:n?[Ne({sectionId:e.sectionId,lineId:e.lineId})]:[]}},ne=(e,t={})=>{if(e?.rollback)return Tn(e.rollback),Array.isArray(e.rollback.timeline)||(e.rollback.timeline=[]),typeof e.rollback.currentIndex!="number"&&(e.rollback.currentIndex=e.rollback.timeline.length>0?e.rollback.timeline.length-1:-1),typeof e.rollback.isRestoring!="boolean"&&(e.rollback.isRestoring=!1),typeof e.rollback.replayStartIndex!="number"&&(e.rollback.replayStartIndex=0),e.rollback;let n=e?.pointers?.read;return e.rollback=Ve({pointer:n,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},At=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return;let r=ne(n);if(r.isRestoring)return;r.currentIndex<r.timeline.length-1&&(r.timeline=r.timeline.slice(0,r.currentIndex+1));let o=r.timeline[r.timeline.length-1];if(o?.sectionId===t.sectionId&&o?.lineId===t.lineId&&(o?.rollbackPolicy??"free")===(t.rollbackPolicy??"free")){r.currentIndex=r.timeline.length-1;return}r.timeline.push(Ne(t)),r.currentIndex=r.timeline.length-1},jo=e=>{let n=e.contexts?.[e.contexts.length-1]?.rollback;if(!n||n.isRestoring||!Array.isArray(n.timeline)||typeof n.currentIndex!="number")return null;let r=ge[ge.length-1],o=typeof r?.checkpointIndex=="number"?r.checkpointIndex:n.currentIndex;return o<0||o>=n.timeline.length?null:(typeof r?.checkpointIndex!="number"&&o<n.timeline.length-1&&(n.timeline=n.timeline.slice(0,o+1)),n.timeline[o]??null)},zo=({state:e})=>{let n=e.contexts?.[e.contexts.length-1]?.rollback;return!n||n.isRestoring||!Array.isArray(n.timeline)||typeof n.currentIndex!="number"||n.currentIndex<0||n.currentIndex>=n.timeline.length?(ge.push({checkpointIndex:null}),e):(n.currentIndex<n.timeline.length-1&&(n.timeline=n.timeline.slice(0,n.currentIndex+1)),ge.push({checkpointIndex:n.currentIndex}),e)},Bo=({state:e})=>(ge.pop(),e),W=(e,t,n)=>{let r=jo(e);r&&(Array.isArray(r.executedActions)||(r.executedActions=[]),r.executedActions.push({type:t,payload:V(n)}))},Fo=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return;let r=t?.operations??[];for(let{variableId:o,op:i,value:s}of r){let a=e.projectData.resources?.variables?.[o],c=a?.scope,l=a?.type;Ce(c,o),ke(l,i,o),c==="context"&&(n.variables[o]=Re(n.variables[o],i,s))}},Uo=(e,t)=>{if(!Array.isArray(t?.executedActions))return!1;let n={showDialogueUI:le,hideDialogueUI:Me,toggleDialogueUI:Ct,setNextLineConfig:kt,pushLayeredView:Et,popLayeredView:_t,replaceLastLayeredView:$t,clearLayeredViews:Lt};return t.executedActions.forEach(({type:r,payload:o})=>{if(r==="updateVariable"){Fo(e,o);return}let i=n[r];i&&i({state:e},o)}),!0},Wo=(e,t)=>{let{sectionId:n,lineId:r}=t,s=k({state:e},{sectionId:n})?.lines?.find(l=>l.id===r)?.actions?.updateVariable;if(!s)return;let a=e.contexts?.[e.contexts.length-1];if(!a)return;let c=s.operations||[];for(let{variableId:l,op:u,value:f}of c){let d=e.projectData.resources?.variables?.[l],h=d?.scope,y=d?.type;Ce(h,l),ke(y,u,l),h==="context"&&(a.variables[l]=Re(a.variables[l],u,f))}},Yo=(e,t)=>{let{sectionId:n,lineId:r}=t,s=k({state:e},{sectionId:n})?.lines?.find(c=>c.id===r)?.actions;if(!s)return;let a={showDialogueUI:le,hideDialogueUI:Me,toggleDialogueUI:Ct,setNextLineConfig:kt,pushLayeredView:Et,popLayeredView:_t,replaceLastLayeredView:$t,clearLayeredViews:Lt};Object.entries(s).forEach(([c,l])=>{let u=a[c];u&&u({state:e},l)})},Pn=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return e;let r=ne(n),o=r.timeline[t];if(!o)return e;e.global.autoMode&&be({state:e}),e.global.skipMode&&te({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),r.isRestoring=!0,r.currentIndex=t;try{n.variables=On(e.projectData),e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=V(U),e.global.layeredViews=[],me(e),e.global.isLineCompleted=!0;let i=r.replayStartIndex??0;for(let s=i;s<=t;s++)s>i&&It(e),Uo(e,r.timeline[s])||(Wo(e,r.timeline[s]),Yo(e,r.timeline[s]));n.pointers.read={sectionId:o.sectionId,lineId:o.lineId},n.currentPointerMode="read",n.pointers?.history&&(n.pointers.history={sectionId:null,lineId:null}),e.global.pendingEffects=e.global.pendingEffects.filter(s=>s?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{r.isRestoring=!1}return e},Ho=e=>{let{projectData:t}=e,n=e.global??{},{saveSlots:r={},variables:o={}}=n;kn(t);let i=t.story.initialSceneId,s=t.story.scenes[i],a=s.initialSectionId,c=s.sections[a],l={sceneId:i,sectionId:a,lineId:c.initialLineId??c.lines[0].id},{contextVariableDefaultValues:u,globalVariablesDefaultValues:f}=ot(t),d={...f,...o};return{projectData:t,global:{isLineCompleted:!1,pendingEffects:[],autoMode:!1,skipMode:!1,dialogueUIHidden:!1,confirmDialog:null,viewedRegistry:{sections:[],resources:[]},nextLineConfig:{manual:{...U.manual},auto:{...U.auto},applyMode:U.applyMode},saveSlots:So(r),layeredViews:[],variables:d},contexts:[{currentPointerMode:"read",pointers:{read:l,history:{sectionId:void 0,lineId:void 0}},configuration:{},views:[],bgm:{resourceId:void 0},variables:u,rollback:Ve({pointer:l})}]}},Jo=({state:e})=>e.global.layeredViews||[],qo=({state:e})=>e.global.pendingEffects,Nn=({state:e})=>e.global.skipMode,Ko=({state:e})=>e.global.autoMode,Vn=({state:e})=>e.global.dialogueUIHidden,Dn=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],n=t[t.length-1];if(!n)return[];let{sectionId:r,lineId:o}=n.pointers.read,i=k({state:e},{sectionId:r});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(l=>l.id===o);return i.lines.slice(0,s+1).filter(l=>l.actions?.dialogue).map(l=>{let u=l.actions.dialogue,f="";return u.characterId&&(f=e.projectData.resources?.characters?.[u.characterId]?.name||""),{content:u.content,characterId:u.characterId,characterName:f}})},Go=({state:e})=>e.global.confirmDialog??null,xt=({state:e},t)=>{let{sectionId:n,lineId:r}=t,o=e.global.viewedRegistry.sections.find(c=>c.sectionId===n);if(!o)return!1;if(o.lastLineId===void 0||r===void 0)return!0;let i=k({state:e},{sectionId:n});if(!i||!i.lines||!Array.isArray(i.lines))return o.lastLineId===r;let s=i.lines.findIndex(c=>c.id===o.lastLineId),a=i.lines.findIndex(c=>c.id===r);return s===-1||a===-1?o.lastLineId===r:a<=s},Xo=({state:e},t)=>{let{resourceId:n}=t;return!!e.global.viewedRegistry.resources.find(o=>o.resourceId===n)},Zo=({state:e})=>e.global.nextLineConfig,Qo=({state:e})=>structuredClone(e),Mn=({state:e})=>e.global.saveSlots,ei=({state:e},t)=>{let n=t?.slotId,r=De(n);return e.global.saveSlots[r]},ti=({state:e})=>({...e.global?.variables??{},...e.contexts?.[e.contexts.length-1]?.variables??{}}),j=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],n=t[t.length-1];if(!n)return;let r=n.pointers?.[n.currentPointerMode];return{currentPointerMode:n.currentPointerMode,pointer:r}},k=({state:e},t)=>{let{sectionId:n}=t;return Cn(e.projectData,n).section},jn=({state:e})=>{let t=j({state:e});if(!t?.pointer)return;let{sectionId:n,lineId:r}=t.pointer,o=k({state:e},{sectionId:n});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===r)},ni=({state:e})=>{let t=j({state:e})?.pointer,n=t?.sectionId,r=t?.lineId,i=k({state:e},{sectionId:n})?.lines||[],s=i.findIndex(l=>l.id===r);if(s<0)return;let a;return i.slice(0,s+1).forEach(l=>{if(!l?.actions||!Object.prototype.hasOwnProperty.call(l.actions,"choice"))return;let u=l.actions.choice;if(!u?.resourceId){u?.animations||(a=void 0);return}a=u.resourceId}),a},zn=({state:e})=>{let{sectionId:t,lineId:n}=j({state:e}).pointer,o=k({state:e},{sectionId:t})?.lines||[],i=o.findIndex(l=>l.id===n),a=o.slice(0,i+1).map(l=>{let u=l.actions||{},f={};return Object.keys(u).forEach(d=>{f[d]=u[d]}),f});return de(a)},ri=({state:e})=>{let t=Bn({state:e}),r=jn({state:e})?.actions??{},o=de([t??{},r]);return st(t??{},o??{})},oi=({state:e},{sectionId:t})=>{let n=k({state:e},{sectionId:t});if(!n?.lines)return{lines:[]};let r=[],o={};for(let i of n.lines){let s=i.actions||{},a=de([o,s]),c=st(o,a);r.push({id:i.id,changes:c}),o=lt(a)}return{lines:r}},Bn=({state:e})=>{let{sectionId:t,lineId:n}=j({state:e}).pointer,o=k({state:e},{sectionId:t})?.lines||[],i=o.findIndex(c=>c.id===n);if(i<=0)return null;let a=o.slice(0,i).map(c=>{let l=c.actions||{},u={};return Object.keys(l).forEach(f=>{u[f]=l[f]}),u});return lt(de(a))},vt=({state:e},{slotsPerPage:t=6}={})=>{let o=(({...e.global.variables,...e.contexts[e.contexts.length-1].variables}.loadPage??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let a=o+s,c=e.global.saveSlots&&e.global.saveSlots[De(a)]||{};i.push({...c,slotId:a})}return{saveSlots:i}},ii=Mn,si=vt,li=e=>{let n=e.contexts?.[e.contexts.length-1]?.rollback;return!n||!Array.isArray(n.timeline)||typeof n.currentIndex!="number"?!1:n.currentIndex>=0&&n.currentIndex<n.timeline.length-1},ci=({state:e})=>{let t=zn({state:e}),n=Bn({state:e}),r={...e.global.variables,...e.contexts[e.contexts.length-1].variables},{saveSlots:o}=vt({state:e}),i=li(e);return En({presentationState:t,previousPresentationState:n,resources:e.projectData.resources,screen:e.projectData.screen,dialogueUIHidden:e.global.dialogueUIHidden,autoMode:e.global.autoMode,skipMode:e.global.skipMode,canRollback:Yn({state:e}),skipOnlyViewedLines:!r._skipUnseenText,isLineCompleted:e.global.isLineCompleted,skipTransitionsAndAnimations:!!r._skipTransitionsAndAnimations||i,layeredViews:e.global.layeredViews,confirmDialog:e.global.confirmDialog,dialogueHistory:Dn({state:e}),saveSlots:o,variables:r})},ai=({state:e},t)=>(e.global.confirmDialog=Mo(t),e.global.pendingEffects.push({name:"render"}),e),ui=({state:e})=>(e.global.confirmDialog&&(me(e),e.global.pendingEffects.push({name:"render"})),e),Et=({state:e},t)=>(e.global.layeredViews.push(t),e.global.pendingEffects.push({name:"render"}),W(e,"pushLayeredView",t),e),_t=({state:e})=>(e.global.layeredViews.pop(),e.global.pendingEffects.push({name:"render"}),W(e,"popLayeredView",void 0),e),$t=({state:e},t)=>(e.global.layeredViews.length>0&&(e.global.layeredViews[e.global.layeredViews.length-1]=t),e.global.pendingEffects.push({name:"render"}),W(e,"replaceLastLayeredView",t),e),Lt=({state:e})=>(e.global.layeredViews=[],me(e),e.global.pendingEffects.push({name:"render"}),W(e,"clearLayeredViews",void 0),e),Fn=({state:e})=>{if(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){let t=e.global.variables._autoForwardTime??1e3;e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:t}})}return e.global.pendingEffects.push({name:"render"}),e},be=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),fi=({state:e})=>(e.global.autoMode?be({state:e}):Fn({state:e}),e),Un=({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),te=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),di=({state:e})=>(Nn({state:e})?te({state:e}):Un({state:e}),e),le=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),W(e,"showDialogueUI",void 0),e),Me=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),W(e,"hideDialogueUI",void 0),e),Ct=({state:e})=>(Vn({state:e})?le({state:e}):Me({state:e}),e),pi=({state:e})=>(e.global.pendingEffects=[],e),hi=({state:e},t)=>(e.global.pendingEffects.push(t),e),ye=(e,{sectionId:t,lineId:n})=>{e.global.viewedRegistry||(e.global.viewedRegistry={}),Array.isArray(e.global.viewedRegistry.sections)||(e.global.viewedRegistry.sections=[]);let r=e.global.viewedRegistry.sections.find(o=>o.sectionId===t);if(r){let o=k({state:e},{sectionId:t});if(o?.lines&&r.lastLineId!==void 0){let i=o.lines.findIndex(a=>a.id===r.lastLineId),s=o.lines.findIndex(a=>a.id===n);(i===-1||s>i)&&(r.lastLineId=n)}else r.lastLineId=n}else e.global.viewedRegistry.sections.push({sectionId:t,lastLineId:n})},gi=({state:e},t)=>(ye(e,t),e.global.pendingEffects.push({name:"render"}),e),yi=({state:e},t)=>{let{resourceId:n}=t;return e.global.viewedRegistry.resources.find(o=>o.resourceId===n)||e.global.viewedRegistry.resources.push({resourceId:n}),e.global.pendingEffects.push({name:"render"}),e},kt=({state:e},t)=>{let n=ko(t.manual),{auto:r,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,a=e.contexts?.[e.contexts.length-1]?.rollback?.isRestoring===!0;n&&r?(e.global.nextLineConfig={manual:n,auto:r},o!==void 0?e.global.nextLineConfig.applyMode=o:s!==void 0&&(e.global.nextLineConfig.applyMode=s)):(n&&(e.global.nextLineConfig.manual=n),r&&(e.global.nextLineConfig.auto=r),o!==void 0&&(e.global.nextLineConfig.applyMode=o));let c=e.global.nextLineConfig.auto?.enabled;return!a&&c===!0&&!i?e.global.nextLineConfig.auto?.trigger==="fromStart"?e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):e.global.isLineCompleted&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):!a&&c===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),W(e,"setNextLineConfig",t),e},mi=({state:e},t)=>{let n=t?.slotId;if(n==null||n==="")throw new Error("saveSlot requires slotId");let{thumbnailImage:r}=t,o=t?.savedAt,i=De(n),s=V(e.contexts);s?.forEach(l=>{Tn(l.rollback)});let a={contexts:s,viewedRegistry:V(e.global.viewedRegistry)},c={formatVersion:Ln,slotId:Rn(n),savedAt:typeof o=="number"?o:Date.now(),image:r,state:a};return e.global.saveSlots[i]=c,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},bi=({state:e},t)=>{let n=t?.slotId;if(n==null||n==="")throw new Error("loadSlot requires slotId");let r=De(n),o=e.global.saveSlots[r];if(o){let i=Do(o,e.projectData);e.global.viewedRegistry=i.state.viewedRegistry,e.contexts=i.state.contexts,e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=V(U),e.global.layeredViews=[],e.global.isLineCompleted=!0,me(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},Ii=({state:e},t)=>{let{projectData:n}=t;return kn(n),e.projectData=n,me(e),e.global.pendingEffects.push({name:"render"}),e},wi=({state:e},t)=>{let{sectionId:n,lineId:r}=t;if(!r)return console.warn("jumpToLine requires lineId parameter"),e;let o=e.contexts[e.contexts.length-1];if(!o)return console.warn("No context available for jumpToLine"),e;let i=n||o.pointers.read?.sectionId;if(n&&!k({state:e},{sectionId:n}))return console.warn(`Section not found: ${n}`),e;let s=k({state:e},{sectionId:i});return!s?.lines||!Array.isArray(s.lines)?(console.warn(`Section ${i} has no lines`),e):s.lines.find(c=>c.id===r)?(o.pointers.read={sectionId:i,lineId:r},e.global.isLineCompleted=!1,e.global.pendingEffects.push({name:"handleLineActions"}),e):(console.warn(`Line not found: ${r} in section ${i}`),e)},Ai=({state:e})=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return le({state:e}),e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0;let c=j({state:e})?.pointer,l=c?.sectionId,u=c?.lineId;if(l&&u&&ye(e,{sectionId:l,lineId:u}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode){let d=e.global.variables._autoForwardTime??1e3;e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:d}})}let f=e.global.nextLineConfig;return f?.auto?.enabled&&f.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:f.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e}let t=j({state:e})?.pointer,n=t?.sectionId,r=k({state:e},{sectionId:n}),o=e.contexts[e.contexts.length-1],i=r?.lines||[],a=i.findIndex(c=>c.id===t?.lineId)+1;if(a<i.length){let c=i[a],l=!e.global.variables?._skipUnseenText;if(e.global.skipMode&&l&&!xt({state:e},{sectionId:n,lineId:c.id}))return te({state:e}),e;if(o&&!o.rollback&&ne(o,{compatibilityAnchor:!0}),o){let f=o.pointers.read.lineId;f&&n&&ye(e,{sectionId:n,lineId:f}),o.pointers.read={sectionId:n,lineId:c.id}}e.global.isLineCompleted=!1,At(e,{sectionId:n,lineId:c.id}),It(e),e.global.pendingEffects.push({name:"handleLineActions"});let u=e.global.nextLineConfig;u?.auto?.enabled&&u.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:u.auto.delay}})}else e.global.autoMode&&be({state:e}),e.global.skipMode&&te({state:e});return e},xi=({state:e})=>{if(e.global.isLineCompleted)return e;if(e.global.isLineCompleted=!0,e.global.autoMode){let i=e.global.variables._autoForwardTime??1e3;e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:i}})}let t=j({state:e})?.pointer,n=t?.sectionId,r=t?.lineId;n&&r&&ye(e,{sectionId:n,lineId:r});let o=e.global.nextLineConfig;return o?.auto?.enabled&&o.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:o.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e},vi=({state:e},t)=>{let n=t?.sectionId??j({state:e})?.pointer?.sectionId,r=k({state:e},{sectionId:n});if(!r||!r.lines||r.lines.length===0)return e;let o=r.lines,i=e.contexts[e.contexts.length-1];if(!i||!i.pointers)return e;let s=i.pointers.history||i.pointers.read;if(i.currentPointerMode!=="history"||!i.pointers.history){if(!s)return e;i.currentPointerMode="history",i.pointers.history={sectionId:n,lineId:s?.lineId};let u=o.findIndex(f=>f.id===s.lineId)-1;if(u>=0&&u<o.length){let f=o[u];i.pointers.history={sectionId:n,lineId:f.id}}return e.global.pendingEffects.push({name:"render"}),e}let c=o.findIndex(l=>l.id===i.pointers.history.lineId)-1;if(c>=0&&c<o.length){let l=o[c];i.pointers.history={sectionId:n,lineId:l.id},e.global.pendingEffects.push({name:"render"})}return e},Ei=({state:e},t)=>{let{sectionId:n}=t,r=k({state:e},{sectionId:n});if(!r)return console.warn(`Section not found: ${n}`),e;let o=r.lines?.[0];if(!o)return console.warn(`Section ${n} has no lines`),e;e.global.autoMode&&be({state:e}),e.global.skipMode&&te({state:e});let i=e.contexts[e.contexts.length-1];return i&&(i.rollback||ne(i,{compatibilityAnchor:!0}),i.pointers.read={sectionId:n,lineId:o.id},At(e,{sectionId:n,lineId:o.id})),e.global.isLineCompleted=!1,e.global.pendingEffects.push({name:"handleLineActions"}),e},_i=({state:e})=>{if(e.global.dialogueUIHidden)return le({state:e}),e;if(ni({state:e}))return e;let t=j({state:e})?.pointer,n=t?.sectionId,r=k({state:e},{sectionId:n}),o=e.contexts[e.contexts.length-1],i=r?.lines||[],a=i.findIndex(c=>c.id===t?.lineId)+1;if(a<i.length){let c=i[a],l=!e.global.variables?._skipUnseenText;if(e.global.skipMode&&l&&!xt({state:e},{sectionId:n,lineId:c.id}))return te({state:e}),e;if(o&&!o.rollback&&ne(o,{compatibilityAnchor:!0}),o){let u=o.pointers.read.lineId;u&&n&&ye(e,{sectionId:n,lineId:u}),o.pointers.read={sectionId:n,lineId:c.id}}e.global.isLineCompleted=!1,At(e,{sectionId:n,lineId:c.id}),It(e),e.global.pendingEffects.push({name:"handleLineActions"}),e.global.nextLineConfig.auto?.enabled&&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},$i=({state:e},t)=>{let{id:n,operations:r=[]}=t;if(!n)throw new Error("updateVariable requires an id field");if(typeof n!="string"||!/^[a-zA-Z0-9]+$/.test(n))throw new Error(`updateVariable id must be alphanumeric, got: "${n}"`);let o=e.contexts[e.contexts.length-1];if(o?.rollback?.isRestoring)return e;let i=!1,s=!1,a=!1,c=[];if(r.forEach(({variableId:l,op:u,value:f})=>{let d=e.projectData.resources?.variables?.[l],h=d?.scope,y=d?.type;Ce(h,l),ke(y,u,l);let g=h==="context"?o.variables:e.global.variables;h==="context"?(i=!0,c.push({variableId:l,op:u,value:f})):h==="global-device"?s=!0:h==="global-account"&&(a=!0),g[l]=Re(g[l],u,f)}),i&&W(e,"updateVariable",{id:n,operations:c}),s){let l=it(e.global.variables,e.projectData.resources?.variables,"global-device");e.global.pendingEffects.push({name:"saveGlobalDeviceVariables",payload:{globalDeviceVariables:l}})}if(a){let l=it(e.global.variables,e.projectData.resources?.variables,"global-account");e.global.pendingEffects.push({name:"saveGlobalAccountVariables",payload:{globalAccountVariables:l}})}return e.global.pendingEffects.push({name:"render"}),e},Wn=({state:e},t)=>{let{offset:n}=t;if(n===void 0||typeof n!="number")return console.warn("selectLineIdByOffset requires a numeric offset"),null;let r=e.contexts[e.contexts.length-1];if(!r)return null;let o=r.rollback;if(!Array.isArray(o?.timeline)||typeof o?.currentIndex!="number")return null;let i=o.currentIndex+n;if(i<0||i>=o.timeline.length)return null;let s=o.timeline[i];return{sectionId:s.sectionId,lineId:s.lineId}},Yn=({state:e})=>Wn({state:e},{offset:-1})!==null,Li=({state:e},t)=>{let{offset:n=-1}=t;if(n>=0)throw new Error("rollbackByOffset requires a negative offset");let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let o=ne(r,{compatibilityAnchor:!r.rollback}),i=o.currentIndex+n;return i<0||i>=o.timeline.length?e:Pn(e,i)},Ci=({state:e},t)=>{let{sectionId:n,lineId:r}=t,o=e.contexts[e.contexts.length-1];if(!o)throw new Error("No context available for rollbackToLine");let i=ne(o,{compatibilityAnchor:!o.rollback}),a=i.timeline.slice(0,i.currentIndex+1).findLastIndex(c=>c.sectionId===n&&c.lineId===r);if(a===-1)throw new Error(`Line ${r} not found in section ${n} rollback timeline`);return a===i.currentIndex?e:Pn(e,a)},Hn=e=>{let t=Ho(e);return rn(t,{selectPendingEffects:qo,selectSkipMode:Nn,selectAutoMode:Ko,selectDialogueUIHidden:Vn,selectDialogueHistory:Dn,selectConfirmDialog:Go,selectIsLineViewed:xt,selectIsResourceViewed:Xo,selectNextLineConfig:Zo,selectSystemState:Qo,selectSaveSlotMap:Mn,selectSaveSlots:ii,selectSaveSlot:ei,selectAllVariables:ti,selectCurrentPointer:j,selectSection:k,selectCurrentLine:jn,selectPresentationState:zn,selectPresentationChanges:ri,selectSectionLineChanges:oi,selectSaveSlotPage:vt,selectCurrentPageSlots:si,selectRenderState:ci,selectLayeredViews:Jo,selectLineIdByOffset:Wn,selectCanRollback:Yn,startAutoMode:Fn,stopAutoMode:be,toggleAutoMode:fi,startSkipMode:Un,stopSkipMode:te,toggleSkipMode:di,showDialogueUI:le,hideDialogueUI:Me,toggleDialogueUI:Ct,showConfirmDialog:ai,hideConfirmDialog:ui,clearPendingEffects:pi,appendPendingEffect:hi,beginRollbackActionBatch:zo,endRollbackActionBatch:Bo,addViewedLine:gi,addViewedResource:yi,setNextLineConfig:kt,saveSlot:mi,loadSlot:bi,updateProjectData:Ii,sectionTransition:Ei,jumpToLine:wi,nextLine:Ai,markLineCompleted:xi,prevLine:vi,rollbackToLine:Ci,rollbackByOffset:Li,pushLayeredView:Et,popLayeredView:_t,replaceLastLayeredView:$t,clearLayeredViews:Lt,updateVariable:$i,nextLineFromSystem:_i},{transformActionFirstArgument:r=>({state:r}),transformSelectorFirstArgument:r=>({state:r})})};function Rt(e){let t,n=0,{handlePendingEffects:r}=e,o=()=>{for(;t.selectPendingEffects().length>0;){let w=[...t.selectPendingEffects()];t.clearPendingEffects();try{r(w)}catch(E){throw t.clearPendingEffects(),w.forEach($=>{t.appendPendingEffect($)}),E}}},i=({initialState:w})=>{t=Hn(w),n=0,t.appendPendingEffect({name:"handleLineActions"}),o()},s=()=>t.selectPresentationState(),a=()=>t.selectPresentationChanges(),c=w=>t.selectSectionLineChanges(w),l=()=>(n+=1,{...t.selectRenderState(),id:`render-${n}`}),u=()=>t.selectSystemState(),f=()=>t.selectSaveSlotMap(),d=w=>t.selectSaveSlot(w),h=w=>t.selectSaveSlotPage(w),y=()=>t.selectSkipMode(),g=()=>t.selectAutoMode(),I=(w,E)=>{t[w]&&(t[w](E),o())},m=(w,E)=>{I(w,E)},b=w=>{if(!w)return{variables:t.selectAllVariables?t.selectAllVariables():void 0};if(Object.prototype.hasOwnProperty.call(w,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:E,...$}=w,M=t.selectAllVariables?t.selectAllVariables():void 0;return{...$,_event:E,variables:M}},A=(w,E)=>{let $=b(E),M=sn(w,$);t.beginRollbackActionBatch({});try{Object.entries(M).forEach(([ze,re])=>{I(ze,re)})}finally{t.endRollbackActionBatch({})}};return{init:i,handleAction:I,handleInternalAction:m,handleActions:A,selectRenderState:l,selectPresentationState:s,selectPresentationChanges:a,selectSectionLineChanges:c,selectSystemState:u,selectSaveSlotMap:f,selectSaveSlot:d,selectSaveSlotPage:h,selectSaveSlots:f,handleLineActions:()=>{let w=t.selectCurrentLine();return w?.actions?(A(w.actions),!0):!1}}}var St=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:n=>{e=n},addElapsed:n=>{e+=n},getCallback:()=>t,setCallback:n=>{t=n}}},qn=({engine:e,routeGraphics:t,trackRenderDispatch:n},r)=>{let o=e.selectRenderState();n?.(o),t.render(o)},ki=({engine:e,routeGraphics:t,trackRenderDispatch:n,getRenderDispatchCount:r},o)=>{let i=r?.()??0,s=e.handleLineActions();(r?.()??0)===i&&qn({engine:e,routeGraphics:t,trackRenderDispatch:n},o)},Ri=({engine:e,ticker:t,autoTimer:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let a=r.delay??1e3;n.getElapsed()>=a&&(t.remove(i),n.setCallback(null),n.setElapsed(0),je(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},Si=({ticker:e,autoTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Oi=({engine:e,ticker:t,skipTimer:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS),n.getElapsed()>=30&&(n.setElapsed(0),je(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},Ti=({ticker:e,skipTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Pi=({engine:e,ticker:t,nextLineConfigTimerState:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let a=r.delay??1e3;n.getElapsed()>=a&&(n.setElapsed(0),je(e,"nextLineFromSystem",{}),t.remove(i),n.setCallback(null))};n.setCallback(i),t.add(i)},Ni=({ticker:e,nextLineConfigTimerState:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Vi=({},e)=>{localStorage.setItem("saveSlots",JSON.stringify(e.saveSlots))},Di=({},e)=>{localStorage.setItem("globalDeviceVariables",JSON.stringify(e.globalDeviceVariables))},Mi=({},e)=>{localStorage.setItem("globalAccountVariables",JSON.stringify(e.globalAccountVariables))},Jn={render:qn,saveSlots:Vi,saveGlobalDeviceVariables:Di,saveGlobalAccountVariables:Mi,handleLineActions:ki,startAutoNextTimer:Ri,clearAutoNextTimer:Si,startSkipNextTimer:Oi,clearSkipNextTimer:Ti,nextLineConfigTimer:Pi,clearNextLineConfigTimer:Ni},ji=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),je=(e,t,n)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,n)},zi=(e=[])=>{let t=new Set,n=[];for(let r=e.length-1;r>=0;r-=1){let o=e[r];if(typeof o?.name!="string"||o.name.length===0)throw new Error("Pending effect is missing a valid name.");if(!ji.has(o.name)){n.unshift(o);continue}t.has(o.name)||(t.add(o.name),n.unshift(o))}return n},Bi=({getEngine:e,routeGraphics:t,ticker:n,handleUnhandledEffect:r})=>{let o=St(),i=St(),s=St(),a=null,c=null,l=!1,u=0,f=m=>{let b=typeof m?.id=="string"&&m.id.length>0?m.id:null;u+=1,a=b,l=!1},d=()=>u,h=(m={})=>{if(m?.aborted===!0)return!1;let b=typeof m?.id=="string"&&m.id.length>0?m.id:null;return b?b!==a||b===c?!1:(c=b,!0):a!==null||l?!1:(l=!0,!0)},y=(m,b={})=>{if(m!=="renderComplete"||!h(b))return!1;let A=e();return je(A,"markLineCompleted",{}),!0},g=({preprocessPayload:m,onEvent:b}={})=>async(A,x={})=>{let w=await m?.(A,x)??x;if(y(A,w),w?.actions){let E=w?._event?{_event:w._event}:w?.event?{_event:w.event}:void 0;e().handleActions(w.actions,E)}return b?.(A,w)},I=m=>{let b=e(),A=zi(m);A.forEach(w=>{if(!Jn[w.name]&&!r)throw new Error(`Unhandled pending effect "${w.name}".`)});let x={engine:b,routeGraphics:t,ticker:n,autoTimer:o,skipTimer:i,nextLineConfigTimerState:s,trackRenderDispatch:f,getRenderDispatchCount:d};for(let w of A){let E=Jn[w.name];if(E){E(x,w.payload);continue}r(w,x)}};return I.handleRouteGraphicsEvent=y,I.createRouteGraphicsEventHandler=g,I},Fi=Bi;var Ui=(e,t={})=>{let{resources:n={}}=t;return mt(e,n)};var Ws=Rt;export{Fi as createEffectsHandler,Ws as default,Ui as resolveLayoutReferences};
1
+ var nr=Object.defineProperty;var rr=(e,t)=>{for(var n in t)nr(e,n,{get:t[n],enumerable:!0})};var Ut=Symbol.for("immer-nothing"),Mt=Symbol.for("immer-draftable"),O=Symbol.for("immer-state");function D(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var oe=Object.getPrototypeOf;function z(e){return!!e&&!!e[O]}function Y(e){return e?Wt(e)||Array.isArray(e)||!!e[Mt]||!!e.constructor?.[Mt]||ve(e)||Ee(e):!1}var or=Object.prototype.constructor.toString();function Wt(e){if(!e||typeof e!="object")return!1;let t=oe(e);if(t===null)return!0;let n=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return n===Object?!0:typeof n=="function"&&Function.toString.call(n)===or}function Ie(e,t){Ae(e)===0?Reflect.ownKeys(e).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function Ae(e){let t=e[O];return t?t.type_:Array.isArray(e)?1:ve(e)?2:Ee(e)?3:0}function Ye(e,t){return Ae(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Yt(e,t,n){let r=Ae(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function ir(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function ve(e){return e instanceof Map}function Ee(e){return e instanceof Set}function W(e){return e.copy_||e.base_}function He(e,t){if(ve(e))return new Map(e);if(Ee(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let n=Wt(e);if(t===!0||t==="class_only"&&!n){let r=Object.getOwnPropertyDescriptors(e);delete r[O];let o=Reflect.ownKeys(r);for(let i=0;i<o.length;i++){let s=o[i],a=r[s];a.writable===!1&&(a.writable=!0,a.configurable=!0),(a.get||a.set)&&(r[s]={configurable:!0,writable:!0,enumerable:a.enumerable,value:e[s]})}return Object.create(oe(e),r)}else{let r=oe(e);if(r!==null&&n)return{...e};let o=Object.create(r);return Object.assign(o,e)}}function Xe(e,t=!1){return _e(e)||z(e)||!Y(e)||(Ae(e)>1&&(e.set=e.add=e.clear=e.delete=sr),Object.freeze(e),t&&Object.entries(e).forEach(([n,r])=>Xe(r,!0))),e}function sr(){D(2)}function _e(e){return Object.isFrozen(e)}var lr={};function H(e){let t=lr[e];return t||D(0,e),t}var ue;function Ht(){return ue}function cr(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function jt(e,t){t&&(H("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Je(e){qe(e),e.drafts_.forEach(ar),e.drafts_=null}function qe(e){e===ue&&(ue=e.parent_)}function Bt(e){return ue=cr(ue,e)}function ar(e){let t=e[O];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function zt(e,t){t.unfinalizedDrafts_=t.drafts_.length;let n=t.drafts_[0];return e!==void 0&&e!==n?(n[O].modified_&&(Je(t),D(4)),Y(e)&&(e=we(t,e),t.parent_||xe(t,e)),t.patches_&&H("Patches").generateReplacementPatches_(n[O].base_,e,t.patches_,t.inversePatches_)):e=we(t,n,[]),Je(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Ut?e:void 0}function we(e,t,n){if(_e(t))return t;let r=t[O];if(!r)return Ie(t,(o,i)=>Ft(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return xe(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;let o=r.copy_,i=o,s=!1;r.type_===3&&(i=new Set(o),o.clear(),s=!0),Ie(i,(a,c)=>Ft(e,r,o,a,c,n,s)),xe(e,o,!1),n&&e.patches_&&H("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function Ft(e,t,n,r,o,i,s){if(z(o)){let a=i&&t&&t.type_!==3&&!Ye(t.assigned_,r)?i.concat(r):void 0,c=we(e,o,a);if(Yt(n,r,c),z(c))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if(Y(o)&&!_e(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;we(e,o),(!t||!t.scope_.parent_)&&typeof r!="symbol"&&Object.prototype.propertyIsEnumerable.call(n,r)&&xe(e,o)}}function xe(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&Xe(t,n)}function ur(e,t){let n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:Ht(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=r,i=Ze;n&&(o=[r],i=fe);let{revoke:s,proxy:a}=Proxy.revocable(o,i);return r.draft_=a,r.revoke_=s,a}var Ze={get(e,t){if(t===O)return e;let n=W(e);if(!Ye(n,t))return fr(e,n,t);let r=n[t];return e.finalized_||!Y(r)?r:r===Ue(e.base_,t)?(We(e),e.copy_[t]=Ge(r,e)):r},has(e,t){return t in W(e)},ownKeys(e){return Reflect.ownKeys(W(e))},set(e,t,n){let r=Jt(W(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){let o=Ue(W(e),t),i=o?.[O];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(ir(n,o)&&(n!==void 0||Ye(e.base_,t)))return!0;We(e),Ke(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return Ue(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,We(e),Ke(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let n=W(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){D(11)},getPrototypeOf(e){return oe(e.base_)},setPrototypeOf(){D(12)}},fe={};Ie(Ze,(e,t)=>{fe[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});fe.deleteProperty=function(e,t){return fe.set.call(this,e,t,void 0)};fe.set=function(e,t,n){return Ze.set.call(this,e[0],t,n,e[0])};function Ue(e,t){let n=e[O];return(n?W(n):e)[t]}function fr(e,t,n){let r=Jt(t,n);return r?"value"in r?r.value:r.get?.call(e.draft_):void 0}function Jt(e,t){if(!(t in e))return;let n=oe(e);for(;n;){let r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=oe(n)}}function Ke(e){e.modified_||(e.modified_=!0,e.parent_&&Ke(e.parent_))}function We(e){e.copy_||(e.copy_=He(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var dr=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){let i=n;n=t;let s=this;return function(c=i,...l){return s.produce(c,u=>n.call(this,u,...l))}}typeof n!="function"&&D(6),r!==void 0&&typeof r!="function"&&D(7);let o;if(Y(t)){let i=Bt(this),s=Ge(t,void 0),a=!0;try{o=n(s),a=!1}finally{a?Je(i):qe(i)}return jt(i,r),zt(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===Ut&&(o=void 0),this.autoFreeze_&&Xe(o,!0),r){let i=[],s=[];H("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else D(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...a)=>this.produceWithPatches(s,c=>t(c,...a));let r,o;return[this.produce(t,n,(s,a)=>{r=s,o=a}),r,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){Y(e)||D(8),z(e)&&(e=Qe(e));let t=Bt(this),n=Ge(e,void 0);return n[O].isManual_=!0,qe(t),n}finishDraft(e,t){let n=e&&e[O];(!n||!n.isManual_)&&D(9);let{scope_:r}=n;return jt(r,t),zt(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){let o=t[n];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}n>-1&&(t=t.slice(n+1));let r=H("Patches").applyPatches_;return z(e)?r(e,t):this.produce(e,o=>r(o,t))}};function Ge(e,t){let n=ve(e)?H("MapSet").proxyMap_(e,t):Ee(e)?H("MapSet").proxySet_(e,t):ur(e,t);return(t?t.scope_:Ht()).drafts_.push(n),n}function Qe(e){return z(e)||D(10,e),qt(e)}function qt(e){if(!Y(e)||_e(e))return e;let t=e[O],n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=He(e,t.scope_.immer_.useStrictShallowCopy_)}else n=He(e,!0);return Ie(n,(r,o)=>{Yt(n,r,qt(o))}),t&&(t.finalized_=!1),n}var T=new dr,et=T.produce,ts=T.produceWithPatches.bind(T),ns=T.setAutoFreeze.bind(T),rs=T.setUseStrictShallowCopy.bind(T),os=T.applyPatches.bind(T),is=T.createDraft.bind(T),ss=T.finishDraft.bind(T);var p={LITERAL:0,VARIABLE:1,INTERPOLATION:2,FUNCTION:3,BINARY:4,UNARY:5,CONDITIONAL:6,LOOP:7,OBJECT:8,ARRAY:9,PARTIAL:10,PATH_REFERENCE:11},L={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},de={NOT:0};var v=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},R=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var tt=e=>{if(!e||e.trim()==="")throw new v("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let n=e.includes("===")?"==":"!=";throw new v(`Invalid comparison operator '${e.includes("===")?"===":"!=="}' - did you mean '${n}'? (got: '${e}')`)}let t=["<",">","<=",">=","==","!="];for(let n of t)if(e.trim().endsWith(n))throw new v(`Incomplete comparison expression - missing right operand (got: '${e}')`)},Kt=e=>{if(e.trim().endsWith(" in"))throw new v(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new v(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,n]=e.split(" in ");if(!n||n.trim()==="")throw new v(`Missing iterable expression after 'in' (got: '$for ${e}')`);let r=t.includes(",")?t.split(",").map(o=>o.trim()):[t.trim()];for(let o of r){if(!o)throw new v(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new v(`Invalid loop syntax (got: '$for ${e}')`)}};var Gt=(e,t,n=!1)=>{if(t===null)return new R(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new R(`Cannot iterate over undefined value at '$for ${e}'`);let r=typeof t;return n?new R(`Cannot iterate over non-array value in loop '${e}' - got ${r} instead`):new R(`Cannot iterate over non-array value (got: ${r}) at '$for ${e}'`)},Xt=(e,t)=>{let n=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new R(`Unknown function '${e}' (${n})`)};var pr=(e,t,n={})=>{let r={},o={};n&&typeof n=="object"&&(n.functions!==void 0||n.partials!==void 0?(r=n.functions||{},o=n.partials||{}):typeof n=="object"&&(r=n));let s=_(e,{functions:r,partials:o},t,{});return s===void 0?{}:s},_=(e,t,n,r)=>{let o=t.functions||t;if(e.var&&!e.type)return C(e.var,n,r);if(e.type===p.LITERAL)return e.value;if(e.type===p.VARIABLE)return C(e.path,n,r);if(e.type===p.INTERPOLATION)return gr(e.parts,t,n,r);switch(e.type){case p.FUNCTION:return Qt(e,t,n,r);case p.BINARY:return en(e,t,n,r);case p.UNARY:return tn(e,t,n,r);case p.CONDITIONAL:return mr(e,t,n,r);case p.LOOP:return Ar(e,t,n,r);case p.OBJECT:return Er(e,t,n,r);case p.ARRAY:return _r(e,t,n,r);case p.PARTIAL:return $r(e,t,n,r);case p.PATH_REFERENCE:return Lr(e,t,n,r);default:throw new Error(`Unknown node type: ${e.type}`)}},Zt=new Map,hr=e=>{let t=[],n="",r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(i==="[")n&&(t.push({type:"property",value:n}),n=""),r=!0;else if(i==="]"){if(r&&n){let s=n.trim();if(/^\d+$/.test(s))t.push({type:"index",value:parseInt(s,10)});else if(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'")){let a=s.slice(1,-1);t.push({type:"property",value:a})}else t.push({type:"property",value:s});n=""}r=!1}else n+=i}return n&&t.push({type:"property",value:n}),t},C=(e,t,n)=>{if(!e)return;if(e in n)return n[e];let r=Zt.get(e);if(!r){let i=[],s="",a=0;for(let c=0;c<e.length;c++){let l=e[c];l==="["?(a++,s+=l):l==="]"?(a--,s+=l):l==="."&&a===0?s&&(i.push(s),s=""):s+=l}s&&i.push(s),r=[];for(let c of i){let l=hr(c.trim());r.push(...l)}Zt.set(e,r)}let o=t;for(let i=0;i<r.length;i++){let s=r[i];if(s.type==="property"&&s.value in n){o=n[s.value];continue}if(o==null)return;(s.type==="property"||s.type==="index")&&(o=o[s.value])}return o},gr=(e,t,n,r)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=_(i,t,n,r);o.push(s!=null?String(s):"")}return o.join("")},Qt=(e,t,n,r)=>{let o=t.functions||t,i=o[e.name];if(!i)throw Xt(e.name,o);let s=e.args.map(a=>_(a,t,n,r));return i(...s)},ie=(e,t,n,r)=>{if(e.var&&!e.type)return C(e.var,n,r);switch(e.type){case p.VARIABLE:return C(e.path,n,r);case p.LITERAL:return e.value;case p.BINARY:return en(e,t,n,r);case p.UNARY:return tn(e,t,n,r);case p.FUNCTION:return Qt(e,t,n,r);default:return _(e,t,n,r)}},en=(e,t,n,r)=>{if(e.op===L.AND||e.op===L.OR){let s=ie(e.left,t,n,r),a=ie(e.right,t,n,r);switch(e.op){case L.AND:return s&&a;case L.OR:return s||a}}let o=_(e.left,t,n,r),i=_(e.right,t,n,r);switch(e.op){case L.EQ:return o==i;case L.NEQ:return o!=i;case L.GT:return o>i;case L.LT:return o<i;case L.GTE:return o>=i;case L.LTE:return o<=i;case L.IN:return Array.isArray(i)?i.includes(o):!1;case L.ADD:if(typeof o!="number"||typeof i!="number")throw new R(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case L.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new R(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},tn=(e,t,n,r)=>{let o=e.op===de.NOT?ie(e.operand,t,n,r):_(e.operand,t,n,r);if(e.op===de.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},yr=(e,t,n,r)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===p.VARIABLE)if(C(o.path,n,r)){let s=e.bodies[0];if(s.type===p.OBJECT&&s.properties.length<=5){let a={};for(let c of s.properties){let l=c.parsedKey?_(c.parsedKey,t,n,r):c.key,u=c.value;if(u.type===p.LITERAL)a[l]=u.value;else if(u.type===p.VARIABLE)a[l]=C(u.path,n,r);else if(u.type===p.INTERPOLATION){let f=[];for(let d of u.parts)if(typeof d=="string")f.push(d);else if(d.type===p.VARIABLE){let h=C(d.path,n,r);f.push(h!=null?String(h):"")}else{let h=_(d,t,n,r);f.push(h!=null?String(h):"")}a[l]=f.join("")}else a[l]=_(u,t,n,r)}return a}}else{let s=e.bodies[1];if(s.type===p.OBJECT&&s.properties.length<=5){let a={};for(let c of s.properties){let l=c.parsedKey?_(c.parsedKey,t,n,r):c.key,u=c.value;if(u.type===p.LITERAL)a[l]=u.value;else if(u.type===p.VARIABLE)a[l]=C(u.path,n,r);else if(u.type===p.INTERPOLATION){let f=[];for(let d of u.parts)if(typeof d=="string")f.push(d);else if(d.type===p.VARIABLE){let h=C(d.path,n,r);f.push(h!=null?String(h):"")}else{let h=_(d,t,n,r);f.push(h!=null?String(h):"")}a[l]=f.join("")}else a[l]=_(u,t,n,r)}return a}}}return null},mr=(e,t,n,r)=>{let o=yr(e,t,n,r);if(o!==null)return o;for(let i=0;i<e.conditions.length;i++){let s=e.conditions[i];if(s===null||ie(s,t,n,r))return _(e.bodies[i],t,n,r)}return nn},br=(e,t)=>{let n=e.body,r=e.itemVar;if(n.type===p.CONDITIONAL&&n.conditions.length===1&&n.conditions[0].type===p.VARIABLE){let o=n.conditions[0].path,i=n.bodies[0];if(o.startsWith(r+".")){let s=o.substring(r.length+1);if(i.type===p.OBJECT&&i.properties.length<=5){for(let c of i.properties)if(c.parsedKey)return null;let a=[];for(let c=0;c<t.length;c++){let l=t[c];if(l[s]){let u={};for(let f of i.properties){let d=f.key,h=f.value;if(h.type===p.LITERAL)u[d]=h.value;else if(h.type===p.VARIABLE){let y=h.path;if(y===r)u[d]=l;else if(y.startsWith(r+".")){let g=y.substring(r.length+1);u[d]=l[g]}else return null}else if(h.type===p.INTERPOLATION){let y=[],g=!0;for(let I of h.parts)if(typeof I=="string")y.push(I);else if(I.type===p.VARIABLE){let m=I.path;if(m===r)y.push(l!=null?String(l):"");else if(m.startsWith(r+".")){let b=m.substring(r.length+1),x=l[b];y.push(x!=null?String(x):"")}else{g=!1;break}}else{g=!1;break}if(!g)return null;u[d]=y.join("")}else return null}a.push(u)}}return a}}}return null},Ir=(e,t)=>{let n=e.body,r=e.itemVar,o=br(e,t);if(o!==null)return o;if(n.type===p.OBJECT&&n.properties.length<=5&&!n.whenCondition){for(let a of n.properties)if(a.parsedKey)return null;let i=[],s=!0;for(let a of n.properties){let c=a.key,l=a.value;if(l.type===p.LITERAL)i.push({key:c,type:"literal",value:l.value});else if(l.type===p.VARIABLE){let u=l.path;if(u===r)i.push({key:c,type:"item"});else if(u.startsWith(r+".")){let f=u.substring(r.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:c,type:"prop",prop:f});else{s=!1;break}}else{s=!1;break}}else if(l.type===p.INTERPOLATION&&l.parts.length===1){let u=l.parts[0];if(u.type===p.VARIABLE){let f=u.path;if(f===r)i.push({key:c,type:"item_string"});else if(f.startsWith(r+".")){let d=f.substring(r.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:c,type:"prop_string",prop:d});else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}if(s){let a=new Array(t.length);if(i.length===3&&i[0].type==="prop"&&i[0].key==="id"&&i[1].type==="prop_string"&&i[1].key==="title"&&i[2].type==="prop"&&i[2].key==="completed")for(let c=0;c<t.length;c++){let l=t[c];a[c]={id:l.id,title:l.title!=null?String(l.title):"",completed:l.completed}}else for(let c=0;c<t.length;c++){let l=t[c],u={};for(let f of i)if(f.type==="literal")u[f.key]=f.value;else if(f.type==="item")u[f.key]=l;else if(f.type==="prop")u[f.key]=l[f.prop];else if(f.type==="item_string")u[f.key]=l!=null?String(l):"";else if(f.type==="prop_string"){let d=l[f.prop];u[f.key]=d!=null?String(d):""}a[c]=u}return a}}return null},wr=(e,t,n,r,o)=>{let i=[],s=e.body;if(s.type===p.OBJECT&&s.fast!==!1){let a=e.itemVar,c=e.indexVar;for(let l=0;l<o.length;l++){let u=o[l],f={},d={...r,[a]:u,...c&&{[c]:l}};d.__paths__||(d.__paths__=r.__paths__||{});let h=e.iterable.path||"";if(r&&r.__paths__&&h){let y=h.split("."),g=y[0];g in r.__paths__&&(h=r.__paths__[g],y.length>1&&(h+="."+y.slice(1).join(".")))}d.__paths__={...d.__paths__,[a]:`${h}[${l}]`,...c&&{[c]:l}};for(let y of s.properties){let g=y.parsedKey?_(y.parsedKey,t,n,d):y.key,I=y.value;if(I.type===p.LITERAL)f[g]=I.value;else if(I.type===p.VARIABLE){let m=I.path;if(m===a)f[g]=u;else if(m===c)f[g]=l;else if(m.startsWith(a+".")){let b=m.substring(a.length+1);!b.includes(".")&&!b.includes("[")?f[g]=u[b]:f[g]=C(m,n,{...r,[a]:u,...c&&{[c]:l}})}else f[g]=C(m,n,{...r,[a]:u,...c&&{[c]:l}})}else if(I.type===p.INTERPOLATION){let m=[];for(let b of I.parts)if(typeof b=="string")m.push(b);else if(b.type===p.VARIABLE){let x=b.path,A;if(x===a)A=u;else if(x===c)A=l;else if(x.startsWith(a+".")){let w=x.substring(a.length+1);!w.includes(".")&&!w.includes("[")?A=u[w]:A=C(x,n,{...r,[a]:u,...c&&{[c]:l}})}else A=C(x,n,{...r,[a]:u,...c&&{[c]:l}});m.push(A!=null?String(A):"")}else{let x={...r,[a]:u,...c&&{[c]:l}},A=_(b,t,n,x);m.push(A!=null?String(A):"")}f[g]=m.join("")}else{let m={...r,[a]:u,...c&&{[c]:l}};f[g]=_(I,t,n,m)}}i.push(f)}return i}return null},xr=(e,t,n)=>{let r=e.body;if(r.type===p.OBJECT&&r.properties.length===1&&r.properties[0].key==="$if item.visible"){let i=r.properties[0].value;if(i.type===p.CONDITIONAL&&i.conditions.length===1&&i.conditions[0].type===p.VARIABLE&&i.conditions[0].path==="item.visible"){let s=i.bodies[0];if(s.type===p.OBJECT&&s.properties.length===2){let a=s.properties[0],c=s.properties[1];if(a.key==="id"&&a.value.type===p.VARIABLE&&a.value.path==="item.id"&&c.key==="$if item.highlighted"&&c.value.type===p.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},Ar=(e,t,n,r)=>{let o=_(e.iterable,t,n,r);if(!Array.isArray(o)){let l,u=!1;if(e.iterable.type===p.FUNCTION){u=!0;let d=e.iterable.args.map(h=>h.type===p.LITERAL?typeof h.value=="string"?`'${h.value}'`:String(h.value):h.type===p.VARIABLE?h.path:h.type===p.FUNCTION?`${h.name}(...)`:"?").join(", ");l=`${e.iterable.name}(${d})`}else l=e.iterable.path||"undefined";let f=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${l}`;throw Gt(f,o,u)}if(!e.indexVar){let l=xr(e,o,e.itemVar);if(l!==null)return l}if(!e.indexVar){let l=Ir(e,o);if(l!==null)return l}let i=wr(e,t,n,r,o);if(i!==null)return i;let s=[],a=e.iterable.path||"";if(r&&r.__paths__&&a){let l=a.split("."),u=l[0];u in r.__paths__&&(a=r.__paths__[u],l.length>1&&(a+="."+l.slice(1).join(".")))}let c=!1;e.body.type===p.ARRAY&&(e.body.items.length<=1?c=!1:c=e.body._shouldPreserveArray??=e.body.items.some(l=>l.type===p.OBJECT&&l.properties.some(u=>u.key.startsWith("$if ")||u.key.startsWith("$when "))));for(let l=0;l<o.length;l++){let u=e.indexVar?{...r,[e.itemVar]:o[l],[e.indexVar]:l}:{...r,[e.itemVar]:o[l]};u.__paths__||(u.__paths__=r.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${a}[${l}]`},e.indexVar&&(u.__paths__[e.indexVar]=l);let f=_(e.body,t,n,u);if(Array.isArray(f)&&f.length===1&&!c){let d=f[0];s.push(d===void 0?{}:d)}else s.push(f===void 0?{}:f)}return s},vr=(e,t,n,r)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?_(o.parsedKey,t,n,r):o.key,s=o.value;if(s.type===p.OBJECT&&s.properties.length<=10&&!s.whenCondition){let a={},c={},l=!0;for(let u of s.properties){let f=u.parsedKey?_(u.parsedKey,t,n,r):u.key,d=u.value;if(d.type===p.LITERAL)c[f]=d.value;else if(d.type===p.VARIABLE)c[f]=C(d.path,n,r);else if(d.type===p.INTERPOLATION){let h=[];for(let y of d.parts)if(typeof y=="string")h.push(y);else if(y.type===p.VARIABLE){let g=C(y.path,n,r);h.push(g!=null?String(g):"")}else{l=!1;break}if(!l)break;c[f]=h.join("")}else if(d.type===p.OBJECT&&d.properties.length<=5){let h={};for(let y of d.properties){let g=y.key,I=y.value;if(I.type===p.LITERAL)h[g]=I.value;else if(I.type===p.VARIABLE)h[g]=C(I.path,n,r);else if(I.type===p.INTERPOLATION){let m=[];for(let b of I.parts)if(typeof b=="string")m.push(b);else if(b.type===p.VARIABLE){let x=C(b.path,n,r);m.push(x!=null?String(x):"")}else{l=!1;break}if(!l)break;h[g]=m.join("")}else{l=!1;break}}if(!l)break;c[f]=h}else{l=!1;break}}if(l)return a[i]=c,a}}return null},Er=(e,t,n,r)=>{let o=t.functions||t;if(e.whenCondition&&!ie(e.whenCondition,o,n,r))return;let i=vr(e,t,n,r);if(i!==null)return i;if(e.fast){let l={};for(let u of e.properties){let f=u.parsedKey?_(u.parsedKey,t,n,r):u.key,d=u.value;if(d.type===p.LITERAL)l[f]=d.value;else if(d.type===p.VARIABLE)l[f]=C(d.path,n,r);else if(d.type===p.INTERPOLATION){let h=[];for(let y of d.parts)if(typeof y=="string")h.push(y);else if(y.type===p.VARIABLE){let g=C(y.path,n,r);h.push(g!=null?String(g):"")}else{let g=_(y,t,n,r);h.push(g!=null?String(g):"")}l[f]=h.join("")}else l[f]=_(d,t,n,r)}return l}let s={},a=null,c=!1;for(let l of e.properties)if(!l.key.startsWith("$if ")&&!l.key.match(/^\$if\s+\w+.*:?$/)&&!l.key.startsWith("$elif")&&!l.key.startsWith("$else")&&!l.key.startsWith("$for ")){c=!0;break}for(let l of e.properties)if(l.key.startsWith("$if ")||l.key.match(/^\$if\s+\w+.*:?$/)){let u=_(l.value,t,n,r);if(!c&&u!==null&&u!==void 0)return Array.isArray(u)&&u.length===1?u[0]:u;typeof u=="object"&&u!==null&&!Array.isArray(u)&&Object.assign(s,u)}else if(l.key.startsWith("$for ")){if(e.properties.length===1)return _(l.value,t,n,r)}else{let u=l.value;if(u&&u.type===p.OBJECT&&u.properties){let f=u.properties.find(d=>d.key.startsWith("$for "));if(f){let d=_(f.value,t,n,r);d!==void 0&&(s[l.key]=d)}else{let d=_(l.value,t,n,r);d!==void 0&&(s[l.key]=d)}}else{let f=l.parsedKey?_(l.parsedKey,t,n,r):l.key,d=_(l.value,t,n,r);d!==void 0&&(s[f]=d)}}return s},nn={},_r=(e,t,n,r)=>{let o=[];for(let i of e.items)if(i.type===p.LOOP){let s=_(i,t,n,r);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=_(i,t,n,r);s!==nn&&s!==void 0&&o.push(s)}return o},$r=(e,t,n,r)=>{let{name:o,data:i,whenCondition:s}=e,a=t.partials||{},c=t.functions||t;if(s&&!ie(s,c,n,r))return;if(!a[o])throw new R(`Partial '${o}' is not defined`);let l=r._partialStack||[];if(l.includes(o))throw new R(`Circular partial reference detected: ${o}`);let u=a[o],f=n,d={...r,_partialStack:[...l,o]};if(r){f={...n};for(let h of Object.keys(r))h.startsWith("_")||(f[h]=r[h])}if(i){let h=_(i,t,n,r);f={...f,...h}}return _(u,t,f,d)},Lr=(e,t,n,r)=>{let{path:o}=e,i=o.split("."),s=i[0],a=i.slice(1);if(!r||!(s in r))throw new R(`Path reference '#{${o}}' refers to '${s}' which is not a loop variable in the current scope`);if(r.__paths__||(r.__paths__={}),!(s in r.__paths__))throw new R(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let c=r.__paths__[s];if(typeof c=="number"){if(a.length>0)throw new R(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(c)}return a.length>0&&(c+="."+a.join(".")),c},nt=pr;var Cr=/\$\{([^}]*)\}/g,kr=/#\{([^}]*)\}/g,on=(e,t={})=>{let n=e.match(/^(\w+)\((.*)\)$/);if(!n)return{isFunction:!1};let[,r,o]=n,i=Sr(o,t);return{isFunction:!0,type:p.FUNCTION,name:r,args:i}},Sr=(e,t={})=>e.trim()?Rr(e).map(r=>Or(r.trim(),t)):[],Rr=e=>{let t=[],n="",r=0,o=!1,i="";for(let s=0;s<e.length;s++){let a=e[s],c=s>0?e[s-1]:"";!o&&(a==='"'||a==="'")?(o=!0,i=a,n+=a):o&&a===i&&c!=="\\"?(o=!1,i="",n+=a):!o&&a==="("?(r++,n+=a):!o&&a===")"?(r--,n+=a):!o&&a===","&&r===0?(t.push(n),n=""):n+=a}return n&&t.push(n),t},Or=(e,t={})=>{if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:p.LITERAL,value:e.slice(1,-1)};if(/^-?\d+(\.\d+)?$/.test(e))return{type:p.LITERAL,value:parseFloat(e)};if(e==="true")return{type:p.LITERAL,value:!0};if(e==="false")return{type:p.LITERAL,value:!1};if(e==="null")return{type:p.LITERAL,value:null};let n=on(e,t);if(n.isFunction)return{type:n.type,name:n.name,args:n.args};let r=e.trim(),o=[{op:" + ",type:"ADD"},{op:" - ",type:"SUBTRACT"}],i=-1,s=null;for(let{op:a,type:c}of o){let l=0;for(;l<r.length;){let u=J(r.substring(l),a);if(u===-1)break;let f=l+u;f>i&&(i=f,s={op:a,type:c}),l=f+a.length}}if(i!==-1)try{return S(r,t)}catch{return{type:p.VARIABLE,path:r}}return{type:p.VARIABLE,path:r}},sn=/^\w+\(.*\)$/,Tr=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,Pr=e=>{if(!(!e||e.trim()===""||sn.test(e))&&Tr.test(e))throw e.includes("?")&&e.includes(":")?new v(`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 v(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new v(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},rn=e=>{let t=e.trim();if(sn.test(t))throw new v(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new v(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new v(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new v(`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 v(`Complex expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);return{type:p.PATH_REFERENCE,path:t}},pe=(e,t={})=>{let n=e.trim();Pr(n);let r=on(n,t);if(r.isFunction)return{type:r.type,name:r.name,args:r.args};if(n.includes("[")&&!/[\s+\-*/%|&?:]/.test(n)){let o=0;for(let i of n)i==="["?o++:i==="]"&&o--;if(o!==0)throw new Error("Invalid array index syntax")}return{type:p.VARIABLE,path:n}},rt=(e,t={})=>{let n=e,r=[];(e.includes("\\${")||e.includes("\\#{"))&&(n=e.replace(/\\\\(\$\{[^}]*\})/g,"\\DOUBLE_ESC_VAR$1"),n=n.replace(/\\\\(#\{[^}]*\})/g,"\\DOUBLE_ESC_PATH$1"),n=n.replace(/\\(\$\{[^}]*\})/g,(l,u)=>{let f=`__ESCAPED_${r.length}__`;return r.push(u),f}),n=n.replace(/\\(#\{[^}]*\})/g,(l,u)=>{let f=`__ESCAPED_${r.length}__`;return r.push(u),f}),n=n.replace(/\\DOUBLE_ESC_VAR/g,"\\"),n=n.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...n.matchAll(Cr)],i=[...n.matchAll(kr)],s=[...o.map(l=>({match:l,type:"variable"})),...i.map(l=>({match:l,type:"pathref"}))].sort((l,u)=>l.match.index-u.match.index);if(s.length===0){let l=n;for(let u=0;u<r.length;u++)l=l.replace(`__ESCAPED_${u}__`,r[u]);return{type:p.LITERAL,value:l}}if(s.length===1&&s[0].match[0]===n&&r.length===0){let{match:l,type:u}=s[0];try{return u==="variable"?pe(l[1],t):rn(l[1])}catch(f){if(f.message==="Invalid array index syntax")return{type:p.LITERAL,value:n};throw f}}let a=[],c=0;for(let{match:l,type:u}of s){let[f,d]=l,h=l.index;if(h>c){let y=n.substring(c,h);for(let g=0;g<r.length;g++)y=y.replace(`__ESCAPED_${g}__`,r[g]);y&&a.push(y)}try{let y;u==="variable"?y=pe(d.trim(),t):y=rn(d.trim()),a.push(y)}catch(y){if(y.message==="Invalid array index syntax")a.push(f);else throw y}c=h+f.length}if(c<n.length){let l=n.substring(c);for(let u=0;u<r.length;u++)l=l.replace(`__ESCAPED_${u}__`,r[u]);l&&a.push(l)}return{type:p.INTERPOLATION,parts:a}};var F=(e,t)=>typeof e=="string"?rt(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?Vr(e,t):Dr(e,t):{type:p.LITERAL,value:e},Nr=e=>{let{$each:t,...n}=e;if(typeof t!="string")throw new v("$each value must be a non-empty string");let r=t.trim();if(r==="")throw new v("$each value must be a non-empty string");if(Object.keys(n).length===0)throw new v("Empty $each body not allowed");if(n.$partial!==void 0)throw new v("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${r}`]:n}},Vr=(e,t)=>{let n=[],r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(typeof i=="object"&&i!==null&&!Array.isArray(i)){if(i.$each!==void 0)try{let c=Nr(i),l=Object.keys(c);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let u=ln(l[0],c[l[0]],t,!0);n.push(u),r=!0;continue}}catch(c){throw c instanceof v?c:new v(c.message)}let a=Object.keys(i);if(a.length===1&&/^\$for(?::\w+)?\s/.test(a[0])){let c=ln(a[0],i[a[0]],t);n.push(c),r=!0;continue}}let s=F(i,t);n.push(s),(s.type===p.FUNCTION||s.type===p.CONDITIONAL||s.type===p.LOOP||s.type===p.PARTIAL||s.type===p.OBJECT&&!s.fast||s.type===p.ARRAY&&!s.fast)&&(r=!0)}return{type:p.ARRAY,items:n,fast:!r}},Dr=(e,t)=>{let n=[],r=!1,o=null,i=Object.entries(e),s=0;if(e.$partial!==void 0){if(typeof e.$partial!="string")throw new v("$partial value must be a string");if(e.$partial.trim()==="")throw new v("$partial value cannot be an empty string");let c=["$if","$elif","$else","$for"],l=[];for(let[m]of i)for(let b of c)if(m===b||m.startsWith(b+" ")||m.startsWith(b+"#")){l.push(b);break}if(l.length>0)throw new v(`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,h={},y=!1;for(let[m,b]of Object.entries(d)){let x=m;(m.startsWith("\\$")||m.startsWith("$$"))&&(x=m.slice(1)),h[x]=b,y=!0}let g=null;if(y&&(g=F(h,t),g.type===p.OBJECT)){let m=!1;for(let b of g.properties)if(b.value.type===p.VARIABLE||b.value.type===p.INTERPOLATION||b.value.type===p.FUNCTION||b.value.type===p.CONDITIONAL||b.value.type===p.OBJECT&&!b.value.fast||b.value.type===p.ARRAY&&!b.value.fast){m=!0;break}m&&(g.fast=!1)}let I={type:p.PARTIAL,name:u,data:g};if(f!==void 0){let m;if(typeof f=="string"){if(f.trim()==="")throw new v("Empty condition expression after '$when'");m=S(f,t)}else m={type:p.LITERAL,value:f};I.whenCondition=m}return I}for(let[c,l]of i)if(c==="$when"){if(o!==null)throw new v("Multiple '$when' directives on the same object are not allowed");if(l==null)throw new v("Missing condition expression after '$when'");let u=typeof l=="string"?l:JSON.stringify(l);if(u.trim()==="")throw new v("Empty condition expression after '$when'");o=S(u,t),r=!0}else if(c.startsWith("$when#")||c.startsWith("$when "))throw new v("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<i.length;){let[c,l]=i[s];if(c==="$when"){s++;continue}if(c==="$each")throw new v("$each can only be used inside arrays");if(c.startsWith("$if ")||c.match(/^\$if#\w+\s/)||c.match(/^\$if\s+\w+.*:$/)){let u=Mr(i,s,t);n.push({key:c,value:u.node}),r=!0,s=u.nextIndex}else if(/^\$for(?::\w+)?\s/.test(c)){let u=c.match(/^\$for(?::(\w+))?\s/)?.[1]||"",f=u?`:${u}`:"";throw new v(`$for loops must be inside arrays - use '- $for${f} item in items:' instead of '$for${f} item in items:'. For cleaner object generation syntax, consider using $each.`)}else{if(c.startsWith("$elif ")||c.startsWith("$else"))throw new v(`'${c.split(" ")[0]}' without matching '$if'`);if(c==="$if"||c==="$if:")throw new v("Missing condition expression after '$if'");{let u=F(l,t);(u.type===p.FUNCTION||u.type===p.CONDITIONAL||u.type===p.PARTIAL||u.type===p.OBJECT&&!u.fast||u.type===p.ARRAY&&!u.fast)&&(r=!0);let f=rt(c,t),d={key:c,value:u};(f.type!==p.LITERAL||f.value!==c)&&(d.parsedKey=f),n.push(d),s++}}}let a={type:p.OBJECT,properties:n,fast:!r};return o&&(a.whenCondition=o),a},Mr=(e,t,n={})=>{let r=[],o=[],i=t,[s,a]=e[i],c=null,l;if(s.startsWith("$if#")){let f=s.match(/^\$if#(\w+)\s+(.+)$/);if(f)c=f[1],l=f[2];else throw new v(`Invalid conditional syntax: ${s}`)}else l=s.substring(4),l.endsWith(":")&&(l=l.slice(0,-1).trim());tt(l);let u=S(l,n);for(r.push(u),o.push(F(a,n)),i++;i<e.length;){let[f,d]=e[i],h=!1,y;if(c?f.startsWith(`$elif#${c} `)?(y=f.substring(`$elif#${c} `.length),y.endsWith(":")&&(y=y.slice(0,-1).trim()),h=!0):(f===`$else#${c}`||f===`$else#${c}:`)&&(h=!0,y=null):f.startsWith("$elif ")?(y=f.substring(6),y.endsWith(":")&&(y=y.slice(0,-1).trim()),h=!0):(f==="$else"||f==="$else:")&&(h=!0,y=null),h){if(y===null)r.push(null);else{tt(y);let g=S(y,n);r.push(g)}if(o.push(F(d,n)),i++,y===null)break}else break}return{node:{type:p.CONDITIONAL,conditions:r,bodies:o,id:c},nextIndex:i}},S=(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 S(l,t)}let n=J(e,"||");if(n!==-1)return{type:p.BINARY,op:L.OR,left:S(e.substring(0,n).trim(),t),right:S(e.substring(n+2).trim(),t)};let r=J(e,"&&");if(r!==-1)return{type:p.BINARY,op:L.AND,left:S(e.substring(0,r).trim(),t),right:S(e.substring(r+2).trim(),t)};let o=[{op:">=",type:L.GTE},{op:"<=",type:L.LTE},{op:"==",type:L.EQ},{op:"!=",type:L.NEQ},{op:">",type:L.GT},{op:"<",type:L.LT},{op:" in ",type:L.IN}];for(let{op:l,type:u}of o){let f=J(e,l);if(f!==-1)return{type:p.BINARY,op:u,left:S(e.substring(0,f).trim(),t),right:S(e.substring(f+l.length).trim(),t)}}let i=-1,s=null,a=[{op:" + ",type:L.ADD},{op:" - ",type:L.SUBTRACT}];for(let{op:l,type:u}of a){let f=0;for(;f<e.length;){let d=J(e.substring(f),l);if(d===-1)break;let h=f+d;h>i&&(i=h,s={op:l,type:u}),f=h+l.length}}if(i!==-1&&s)return{type:p.BINARY,op:s.type,left:S(e.substring(0,i).trim(),t),right:S(e.substring(i+s.op.length).trim(),t)};let c=[" * "," / "," % "];for(let l of c)if(J(e,l)!==-1)throw new v(`Arithmetic operations are not allowed in conditionals: "${l}"`);return e.startsWith("!")?{type:p.UNARY,op:de.NOT,operand:S(e.substring(1).trim(),t)}:cn(e,t)},J=(e,t)=>{let n=0,r=0;for(;r<=e.length-t.length;){if(e[r]==="(")n++;else if(e[r]===")")n--;else if(n===0&&e.substring(r,r+t.length)===t)return r;r++}return-1},jr=e=>{if(e=e.trim(),e==="true")return{type:p.LITERAL,value:!0};if(e==="false")return{type:p.LITERAL,value:!1};if(e==="null")return{type:p.LITERAL,value:null};if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:p.LITERAL,value:e.slice(1,-1)};if(e==='""'||e==="''")return{type:p.LITERAL,value:""};if(e==="{}")return{type:p.LITERAL,value:{}};if(e==="[]")return{type:p.LITERAL,value:[]};let t=Number(e);return!isNaN(t)&&isFinite(t)?{type:p.LITERAL,value:t}:{type:p.VARIABLE,path:e}},cn=(e,t)=>{let n=e.trim();if(n.match(/^(\w+)\((.*)\)$/))return pe(n,t);let o=jr(n);if(o.type===p.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(n))return{type:p.VARIABLE,path:n};try{return pe(n,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},Br=(e,t=!1)=>{let n=t?"$each":"$for";try{Kt(e)}catch(r){if(r instanceof v&&t){let o=r.message.replace(/\$for/g,"$each");throw new v(o.replace("Parse Error: ",""))}throw r}},ln=(e,t,n,r=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let I=r?"$each":"$for";throw new v(`Invalid loop syntax (got: '${e.replace("$for",I)}')`)}let s=i[1],a=i[2].trim();Br(a,r);let c=a.match(/^(.+?)\s+in\s+(.+)$/);if(!c){let I=r?"$each":"$for";throw new v(`Invalid loop syntax - missing 'in' keyword (got: '${I} ${a}')`)}let l=c[1].trim(),u=c[2].trim(),f,d=null;if(l.includes(",")){let I=l.split(",").map(m=>m.trim());if(I.length!==2)throw new v(`Invalid loop variables: ${l}. Expected format: "item" or "item, index"`);f=I[0],d=I[1]}else f=l;let h=["this","undefined","null","true","false"];if(h.includes(f))throw new v(`Reserved variable name: ${f}`);if(d&&h.includes(d))throw new v(`Reserved variable name: ${d}`);let y=cn(u,n),g=F(t,n);return{type:p.LOOP,itemVar:f,indexVar:d,iterable:y,body:g,flatten:s!=="nested"}};var zr=(e,t={})=>{let{functions:n={}}=t;return F(e,n)},$e=zr;var ot={};rr(ot,{now:()=>Fr});var Fr=()=>Date.now();var Ur=(e,t,n={})=>{let{functions:r={},partials:o={}}=n,i={...ot,...r},s=$e(e,{functions:i}),a={};for(let[c,l]of Object.entries(o))a[c]=$e(l,{functions:i});return nt(s,t,{functions:i,partials:a})},P=Ur;var an=(e,t,n={})=>{let r=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=c=>c,transformActionFirstArgument:a=c=>c}=n;for(let[c,l]of Object.entries(t))c!=="createInitialState"&&(c.startsWith("select")?o[c]=(...u)=>l(s(r),...u):i[c]=(...u)=>{r=et(r,d=>l(a(d),...u))});return{...o,...i}},Le=(e,t)=>n=>{let r=e(),o=Array.isArray(n)?n:[n];return et(r,i=>{o.forEach(s=>{t.forEach(a=>{a(i,s)})})})};var Wr=(e,t)=>{if(e.default!==void 0)return e.default;let n=["number","boolean","string","object"];if(!n.includes(e.type))throw new Error(`Invalid variable type: ${e.type} for variable ${t}. Expected one of: ${n.join(", ")}`);switch(e.type){case"number":return 0;case"boolean":return!1;case"string":return"";case"object":return{}}},st=e=>{let t={},n={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([r,o])=>{let i=Wr(o,r);o.scope==="context"?t[r]=i:n[r]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}},Ce=(e,t)=>{let n=["context","global-device","global-account"];if(!e)throw new Error(`Variable scope is required for variable: ${t}`);if(!n.includes(e))throw new Error(`Invalid variable scope: ${e} for variable ${t}. Expected one of: ${n.join(", ")}`)},ke=(e,t,n)=>{let r={number:["set","increment","decrement","multiply","divide"],boolean:["set","toggle"],string:["set"],object:["set"]},o=r[e];if(!o)throw new Error(`Unknown variable type: ${e} for variable ${n}`);if(!Object.values(r).flat().includes(t))throw new Error(`Unknown operation: ${t}`);if(!o.includes(t))throw new Error(`Operation "${t}" is not valid for variable "${n}" of type "${e}". Valid operations: ${o.join(", ")}`)},Se=(e,t,n)=>{switch(t){case"set":return n;case"multiply":return(e??1)*n;case"divide":return(e??0)/n;case"increment":return(e??0)+(n??1);case"decrement":return(e??0)-(n??1);case"toggle":return!e;default:throw new Error(`Unknown operation: ${t}`)}},lt=(e,t,n)=>Object.fromEntries(Object.entries(e).filter(([r])=>t?.[r]?.scope===n)),un=(e,t="DD/MM/YYYY - HH:mm")=>{if(!e)return"";let n=new Date(e),r=o=>String(o).padStart(2,"0");return t.replace("DD",r(n.getDate())).replace("MM",r(n.getMonth()+1)).replace("YYYY",n.getFullYear()).replace("YY",String(n.getFullYear()).slice(-2)).replace("HH",r(n.getHours())).replace("mm",r(n.getMinutes())).replace("ss",r(n.getSeconds()))},Yr=(e,t)=>{let n=e?.ui,r=t?.ui;return JSON.stringify(n)===JSON.stringify(r)?null:n&&!r?{changeType:"delete",data:e}:r&&!e?{changeType:"add",data:t}:r&&e?{changeType:"update",data:t}:null},ct=(e={},t={})=>{let n={},r=["sfx","voice"],o=s=>{let a=e[s],c=t[s];c&&!a?n[s]={changeType:"add",data:c}:a&&!c?r.includes(s)||(n[s]={changeType:"delete",data:a}):a&&c&&JSON.stringify(a)!==JSON.stringify(c)&&(n[s]={changeType:"update",data:c})};o("background"),o("bgm"),o("voice");let i=Yr(e.dialogue,t.dialogue);return i&&(n.dialogue=i),o("choice"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),n},at=(e={})=>{let t=structuredClone(e),n=o=>{t[o]&&(delete t[o].animations,Object.keys(t[o]).length===0&&delete t[o])};n("background"),n("layout"),n("choice"),t.dialogue?.ui&&(delete t.dialogue.ui.animations,Object.keys(t.dialogue.ui).length===0&&delete t.dialogue.ui,Object.keys(t.dialogue).length===0&&delete t.dialogue);let r=(o,i)=>{let s=t[o]?.items;Array.isArray(s)&&(t[o].items=s.map(a=>{let c={...a};return delete c.animations,i(c)?c:null}).filter(Boolean),t[o].items.length===0&&delete t[o])};return r("character",o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId),r("visual",o=>o.resourceId||o.transformId),t},Hr=(e,t)=>{if(!e||!t)return;let n=e;for(let r of t.split(".")){if(n==null||!(r in Object(n)))return;n=n[r]}return n},Jr=(e,t)=>{if(typeof e!="string")return e;if(e==="_event"){if(t==null)throw new Error('Action template binding "_event" requires event context "_event".');return t}if(!e.startsWith("_event."))return e;if(t==null)throw new Error(`Action template binding "${e}" requires event context "_event".`);let n=e.slice(7),r=Hr(t,n);if(r===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return r},it=(e,t)=>Array.isArray(e)?e.map(n=>it(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,it(r,t)])):Jr(e,t),fn=(e,t)=>{if(!t)return e;if(Object.prototype.hasOwnProperty.call(t,"event"))throw new Error('Action template context key "event" is no longer supported. Use "_event".');let n=it(e,t._event);return P(n,t)};var Re=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:structuredClone(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},dn=(e,t)=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let n=e.map(r=>structuredClone(r)).filter(r=>t(r)||r.animations);return{hasValidItems:n.length>0,processedItems:n}},qr=()=>({}),Kr=(e,t)=>{if(t.background){let{animationsOnly:n,state:r}=Re(t.background,o=>!!o.resourceId);if(n){e.background=r;return}if(!t.background.resourceId){delete e.background;return}e.background=structuredClone(t.background)}else e.background?.animations&&(e.background.animations={})},Gr=(e,t)=>{if(!t.dialogue){e.dialogue&&e.dialogue.mode==="adv"&&(e.dialogue.content=void 0,e.dialogue.characterId=void 0);return}if(e.dialogue||(e.dialogue={}),t.dialogue.ui){let{animationsOnly:n,state:r}=Re(t.dialogue.ui,o=>!!o.resourceId);n?e.dialogue.ui={...e.dialogue.ui,...r}:e.dialogue.ui={...t.dialogue.ui}}else e.dialogue?.ui?.animations&&(e.dialogue.ui.animations={});if(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"),t.dialogue.content!==void 0&&(e.dialogue.content=t.dialogue.content),delete e.dialogue.characterId,t.dialogue.characterId&&(e.dialogue.characterId=t.dialogue.characterId),t.dialogue.character?e.dialogue.character={...t.dialogue.character}:delete e.dialogue.character,t.dialogue.clear){delete e.dialogue;return}t.dialogue?.clearPage&&e.dialogue?.mode==="nvl"&&(e.dialogue.lines=[]),e.dialogue?.mode==="nvl"&&t.dialogue.content!==void 0&&e.dialogue.lines.push({content:t.dialogue.content,characterId:t.dialogue.characterId||null})},Xr=(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},Zr=(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}}},Qr=(e,t)=>{if(t.visual){let{hasValidItems:n,processedItems:r}=dn(t.visual.items,o=>!!o.resourceId);n?e.visual={items:r}:delete e.visual}else e.visual?.items&&(e.visual.items=e.visual.items.map(n=>n.animations?{...n,animations:{}}:n))},eo=(e,t)=>{if(!t.character){e.character?.items&&(e.character.items=e.character.items.map(o=>o.animations?{...o,animations:{}}:o));return}let{hasValidItems:n,processedItems:r}=dn(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId);n?e.character={items:r}:delete e.character},to=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},no=(e,t)=>{if(t.layout){let{animationsOnly:n,state:r}=Re(t.layout,o=>!!o.resourceId);if(n){e.layout=r;return}if(!t.layout.resourceId){delete e.layout;return}e.layout=t.layout}else e.layout&&delete e.layout},ro=(e,t)=>{if(t.choice){let{animationsOnly:n,state:r}=Re(t.choice,o=>!!o.resourceId);if(n){e.choice={...e.choice,...r};return}if(!t.choice.resourceId){delete e.choice;return}e.choice=t.choice}else e.choice&&delete e.choice},oo=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},io=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},so=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(n=>{delete e[n]})},he=e=>Le(qr,[so,Kr,Xr,Zr,Qr,Gr,eo,to,no,ro,oo,io])(e);var G={objectValues:e=>Object.entries(e).map(([t,n])=>({id:t,...n})),formatDate:un},lo=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,co=(e,t)=>{let n=String(t||"").trim();if(!n)return;let r=n.match(/[A-Za-z_][A-Za-z0-9_]*|\[\d+\]/g)||[],o=e;for(let i of r){if(i.startsWith("[")){let s=Number(i.slice(1,-1));o=Array.isArray(o)?o[s]:void 0;continue}o=o?.[i]}return o},Te=(e,t,n)=>{if(Array.isArray(e)){let o=[];for(let i of e){if(i&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===1){let[s]=Object.keys(i),a=lo.exec(s);if(a){let[,c,l,u]=a,f=co(t,u);if(!Array.isArray(f))continue;let d=Array.isArray(i[s])?i[s]:[];f.forEach((h,y)=>{let g={...t,[c]:h};l&&(g[l]=y),d.forEach(I=>{let m=Te(I,g,n),b=P(m,g,n);Array.isArray(b)?o.push(...b):o.push(b)})});continue}}o.push(Te(i,t,n))}return o}if(!e||typeof e!="object")return e;let r={};return Object.entries(e).forEach(([o,i])=>{r[o]=Te(i,t,n)}),r},wn={live:"update",replace:"transition"},xn=e=>{let t=structuredClone(e);return typeof t.type=="string"&&(t.type=wn[t.type]||t.type),t},ao=({id:e,targetId:t,animation:n})=>{let r=xn(n);return delete r.name,r.id=e,r.targetId=t,r},ut=e=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return wn[e.type]||e.type},Oe=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},uo=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),q=({animations:e,resources:t,animationId:n,instanceId:r,targetId:o})=>{if(!n||!o)return!1;let i=t?.animations?.[n];return i?(e.push(ao({id:r,targetId:o,animation:i})),!0):!1},fo=({hasPrevious:e,hasCurrent:t,previousResourceId:n,currentResourceId:r,sharedTarget:o})=>!e&&t?"enter":e&&!t?"exit":e&&t?n===r&&o?"update":"replace":"none",ft=({animationType:e,animationId:t,animationPath:n,lifecycle:r})=>{if(!(e!=="update"||r==="update"))throw new Error(`[${n}] Animation "${t}" has type "update", but update animations can only be used when the same target persists across the state change. Use type "transition" for enter, exit, and replace.`)},po=(e,{defaultTargetId:t,defaultId:n}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let r=xn(e);return r.id??=n,r.targetId??=t,r},bt=({animations:e,transitions:t,defaultTargetId:n,idPrefix:r})=>{t.forEach((o,i)=>{e.push(po(o,{defaultTargetId:n,defaultId:`${r}-transition-${i}`}))})},pn=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let n=P(e,t);return n&&typeof n=="object"?e:n},hn=(e,t)=>{if(e===void 0)return[];if(!Array.isArray(e)||e.some(n=>n===null||typeof n!="object"||Array.isArray(n)))throw new Error(`${t} must be an array of objects`);return e},gn=(e,t=0)=>{let n=e?.sprites?.map(({resourceId:r})=>r)||[];return n.length===0?`character-container-${e.id}`:`character-container-${e.id}-${t}-${n.join("-")}`},dt=(e,t)=>{if(!t.transformId)throw new Error(`Visual item "${t.id}" requires transformId`);let n=e.transforms?.[t.transformId];if(!n)throw new Error(`Transform "${t.transformId}" not found for visual item "${t.id}"`);return n},ho=(e={})=>e.textStyles||{},go=(e={})=>e.images||{},yo=(e={})=>e.colors||{},mo=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,ge=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,se=(e,t,n)=>{if(typeof e!="string"||e.length===0)throw new Error(`${n} at "${t}" must resolve to a non-empty string`)},yn=(e,t,n)=>{if(e===void 0)return 1;if(typeof e!="number"||!Number.isFinite(e))throw new Error(`${t} for text style "${n}" must be a number between 0 and 1`);if(e<0||e>1)throw new Error(`${t} for text style "${n}" must be a number between 0 and 1`);return e},An=(e,t)=>{if(typeof e!="string"||!mo.test(e))throw new Error(`${t} must resolve to a hex color`);return e.length===4?`#${e.slice(1).split("").map(n=>n.repeat(2)).join("")}`:e},mn=(e,t,n)=>{let r=An(e,n);if(t===1)return r;let o=Number.parseInt(r.slice(1,3),16),i=Number.parseInt(r.slice(3,5),16),s=Number.parseInt(r.slice(5,7),16);return`rgba(${o}, ${i}, ${s}, ${t})`},bo=(e={},t)=>{let n=ho(e)?.[t];if(!n)throw new Error(`Text style "${t}" not found`);let r=e.fonts?.[n.fontId];if(!r)throw new Error(`Font "${n.fontId}" not found for text style "${t}"`);let o=e.colors?.[n.colorId];if(!o)throw new Error(`Color "${n.colorId}" not found for text style "${t}"`);let i=yn(n.colorAlpha,"colorAlpha",t),s={fontFamily:r.fileId,fontSize:n.fontSize??16,fontWeight:n.fontWeight??"400",fontStyle:n.fontStyle??"normal",lineHeight:n.lineHeight??1.2,fill:mn(o.hex,i,`Color "${n.colorId}" for text style "${t}"`)};if(n.align!==void 0&&(s.align=n.align),n.wordWrap!==void 0&&(s.wordWrap=n.wordWrap),n.breakWords!==void 0&&(s.breakWords=n.breakWords),n.wordWrapWidth!==void 0&&(s.wordWrapWidth=n.wordWrapWidth),n.strokeColorId){let a=e.colors?.[n.strokeColorId];if(!a)throw new Error(`Stroke color "${n.strokeColorId}" not found for text style "${t}"`);let c=yn(n.strokeAlpha,"strokeAlpha",t);s.strokeColor=mn(a.hex,c,`Stroke color "${n.strokeColorId}" for text style "${t}"`)}else if(n.strokeAlpha!==void 0)throw new Error(`strokeAlpha for text style "${t}" requires strokeColorId`);return n.strokeWidth!==void 0&&(s.strokeWidth=n.strokeWidth),s},gt=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>gt(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(Object.prototype.hasOwnProperty.call(e,"textStyle"))throw new Error(`Inline textStyle is not allowed in layout elements at "${n}". Use textStyleId instead`);let r={};for(let[o,i]of Object.entries(e))o!=="textStyleId"&&(r[o]=gt(i,t,ge(n,o)));return e.textStyleId!==void 0&&(se(e.textStyleId,n,"textStyleId"),r.textStyle=bo(t,e.textStyleId)),r},vn=(e={},t)=>{let n=yo(e)?.[t];if(!n)throw new Error(`Color "${t}" not found`);return An(n.hex,`Color "${t}"`)},En=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",pt=(e,t,n)=>{let r=e?.[t];if(!(!r||typeof r!="object"||Array.isArray(r))&&Object.prototype.hasOwnProperty.call(r,"fill"))throw new Error(`Inline ${t}.fill is not allowed in rect layout elements at "${n}". Use ${En(`${t}.fill`)} instead`)},Io=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>ye(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;let r={};for(let[o,i]of Object.entries(e))o!=="colorId"&&(r[o]=ye(i,t,ge(n,o)));return e.colorId!==void 0&&(se(e.colorId,n,"colorId"),r.fill=vn(t,e.colorId)),r},ye=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>ye(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="rect"){if(Object.prototype.hasOwnProperty.call(e,"fill"))throw new Error(`Inline fill is not allowed in rect layout elements at "${n}". Use ${En("fill")} instead`);pt(e,"hover",n),pt(e,"click",n),pt(e,"rightClick",n)}let r={};for(let[o,i]of Object.entries(e))if(!(e.type==="rect"&&o==="colorId")){if(e.type==="rect"&&(o==="hover"||o==="click"||o==="rightClick")){r[o]=Io(i,t,ge(n,o));continue}r[o]=ye(i,t,ge(n,o))}return e.type==="rect"&&e.colorId!==void 0&&(se(e.colorId,n,"colorId"),r.fill=vn(t,e.colorId)),r},ht=(e={},t)=>{let n=go(e)?.[t];return n||null},_n=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",bn=(e,t,n,r)=>{let o=e?.[t];if(!(!o||typeof o!="object"||Array.isArray(o))&&Object.prototype.hasOwnProperty.call(o,r))throw new Error(`Inline ${t}.${r} is not allowed in sprite layout elements at "${n}". Use ${_n(`${t}.${r}`)} instead`)},In=(e,t,n)=>{let r=e[t];e[t]={...r&&typeof r=="object"&&!Array.isArray(r)?r:{},src:n}},yt=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>yt(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="sprite"){for(let o of["url","src","hoverUrl","hoverSrc","clickUrl","clickSrc"])if(Object.prototype.hasOwnProperty.call(e,o))throw new Error(`Inline ${o} is not allowed in sprite layout elements at "${n}". Use ${_n(o)} instead`);bn(e,"hover",n,"src"),bn(e,"click",n,"src")}let r={};for(let[o,i]of Object.entries(e))e.type==="sprite"&&(o==="imageId"||o==="hoverImageId"||o==="clickImageId")||(r[o]=yt(i,t,ge(n,o)));if(e.type==="sprite"&&e.imageId!==void 0){se(e.imageId,n,"imageId");let o=ht(t,e.imageId),i=o?.fileId??e.imageId;r.src=i,r.width===void 0&&o?.width!==void 0&&(r.width=o.width),r.height===void 0&&o?.height!==void 0&&(r.height=o.height)}return e.type==="sprite"&&e.hoverImageId!==void 0&&(se(e.hoverImageId,n,"hoverImageId"),In(r,"hover",ht(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(se(e.clickImageId,n,"clickImageId"),In(r,"click",ht(t,e.clickImageId)?.fileId??e.clickImageId)),r},It=(e,t={},n="root")=>yt(ye(gt(e,t,n),t,n),t,n),X=It,Pe=(e=[])=>e.find(t=>t.id==="story"),Z=({variables:e,saveSlots:t=[],isLineCompleted:n,autoMode:r,skipMode:o,canRollback:i,confirmDialog:s,historyDialogue:a=[],characters:c={}}={})=>({variables:e,saveSlots:t,isLineCompleted:n,autoMode:r,skipMode:o,canRollback:i,confirmDialog:s,historyDialogue:a,characters:c,effectiveSoundVolume:e?._muteAll?0:e?._soundVolume??500,textSpeed:e?._textSpeed??50}),mt=e=>{if(Array.isArray(e))return e.map(n=>mt(n));if(!e||typeof e!="object")return e;let t={...e};return Object.keys(t).forEach(n=>{t[n]=mt(t[n])}),t.type==="text-revealing"&&(t.revealEffect="none"),t},Q=(e,{isLineCompleted:t=!1,skipTransitionsAndAnimations:n=!1}={})=>!t&&!n?e:mt(e),$n=({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:{}}}}),Ln=(e=[],t={})=>e.map(n=>{let r=t?.[n.characterId];return{...n,characterName:r?.name||""}}),Cn=({container:e,resources:t,templateData:n,isLineCompleted:r=!1,skipTransitionsAndAnimations:o=!1})=>{let i=P(e,n,{functions:G});return X(Q(i,{isLineCompleted:r,skipTransitionsAndAnimations:o}),t)},wo=(e={})=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,{payload:{actions:structuredClone(n?.actions||{})}}]))},K=({animations:e,animationsDef:t,resources:n,previousResourceId:r,currentResourceId:o,previousTargetId:i,currentTargetId:s,animationPath:a,idPrefix:c})=>{if(!t)return;let l=r!=null&&r!==!1,u=o!=null&&o!==!1,f=i&&s&&i===s,d=fo({hasPrevious:l,hasCurrent:u,previousResourceId:r,currentResourceId:o,sharedTarget:f});if(uo(t)){if(t.in&&!l){let I=Oe(t.in);ft({animationType:ut(n?.animations?.[I]),animationId:I,animationPath:`${a}.in`,lifecycle:"enter"}),q({animations:e,resources:n,animationId:I,instanceId:`${c}-animation-in`,targetId:s})}if(t.out&&l&&r!==o){let I=Oe(t.out);ft({animationType:ut(n?.animations?.[I]),animationId:I,animationPath:`${a}.out`,lifecycle:"exit"}),q({animations:e,resources:n,animationId:I,instanceId:`${c}-animation-out`,targetId:i})}t.update&&l&&u&&r===o&&f&&q({animations:e,resources:n,animationId:Oe(t.update),instanceId:`${c}-animation-update`,targetId:s});return}let h=Oe(t),y=n?.animations?.[h],g=ut(y);if(ft({animationType:g,animationId:h,animationPath:a,lifecycle:d}),g==="update"){l&&u&&r===o&&f&&q({animations:e,resources:n,animationId:h,instanceId:`${c}-animation-update`,targetId:s});return}if(g==="transition"){if(l&&u&&f){q({animations:e,resources:n,animationId:h,instanceId:`${c}-animation-transition`,targetId:s});return}l&&q({animations:e,resources:n,animationId:h,instanceId:`${c}-animation-out`,targetId:i}),u&&q({animations:e,resources:n,animationId:h,instanceId:`${c}-animation-in`,targetId:s})}},xo=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),Ao=(e,{presentationState:t,previousPresentationState:n,resources:r={},isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,autoMode:a,skipMode:c,canRollback:l,saveSlots:u=[]})=>{let{elements:f,animations:d}=e;if(t.background){let h=f.find(y=>y.id==="story");if(!h)return e;if(t.background.resourceId){let{images:y={},videos:g={}}=r,I=y[t.background.resourceId]||g[t.background.resourceId];if(I){let m=g[t.background.resourceId]!==void 0,b={id:`bg-cg-${t.background.resourceId}`,type:m?"video":"sprite",x:0,y:0,src:I.fileId,width:I.width,height:I.height,alpha:1,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1};m&&(b.loop=t.background.loop??!1,b.volume=I.volume??500),h.children.push(b)}}if(t.background.resourceId){let{layouts:y={}}=r,g=y[t.background.resourceId];if(g){let I={id:`bg-cg-${t.background.resourceId}`,type:"container",children:g.elements},m=P(I,Z({variables:s,saveSlots:u,isLineCompleted:o,autoMode:a,skipMode:c,canRollback:l}),{functions:G});h.children.push(X(Q(m,{isLineCompleted:o,skipTransitionsAndAnimations:i}),r))}}if(t.background.animations&&!o&&!i){let y=n?.background?.resourceId,g=t.background.resourceId;K({animations:d,animationsDef:t.background.animations,resources:r,previousResourceId:y,currentResourceId:g,previousTargetId:y?`bg-cg-${y}`:void 0,currentTargetId:g?`bg-cg-${g}`:void 0,animationPath:"background.animations",idPrefix:"bg-cg"})}}return e},vo=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i})=>{let{elements:s,animations:a}=e;if(t.character&&r){let c=s.find(f=>f.id==="story");if(!c)return e;let l=t.character.items||[],u=n?.character?.items||[];for(let f=0;f<l.length;f++){let d=l[f],{transformId:h,sprites:y}=d,g=u.find($=>$.id===d.id),I=u.findIndex($=>$.id===d.id),m=g?.sprites&&g.sprites.length>0,b=y&&y.length>0,x=I>=0?gn(g,I):void 0;if(d.animations&&!y&&!h&&m&&!o&&!i){K({animations:a,animationsDef:d.animations,resources:r,previousResourceId:x,currentResourceId:void 0,previousTargetId:x,currentTargetId:void 0,animationPath:`character.items[${f}].animations`,idPrefix:"character"});continue}if(d.animations&&!y&&!h)continue;if(!y||y.length===0||!h){console.warn("Character item missing sprites or transformId:",d);continue}let A=gn(d,f),w=r.transforms[h];if(!w){console.warn("Transform not found:",h);continue}let E={type:"container",id:A,x:d.x??w.x,y:d.y??w.y,anchorX:w.anchorX,anchorY:w.anchorY,rotation:w.rotation,scaleX:w.scaleX,scaleY:w.scaleY,children:[]};for(let $ of y){let M=r.images[$.resourceId];if(!M){console.warn(`Image resource not found: ${$.resourceId}`);continue}E.children.push({type:"sprite",id:`${A}-${$.id}`,src:M.fileId,width:M.width,height:M.height,x:0,y:0})}c.children.push(E),d.animations&&!o&&!i&&K({animations:a,animationsDef:d.animations,resources:r,previousResourceId:x,currentResourceId:A,previousTargetId:x,currentTargetId:A,animationPath:`character.items[${f}].animations`,idPrefix:"character"})}}return e},Eo=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,autoMode:a,skipMode:c,canRollback:l,saveSlots:u=[]})=>{let{elements:f,animations:d}=e;if(t.visual&&r){let h=f.find(g=>g.id==="story");if(!h)return e;let y=t.visual.items;for(let g of y){if(g.resourceId){let{images:I={},videos:m={},spritesheets:b={}}=r,x=b[g.resourceId];if(x){let A=dt(r,g),w=g.animationName;if(w){let E=x.animations?.[w];if(!E)throw new Error(`Animation '${w}' not found in spritesheet resource '${g.resourceId}'`);let $={id:`visual-${g.id}`,type:"animated-sprite",x:g.x??A.x,y:g.y??A.y,width:g.width??x.width,height:g.height??x.height,alpha:g.alpha??1,anchorX:A.anchorX,anchorY:A.anchorY,rotation:A.rotation,scaleX:A.scaleX,scaleY:A.scaleY,spritesheetSrc:x.fileId,spritesheetData:x.jsonData,animation:{frames:E.frames,animationSpeed:g.animationSpeed??E.animationSpeed??.5,loop:g.loop??E.loop??!0}};h.children.push(structuredClone($))}}else{let A=I[g.resourceId]||m[g.resourceId];if(A){let w=m[g.resourceId]!==void 0,E=dt(r,g),$={id:`visual-${g.id}`,type:w?"video":"sprite",src:A.fileId,width:A.width,height:A.height,x:E.x,y:E.y,anchorX:E.anchorX,anchorY:E.anchorY,rotation:E.rotation,scaleX:E.scaleX,scaleY:E.scaleY};w&&($.loop=A.loop??!1,$.volume=A.volume??500),h.children.push($)}}}if(g.resourceId){let{layouts:I={}}=r,m=I[g.resourceId];if(m){let b=dt(r,g),x={id:`visual-${g.id}`,type:"container",children:structuredClone(m.elements),x:b.x,y:b.y,anchorX:b.anchorX,anchorY:b.anchorY,rotation:b.rotation,scaleX:b.scaleX,scaleY:b.scaleY},A=P(x,Z({variables:s,saveSlots:u,isLineCompleted:o,autoMode:a,skipMode:c,canRollback:l}),{functions:G});h.children.push(X(Q(A,{isLineCompleted:o,skipTransitionsAndAnimations:i}),r))}}if(g.animations&&!o&&!i){let m=(n?.visual?.items||[]).find(b=>b.id===g.id);K({animations:d,animationsDef:g.animations,resources:r,previousResourceId:m?.resourceId,currentResourceId:g.resourceId,previousTargetId:m?.resourceId?`visual-${g.id}`:void 0,currentTargetId:g.resourceId?`visual-${g.id}`:void 0,animationPath:`visual.items[${g.id}].animations`,idPrefix:g.id})}}}return e},_o=(e,{presentationState:t,previousPresentationState:n,resources:r={},dialogueUIHidden:o,autoMode:i,skipMode:s,canRollback:a,skipOnlyViewedLines:c,isLineCompleted:l,skipTransitionsAndAnimations:u,variables:f,saveSlots:d=[]})=>{let{elements:h,animations:y}=e;if(!t.dialogue||o)return e;let g=h.find(I=>I.id==="story");if(!g)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:I={}}=r,m=I[t.dialogue.ui.resourceId];if(m){let b;t.dialogue.characterId&&(b=r.characters[t.dialogue.characterId]),t.dialogue.character&&(b={...b,name:t.dialogue.character.name});let x={elements:m.elements},A=t.dialogue?.content===void 0?[{text:""}]:hn(t.dialogue.content,"dialogue.content"),w=(t.dialogue?.lines||[]).map((B,tr)=>({content:hn(B.content,`dialogue.lines[${tr}].content`).map(Dt=>({...Dt,text:pn(Dt.text,{variables:f})})),characterName:B.characterId&&r.characters?.[B.characterId]?.name||""})),E={variables:f,autoMode:i,skipMode:s,canRollback:a,skipOnlyViewedLines:c,isLineCompleted:l,saveSlots:d,effectiveSoundVolume:f?._muteAll?0:f?._soundVolume??500,textSpeed:f?._textSpeed??50,dialogueLines:w,dialogue:{character:{name:b?.name||""},content:A.map(B=>({...B,text:pn(B.text,{variables:f})})),lines:w}},$={functions:G},M=Te(x,E,$),Fe=P(M,E,$),re=X(Q(Fe?.elements,{isLineCompleted:l,skipTransitionsAndAnimations:u}),r);if(Array.isArray(re))for(let B of re)g.children.push(B);else re&&g.children.push(re)}}return t.dialogue.ui?.animations&&!l&&!u&&K({animations:y,animationsDef:t.dialogue.ui.animations,resources:r,previousResourceId:n?.dialogue?.ui?.resourceId,currentResourceId:t.dialogue.ui?.resourceId,previousTargetId:n?.dialogue?.ui?.resourceId?"dialogue-container":void 0,currentTargetId:t.dialogue.ui?.resourceId?"dialogue-container":void 0,animationPath:"dialogue.ui.animations",idPrefix:"dialogue-ui"}),e},$o=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,screen:s,variables:a,autoMode:c,skipMode:l,canRollback:u,saveSlots:f=[]})=>{let{elements:d,animations:h}=e;if(t.choice&&r){let y=Pe(d);if(!y)return e;y.children.push({id:"choice-blocker",type:"rect",fill:"transparent",width:s.width,height:s.height,x:0,y:0,click:{payload:{actions:{}}}});let g=r?.layouts[t.choice.resourceId];if(g&&g.elements){let I={elements:g.elements},m=P(I,{...Z({variables:a,saveSlots:f,isLineCompleted:o,autoMode:c,skipMode:l,canRollback:u}),choice:{items:t.choice?.items??[]}},{functions:G}),b=X(Q(m?.elements,{isLineCompleted:o,skipTransitionsAndAnimations:i}),r);if(Array.isArray(b))for(let x of b)y.children.push(x);else b&&y.children.push(b)}t.choice.animations&&!o&&!i&&K({animations:h,animationsDef:t.choice.animations,resources:r,previousResourceId:n?.choice?.resourceId,currentResourceId:t.choice.resourceId,previousTargetId:n?.choice?.resourceId?"choice-container":void 0,currentTargetId:t.choice.resourceId?"choice-container":void 0,animationPath:"choice.animations",idPrefix:"choice"})}return e},Lo=(e,{presentationState:t,resources:n={},variables:r,isLineCompleted:o,autoMode:i,skipMode:s,canRollback:a,saveSlots:c=[],skipTransitionsAndAnimations:l})=>{if(!t.control?.resourceId)return e;let u=n.controls?.[t.control.resourceId];if(!u)return e;let f=wo(u.keyboard);if(f&&Object.keys(f).length>0&&(e.global.keyboard=f),!Array.isArray(u.elements)||u.elements.length===0)return e;let d=Pe(e.elements);if(!d)return e;let h={id:`control-${t.control.resourceId}`,type:"container",x:0,y:0,children:u.elements};return d.children.push(Cn({container:h,resources:n,templateData:Z({variables:r,saveSlots:c,isLineCompleted:o,autoMode:i,skipMode:s,canRollback:a}),isLineCompleted:o,skipTransitionsAndAnimations:l})),e},Co=(e,{presentationState:t,resources:n,variables:r})=>{let{elements:o,audio:i}=e;if(t.bgm&&n){if(!Pe(o))return e;let a=n.sounds[t.bgm.resourceId];if(!a)return e;let c=r?._muteAll?0:r?._musicVolume??500;i.push({id:"bgm",type:"sound",src:a.fileId,loop:t.bgm.loop??!0,volume:c,delay:t.bgm.delay??null})}return e},ko=(e,{presentationState:t,resources:n})=>{let{audio:r}=e;if(t.sfx&&n){let o=t.sfx.items;for(let i of o){let s=n.sounds?.[i.resourceId];s&&r.push({id:i.id,type:"sound",src:s.fileId,loop:i.loop??s.loop??!1,volume:i.volume??s.volume??500,delay:i.delay??s.delay??null})}}return e},So=(e,{presentationState:t,resources:n})=>{let{audio:r}=e;if(!t?.voice)return e;let{fileId:o,volume:i,loop:s}=t.voice;return r.push({id:`voice-${o}`,type:"sound",src:o,volume:i??500,loop:s??!1}),e},Ro=(e,{presentationState:t,previousPresentationState:n,resources:r={},variables:o,autoMode:i,skipMode:s,canRollback:a,saveSlots:c=[],isLineCompleted:l,skipTransitionsAndAnimations:u})=>{let{elements:f,animations:d}=e;if(t.layout){let h=Pe(f);if(!h)return e;let y=r.layouts[t.layout.resourceId];if(!y)return e;Array.isArray(y.transitions)&&!l&&!u&&bt({animations:d,transitions:y.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`});let g={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:y.elements||[]};h.children.push(Cn({container:g,resources:r,templateData:Z({variables:o,saveSlots:c,isLineCompleted:l,autoMode:i,skipMode:s,canRollback:a}),isLineCompleted:l,skipTransitionsAndAnimations:u}))}if(t.layout?.animations&&!l&&!u){let h=n?.layout?.resourceId,y=t.layout?.resourceId;K({animations:d,animationsDef:t.layout.animations,resources:r,previousResourceId:h,currentResourceId:y,previousTargetId:h?`layout-${h}`:void 0,currentTargetId:y?`layout-${y}`:void 0,animationPath:"layout.animations",idPrefix:"layout"})}return e},Oo=(e,{resources:t={},variables:n,autoMode:r,skipMode:o,canRollback:i,layeredViews:s=[],dialogueHistory:a=[],saveSlots:c=[],screen:l,isLineCompleted:u,skipTransitionsAndAnimations:f})=>{let{elements:d,animations:h}=e;return s&&s.length>0&&s.forEach((y,g)=>{let I=t.layouts[y.resourceId];if(!I){console.warn(`LayeredView layout not found: ${y.resourceId}`);return}Array.isArray(I.transitions)&&(f||bt({animations:h,transitions:I.transitions,defaultTargetId:`layeredView-${g}`,idPrefix:`layeredView-${g}`}));let m={id:`layeredView-${g}`,type:"container",x:0,y:0,children:[$n({id:`layeredView-${g}-blocker`,screen:l}),...I.elements||[]]},b=Ln(a,t.characters),x=Z({variables:n,saveSlots:c,isLineCompleted:u,autoMode:r,skipMode:o,canRollback:i,historyDialogue:b,characters:t.characters||{}}),A=P(m,x,{functions:G}),[w,...E]=A.children||[],$=X(Q({...A,children:E},{isLineCompleted:u,skipTransitionsAndAnimations:f}),t);d.push({...$,children:w?[w,...$.children||[]]:$.children})}),e},To=(e,{resources:t={},variables:n,saveSlots:r=[],autoMode:o,skipMode:i,canRollback:s,confirmDialog:a,dialogueHistory:c=[],screen:l,isLineCompleted:u,skipTransitionsAndAnimations:f})=>{let{elements:d,animations:h}=e;if(!a?.resourceId)return e;let y=t.layouts?.[a.resourceId];if(!y)return console.warn(`ConfirmDialog layout not found: ${a.resourceId}`),e;Array.isArray(y.transitions)&&!f&&bt({animations:h,transitions:y.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog"});let g={id:"confirmDialog",type:"container",x:0,y:0,children:[$n({id:"confirmDialog-blocker",screen:l}),...y.elements||[]]},I=Ln(c,t.characters),m=P(g,Z({variables:n,saveSlots:r,isLineCompleted:u,autoMode:o,skipMode:i,canRollback:s,confirmDialog:a,historyDialogue:I,characters:t.characters||{}}),{functions:G}),[b,...x]=m.children||[],A=X(Q({...m,children:x},{isLineCompleted:u,skipTransitionsAndAnimations:f}),t);return d.push({...A,children:b?[b,...A.children||[]]:A.children}),e},kn=e=>Le(xo,[Lo,Ao,vo,Eo,_o,$o,Ro,Co,ko,So,Oo,To])(e);var Ne={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},On=1,Me=()=>({manual:{...Ne.manual},auto:{...Ne.auto},applyMode:Ne.applyMode}),wt=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let n=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...Me()},n&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},V=e=>{let t=z(e)?Qe(e):e;return structuredClone(t)},N=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),je=e=>String(e),xt=()=>({sections:[],resources:[]}),Ve=()=>({sectionId:void 0,lineId:void 0}),Po=()=>({resourceId:void 0}),No=e=>{if(!N(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},Tn=(e,t)=>{let n=e?.story?.scenes??{};for(let[r,o]of Object.entries(n))if(o?.sections?.[t])return{sceneId:r,section:o.sections[t]};return{sceneId:void 0,section:void 0}},Pn=e=>{let t=e?.story?.scenes??{},n=new Map;for(let[r,o]of Object.entries(t)){let i=o?.sections??{};for(let s of Object.keys(i)){let a=n.get(s);if(a!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${a}" and "${r}". Section IDs must be globally unique.`);n.set(s,r)}}},Nn=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},Vn=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==On)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},Vo=(e,t={})=>{let n;try{n=Vn(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let r={...t,formatVersion:n,slotId:Nn(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete r.slotKey,delete r.date,r},Do=(e={})=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Vo(t,n)])),Sn=(e,t,n)=>{let r=t==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[r]:String(e)};if(!N(e))throw new Error(`Malformed save slot viewedRegistry.${t}[${n}] entry.`);if(typeof e[r]!="string"||e[r].length===0)throw new Error(`Malformed save slot viewedRegistry.${t}[${n}] entry: missing ${r}.`);if(t==="sections"){let o={sectionId:e.sectionId};if(e.lastLineId!==void 0&&e.lastLineId!==null&&typeof e.lastLineId!="string")throw new Error(`Malformed save slot viewedRegistry.sections[${n}] entry: invalid lastLineId.`);return typeof e.lastLineId=="string"&&e.lastLineId.length>0&&(o.lastLineId=e.lastLineId),o}return{resourceId:e.resourceId}},Mo=e=>{if(e===void 0)return xt();if(!N(e))throw new Error("Malformed save slot viewedRegistry.");if(e.sections!==void 0&&!Array.isArray(e.sections))throw new Error("Malformed save slot viewedRegistry.sections.");if(e.resources!==void 0&&!Array.isArray(e.resources))throw new Error("Malformed save slot viewedRegistry.resources.");let t=e.sections??[],n=e.resources??[];return{sections:Object.values(Object.fromEntries(t.map((r,o)=>{let i=Sn(r,"sections",o);return[i.sectionId,i]}))),resources:Object.values(Object.fromEntries(n.map((r,o)=>{let i=Sn(r,"resources",o);return[i.resourceId,i]})))}},At=(e,t,n)=>{if(!N(e))throw new Error(`Malformed save slot ${n}.`);let{sectionId:r,lineId:o}=e;if(typeof r!="string"||r.length===0)throw new Error(`Malformed save slot ${n}: missing sectionId.`);if(typeof o!="string"||o.length===0)throw new Error(`Malformed save slot ${n}: missing lineId.`);let{sceneId:i,section:s}=Tn(t,r);if(!s)throw new Error(`Malformed save slot ${n}: section "${r}" does not exist in projectData.`);if(!s.lines?.some(c=>c.id===o))throw new Error(`Malformed save slot ${n}: line "${o}" does not exist in section "${r}".`);return{sceneId:i,sectionId:r,lineId:o}},jo=(e,t)=>{if(!N(e)||typeof e.sectionId!="string"||e.sectionId.length===0||typeof e.lineId!="string"||e.lineId.length===0)return Ve();try{let n=At(e,t,"contexts[*].pointers.history");return{sectionId:n.sectionId,lineId:n.lineId}}catch{return Ve()}},Bo=(e,t,n)=>{if(!N(e)||!Array.isArray(e.timeline))return le({pointer:t,replayStartIndex:1});let r=e.timeline.flatMap((a,c)=>{if(!N(a))return[];try{let l=At(a,n,`rollback.timeline[${c}]`),u=De({sectionId:l.sectionId,lineId:l.lineId,rollbackPolicy:a.rollbackPolicy});return Array.isArray(a.executedActions)&&(u.executedActions=V(a.executedActions)),[u]}catch{return[]}});if(r.length===0)return le({pointer:t,replayStartIndex:1});let o=typeof e.currentIndex=="number"?Math.trunc(e.currentIndex):r.length-1;(o<0||o>=r.length)&&(o=r.length-1);let i=r[o];if(i?.sectionId!==t.sectionId||i?.lineId!==t.lineId){let a=r.findLastIndex(c=>c.sectionId===t.sectionId&&c.lineId===t.lineId);a>=0?o=a:(r.push(De({sectionId:t.sectionId,lineId:t.lineId})),o=r.length-1)}let s=typeof e.replayStartIndex=="number"?Math.min(Math.max(Math.trunc(e.replayStartIndex),0),o):0;return{currentIndex:o,isRestoring:!1,replayStartIndex:s,timeline:r}},zo=(e,t,n)=>{if(!N(e))throw new Error(`Malformed save slot contexts[${n}] entry.`);let r=_t(t),o=At(e.pointers?.read,t,`contexts[${n}].pointers.read`);if(e.variables!==void 0&&!N(e.variables))throw new Error(`Malformed save slot contexts[${n}].variables entry.`);let i=jo(e.pointers?.history,t);return{currentPointerMode:e.currentPointerMode==="history"&&i.lineId?"history":"read",pointers:{read:o,history:i},configuration:N(e.configuration)?V(e.configuration):{},views:Array.isArray(e.views)?V(e.views):[],bgm:N(e.bgm)?V(e.bgm):{resourceId:void 0},variables:{...r,...e.variables?V(e.variables):{}},rollback:Bo(e.rollback,o,t)}},Fo=(e,t)=>{if(!N(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{viewedRegistry:Mo(e.viewedRegistry),contexts:e.contexts.map((n,r)=>zo(n,t,r))}},Uo=(e,t)=>{if(!N(e))throw new Error("Malformed save slot.");let n=Vn(e.formatVersion);return{...e,formatVersion:n,state:Fo(e.state,t)}},Rn=(e,t,{required:n=!1}={})=>{if(e===void 0){if(n)throw new Error(`showConfirmDialog requires ${t}`);return{hideConfirmDialog:{}}}if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`showConfirmDialog ${t} must be an action object`);let r=V(e);return Object.prototype.hasOwnProperty.call(r,"hideConfirmDialog")||(r.hideConfirmDialog={}),r},Wo=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:Rn(e.confirmActions,"confirmActions",{required:!0}),cancelActions:Rn(e.cancelActions,"cancelActions")}},ce=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},ee=[],vt=()=>ee[ee.length-1]??null,Et=e=>{let t=vt();t&&(t.checkpointIndex=e)},Yo=()=>{let e=vt();e&&(e.pendingStorySessionReset=!0)},Dn=()=>{let e=vt();return e?.pendingStorySessionReset?(delete e.pendingStorySessionReset,!0):!1},De=({sectionId:e,lineId:t,rollbackPolicy:n})=>({sectionId:e,lineId:t,rollbackPolicy:n??"free"}),_t=e=>{let{contextVariableDefaultValues:t}=st(e??{});return V(t)},Mn=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:V(e),history:Ve()},configuration:{},views:[],bgm:Po(),variables:_t(t),rollback:le({pointer:e})}),Ho=e=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,ce(e),e.global.viewedRegistry=xt(),e.global.nextLineConfig=Me(),e.global.layeredViews=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})},jn=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},le=({pointer:e,replayStartIndex:t=0})=>{let n=e?.sectionId&&e?.lineId;return{currentIndex:n?0:-1,isRestoring:!1,replayStartIndex:t,timeline:n?[De({sectionId:e.sectionId,lineId:e.lineId})]:[]}},ne=(e,t={})=>{if(e?.rollback)return jn(e.rollback),Array.isArray(e.rollback.timeline)||(e.rollback.timeline=[]),typeof e.rollback.currentIndex!="number"&&(e.rollback.currentIndex=e.rollback.timeline.length>0?e.rollback.timeline.length-1:-1),typeof e.rollback.isRestoring!="boolean"&&(e.rollback.isRestoring=!1),typeof e.rollback.replayStartIndex!="number"&&(e.rollback.replayStartIndex=0),e.rollback;let n=e?.pointers?.read;return e.rollback=le({pointer:n,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},$t=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return;let r=ne(n);if(r.isRestoring)return;r.currentIndex<r.timeline.length-1&&(r.timeline=r.timeline.slice(0,r.currentIndex+1));let o=r.timeline[r.timeline.length-1];if(o?.sectionId===t.sectionId&&o?.lineId===t.lineId&&(o?.rollbackPolicy??"free")===(t.rollbackPolicy??"free")){r.currentIndex=r.timeline.length-1;return}r.timeline.push(De(t)),r.currentIndex=r.timeline.length-1},Jo=e=>{let n=e.contexts?.[e.contexts.length-1]?.rollback;if(!n||n.isRestoring||!Array.isArray(n.timeline)||typeof n.currentIndex!="number")return null;let r=ee[ee.length-1],o=typeof r?.checkpointIndex=="number"?r.checkpointIndex:n.currentIndex;return o<0||o>=n.timeline.length?null:(typeof r?.checkpointIndex!="number"&&o<n.timeline.length-1&&(n.timeline=n.timeline.slice(0,o+1)),n.timeline[o]??null)},qo=({state:e})=>{let n=e.contexts?.[e.contexts.length-1]?.rollback;return!n||n.isRestoring||!Array.isArray(n.timeline)||typeof n.currentIndex!="number"||n.currentIndex<0||n.currentIndex>=n.timeline.length?(ee.push({checkpointIndex:null}),e):(n.currentIndex<n.timeline.length-1&&(n.timeline=n.timeline.slice(0,n.currentIndex+1)),ee.push({checkpointIndex:n.currentIndex}),e)},Ko=({state:e})=>(ee.pop(),e),U=(e,t,n)=>{let r=Jo(e);r&&(Array.isArray(r.executedActions)||(r.executedActions=[]),r.executedActions.push({type:t,payload:V(n)}))},Go=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return;let r=t?.operations??[];for(let{variableId:o,op:i,value:s}of r){let a=e.projectData.resources?.variables?.[o],c=a?.scope,l=a?.type;Ce(c,o),ke(l,i,o),c==="context"&&(n.variables[o]=Se(n.variables[o],i,s))}},Xo=(e,t)=>{if(!Array.isArray(t?.executedActions))return!1;let n={showDialogueUI:ae,hideDialogueUI:Be,toggleDialogueUI:Tt,setNextLineConfig:Pt,pushLayeredView:kt,popLayeredView:St,replaceLastLayeredView:Rt,clearLayeredViews:Ot};return t.executedActions.forEach(({type:r,payload:o})=>{if(r==="updateVariable"){Go(e,o);return}let i=n[r];i&&i({state:e},o)}),!0},Zo=(e,t)=>{let{sectionId:n,lineId:r}=t,s=k({state:e},{sectionId:n})?.lines?.find(l=>l.id===r)?.actions?.updateVariable;if(!s)return;let a=e.contexts?.[e.contexts.length-1];if(!a)return;let c=s.operations||[];for(let{variableId:l,op:u,value:f}of c){let d=e.projectData.resources?.variables?.[l],h=d?.scope,y=d?.type;Ce(h,l),ke(y,u,l),h==="context"&&(a.variables[l]=Se(a.variables[l],u,f))}},Qo=(e,t)=>{let{sectionId:n,lineId:r}=t,s=k({state:e},{sectionId:n})?.lines?.find(c=>c.id===r)?.actions;if(!s)return;let a={showDialogueUI:ae,hideDialogueUI:Be,toggleDialogueUI:Tt,setNextLineConfig:Pt,pushLayeredView:kt,popLayeredView:St,replaceLastLayeredView:Rt,clearLayeredViews:Ot};Object.entries(s).forEach(([c,l])=>{let u=a[c];u&&u({state:e},l)})},Bn=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return e;let r=ne(n),o=r.timeline[t];if(!o)return e;e.global.autoMode&&be({state:e}),e.global.skipMode&&te({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),r.isRestoring=!0,r.currentIndex=t;try{n.variables=_t(e.projectData),e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=V(Ne),e.global.layeredViews=[],ce(e),e.global.isLineCompleted=!0;let i=r.replayStartIndex??0;for(let s=i;s<=t;s++)s>i&&wt(e),Xo(e,r.timeline[s])||(Zo(e,r.timeline[s]),Qo(e,r.timeline[s]));n.pointers.read={sectionId:o.sectionId,lineId:o.lineId},n.currentPointerMode="read",n.pointers?.history&&(n.pointers.history={sectionId:null,lineId:null}),e.global.pendingEffects=e.global.pendingEffects.filter(s=>s?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{r.isRestoring=!1}return e},ei=e=>{let{projectData:t}=e,n=e.global??{},{saveSlots:r={},variables:o={}}=n;Pn(t);let i=t.story.initialSceneId,s=t.story.scenes[i],a=s.initialSectionId,c=s.sections[a],l={sceneId:i,sectionId:a,lineId:c.initialLineId??c.lines[0].id},{globalVariablesDefaultValues:u}=st(t),f={...u,...o};return{projectData:t,global:{isLineCompleted:!1,pendingEffects:[],autoMode:!1,skipMode:!1,dialogueUIHidden:!1,confirmDialog:null,viewedRegistry:xt(),nextLineConfig:Me(),saveSlots:Do(r),layeredViews:[],variables:f},contexts:[Mn({pointer:l,projectData:t})]}},ti=({state:e})=>e.global.layeredViews||[],ni=({state:e})=>e.global.pendingEffects,zn=({state:e})=>e.global.skipMode,ri=({state:e})=>e.global.autoMode,Fn=({state:e})=>e.global.dialogueUIHidden,Un=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],n=t[t.length-1];if(!n)return[];let{sectionId:r,lineId:o}=n.pointers.read,i=k({state:e},{sectionId:r});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(l=>l.id===o);return i.lines.slice(0,s+1).filter(l=>l.actions?.dialogue).map(l=>{let u=l.actions.dialogue,f="";return u.characterId&&(f=e.projectData.resources?.characters?.[u.characterId]?.name||""),{content:u.content,characterId:u.characterId,characterName:f}})},oi=({state:e})=>e.global.confirmDialog??null,Lt=({state:e},t)=>{let{sectionId:n,lineId:r}=t,o=e.global.viewedRegistry.sections.find(c=>c.sectionId===n);if(!o)return!1;if(o.lastLineId===void 0||r===void 0)return!0;let i=k({state:e},{sectionId:n});if(!i||!i.lines||!Array.isArray(i.lines))return o.lastLineId===r;let s=i.lines.findIndex(c=>c.id===o.lastLineId),a=i.lines.findIndex(c=>c.id===r);return s===-1||a===-1?o.lastLineId===r:a<=s},ii=({state:e},t)=>{let{resourceId:n}=t;return!!e.global.viewedRegistry.resources.find(o=>o.resourceId===n)},si=({state:e})=>e.global.nextLineConfig,li=({state:e})=>structuredClone(e),Wn=({state:e})=>e.global.saveSlots,ci=({state:e},t)=>{let n=t?.slotId,r=je(n);return e.global.saveSlots[r]},ai=({state:e})=>({...e.global?.variables??{},...e.contexts?.[e.contexts.length-1]?.variables??{}}),j=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],n=t[t.length-1];if(!n)return;let r=n.pointers?.[n.currentPointerMode];return{currentPointerMode:n.currentPointerMode,pointer:r}},k=({state:e},t)=>{let{sectionId:n}=t;return Tn(e.projectData,n).section},Yn=({state:e})=>{let t=j({state:e});if(!t?.pointer)return;let{sectionId:n,lineId:r}=t.pointer,o=k({state:e},{sectionId:n});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===r)},ui=({state:e})=>{let t=j({state:e})?.pointer,n=t?.sectionId,r=t?.lineId,i=k({state:e},{sectionId:n})?.lines||[],s=i.findIndex(l=>l.id===r);if(s<0)return;let a;return i.slice(0,s+1).forEach(l=>{if(!l?.actions||!Object.prototype.hasOwnProperty.call(l.actions,"choice"))return;let u=l.actions.choice;if(!u?.resourceId){u?.animations||(a=void 0);return}a=u.resourceId}),a},Hn=({state:e})=>{let{sectionId:t,lineId:n}=j({state:e}).pointer,o=k({state:e},{sectionId:t})?.lines||[],i=o.findIndex(l=>l.id===n),a=o.slice(0,i+1).map(l=>{let u=l.actions||{},f={};return Object.keys(u).forEach(d=>{f[d]=u[d]}),f});return he(a)},fi=({state:e})=>{let t=Jn({state:e}),r=Yn({state:e})?.actions??{},o=he([t??{},r]);return ct(t??{},o??{})},di=({state:e},{sectionId:t})=>{let n=k({state:e},{sectionId:t});if(!n?.lines)return{lines:[]};let r=[],o={};for(let i of n.lines){let s=i.actions||{},a=he([o,s]),c=ct(o,a);r.push({id:i.id,changes:c}),o=at(a)}return{lines:r}},Jn=({state:e})=>{let{sectionId:t,lineId:n}=j({state:e}).pointer,o=k({state:e},{sectionId:t})?.lines||[],i=o.findIndex(c=>c.id===n);if(i<=0)return null;let a=o.slice(0,i).map(c=>{let l=c.actions||{},u={};return Object.keys(l).forEach(f=>{u[f]=l[f]}),u});return at(he(a))},Ct=({state:e},{slotsPerPage:t=6}={})=>{let o=(({...e.global.variables,...e.contexts[e.contexts.length-1].variables}.loadPage??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let a=o+s,c=e.global.saveSlots&&e.global.saveSlots[je(a)]||{};i.push({...c,slotId:a})}return{saveSlots:i}},pi=Wn,hi=Ct,gi=e=>{let n=e.contexts?.[e.contexts.length-1]?.rollback;return!n||!Array.isArray(n.timeline)||typeof n.currentIndex!="number"?!1:n.currentIndex>=0&&n.currentIndex<n.timeline.length-1},yi=({state:e})=>{let t=Hn({state:e}),n=Jn({state:e}),r={...e.global.variables,...e.contexts[e.contexts.length-1].variables},{saveSlots:o}=Ct({state:e}),i=gi(e);return kn({presentationState:t,previousPresentationState:n,resources:e.projectData.resources,screen:e.projectData.screen,dialogueUIHidden:e.global.dialogueUIHidden,autoMode:e.global.autoMode,skipMode:e.global.skipMode,canRollback:Xn({state:e}),skipOnlyViewedLines:!r._skipUnseenText,isLineCompleted:e.global.isLineCompleted,skipTransitionsAndAnimations:!!r._skipTransitionsAndAnimations||i,layeredViews:e.global.layeredViews,confirmDialog:e.global.confirmDialog,dialogueHistory:Un({state:e}),saveSlots:o,variables:r})},mi=({state:e},t)=>(e.global.confirmDialog=Wo(t),e.global.pendingEffects.push({name:"render"}),e),bi=({state:e})=>(e.global.confirmDialog&&(ce(e),e.global.pendingEffects.push({name:"render"})),e),kt=({state:e},t)=>(e.global.layeredViews.push(t),e.global.pendingEffects.push({name:"render"}),U(e,"pushLayeredView",t),e),St=({state:e})=>(e.global.layeredViews.pop(),e.global.pendingEffects.push({name:"render"}),U(e,"popLayeredView",void 0),e),Rt=({state:e},t)=>(e.global.layeredViews.length>0&&(e.global.layeredViews[e.global.layeredViews.length-1]=t),e.global.pendingEffects.push({name:"render"}),U(e,"replaceLastLayeredView",t),e),Ot=({state:e})=>(e.global.layeredViews=[],ce(e),e.global.pendingEffects.push({name:"render"}),U(e,"clearLayeredViews",void 0),e),qn=({state:e})=>{if(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){let t=e.global.variables._autoForwardTime??1e3;e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:t}})}return e.global.pendingEffects.push({name:"render"}),e},be=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Ii=({state:e})=>(e.global.autoMode?be({state:e}):qn({state:e}),e),Kn=({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),te=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),wi=({state:e})=>(zn({state:e})?te({state:e}):Kn({state:e}),e),ae=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),U(e,"showDialogueUI",void 0),e),Be=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),U(e,"hideDialogueUI",void 0),e),Tt=({state:e})=>(Fn({state:e})?ae({state:e}):Be({state:e}),e),xi=({state:e})=>(e.global.pendingEffects=[],e),Ai=({state:e},t)=>(e.global.pendingEffects.push(t),e),vi=({state:e})=>{let t=e.contexts?.[e.contexts.length-1],n=t?.pointers?.read;return!t||!n?.sectionId||!n?.lineId||(e.contexts[e.contexts.length-1]=Mn({pointer:n,projectData:e.projectData}),Ho(e),Yo(),Et(0)),e},me=(e,{sectionId:t,lineId:n})=>{e.global.viewedRegistry||(e.global.viewedRegistry={}),Array.isArray(e.global.viewedRegistry.sections)||(e.global.viewedRegistry.sections=[]);let r=e.global.viewedRegistry.sections.find(o=>o.sectionId===t);if(r){let o=k({state:e},{sectionId:t});if(o?.lines&&r.lastLineId!==void 0){let i=o.lines.findIndex(a=>a.id===r.lastLineId),s=o.lines.findIndex(a=>a.id===n);(i===-1||s>i)&&(r.lastLineId=n)}else r.lastLineId=n}else e.global.viewedRegistry.sections.push({sectionId:t,lastLineId:n})},Ei=({state:e},t)=>(me(e,t),e.global.pendingEffects.push({name:"render"}),e),_i=({state:e},t)=>{let{resourceId:n}=t;return e.global.viewedRegistry.resources.find(o=>o.resourceId===n)||e.global.viewedRegistry.resources.push({resourceId:n}),e.global.pendingEffects.push({name:"render"}),e},Pt=({state:e},t)=>{let n=No(t.manual),{auto:r,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,a=e.contexts?.[e.contexts.length-1]?.rollback?.isRestoring===!0;n&&r?(e.global.nextLineConfig={manual:n,auto:r},o!==void 0?e.global.nextLineConfig.applyMode=o:s!==void 0&&(e.global.nextLineConfig.applyMode=s)):(n&&(e.global.nextLineConfig.manual=n),r&&(e.global.nextLineConfig.auto=r),o!==void 0&&(e.global.nextLineConfig.applyMode=o));let c=e.global.nextLineConfig.auto?.enabled;return!a&&c===!0&&!i?e.global.nextLineConfig.auto?.trigger==="fromStart"?e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):e.global.isLineCompleted&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):!a&&c===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),U(e,"setNextLineConfig",t),e},$i=({state:e},t)=>{let n=t?.slotId;if(n==null||n==="")throw new Error("saveSlot requires slotId");let{thumbnailImage:r}=t,o=t?.savedAt,i=je(n),s=V(e.contexts);s?.forEach(l=>{jn(l.rollback)});let a={contexts:s,viewedRegistry:V(e.global.viewedRegistry)},c={formatVersion:On,slotId:Nn(n),savedAt:typeof o=="number"?o:Date.now(),image:r,state:a};return e.global.saveSlots[i]=c,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},Li=({state:e},t)=>{let n=t?.slotId;if(n==null||n==="")throw new Error("loadSlot requires slotId");let r=je(n),o=e.global.saveSlots[r];if(o){let i=Uo(o,e.projectData);e.global.viewedRegistry=i.state.viewedRegistry,e.contexts=i.state.contexts,e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=Me(),e.global.layeredViews=[],e.global.isLineCompleted=!0,ce(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},Ci=({state:e},t)=>{let{projectData:n}=t;return Pn(n),e.projectData=n,ce(e),e.global.pendingEffects.push({name:"render"}),e},ki=({state:e},t)=>{let{sectionId:n,lineId:r}=t;if(!r)return console.warn("jumpToLine requires lineId parameter"),e;let o=e.contexts[e.contexts.length-1];if(!o)return console.warn("No context available for jumpToLine"),e;let i=n||o.pointers.read?.sectionId;if(n&&!k({state:e},{sectionId:n}))return console.warn(`Section not found: ${n}`),e;let s=k({state:e},{sectionId:i});return!s?.lines||!Array.isArray(s.lines)?(console.warn(`Section ${i} has no lines`),e):s.lines.find(c=>c.id===r)?(o.pointers.read={sectionId:i,lineId:r},Dn()&&(o.rollback=le({pointer:o.pointers.read}),Et(o.rollback.currentIndex)),e.global.isLineCompleted=!1,e.global.pendingEffects.push({name:"handleLineActions"}),e):(console.warn(`Line not found: ${r} in section ${i}`),e)},Si=({state:e})=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return ae({state:e}),e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0;let c=j({state:e})?.pointer,l=c?.sectionId,u=c?.lineId;if(l&&u&&me(e,{sectionId:l,lineId:u}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode){let d=e.global.variables._autoForwardTime??1e3;e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:d}})}let f=e.global.nextLineConfig;return f?.auto?.enabled&&f.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:f.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e}let t=j({state:e})?.pointer,n=t?.sectionId,r=k({state:e},{sectionId:n}),o=e.contexts[e.contexts.length-1],i=r?.lines||[],a=i.findIndex(c=>c.id===t?.lineId)+1;if(a<i.length){let c=i[a],l=!e.global.variables?._skipUnseenText;if(e.global.skipMode&&l&&!Lt({state:e},{sectionId:n,lineId:c.id}))return te({state:e}),e;if(o&&!o.rollback&&ne(o,{compatibilityAnchor:!0}),o){let f=o.pointers.read.lineId;f&&n&&me(e,{sectionId:n,lineId:f}),o.pointers.read={sectionId:n,lineId:c.id}}e.global.isLineCompleted=!1,$t(e,{sectionId:n,lineId:c.id}),wt(e),e.global.pendingEffects.push({name:"handleLineActions"});let u=e.global.nextLineConfig;u?.auto?.enabled&&u.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:u.auto.delay}})}else e.global.autoMode&&be({state:e}),e.global.skipMode&&te({state:e});return e},Ri=({state:e})=>{if(e.global.isLineCompleted)return e;if(e.global.isLineCompleted=!0,e.global.autoMode){let i=e.global.variables._autoForwardTime??1e3;e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:i}})}let t=j({state:e})?.pointer,n=t?.sectionId,r=t?.lineId;n&&r&&me(e,{sectionId:n,lineId:r});let o=e.global.nextLineConfig;return o?.auto?.enabled&&o.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:o.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e},Oi=({state:e},t)=>{let n=t?.sectionId??j({state:e})?.pointer?.sectionId,r=k({state:e},{sectionId:n});if(!r||!r.lines||r.lines.length===0)return e;let o=r.lines,i=e.contexts[e.contexts.length-1];if(!i||!i.pointers)return e;let s=i.pointers.history||i.pointers.read;if(i.currentPointerMode!=="history"||!i.pointers.history){if(!s)return e;i.currentPointerMode="history",i.pointers.history={sectionId:n,lineId:s?.lineId};let u=o.findIndex(f=>f.id===s.lineId)-1;if(u>=0&&u<o.length){let f=o[u];i.pointers.history={sectionId:n,lineId:f.id}}return e.global.pendingEffects.push({name:"render"}),e}let c=o.findIndex(l=>l.id===i.pointers.history.lineId)-1;if(c>=0&&c<o.length){let l=o[c];i.pointers.history={sectionId:n,lineId:l.id},e.global.pendingEffects.push({name:"render"})}return e},Ti=({state:e},t)=>{let{sectionId:n}=t,r=k({state:e},{sectionId:n});if(!r)return console.warn(`Section not found: ${n}`),e;let o=r.lines?.[0];if(!o)return console.warn(`Section ${n} has no lines`),e;e.global.autoMode&&be({state:e}),e.global.skipMode&&te({state:e});let i=e.contexts[e.contexts.length-1];return i&&(i.rollback||ne(i,{compatibilityAnchor:!0}),i.pointers.read={sectionId:n,lineId:o.id},Dn()?(i.rollback=le({pointer:i.pointers.read}),Et(i.rollback.currentIndex)):$t(e,{sectionId:n,lineId:o.id})),e.global.isLineCompleted=!1,e.global.pendingEffects.push({name:"handleLineActions"}),e},Pi=({state:e})=>{if(e.global.dialogueUIHidden)return ae({state:e}),e;if(ui({state:e}))return e;let t=j({state:e})?.pointer,n=t?.sectionId,r=k({state:e},{sectionId:n}),o=e.contexts[e.contexts.length-1],i=r?.lines||[],a=i.findIndex(c=>c.id===t?.lineId)+1;if(a<i.length){let c=i[a],l=!e.global.variables?._skipUnseenText;if(e.global.skipMode&&l&&!Lt({state:e},{sectionId:n,lineId:c.id}))return te({state:e}),e;if(o&&!o.rollback&&ne(o,{compatibilityAnchor:!0}),o){let u=o.pointers.read.lineId;u&&n&&me(e,{sectionId:n,lineId:u}),o.pointers.read={sectionId:n,lineId:c.id}}e.global.isLineCompleted=!1,$t(e,{sectionId:n,lineId:c.id}),wt(e),e.global.pendingEffects.push({name:"handleLineActions"}),e.global.nextLineConfig.auto?.enabled&&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},Ni=({state:e},t)=>{let{id:n,operations:r=[]}=t;if(!n)throw new Error("updateVariable requires an id field");if(typeof n!="string"||!/^[a-zA-Z0-9]+$/.test(n))throw new Error(`updateVariable id must be alphanumeric, got: "${n}"`);let o=e.contexts[e.contexts.length-1];if(o?.rollback?.isRestoring)return e;let i=!1,s=!1,a=!1,c=[];if(r.forEach(({variableId:l,op:u,value:f})=>{let d=e.projectData.resources?.variables?.[l],h=d?.scope,y=d?.type;Ce(h,l),ke(y,u,l);let g=h==="context"?o.variables:e.global.variables;h==="context"?(i=!0,c.push({variableId:l,op:u,value:f})):h==="global-device"?s=!0:h==="global-account"&&(a=!0),g[l]=Se(g[l],u,f)}),i&&U(e,"updateVariable",{id:n,operations:c}),s){let l=lt(e.global.variables,e.projectData.resources?.variables,"global-device");e.global.pendingEffects.push({name:"saveGlobalDeviceVariables",payload:{globalDeviceVariables:l}})}if(a){let l=lt(e.global.variables,e.projectData.resources?.variables,"global-account");e.global.pendingEffects.push({name:"saveGlobalAccountVariables",payload:{globalAccountVariables:l}})}return e.global.pendingEffects.push({name:"render"}),e},Gn=({state:e},t)=>{let{offset:n}=t;if(n===void 0||typeof n!="number")return console.warn("selectLineIdByOffset requires a numeric offset"),null;let r=e.contexts[e.contexts.length-1];if(!r)return null;let o=r.rollback;if(!Array.isArray(o?.timeline)||typeof o?.currentIndex!="number")return null;let i=o.currentIndex+n;if(i<0||i>=o.timeline.length)return null;let s=o.timeline[i];return{sectionId:s.sectionId,lineId:s.lineId}},Xn=({state:e})=>Gn({state:e},{offset:-1})!==null,Vi=({state:e},t)=>{let{offset:n=-1}=t;if(n>=0)throw new Error("rollbackByOffset requires a negative offset");let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let o=ne(r,{compatibilityAnchor:!r.rollback}),i=o.currentIndex+n;return i<0||i>=o.timeline.length?e:Bn(e,i)},Di=({state:e},t)=>{let{sectionId:n,lineId:r}=t,o=e.contexts[e.contexts.length-1];if(!o)throw new Error("No context available for rollbackToLine");let i=ne(o,{compatibilityAnchor:!o.rollback}),a=i.timeline.slice(0,i.currentIndex+1).findLastIndex(c=>c.sectionId===n&&c.lineId===r);if(a===-1)throw new Error(`Line ${r} not found in section ${n} rollback timeline`);return a===i.currentIndex?e:Bn(e,a)},Zn=e=>{let t=ei(e);return an(t,{selectPendingEffects:ni,selectSkipMode:zn,selectAutoMode:ri,selectDialogueUIHidden:Fn,selectDialogueHistory:Un,selectConfirmDialog:oi,selectIsLineViewed:Lt,selectIsResourceViewed:ii,selectNextLineConfig:si,selectSystemState:li,selectSaveSlotMap:Wn,selectSaveSlots:pi,selectSaveSlot:ci,selectAllVariables:ai,selectCurrentPointer:j,selectSection:k,selectCurrentLine:Yn,selectPresentationState:Hn,selectPresentationChanges:fi,selectSectionLineChanges:di,selectSaveSlotPage:Ct,selectCurrentPageSlots:hi,selectRenderState:yi,selectLayeredViews:ti,selectLineIdByOffset:Gn,selectCanRollback:Xn,startAutoMode:qn,stopAutoMode:be,toggleAutoMode:Ii,startSkipMode:Kn,stopSkipMode:te,toggleSkipMode:wi,showDialogueUI:ae,hideDialogueUI:Be,toggleDialogueUI:Tt,showConfirmDialog:mi,hideConfirmDialog:bi,resetStorySession:vi,clearPendingEffects:xi,appendPendingEffect:Ai,beginRollbackActionBatch:qo,endRollbackActionBatch:Ko,addViewedLine:Ei,addViewedResource:_i,setNextLineConfig:Pt,saveSlot:$i,loadSlot:Li,updateProjectData:Ci,sectionTransition:Ti,jumpToLine:ki,nextLine:Si,markLineCompleted:Ri,prevLine:Oi,rollbackToLine:Di,rollbackByOffset:Vi,pushLayeredView:kt,popLayeredView:St,replaceLastLayeredView:Rt,clearLayeredViews:Ot,updateVariable:Ni,nextLineFromSystem:Pi},{transformActionFirstArgument:r=>({state:r}),transformSelectorFirstArgument:r=>({state:r})})};function Nt(e){let t,n=0,{handlePendingEffects:r}=e,o=()=>{for(;t.selectPendingEffects().length>0;){let w=[...t.selectPendingEffects()];t.clearPendingEffects();try{r(w)}catch(E){throw t.clearPendingEffects(),w.forEach($=>{t.appendPendingEffect($)}),E}}},i=({initialState:w})=>{t=Zn(w),n=0,t.appendPendingEffect({name:"handleLineActions"}),o()},s=()=>t.selectPresentationState(),a=()=>t.selectPresentationChanges(),c=w=>t.selectSectionLineChanges(w),l=()=>(n+=1,{...t.selectRenderState(),id:`render-${n}`}),u=()=>t.selectSystemState(),f=()=>t.selectSaveSlotMap(),d=w=>t.selectSaveSlot(w),h=w=>t.selectSaveSlotPage(w),y=()=>t.selectSkipMode(),g=()=>t.selectAutoMode(),I=(w,E)=>{t[w]&&(t[w](E),o())},m=(w,E)=>{I(w,E)},b=w=>{if(!w)return{variables:t.selectAllVariables?t.selectAllVariables():void 0};if(Object.prototype.hasOwnProperty.call(w,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:E,...$}=w,M=t.selectAllVariables?t.selectAllVariables():void 0;return{...$,_event:E,variables:M}},x=(w,E)=>{let $=b(E),M=fn(w,$);t.beginRollbackActionBatch({});try{Object.entries(M).forEach(([Fe,re])=>{I(Fe,re)})}finally{t.endRollbackActionBatch({})}};return{init:i,handleAction:I,handleInternalAction:m,handleActions:x,selectRenderState:l,selectPresentationState:s,selectPresentationChanges:a,selectSectionLineChanges:c,selectSystemState:u,selectSaveSlotMap:f,selectSaveSlot:d,selectSaveSlotPage:h,selectSaveSlots:f,handleLineActions:()=>{let w=t.selectCurrentLine();return w?.actions?(x(w.actions),!0):!1}}}var Vt=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:n=>{e=n},addElapsed:n=>{e+=n},getCallback:()=>t,setCallback:n=>{t=n}}},er=({engine:e,routeGraphics:t,trackRenderDispatch:n},r)=>{let o=e.selectRenderState();n?.(o),t.render(o)},Mi=({engine:e,routeGraphics:t,trackRenderDispatch:n,getRenderDispatchCount:r},o)=>{let i=r?.()??0,s=e.handleLineActions();(r?.()??0)===i&&er({engine:e,routeGraphics:t,trackRenderDispatch:n},o)},ji=({engine:e,ticker:t,autoTimer:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let a=r.delay??1e3;n.getElapsed()>=a&&(t.remove(i),n.setCallback(null),n.setElapsed(0),ze(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},Bi=({ticker:e,autoTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},zi=({engine:e,ticker:t,skipTimer:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS),n.getElapsed()>=30&&(n.setElapsed(0),ze(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},Fi=({ticker:e,skipTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Ui=({engine:e,ticker:t,nextLineConfigTimerState:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let a=r.delay??1e3;n.getElapsed()>=a&&(n.setElapsed(0),ze(e,"nextLineFromSystem",{}),t.remove(i),n.setCallback(null))};n.setCallback(i),t.add(i)},Wi=({ticker:e,nextLineConfigTimerState:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Yi=({},e)=>{localStorage.setItem("saveSlots",JSON.stringify(e.saveSlots))},Hi=({},e)=>{localStorage.setItem("globalDeviceVariables",JSON.stringify(e.globalDeviceVariables))},Ji=({},e)=>{localStorage.setItem("globalAccountVariables",JSON.stringify(e.globalAccountVariables))},Qn={render:er,saveSlots:Yi,saveGlobalDeviceVariables:Hi,saveGlobalAccountVariables:Ji,handleLineActions:Mi,startAutoNextTimer:ji,clearAutoNextTimer:Bi,startSkipNextTimer:zi,clearSkipNextTimer:Fi,nextLineConfigTimer:Ui,clearNextLineConfigTimer:Wi},qi=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),ze=(e,t,n)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,n)},Ki=(e=[])=>{let t=new Set,n=[];for(let r=e.length-1;r>=0;r-=1){let o=e[r];if(typeof o?.name!="string"||o.name.length===0)throw new Error("Pending effect is missing a valid name.");if(!qi.has(o.name)){n.unshift(o);continue}t.has(o.name)||(t.add(o.name),n.unshift(o))}return n},Gi=({getEngine:e,routeGraphics:t,ticker:n,handleUnhandledEffect:r})=>{let o=Vt(),i=Vt(),s=Vt(),a=null,c=null,l=!1,u=0,f=m=>{let b=typeof m?.id=="string"&&m.id.length>0?m.id:null;u+=1,a=b,l=!1},d=()=>u,h=(m={})=>{if(m?.aborted===!0)return!1;let b=typeof m?.id=="string"&&m.id.length>0?m.id:null;return b?b!==a||b===c?!1:(c=b,!0):a!==null||l?!1:(l=!0,!0)},y=(m,b={})=>{if(m!=="renderComplete"||!h(b))return!1;let x=e();return ze(x,"markLineCompleted",{}),!0},g=({preprocessPayload:m,onEvent:b}={})=>async(x,A={})=>{let w=await m?.(x,A)??A;if(y(x,w),w?.actions){let E=w?._event?{_event:w._event}:w?.event?{_event:w.event}:void 0;e().handleActions(w.actions,E)}return b?.(x,w)},I=m=>{let b=e(),x=Ki(m);x.forEach(w=>{if(!Qn[w.name]&&!r)throw new Error(`Unhandled pending effect "${w.name}".`)});let A={engine:b,routeGraphics:t,ticker:n,autoTimer:o,skipTimer:i,nextLineConfigTimerState:s,trackRenderDispatch:f,getRenderDispatchCount:d};for(let w of x){let E=Qn[w.name];if(E){E(A,w.payload);continue}r(w,A)}};return I.handleRouteGraphicsEvent=y,I.createRouteGraphicsEventHandler=g,I},Xi=Gi;var Zi=(e,t={})=>{let{resources:n={}}=t;return It(e,n)};var Qs=Nt;export{Xi as createEffectsHandler,Qs as default,Zi as resolveLayoutReferences};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "route-engine-js",
3
- "version": "0.6.0",
3
+ "version": "0.7.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",