route-engine-js 0.5.0 → 0.5.2

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