route-engine-js 0.1.24 → 0.1.26

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 yt=Object.defineProperty;var mt=(e,t)=>{for(var n in t)yt(e,n,{get:t[n],enumerable:!0})};var Re=Symbol.for("immer-nothing"),$e=Symbol.for("immer-draftable"),k=Symbol.for("immer-state");function S(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var B=Object.getPrototypeOf;function j(e){return!!e&&!!e[k]}function T(e){return e?Ne(e)||Array.isArray(e)||!!e[$e]||!!e.constructor?.[$e]||Q(e)||Z(e):!1}var bt=Object.prototype.constructor.toString();function Ne(e){if(!e||typeof e!="object")return!1;let t=B(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)===bt}function J(e,t){q(e)===0?Reflect.ownKeys(e).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function q(e){let t=e[k];return t?t.type_:Array.isArray(e)?1:Q(e)?2:Z(e)?3:0}function se(e,t){return q(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Pe(e,t,n){let r=q(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function It(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Q(e){return e instanceof Map}function Z(e){return e instanceof Set}function P(e){return e.copy_||e.base_}function ae(e,t){if(Q(e))return new Map(e);if(Z(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let n=Ne(e);if(t===!0||t==="class_only"&&!n){let r=Object.getOwnPropertyDescriptors(e);delete r[k];let o=Reflect.ownKeys(r);for(let i=0;i<o.length;i++){let a=o[i],c=r[a];c.writable===!1&&(c.writable=!0,c.configurable=!0),(c.get||c.set)&&(r[a]={configurable:!0,writable:!0,enumerable:c.enumerable,value:e[a]})}return Object.create(B(e),r)}else{let r=B(e);if(r!==null&&n)return{...e};let o=Object.create(r);return Object.assign(o,e)}}function de(e,t=!1){return ee(e)||j(e)||!T(e)||(q(e)>1&&(e.set=e.add=e.clear=e.delete=wt),Object.freeze(e),t&&Object.entries(e).forEach(([n,r])=>de(r,!0))),e}function wt(){S(2)}function ee(e){return Object.isFrozen(e)}var _t={};function V(e){let t=_t[e];return t||S(0,e),t}var U;function Te(){return U}function vt(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function Ce(e,t){t&&(V("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function le(e){ce(e),e.drafts_.forEach(Et),e.drafts_=null}function ce(e){e===U&&(U=e.parent_)}function ke(e){return U=vt(U,e)}function Et(e){let t=e[k];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function Oe(e,t){t.unfinalizedDrafts_=t.drafts_.length;let n=t.drafts_[0];return e!==void 0&&e!==n?(n[k].modified_&&(le(t),S(4)),T(e)&&(e=X(t,e),t.parent_||G(t,e)),t.patches_&&V("Patches").generateReplacementPatches_(n[k].base_,e,t.patches_,t.inversePatches_)):e=X(t,n,[]),le(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Re?e:void 0}function X(e,t,n){if(ee(t))return t;let r=t[k];if(!r)return J(t,(o,i)=>Se(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return G(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;let o=r.copy_,i=o,a=!1;r.type_===3&&(i=new Set(o),o.clear(),a=!0),J(i,(c,l)=>Se(e,r,o,c,l,n,a)),G(e,o,!1),n&&e.patches_&&V("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function Se(e,t,n,r,o,i,a){if(j(o)){let c=i&&t&&t.type_!==3&&!se(t.assigned_,r)?i.concat(r):void 0,l=X(e,o,c);if(Pe(n,r,l),j(l))e.canAutoFreeze_=!1;else return}else a&&n.add(o);if(T(o)&&!ee(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;X(e,o),(!t||!t.scope_.parent_)&&typeof r!="symbol"&&Object.prototype.propertyIsEnumerable.call(n,r)&&G(e,o)}}function G(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&de(t,n)}function xt(e,t){let n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:Te(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=r,i=pe;n&&(o=[r],i=W);let{revoke:a,proxy:c}=Proxy.revocable(o,i);return r.draft_=c,r.revoke_=a,c}var pe={get(e,t){if(t===k)return e;let n=P(e);if(!se(n,t))return At(e,n,t);let r=n[t];return e.finalized_||!T(r)?r:r===oe(e.base_,t)?(ie(e),e.copy_[t]=fe(r,e)):r},has(e,t){return t in P(e)},ownKeys(e){return Reflect.ownKeys(P(e))},set(e,t,n){let r=Ve(P(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){let o=oe(P(e),t),i=o?.[k];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(It(n,o)&&(n!==void 0||se(e.base_,t)))return!0;ie(e),ue(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 oe(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,ie(e),ue(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let n=P(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){S(11)},getPrototypeOf(e){return B(e.base_)},setPrototypeOf(){S(12)}},W={};J(pe,(e,t)=>{W[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});W.deleteProperty=function(e,t){return W.set.call(this,e,t,void 0)};W.set=function(e,t,n){return pe.set.call(this,e[0],t,n,e[0])};function oe(e,t){let n=e[k];return(n?P(n):e)[t]}function At(e,t,n){let r=Ve(t,n);return r?"value"in r?r.value:r.get?.call(e.draft_):void 0}function Ve(e,t){if(!(t in e))return;let n=B(e);for(;n;){let r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=B(n)}}function ue(e){e.modified_||(e.modified_=!0,e.parent_&&ue(e.parent_))}function ie(e){e.copy_||(e.copy_=ae(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Lt=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 a=this;return function(l=i,...s){return a.produce(l,u=>n.call(this,u,...s))}}typeof n!="function"&&S(6),r!==void 0&&typeof r!="function"&&S(7);let o;if(T(t)){let i=ke(this),a=fe(t,void 0),c=!0;try{o=n(a),c=!1}finally{c?le(i):ce(i)}return Ce(i,r),Oe(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===Re&&(o=void 0),this.autoFreeze_&&de(o,!0),r){let i=[],a=[];V("Patches").generateReplacementPatches_(t,o,i,a),r(i,a)}return o}else S(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(a,...c)=>this.produceWithPatches(a,l=>t(l,...c));let r,o;return[this.produce(t,n,(a,c)=>{r=a,o=c}),r,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){T(e)||S(8),j(e)&&(e=$t(e));let t=ke(this),n=fe(e,void 0);return n[k].isManual_=!0,ce(t),n}finishDraft(e,t){let n=e&&e[k];(!n||!n.isManual_)&&S(9);let{scope_:r}=n;return Ce(r,t),Oe(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=V("Patches").applyPatches_;return j(e)?r(e,t):this.produce(e,o=>r(o,t))}};function fe(e,t){let n=Q(e)?V("MapSet").proxyMap_(e,t):Z(e)?V("MapSet").proxySet_(e,t):xt(e,t);return(t?t.scope_:Te()).drafts_.push(n),n}function $t(e){return j(e)||S(10,e),De(e)}function De(e){if(!T(e)||ee(e))return e;let t=e[k],n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=ae(e,t.scope_.immer_.useStrictShallowCopy_)}else n=ae(e,!0);return J(n,(r,o)=>{Pe(n,r,De(o))}),t&&(t.finalized_=!1),n}var O=new Lt,he=O.produce,Vr=O.produceWithPatches.bind(O),Dr=O.setAutoFreeze.bind(O),Mr=O.setUseStrictShallowCopy.bind(O),Br=O.applyPatches.bind(O),jr=O.createDraft.bind(O),Fr=O.finishDraft.bind(O);var Me=(e,t,n={})=>{let r=structuredClone(e),o={},i={},{transformSelectorFirstArgument:a=l=>l,transformActionFirstArgument:c=l=>l}=n;for(let[l,s]of Object.entries(t))l!=="createInitialState"&&(l.startsWith("select")?o[l]=(...u)=>s(a(r),...u):i[l]=(...u)=>{r=he(r,d=>s(c(d),...u))});return{...o,...i}},te=(e,t)=>n=>{let r=e(),o=Array.isArray(n)?n:[n];return he(r,i=>{o.forEach(a=>{t.forEach(c=>{c(i,a)})})})};var Ct=(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{}}},Be=e=>{let t={},n={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([r,o])=>{let i=Ct(o,r);o.scope==="context"?t[r]=i:n[r]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}},je=(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(", ")}`)},Fe=(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(", ")}`)},Ue=(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}`)}},ge=(e,t,n)=>Object.fromEntries(Object.entries(e).filter(([r])=>t?.[r]?.scope===n)),We=(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()))},kt=(e,t)=>{let n=e?.gui,r=t?.gui;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},ye=(e={},t={})=>{let n={},r=["sfx","voice"],o=a=>{let c=e[a],l=t[a];l&&!c?n[a]={changeType:"add",data:l}:c&&!l?r.includes(a)||(n[a]={changeType:"delete",data:c}):c&&l&&JSON.stringify(c)!==JSON.stringify(l)&&(n[a]={changeType:"update",data:l})};o("background"),o("base"),o("bgm"),o("voice");let i=kt(e.dialogue,t.dialogue);return i&&(n.dialogue=i),o("choice"),o("layout"),o("animation"),o("keyboard"),o("character"),o("visual"),o("sfx"),n};var Ot=()=>({}),St=(e,t)=>{t.base&&(e.base={...t.base})},Rt=(e,t)=>{if(t.background){if(!t.background.resourceId){delete e.background;return}e.background=structuredClone(t.background)}else e.background?.animations&&(e.background.animations={})},Nt=(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.gui&&(e.dialogue.gui={...t.dialogue.gui}),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}),t.dialogue.clear){delete e.dialogue;return}t.dialogue?.mode==="nvl"&&t.dialogue.content!==void 0&&(t.dialogue.clear&&(e.dialogue.lines=[]),e.dialogue.lines.push({content:t.dialogue.content}))},Pt=(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},Tt=(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}}},Vt=(e,t)=>{t.visual?e.visual=structuredClone(t.visual):e.visual?.items&&(e.visual.items=e.visual.items.map(n=>n.animations?{...n,animations:{}}:n))},Dt=(e,t)=>{if(!t.character){e.character?.items&&(e.character.items=e.character.items.map(n=>n.animations?{...n,animations:{}}:n));return}if(!t.character.items||t.character.items.length===0){delete e.character;return}e.character=structuredClone(t.character)},Mt=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},Bt=(e,t)=>{t.layout?e.layout=t.layout:e.layout&&delete e.layout},jt=(e,t)=>{t.choice?e.choice=t.choice:e.choice&&delete e.choice},Ft=(e,t)=>{t.keyboard&&(e.keyboard=t.keyboard)},Ut=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},Wt=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(n=>{delete e[n]})},z=e=>te(Ot,[Wt,St,Rt,Pt,Tt,Vt,Nt,Dt,Mt,Bt,jt,Ft,Ut])(e);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},E={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},Y={NOT:0};var I=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},L=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var me=e=>{if(!e||e.trim()==="")throw new I("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let n=e.includes("===")?"==":"!=";throw new I(`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 I(`Incomplete comparison expression - missing right operand (got: '${e}')`)},ze=e=>{if(e.trim().endsWith(" in"))throw new I(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new I(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,n]=e.split(" in ");if(!n||n.trim()==="")throw new I(`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 I(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new I(`Invalid loop syntax (got: '$for ${e}')`)}};var Ye=(e,t,n=!1)=>{if(t===null)return new L(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new L(`Cannot iterate over undefined value at '$for ${e}'`);let r=typeof t;return n?new L(`Cannot iterate over non-array value in loop '${e}' - got ${r} instead`):new L(`Cannot iterate over non-array value (got: ${r}) at '$for ${e}'`)},Ke=(e,t)=>{let n=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new L(`Unknown function '${e}' (${n})`)};var zt=(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 a=_(e,{functions:r,partials:o},t,{});return a===void 0?{}:a},_=(e,t,n,r)=>{let o=t.functions||t;if(e.var&&!e.type)return x(e.var,n,r);if(e.type===p.LITERAL)return e.value;if(e.type===p.VARIABLE)return x(e.path,n,r);if(e.type===p.INTERPOLATION)return Kt(e.parts,t,n,r);switch(e.type){case p.FUNCTION:return Je(e,t,n,r);case p.BINARY:return Xe(e,t,n,r);case p.UNARY:return Ge(e,t,n,r);case p.CONDITIONAL:return Jt(e,t,n,r);case p.LOOP:return Zt(e,t,n,r);case p.OBJECT:return tn(e,t,n,r);case p.ARRAY:return nn(e,t,n,r);case p.PARTIAL:return rn(e,t,n,r);case p.PATH_REFERENCE:return on(e,t,n,r);default:throw new Error(`Unknown node type: ${e.type}`)}},He=new Map,Yt=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 a=n.trim();if(/^\d+$/.test(a))t.push({type:"index",value:parseInt(a,10)});else if(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'")){let c=a.slice(1,-1);t.push({type:"property",value:c})}else t.push({type:"property",value:a});n=""}r=!1}else n+=i}return n&&t.push({type:"property",value:n}),t},x=(e,t,n)=>{if(!e)return;if(e in n)return n[e];let r=He.get(e);if(!r){let i=[],a="",c=0;for(let l=0;l<e.length;l++){let s=e[l];s==="["?(c++,a+=s):s==="]"?(c--,a+=s):s==="."&&c===0?a&&(i.push(a),a=""):a+=s}a&&i.push(a),r=[];for(let l of i){let s=Yt(l.trim());r.push(...s)}He.set(e,r)}let o=t;for(let i=0;i<r.length;i++){let a=r[i];if(a.type==="property"&&a.value in n){o=n[a.value];continue}if(o==null)return;(a.type==="property"||a.type==="index")&&(o=o[a.value])}return o},Kt=(e,t,n,r)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let a=_(i,t,n,r);o.push(a!=null?String(a):"")}return o.join("")},Je=(e,t,n,r)=>{let o=t.functions||t,i=o[e.name];if(!i)throw Ke(e.name,o);let a=e.args.map(c=>_(c,t,n,r));return i(...a)},F=(e,t,n,r)=>{if(e.var&&!e.type)return x(e.var,n,r);switch(e.type){case p.VARIABLE:return x(e.path,n,r);case p.LITERAL:return e.value;case p.BINARY:return Xe(e,t,n,r);case p.UNARY:return Ge(e,t,n,r);case p.FUNCTION:return Je(e,t,n,r);default:return _(e,t,n,r)}},Xe=(e,t,n,r)=>{if(e.op===E.AND||e.op===E.OR){let a=F(e.left,t,n,r),c=F(e.right,t,n,r);switch(e.op){case E.AND:return a&&c;case E.OR:return a||c}}let o=_(e.left,t,n,r),i=_(e.right,t,n,r);switch(e.op){case E.EQ:return o==i;case E.NEQ:return o!=i;case E.GT:return o>i;case E.LT:return o<i;case E.GTE:return o>=i;case E.LTE:return o<=i;case E.IN:return Array.isArray(i)?i.includes(o):!1;case E.ADD:if(typeof o!="number"||typeof i!="number")throw new L(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case E.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new L(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},Ge=(e,t,n,r)=>{let o=e.op===Y.NOT?F(e.operand,t,n,r):_(e.operand,t,n,r);if(e.op===Y.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},Ht=(e,t,n,r)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===p.VARIABLE)if(x(o.path,n,r)){let a=e.bodies[0];if(a.type===p.OBJECT&&a.properties.length<=5){let c={};for(let l of a.properties){let s=l.parsedKey?_(l.parsedKey,t,n,r):l.key,u=l.value;if(u.type===p.LITERAL)c[s]=u.value;else if(u.type===p.VARIABLE)c[s]=x(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=x(d.path,n,r);f.push(h!=null?String(h):"")}else{let h=_(d,t,n,r);f.push(h!=null?String(h):"")}c[s]=f.join("")}else c[s]=_(u,t,n,r)}return c}}else{let a=e.bodies[1];if(a.type===p.OBJECT&&a.properties.length<=5){let c={};for(let l of a.properties){let s=l.parsedKey?_(l.parsedKey,t,n,r):l.key,u=l.value;if(u.type===p.LITERAL)c[s]=u.value;else if(u.type===p.VARIABLE)c[s]=x(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=x(d.path,n,r);f.push(h!=null?String(h):"")}else{let h=_(d,t,n,r);f.push(h!=null?String(h):"")}c[s]=f.join("")}else c[s]=_(u,t,n,r)}return c}}}return null},Jt=(e,t,n,r)=>{let o=Ht(e,t,n,r);if(o!==null)return o;for(let i=0;i<e.conditions.length;i++){let a=e.conditions[i];if(a===null||F(a,t,n,r))return _(e.bodies[i],t,n,r)}return qe},Xt=(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 a=o.substring(r.length+1);if(i.type===p.OBJECT&&i.properties.length<=5){for(let l of i.properties)if(l.parsedKey)return null;let c=[];for(let l=0;l<t.length;l++){let s=t[l];if(s[a]){let u={};for(let f of i.properties){let d=f.key,h=f.value;if(h.type===p.LITERAL)u[d]=h.value;else if(h.type===p.VARIABLE){let g=h.path;if(g===r)u[d]=s;else if(g.startsWith(r+".")){let y=g.substring(r.length+1);u[d]=s[y]}else return null}else if(h.type===p.INTERPOLATION){let g=[],y=!0;for(let m of h.parts)if(typeof m=="string")g.push(m);else if(m.type===p.VARIABLE){let b=m.path;if(b===r)g.push(s!=null?String(s):"");else if(b.startsWith(r+".")){let w=b.substring(r.length+1),v=s[w];g.push(v!=null?String(v):"")}else{y=!1;break}}else{y=!1;break}if(!y)return null;u[d]=g.join("")}else return null}c.push(u)}}return c}}}return null},Gt=(e,t)=>{let n=e.body,r=e.itemVar,o=Xt(e,t);if(o!==null)return o;if(n.type===p.OBJECT&&n.properties.length<=5&&!n.whenCondition){for(let c of n.properties)if(c.parsedKey)return null;let i=[],a=!0;for(let c of n.properties){let l=c.key,s=c.value;if(s.type===p.LITERAL)i.push({key:l,type:"literal",value:s.value});else if(s.type===p.VARIABLE){let u=s.path;if(u===r)i.push({key:l,type:"item"});else if(u.startsWith(r+".")){let f=u.substring(r.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:l,type:"prop",prop:f});else{a=!1;break}}else{a=!1;break}}else if(s.type===p.INTERPOLATION&&s.parts.length===1){let u=s.parts[0];if(u.type===p.VARIABLE){let f=u.path;if(f===r)i.push({key:l,type:"item_string"});else if(f.startsWith(r+".")){let d=f.substring(r.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:l,type:"prop_string",prop:d});else{a=!1;break}}else{a=!1;break}}else{a=!1;break}}else{a=!1;break}}if(a){let c=new Array(t.length);if(i.length===3&&i[0].type==="prop"&&i[0].key==="id"&&i[1].type==="prop_string"&&i[1].key==="title"&&i[2].type==="prop"&&i[2].key==="completed")for(let l=0;l<t.length;l++){let s=t[l];c[l]={id:s.id,title:s.title!=null?String(s.title):"",completed:s.completed}}else for(let l=0;l<t.length;l++){let s=t[l],u={};for(let f of i)if(f.type==="literal")u[f.key]=f.value;else if(f.type==="item")u[f.key]=s;else if(f.type==="prop")u[f.key]=s[f.prop];else if(f.type==="item_string")u[f.key]=s!=null?String(s):"";else if(f.type==="prop_string"){let d=s[f.prop];u[f.key]=d!=null?String(d):""}c[l]=u}return c}}return null},qt=(e,t,n,r,o)=>{let i=[],a=e.body;if(a.type===p.OBJECT&&a.fast!==!1){let c=e.itemVar,l=e.indexVar;for(let s=0;s<o.length;s++){let u=o[s],f={},d={...r,[c]:u,...l&&{[l]:s}};d.__paths__||(d.__paths__=r.__paths__||{});let h=e.iterable.path||"";if(r&&r.__paths__&&h){let g=h.split("."),y=g[0];y in r.__paths__&&(h=r.__paths__[y],g.length>1&&(h+="."+g.slice(1).join(".")))}d.__paths__={...d.__paths__,[c]:`${h}[${s}]`,...l&&{[l]:s}};for(let g of a.properties){let y=g.parsedKey?_(g.parsedKey,t,n,d):g.key,m=g.value;if(m.type===p.LITERAL)f[y]=m.value;else if(m.type===p.VARIABLE){let b=m.path;if(b===c)f[y]=u;else if(b===l)f[y]=s;else if(b.startsWith(c+".")){let w=b.substring(c.length+1);!w.includes(".")&&!w.includes("[")?f[y]=u[w]:f[y]=x(b,n,{...r,[c]:u,...l&&{[l]:s}})}else f[y]=x(b,n,{...r,[c]:u,...l&&{[l]:s}})}else if(m.type===p.INTERPOLATION){let b=[];for(let w of m.parts)if(typeof w=="string")b.push(w);else if(w.type===p.VARIABLE){let v=w.path,C;if(v===c)C=u;else if(v===l)C=s;else if(v.startsWith(c+".")){let re=v.substring(c.length+1);!re.includes(".")&&!re.includes("[")?C=u[re]:C=x(v,n,{...r,[c]:u,...l&&{[l]:s}})}else C=x(v,n,{...r,[c]:u,...l&&{[l]:s}});b.push(C!=null?String(C):"")}else{let v={...r,[c]:u,...l&&{[l]:s}},C=_(w,t,n,v);b.push(C!=null?String(C):"")}f[y]=b.join("")}else{let b={...r,[c]:u,...l&&{[l]:s}};f[y]=_(m,t,n,b)}}i.push(f)}return i}return null},Qt=(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 a=i.bodies[0];if(a.type===p.OBJECT&&a.properties.length===2){let c=a.properties[0],l=a.properties[1];if(c.key==="id"&&c.value.type===p.VARIABLE&&c.value.path==="item.id"&&l.key==="$if item.highlighted"&&l.value.type===p.CONDITIONAL){let s=[];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),s.push(d)}}return s}}}}return null},Zt=(e,t,n,r)=>{let o=_(e.iterable,t,n,r);if(!Array.isArray(o)){let s,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(", ");s=`${e.iterable.name}(${d})`}else s=e.iterable.path||"undefined";let f=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${s}`;throw Ye(f,o,u)}if(!e.indexVar){let s=Qt(e,o,e.itemVar);if(s!==null)return s}if(!e.indexVar){let s=Gt(e,o);if(s!==null)return s}let i=qt(e,t,n,r,o);if(i!==null)return i;let a=[],c=e.iterable.path||"";if(r&&r.__paths__&&c){let s=c.split("."),u=s[0];u in r.__paths__&&(c=r.__paths__[u],s.length>1&&(c+="."+s.slice(1).join(".")))}let l=!1;e.body.type===p.ARRAY&&(e.body.items.length<=1?l=!1:l=e.body._shouldPreserveArray??=e.body.items.some(s=>s.type===p.OBJECT&&s.properties.some(u=>u.key.startsWith("$if ")||u.key.startsWith("$when "))));for(let s=0;s<o.length;s++){let u=e.indexVar?{...r,[e.itemVar]:o[s],[e.indexVar]:s}:{...r,[e.itemVar]:o[s]};u.__paths__||(u.__paths__=r.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${c}[${s}]`},e.indexVar&&(u.__paths__[e.indexVar]=s);let f=_(e.body,t,n,u);if(Array.isArray(f)&&f.length===1&&!l){let d=f[0];a.push(d===void 0?{}:d)}else a.push(f===void 0?{}:f)}return a},en=(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,a=o.value;if(a.type===p.OBJECT&&a.properties.length<=10&&!a.whenCondition){let c={},l={},s=!0;for(let u of a.properties){let f=u.parsedKey?_(u.parsedKey,t,n,r):u.key,d=u.value;if(d.type===p.LITERAL)l[f]=d.value;else if(d.type===p.VARIABLE)l[f]=x(d.path,n,r);else if(d.type===p.INTERPOLATION){let h=[];for(let g of d.parts)if(typeof g=="string")h.push(g);else if(g.type===p.VARIABLE){let y=x(g.path,n,r);h.push(y!=null?String(y):"")}else{s=!1;break}if(!s)break;l[f]=h.join("")}else if(d.type===p.OBJECT&&d.properties.length<=5){let h={};for(let g of d.properties){let y=g.key,m=g.value;if(m.type===p.LITERAL)h[y]=m.value;else if(m.type===p.VARIABLE)h[y]=x(m.path,n,r);else if(m.type===p.INTERPOLATION){let b=[];for(let w of m.parts)if(typeof w=="string")b.push(w);else if(w.type===p.VARIABLE){let v=x(w.path,n,r);b.push(v!=null?String(v):"")}else{s=!1;break}if(!s)break;h[y]=b.join("")}else{s=!1;break}}if(!s)break;l[f]=h}else{s=!1;break}}if(s)return c[i]=l,c}}return null},tn=(e,t,n,r)=>{let o=t.functions||t;if(e.whenCondition&&!F(e.whenCondition,o,n,r))return;let i=en(e,t,n,r);if(i!==null)return i;if(e.fast){let s={};for(let u of e.properties){let f=u.parsedKey?_(u.parsedKey,t,n,r):u.key,d=u.value;if(d.type===p.LITERAL)s[f]=d.value;else if(d.type===p.VARIABLE)s[f]=x(d.path,n,r);else if(d.type===p.INTERPOLATION){let h=[];for(let g of d.parts)if(typeof g=="string")h.push(g);else if(g.type===p.VARIABLE){let y=x(g.path,n,r);h.push(y!=null?String(y):"")}else{let y=_(g,t,n,r);h.push(y!=null?String(y):"")}s[f]=h.join("")}else s[f]=_(d,t,n,r)}return s}let a={},c=null,l=!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 ")){l=!0;break}for(let s of e.properties)if(s.key.startsWith("$if ")||s.key.match(/^\$if\s+\w+.*:?$/)){let u=_(s.value,t,n,r);if(!l&&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(a,u)}else if(s.key.startsWith("$for ")){if(e.properties.length===1)return _(s.value,t,n,r)}else{let u=s.value;if(u&&u.type===p.OBJECT&&u.properties){let f=u.properties.find(d=>d.key.startsWith("$for "));if(f){let d=_(f.value,t,n,r);d!==void 0&&(a[s.key]=d)}else{let d=_(s.value,t,n,r);d!==void 0&&(a[s.key]=d)}}else{let f=s.parsedKey?_(s.parsedKey,t,n,r):s.key,d=_(s.value,t,n,r);d!==void 0&&(a[f]=d)}}return a},qe={},nn=(e,t,n,r)=>{let o=[];for(let i of e.items)if(i.type===p.LOOP){let a=_(i,t,n,r);Array.isArray(a)&&i.flatten!==!1?o.push(...a):o.push(a)}else{let a=_(i,t,n,r);a!==qe&&a!==void 0&&o.push(a)}return o},rn=(e,t,n,r)=>{let{name:o,data:i,whenCondition:a}=e,c=t.partials||{},l=t.functions||t;if(a&&!F(a,l,n,r))return;if(!c[o])throw new L(`Partial '${o}' is not defined`);let s=r._partialStack||[];if(s.includes(o))throw new L(`Circular partial reference detected: ${o}`);let u=c[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 _(u,t,f,d)},on=(e,t,n,r)=>{let{path:o}=e,i=o.split("."),a=i[0],c=i.slice(1);if(!r||!(a in r))throw new L(`Path reference '#{${o}}' refers to '${a}' which is not a loop variable in the current scope`);if(r.__paths__||(r.__paths__={}),!(a in r.__paths__))throw new L(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let l=r.__paths__[a];if(typeof l=="number"){if(c.length>0)throw new L(`Path reference '#{${o}}' - cannot access properties on index variable '${a}'`);return String(l)}return c.length>0&&(l+="."+c.join(".")),l},be=zt;var sn=/\$\{([^}]*)\}/g,an=/#\{([^}]*)\}/g,Ze=(e,t={})=>{let n=e.match(/^(\w+)\((.*)\)$/);if(!n)return{isFunction:!1};let[,r,o]=n,i=ln(o,t);return{isFunction:!0,type:p.FUNCTION,name:r,args:i}},ln=(e,t={})=>e.trim()?cn(e).map(r=>un(r.trim(),t)):[],cn=e=>{let t=[],n="",r=0,o=!1,i="";for(let a=0;a<e.length;a++){let c=e[a],l=a>0?e[a-1]:"";!o&&(c==='"'||c==="'")?(o=!0,i=c,n+=c):o&&c===i&&l!=="\\"?(o=!1,i="",n+=c):!o&&c==="("?(r++,n+=c):!o&&c===")"?(r--,n+=c):!o&&c===","&&r===0?(t.push(n),n=""):n+=c}return n&&t.push(n),t},un=(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=Ze(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,a=null;for(let{op:c,type:l}of o){let s=0;for(;s<r.length;){let u=D(r.substring(s),c);if(u===-1)break;let f=s+u;f>i&&(i=f,a={op:c,type:l}),s=f+c.length}}if(i!==-1)try{return A(r,t)}catch{return{type:p.VARIABLE,path:r}}return{type:p.VARIABLE,path:r}},et=/^\w+\(.*\)$/,fn=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,dn=e=>{if(!(!e||e.trim()===""||et.test(e))&&fn.test(e))throw e.includes("?")&&e.includes(":")?new I(`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 I(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new I(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},Qe=e=>{let t=e.trim();if(et.test(t))throw new I(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new I(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new I(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new I(`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 I(`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}},K=(e,t={})=>{let n=e.trim();dn(n);let r=Ze(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}},Ie=(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,u)=>{let f=`__ESCAPED_${r.length}__`;return r.push(u),f}),n=n.replace(/\\(#\{[^}]*\})/g,(s,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(sn)],i=[...n.matchAll(an)],a=[...o.map(s=>({match:s,type:"variable"})),...i.map(s=>({match:s,type:"pathref"}))].sort((s,u)=>s.match.index-u.match.index);if(a.length===0){let s=n;for(let u=0;u<r.length;u++)s=s.replace(`__ESCAPED_${u}__`,r[u]);return{type:p.LITERAL,value:s}}if(a.length===1&&a[0].match[0]===n&&r.length===0){let{match:s,type:u}=a[0];try{return u==="variable"?K(s[1],t):Qe(s[1])}catch(f){if(f.message==="Invalid array index syntax")return{type:p.LITERAL,value:n};throw f}}let c=[],l=0;for(let{match:s,type:u}of a){let[f,d]=s,h=s.index;if(h>l){let g=n.substring(l,h);for(let y=0;y<r.length;y++)g=g.replace(`__ESCAPED_${y}__`,r[y]);g&&c.push(g)}try{let g;u==="variable"?g=K(d.trim(),t):g=Qe(d.trim()),c.push(g)}catch(g){if(g.message==="Invalid array index syntax")c.push(f);else throw g}l=h+f.length}if(l<n.length){let s=n.substring(l);for(let u=0;u<r.length;u++)s=s.replace(`__ESCAPED_${u}__`,r[u]);s&&c.push(s)}return{type:p.INTERPOLATION,parts:c}};var N=(e,t)=>typeof e=="string"?Ie(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?hn(e,t):gn(e,t):{type:p.LITERAL,value:e},pn=e=>{let{$each:t,...n}=e;if(typeof t!="string")throw new I("$each value must be a non-empty string");let r=t.trim();if(r==="")throw new I("$each value must be a non-empty string");if(Object.keys(n).length===0)throw new I("Empty $each body not allowed");if(n.$partial!==void 0)throw new I("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${r}`]:n}},hn=(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 l=pn(i),s=Object.keys(l);if(s.length===1&&/^\$for(?::\w+)?\s/.test(s[0])){let u=tt(s[0],l[s[0]],t,!0);n.push(u),r=!0;continue}}catch(l){throw l instanceof I?l:new I(l.message)}let c=Object.keys(i);if(c.length===1&&/^\$for(?::\w+)?\s/.test(c[0])){let l=tt(c[0],i[c[0]],t);n.push(l),r=!0;continue}}let a=N(i,t);n.push(a),(a.type===p.FUNCTION||a.type===p.CONDITIONAL||a.type===p.LOOP||a.type===p.PARTIAL||a.type===p.OBJECT&&!a.fast||a.type===p.ARRAY&&!a.fast)&&(r=!0)}return{type:p.ARRAY,items:n,fast:!r}},gn=(e,t)=>{let n=[],r=!1,o=null,i=Object.entries(e),a=0;if(e.$partial!==void 0){if(typeof e.$partial!="string")throw new I("$partial value must be a string");if(e.$partial.trim()==="")throw new I("$partial value cannot be an empty string");let l=["$if","$elif","$else","$for"],s=[];for(let[b]of i)for(let w of l)if(b===w||b.startsWith(w+" ")||b.startsWith(w+"#")){s.push(w);break}if(s.length>0)throw new I(`Cannot use $partial with ${s.join(", ")} at the same level. Wrap $partial in a parent object if you need conditionals.`);let{$partial:u,$when:f,...d}=e,h={},g=!1;for(let[b,w]of Object.entries(d)){let v=b;(b.startsWith("\\$")||b.startsWith("$$"))&&(v=b.slice(1)),h[v]=w,g=!0}let y=null;if(g&&(y=N(h,t),y.type===p.OBJECT)){let b=!1;for(let w of y.properties)if(w.value.type===p.VARIABLE||w.value.type===p.INTERPOLATION||w.value.type===p.FUNCTION||w.value.type===p.CONDITIONAL||w.value.type===p.OBJECT&&!w.value.fast||w.value.type===p.ARRAY&&!w.value.fast){b=!0;break}b&&(y.fast=!1)}let m={type:p.PARTIAL,name:u,data:y};if(f!==void 0){let b;if(typeof f=="string"){if(f.trim()==="")throw new I("Empty condition expression after '$when'");b=A(f,t)}else b={type:p.LITERAL,value:f};m.whenCondition=b}return m}for(let[l,s]of i)if(l==="$when"){if(o!==null)throw new I("Multiple '$when' directives on the same object are not allowed");if(s==null)throw new I("Missing condition expression after '$when'");let u=typeof s=="string"?s:JSON.stringify(s);if(u.trim()==="")throw new I("Empty condition expression after '$when'");o=A(u,t),r=!0}else if(l.startsWith("$when#")||l.startsWith("$when "))throw new I("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;a<i.length;){let[l,s]=i[a];if(l==="$when"){a++;continue}if(l==="$each")throw new I("$each can only be used inside arrays");if(l.startsWith("$if ")||l.match(/^\$if#\w+\s/)||l.match(/^\$if\s+\w+.*:$/)){let u=yn(i,a,t);n.push({key:l,value:u.node}),r=!0,a=u.nextIndex}else if(/^\$for(?::\w+)?\s/.test(l)){let u=l.match(/^\$for(?::(\w+))?\s/)?.[1]||"",f=u?`:${u}`:"";throw new I(`$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(l.startsWith("$elif ")||l.startsWith("$else"))throw new I(`'${l.split(" ")[0]}' without matching '$if'`);if(l==="$if"||l==="$if:")throw new I("Missing condition expression after '$if'");{let u=N(s,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=Ie(l,t),d={key:l,value:u};(f.type!==p.LITERAL||f.value!==l)&&(d.parsedKey=f),n.push(d),a++}}}let c={type:p.OBJECT,properties:n,fast:!r};return o&&(c.whenCondition=o),c},yn=(e,t,n={})=>{let r=[],o=[],i=t,[a,c]=e[i],l=null,s;if(a.startsWith("$if#")){let f=a.match(/^\$if#(\w+)\s+(.+)$/);if(f)l=f[1],s=f[2];else throw new I(`Invalid conditional syntax: ${a}`)}else s=a.substring(4),s.endsWith(":")&&(s=s.slice(0,-1).trim());me(s);let u=A(s,n);for(r.push(u),o.push(N(c,n)),i++;i<e.length;){let[f,d]=e[i],h=!1,g;if(l?f.startsWith(`$elif#${l} `)?(g=f.substring(`$elif#${l} `.length),g.endsWith(":")&&(g=g.slice(0,-1).trim()),h=!0):(f===`$else#${l}`||f===`$else#${l}:`)&&(h=!0,g=null):f.startsWith("$elif ")?(g=f.substring(6),g.endsWith(":")&&(g=g.slice(0,-1).trim()),h=!0):(f==="$else"||f==="$else:")&&(h=!0,g=null),h){if(g===null)r.push(null);else{me(g);let y=A(g,n);r.push(y)}if(o.push(N(d,n)),i++,g===null)break}else break}return{node:{type:p.CONDITIONAL,conditions:r,bodies:o,id:l},nextIndex:i}},A=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let s=e.slice(1,-1),u=0,f=!0;for(let d=0;d<s.length;d++)if(s[d]==="("?u++:s[d]===")"&&u--,u<0){f=!1;break}if(f&&u===0)return A(s,t)}let n=D(e,"||");if(n!==-1)return{type:p.BINARY,op:E.OR,left:A(e.substring(0,n).trim(),t),right:A(e.substring(n+2).trim(),t)};let r=D(e,"&&");if(r!==-1)return{type:p.BINARY,op:E.AND,left:A(e.substring(0,r).trim(),t),right:A(e.substring(r+2).trim(),t)};let o=[{op:">=",type:E.GTE},{op:"<=",type:E.LTE},{op:"==",type:E.EQ},{op:"!=",type:E.NEQ},{op:">",type:E.GT},{op:"<",type:E.LT},{op:" in ",type:E.IN}];for(let{op:s,type:u}of o){let f=D(e,s);if(f!==-1)return{type:p.BINARY,op:u,left:A(e.substring(0,f).trim(),t),right:A(e.substring(f+s.length).trim(),t)}}let i=-1,a=null,c=[{op:" + ",type:E.ADD},{op:" - ",type:E.SUBTRACT}];for(let{op:s,type:u}of c){let f=0;for(;f<e.length;){let d=D(e.substring(f),s);if(d===-1)break;let h=f+d;h>i&&(i=h,a={op:s,type:u}),f=h+s.length}}if(i!==-1&&a)return{type:p.BINARY,op:a.type,left:A(e.substring(0,i).trim(),t),right:A(e.substring(i+a.op.length).trim(),t)};let l=[" * "," / "," % "];for(let s of l)if(D(e,s)!==-1)throw new I(`Arithmetic operations are not allowed in conditionals: "${s}"`);return e.startsWith("!")?{type:p.UNARY,op:Y.NOT,operand:A(e.substring(1).trim(),t)}:nt(e,t)},D=(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},mn=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}},nt=(e,t)=>{let n=e.trim();if(n.match(/^(\w+)\((.*)\)$/))return K(n,t);let o=mn(n);if(o.type===p.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(n))return{type:p.VARIABLE,path:n};try{return K(n,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},bn=(e,t=!1)=>{let n=t?"$each":"$for";try{ze(e)}catch(r){if(r instanceof I&&t){let o=r.message.replace(/\$for/g,"$each");throw new I(o.replace("Parse Error: ",""))}throw r}},tt=(e,t,n,r=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let m=r?"$each":"$for";throw new I(`Invalid loop syntax (got: '${e.replace("$for",m)}')`)}let a=i[1],c=i[2].trim();bn(c,r);let l=c.match(/^(.+?)\s+in\s+(.+)$/);if(!l){let m=r?"$each":"$for";throw new I(`Invalid loop syntax - missing 'in' keyword (got: '${m} ${c}')`)}let s=l[1].trim(),u=l[2].trim(),f,d=null;if(s.includes(",")){let m=s.split(",").map(b=>b.trim());if(m.length!==2)throw new I(`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 I(`Reserved variable name: ${f}`);if(d&&h.includes(d))throw new I(`Reserved variable name: ${d}`);let g=nt(u,n),y=N(t,n);return{type:p.LOOP,itemVar:f,indexVar:d,iterable:g,body:y,flatten:a!=="nested"}};var In=(e,t={})=>{let{functions:n={}}=t;return N(e,n)},ne=In;var we={};mt(we,{now:()=>wn});var wn=()=>Date.now();var _n=(e,t,n={})=>{let{functions:r={},partials:o={}}=n,i={...we,...r},a=ne(e,{functions:i}),c={};for(let[l,s]of Object.entries(o))c[l]=ne(s,{functions:i});return be(a,t,{functions:i,partials:c})},R=_n;var _e={objectValues:e=>Object.entries(e).map(([t,n])=>({id:t,...n})),formatDate:We},vn=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),En=(e,{presentationState:t,resources:n})=>{let{elements:r}=e;if(t.base){let o=r.find(i=>i.id==="story");if(!o)return e;if(t.base.resourceId){let i=n?.layouts[t.base.resourceId];i&&o.children.unshift({id:"base",type:"container",children:i.elements})}}return e},xn=(e,{presentationState:t,previousPresentationState:n,resources:r={},variables:o,autoMode:i,skipMode:a,currentLocalizationPackageId:c})=>{let{elements:l}=e,s=e.animations||[];if(t.background){let u=l.find(f=>f.id==="story");if(!u)return e;if(t.background.resourceId){let{images:f={},videos:d={}}=r,h=f[t.background.resourceId]||d[t.background.resourceId];if(h){let g=d[t.background.resourceId]!==void 0,y={id:`bg-cg-${t.background.resourceId}`,type:g?"video":"sprite",x:0,y:0,src:h.fileId,width:h.width,height:h.height};g&&(y.loop=h.loop??!1,y.volume=h.volume??500),u.children.push(y)}}if(t.background.resourceId){let{layouts:f={}}=r,d=f[t.background.resourceId];d&&u.children.push({id:`bg-cg-${t.background.resourceId}`,type:"container",children:d.elements})}if(t.background.animations){if(t.background.animations.in){let f=t.background.animations.in.resourceId,d=r?.tweens[f];d&&s.push({id:"bg-cg-animation-in",type:"tween",targetId:`bg-cg-${t.background.resourceId}`,properties:d.properties})}if(t.background.animations.out){let f=t.background.animations.out.resourceId,d=n?.background?.resourceId,h=r?.tweens[f];h&&d&&s.push({id:"bg-cg-animation-out",type:"tween",targetId:`bg-cg-${d}`,properties:h.properties})}if(t.background.animations.update){let f=t.background.animations.update.resourceId,d=r?.tweens[f];d&&s.push({id:"bg-cg-animation-update",type:"tween",targetId:`bg-cg-${t.background.resourceId}`,properties:d.properties})}}}return e},An=(e,{presentationState:t,resources:n})=>{let{elements:r}=e,o=e.animations||[];if(t.character&&n){let i=r.find(c=>c.id==="story");if(!i)return e;let a=t.character.items||[];for(let c=0;c<a.length;c++){let l=a[c],{transformId:s,sprites:u}=l;if(l.animations&&l.animations.out&&!u&&!s){let y=l.animations.out.resourceId,m=n?.tweens[y];if(m){let b={id:"character-animation-out",type:"tween",targetId:`character-container-${l.id}`,properties:m.properties};o.push(b)}continue}if(!u||u.length===0||!s){console.warn("Character item missing sprites or transformId:",l);continue}let f=u.map(({resourceId:y})=>y),d=`character-container-${l.id}-${c}-${f.join("-")}`,h=n.transforms[s];if(!h){console.warn("Transform not found:",s);continue}let g={type:"container",id:d,x:l.x??h.x,y:l.y??h.y,anchorX:h.anchorX,anchorY:h.anchorY,rotation:h.rotation,scaleX:h.scaleX,scaleY:h.scaleY,children:[]};for(let y of u){let m=n.images[y.resourceId];if(!m){console.warn(`Image resource not found: ${y.resourceId}`);continue}g.children.push({type:"sprite",id:`${d}-${y.id}`,src:m.fileId,width:m.width,height:m.height,x:0,y:0})}if(i.children.push(g),l.animations){if(l.animations.in){let y=l.animations.in.resourceId,m=n?.tweens[y];m&&o.push({id:"character-animation-in",type:"tween",targetId:d,properties:m.properties})}if(l.animations.update){let y=l.animations.update.resourceId,m=n?.tweens[y];if(m){let b={id:"character-animation-update",type:"tween",targetId:d,properties:m.properties};o.push(b)}}}}}return e},Ln=(e,{presentationState:t,resources:n})=>{let{elements:r}=e,o=e.animations||[];if(t.visual&&n){let i=r.find(c=>c.id==="story");if(!i)return e;let a=t.visual.items;for(let c of a){if(c.resourceId){let{images:l={},videos:s={},spritesheets:u={}}=n,f=u[c.resourceId];if(f){let d=n.transforms?.[c.transformId]||{},h=c.animationName;if(h){let g=f.animations?.[h];if(!g)throw new Error(`Animation '${h}' not found in spritesheet resource '${c.resourceId}'`);let y={id:`visual-${c.id}`,type:"animated-sprite",x:c.x??d.x??0,y:c.y??d.y??0,width:c.width??100,height:c.height??100,alpha:c.alpha??1,anchorX:d.anchorX,anchorY:d.anchorY,rotation:d.rotation,scaleX:d.scaleX,scaleY:d.scaleY,spritesheetSrc:f.fileId,spritesheetData:f.jsonData,animation:{frames:g.frames,animationSpeed:c.animationSpeed??g.animationSpeed??.5,loop:c.loop??g.loop??!0}};i.children.push(structuredClone(y))}}else{let d=l[c.resourceId]||s[c.resourceId];if(d){let h=s[c.resourceId]!==void 0,g=n.transforms[c.transformId],y={id:`visual-${c.id}`,type:h?"video":"sprite",src:d.fileId,width:d.width,height:d.height,x:g.x,y:g.y,anchorX:g.anchorX,anchorY:g.anchorY,rotation:g.rotation,scaleX:g.scaleX,scaleY:g.scaleY};h&&(y.loop=d.loop??!1,y.volume=d.volume??500),i.children.push(y)}}}if(c.resourceId){let{layouts:l={}}=n,s=l[c.resourceId];if(s){let u=n.transforms[c.transformId];i.children.push({id:`visual-${c.id}`,type:"container",children:structuredClone(s.elements),x:u.x,y:u.y,anchorX:u.anchorX,anchorY:u.anchorY,rotation:u.rotation,scaleX:u.scaleX,scaleY:u.scaleY})}}if(c.animations){if(c.animations.in){let l=c.animations.in.resourceId||c.animations.in,s=n?.tweens[l];s&&o.push({id:`${c.id}-animation`,type:"tween",targetId:`visual-${c.id}`,properties:structuredClone(s.properties)})}if(c.animations.out){let l=c.animations.out.resourceId||c.animations.out,s=n?.tweens[l];s&&o.push({id:`${c.id}-animation-2`,type:"tween",targetId:`visual-${c.id}`,properties:structuredClone(s.properties)})}}}}return e},$n=(e,{presentationState:t,resources:n={},dialogueUIHidden:r,autoMode:o,skipMode:i,skipOnlyViewedLines:a,isLineCompleted:c,l10n:l,variables:s,saveSlots:u=[]})=>{let{elements:f}=e;if(!t.dialogue||r)return e;let d=f.find(h=>h.id==="story");if(!d)return e;if(t.dialogue.gui&&t.dialogue.gui.resourceId){let{layouts:h={}}=n,g=h[t.dialogue.gui.resourceId];if(g){let y;t.dialogue.characterId&&(y=n.characters[t.dialogue.characterId]),t.dialogue.character&&(y={...y,name:t.dialogue.character.name});let m={elements:g.elements},b={variables:s,autoMode:o,skipMode:i,skipOnlyViewedLines:a,isLineCompleted:c,saveSlots:u,dialogue:{character:{name:y?.name||""},content:t.dialogue?.content||[{text:""}],lines:t.dialogue?.lines||[]},l10n:l},w=R(m,b,{functions:_e});w=R(w,{l10n:l});let v=w?.elements;if(Array.isArray(v))for(let C of v)d.children.push(structuredClone(C));else v&&d.children.push(structuredClone(v))}}return e},Cn=(e,{presentationState:t,resources:n})=>{let{elements:r}=e;if(t.choice&&n){let o=r.find(s=>s.id==="story");if(!o)return e;o.children.push({id:"choice-blocker",type:"rect",fill:"transparent",width:1920,height:1080,x:0,y:0,click:{actionPayload:{actions:{}}}});let i=n?.layouts[t.choice.resourceId];if(!i||!i.elements)return e;let a={elements:i.elements},l=R(a,{choice:{items:t.choice?.items??[]}})?.elements;if(Array.isArray(l))for(let s of l)o.children.push(structuredClone(s));else l&&o.children.push(structuredClone(l))}return e},kn=(e,{presentationState:t,resources:n})=>{if(t.keyboard?.resourceId){let r=n?.keyboards?.[t.keyboard.resourceId];r&&(e.global.keyboard=r)}return e},On=(e,{presentationState:t,resources:n})=>{let{elements:r,audio:o}=e;if(t.bgm&&n){if(!r.find(c=>c.id==="story"))return e;let a=n.sounds[t.bgm.resourceId];if(!a)return e;o.push({id:"bgm",type:"sound",src:a.fileId,loop:t.bgm.loop??!0,volume:t.bgm.volume??500,delay:t.bgm.delay??null})}return e},Sn=(e,{presentationState:t,resources:n})=>{let{audio:r}=e;if(t.sfx&&n){let o=t.sfx.items;for(let i of o){let a=n.sounds?.[i.resourceId];a&&r.push({id:i.id,type:"sound",src:a.fileId,loop:i.loop??a.loop??!0,volume:i.volume??a.volume??500,delay:i.delay??a.delay??null})}}return e},Rn=(e,{presentationState:t,resources:n})=>{let{audio:r}=e;if(!t?.voice)return e;let{fileId:o,volume:i,loop:a}=t.voice;return r.push({id:`voice-${o}`,type:"sound",src:o,volume:i??500,loop:a??!1}),e},Nn=(e,{presentationState:t,resources:n={},variables:r,autoMode:o,skipMode:i,currentLocalizationPackageId:a,saveSlots:c=[]})=>{let{elements:l}=e,s=e.animations||[];if(t.layout){let u=l.find(m=>m.id==="story");if(!u)return e;let f=n.layouts[t.layout.resourceId];if(!f)return e;Array.isArray(f.transitions)&&f.transitions.forEach(m=>{s.push(m)});let d={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:f.elements||[]},g=R(d,{variables:r,saveSlots:c,autoMode:o,skipMode:i,currentLocalizationPackageId:a},{functions:_e});g=R(g,{i18n:{}});let y=m=>{let b={...m};return m.src&&m.src.startsWith("file:")&&(b.src=m.src),m.children&&Array.isArray(m.children)&&(b.children=m.children.map(y)),b};u.children.push(y(g))}return e},Pn=(e,{resources:t={},variables:n,autoMode:r,skipMode:o,currentLocalizationPackageId:i,layeredViews:a=[],dialogueHistory:c=[],saveSlots:l=[],l10n:s})=>{let{elements:u}=e,f=e.animations||[];return a&&a.length>0&&a.forEach((d,h)=>{let g=t.layouts[d.resourceId];if(!g){console.warn(`LayeredView layout not found: ${d.resourceId}`);return}Array.isArray(g.transitions)&&g.transitions.forEach(v=>{f.push(v)});let y={id:`layeredView-${h}`,type:"container",x:0,y:0,children:g.elements||[]},m=c.map(v=>{let C=t.characters?.[v.characterId];return{...v,characterName:C?.name||""}}),b={variables:n,autoMode:r,skipMode:o,currentLocalizationPackageId:i,saveSlots:l,historyDialogue:m,characters:t.characters||{}},w=R(y,b,{functions:_e});w=R(w,{i18n:{},l10n:s}),u.push(w)}),e},rt=e=>te(vn,[En,xn,An,Ln,$n,Cn,kn,Nn,On,Sn,Rn,Pn])(e);var Tn=e=>{let{global:{currentLocalizationPackageId:t,saveSlots:n={},variables:r={}},projectData:o}=e,i={sceneId:o.story.initialSceneId,sectionId:o.story.scenes[o.story.initialSceneId].initialSectionId,lineId:o.story.scenes[o.story.initialSceneId].sections[o.story.scenes[o.story.initialSceneId].initialSectionId].lines[0].id},{contextVariableDefaultValues:a,globalVariablesDefaultValues:c}=Be(o),l={...c,...r},s={projectData:o,global:{autoplayDelay:1e3,isLineCompleted:!1,pendingEffects:[],autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isDialogueHistoryShowing:!1,currentLocalizationPackageId:t,viewedRegistry:{sections:[],resources:[]},nextLineConfig:{manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1}},saveSlots:n,layeredViews:[],variables:l},contexts:[{currentPointerMode:"read",pointers:{read:i,history:{sectionId:void 0,lineId:void 0,historySequenceIndex:void 0}},historySequence:[{sectionId:"..."}],configuration:{},views:[],bgm:{resourceId:void 0},variables:a}]};return console.log("Initial State:",s),s},Vn=({state:e})=>e.global.layeredViews||[],Dn=({state:e})=>e.global.pendingEffects,ot=({state:e})=>e.global.skipMode,Mn=({state:e})=>e.global.autoMode,it=({state:e})=>e.global.dialogueUIHidden,Bn=({state:e})=>e.global.autoplayDelay,ve=({state:e})=>{let t=e.contexts[e.contexts.length-1];if(!t)return[];let{sectionId:n,lineId:r}=t.pointers.read,o=$({state:e},{sectionId:n});if(!o?.lines||!Array.isArray(o.lines))return[];let i=o.lines.findIndex(l=>l.id===r);return o.lines.slice(0,i+1).filter(l=>l.actions?.dialogue).map(l=>{let s=l.actions.dialogue,u="";return s.characterId&&(u=e.projectData.resources?.characters?.[s.characterId]?.name||""),{content:s.content,characterId:s.characterId,characterName:u}})},jn=({state:e})=>e.global.currentLocalizationPackageId,Ee=({state:e},t)=>{let{sectionId:n,lineId:r}=t,o=e.global.viewedRegistry.sections.find(l=>l.sectionId===n);if(!o)return!1;if(o.lastLineId===void 0||r===void 0)return!0;let i=$({state:e},{sectionId:n});if(!i||!i.lines||!Array.isArray(i.lines))return!1;let a=i.lines.findIndex(l=>l.id===o.lastLineId),c=i.lines.findIndex(l=>l.id===r);return a===-1||c===-1?o.lastLineId===r:c<a},Fn=({state:e},t)=>{let{resourceId:n}=t;return!!e.global.viewedRegistry.resources.find(o=>o.resourceId===n)},Un=({state:e})=>e.global.nextLineConfig,Wn=({state:e})=>e.global.saveSlots,zn=({state:e},t)=>{let{slotKey:n}=t;return e.global.saveSlots[n]},M=({state:e})=>{let t=e.contexts[e.contexts.length-1];if(!t)return;let n=t.pointers?.[t.currentPointerMode];return{currentPointerMode:t.currentPointerMode,pointer:n}},$=({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]}},st=({state:e})=>{let t=M({state:e});if(!t?.pointer)return;let{sectionId:n,lineId:r}=t.pointer,o=$({state:e},{sectionId:n});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===r)},at=({state:e})=>{let{sectionId:t,lineId:n}=M({state:e}).pointer,o=$({state:e},{sectionId:t})?.lines||[],i=o.findIndex(s=>s.id===n),a=o.slice(0,i+1);console.log("currentLines",a);let c=a.map(s=>{let u=s.actions||{},f={};return Object.keys(u).forEach(d=>{f[d]=u[d]}),f});return z(c)},Yn=({state:e})=>{let t=lt({state:e}),r=st({state:e})?.actions??{},o=z([t??{},r]);return ye(t??{},o??{})},Kn=({state:e},{sectionId:t})=>{let n=$({state:e},{sectionId:t});if(!n?.lines)return{lines:[]};let r=[],o={};for(let i of n.lines){let a=i.actions||{},c=z([o,a]),l=ye(o,c);r.push({id:i.id,changes:l}),o=c}return{lines:r}},lt=({state:e})=>{let{sectionId:t,lineId:n}=M({state:e}).pointer,o=$({state:e},{sectionId:t})?.lines||[],i=o.findIndex(l=>l.id===n);if(i<=0)return null;let c=o.slice(0,i).map(l=>{let s=l.actions||{},u={};return Object.keys(s).forEach(f=>{u[f]=s[f]}),u});return z(c)},ct=({state:e},{slotsPerPage:t=6}={})=>{let o=(({...e.global.variables,...e.contexts[e.contexts.length-1].variables}.loadPage??1)-1)*t+1,i=[];for(let a=0;a<t;a++){let c=o+a,l=e.global.saveSlots&&e.global.saveSlots[c]||{};i.push({slotNumber:c,...l})}return{saveSlots:i}},Hn=({state:e})=>{let t=at({state:e}),n=lt({state:e});console.log("presentationState",t);let r={...e.global.variables,...e.contexts[e.contexts.length-1].variables},{saveSlots:o}=ct({state:e}),i=rt({presentationState:t,previousPresentationState:n,resources:e.projectData.resources,l10n:e.projectData.l10n.packages[e.global.currentLocalizationPackageId],currentLocalizationPackageId:e.global.currentLocalizationPackageId,dialogueUIHidden:e.global.dialogueUIHidden,autoMode:e.global.autoMode,skipMode:e.global.skipMode,skipOnlyViewedLines:!r._skipUnseenText,isLineCompleted:e.global.isLineCompleted,layeredViews:e.global.layeredViews,dialogueHistory:ve({state:e}),saveSlots:o,variables:r});return console.log("renderState",i),i},Jn=({state:e},t)=>(e.global.layeredViews.push(t),e.global.pendingEffects.push({name:"render"}),e),Xn=({state:e})=>(e.global.layeredViews.pop(),e.global.pendingEffects.push({name:"render"}),e),Gn=({state:e},t)=>(e.global.layeredViews.length>0&&(e.global.layeredViews[e.global.layeredViews.length-1]=t),e.global.pendingEffects.push({name:"render"}),e),qn=({state:e})=>(e.global.layeredViews=[],e.global.pendingEffects.push({name:"render"}),e),ut=({state:e})=>(e.global.skipMode&&(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"})),e.global.autoMode=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:e.global.autoplayDelay}}),e.global.pendingEffects.push({name:"render"}),e),xe=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Qn=({state:e})=>(e.global.autoMode?xe({state:e}):ut({state:e}),e),ft=({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),H=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Zn=({state:e})=>(ot({state:e})?H({state:e}):ft({state:e}),e),dt=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),e),pt=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),e),er=({state:e})=>(it({state:e})?dt({state:e}):pt({state:e}),e),tr=({state:e})=>{let t=ve({state:e});return e.global.isDialogueHistoryShowing=!0,e.global.pendingEffects.push({name:"render"}),e},nr=({state:e})=>(e.global.isDialogueHistoryShowing=!1,e.global.pendingEffects.push({name:"render"}),e),rr=({state:e},t)=>{let{localizationPackageId:n}=t;return e.global.currentLocalizationPackageId=n,e.global.pendingEffects.push({name:"render"}),e},or=({state:e})=>(e.global.pendingEffects=[],e),ir=({state:e},t)=>(e.global.pendingEffects.push(t),e),ht=({state:e},t)=>{let{sectionId:n,lineId:r}=t,o=e.global.viewedRegistry.sections.find(i=>i.sectionId===n);if(o){let i=$({state:e},{sectionId:n});if(i?.lines&&o.lastLineId!==void 0){let a=i.lines.findIndex(l=>l.id===o.lastLineId),c=i.lines.findIndex(l=>l.id===r);(a===-1||c>a)&&(o.lastLineId=r)}else o.lastLineId=r}else e.global.viewedRegistry.sections.push({sectionId:n,lastLineId:r});return e.global.pendingEffects.push({name:"render"}),e},sr=({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},ar=({state:e},t)=>{let{manual:n,auto:r}=t,o=e.global.nextLineConfig.auto?.enabled,i=r?.enabled;return n&&r?e.global.nextLineConfig={manual:n,auto:r}:(n&&(e.global.nextLineConfig.manual=n),r&&(e.global.nextLineConfig.auto=r)),i===!0&&!o?e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):i===!1&&o&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),e},lr=({state:e},{delay:t})=>(e.global.autoplayDelay=t,e.global.autoMode&&(e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:e.global.autoplayDelay}})),e.global.pendingEffects.push({name:"render"}),e),cr=({state:e},t)=>{let{slot:n,thumbnailImage:r}=t,o=String(n),i={contexts:[...e.contexts],viewedRegistry:e.global.viewedRegistry},a={slotKey:o,date:Date.now(),image:r,state:i};return e.global.saveSlots[o]=a,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},ur=({state:e},t)=>{let{slot:n}=t,r=String(n),o=e.global.saveSlots[r];return o&&(e.global.viewedRegistry=o.state.viewedRegistry,e.contexts=o.state.contexts,e.global.pendingEffects.push({name:"render"})),e},fr=({state:e},t)=>{let{projectData:n}=t;return e.projectData=n,e.global.pendingEffects.push({name:"render"}),e},dr=({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&&!$({state:e},{sectionId:n}))return console.warn(`Section not found: ${n}`),e;let a=$({state:e},{sectionId:i});return!a?.lines||!Array.isArray(a.lines)?(console.warn(`Section ${i} has no lines`),e):a.lines.find(l=>l.id===r)?(o.pointers.read={sectionId:i,lineId:r},e.global.isLineCompleted=!1,e.global.pendingEffects.push({name:"render"}),e.global.pendingEffects.push({name:"handleLineActions"}),e):(console.warn(`Line not found: ${r} in section ${i}`),e)},pr=({state:e},t)=>{let{item:n}=t,r=e.contexts[e.contexts.length-1];return r&&r.historySequence&&r.historySequence.push({sectionId:n.sectionId}),e.global.pendingEffects.push({name:"render"}),e},hr=({state:e})=>{if(e.global.nextLineConfig?.auto?.enabled!==!0||e.global.nextLineConfig?.auto?.trigger!=="fromComplete")return e;let t=M({state:e})?.pointer,n=t?.sectionId,o=$({state:e},{sectionId:n})?.lines||[],a=o.findIndex(c=>c.id===t?.lineId)+1;if(a<o.length){let c=o[a],l=e.contexts[e.contexts.length-1];l&&(l.pointers.read={sectionId:n,lineId:c.id}),e.global.isLineCompleted=!1,e.global.nextLineConfig.auto={},e.global.pendingEffects.push({name:"render"}),e.global.pendingEffects.push({name:"handleLineActions"})}return e},gr=({state:e})=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(!e.global.isLineCompleted)return e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"render"}),e;let t=M({state:e})?.pointer,n=t?.sectionId,o=$({state:e},{sectionId:n})?.lines||[],a=o.findIndex(c=>c.id===t?.lineId)+1;if(a<o.length){let c=o[a],l=!e.global.variables?._skipUnseenText;if(e.global.skipMode&&l&&!Ee({state:e},{sectionId:n,lineId:c.id}))return H({state:e}),e;let s=e.contexts[e.contexts.length-1];if(s){let u=s.pointers.read.lineId;u&&n&&ht({state:e},{sectionId:n,lineId:u}),s.pointers.read={sectionId:n,lineId:c.id}}e.global.isLineCompleted=!1,e.global.pendingEffects.push({name:"render"}),e.global.pendingEffects.push({name:"handleLineActions"})}else e.global.autoMode&&xe({state:e}),e.global.skipMode&&H({state:e});return console.log("state",e),e},yr=({state:e})=>(e.global.isLineCompleted||(e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"render"})),e),mr=({state:e},t)=>{let{sectionId:n}=t,r=$({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 a=i.pointers.history||i.pointers.read;if(i.currentPointerMode!=="history"||!i.pointers.history){if(!a)return e;i.currentPointerMode="history",i.pointers.history={sectionId:n,lineId:a?.lineId};let u=o.findIndex(f=>f.id===a.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 l=o.findIndex(s=>s.id===i.pointers.history.lineId)-1;if(l>=0&&l<o.length){let s=o[l];i.pointers.history={sectionId:n,lineId:s.id},e.global.pendingEffects.push({name:"render"})}return e},br=({state:e},t)=>{let{sectionId:n}=t,r=$({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;let i=e.contexts[e.contexts.length-1];return i&&(i.pointers.read={sectionId:n,lineId:o.id}),e.global.isLineCompleted=!1,e.global.pendingEffects.push({name:"render"}),e.global.pendingEffects.push({name:"handleLineActions"}),e},Ir=({state:e})=>{let t=M({state:e})?.pointer,n=t?.sectionId,o=$({state:e},{sectionId:n})?.lines||[],a=o.findIndex(c=>c.id===t?.lineId)+1;if(a<o.length){let c=o[a],l=!e.global.variables?._skipUnseenText;if(e.global.skipMode&&l&&!Ee({state:e},{sectionId:n,lineId:c.id}))return H({state:e}),e;let s=e.contexts[e.contexts.length-1];s&&(s.pointers.read={sectionId:n,lineId:c.id}),e.global.isLineCompleted=!1,e.global.pendingEffects.push({name:"render"}),e.global.pendingEffects.push({name:"handleLineActions"}),e.global.nextLineConfig.auto?.enabled&&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},wr=({state:e},t)=>{let{operations:n=[]}=t,r=!1,o=!1;if(n.forEach(({variableId:i,op:a,value:c})=>{let l=e.projectData.resources?.variables?.[i],s=l?.scope,u=l?.type;je(s,i),Fe(u,a,i);let f=s==="context"?e.contexts[e.contexts.length-1].variables:e.global.variables;s==="global-device"?r=!0:s==="global-account"&&(o=!0),f[i]=Ue(f[i],a,c)}),r){let i=ge(e.global.variables,e.projectData.resources?.variables,"global-device");e.global.pendingEffects.push({name:"saveGlobalDeviceVariables",payload:{globalDeviceVariables:i}})}if(o){let i=ge(e.global.variables,e.projectData.resources?.variables,"global-account");e.global.pendingEffects.push({name:"saveGlobalAccountVariables",payload:{globalAccountVariables:i}})}return e.global.pendingEffects.push({name:"render"}),e},gt=e=>{let t=Tn(e);return Me(t,{selectPendingEffects:Dn,selectSkipMode:ot,selectAutoMode:Mn,selectDialogueUIHidden:it,selectDialogueHistory:ve,selectCurrentLocalizationPackageId:jn,selectIsLineViewed:Ee,selectIsResourceViewed:Fn,selectNextLineConfig:Un,selectSaveSlots:Wn,selectSaveSlot:zn,selectCurrentPointer:M,selectSection:$,selectCurrentLine:st,selectPresentationState:at,selectPresentationChanges:Yn,selectSectionLineChanges:Kn,selectAutoplayDelay:Bn,selectCurrentPageSlots:ct,selectRenderState:Hn,selectLayeredViews:Vn,startAutoMode:ut,stopAutoMode:xe,toggleAutoMode:Qn,startSkipMode:ft,stopSkipMode:H,toggleSkipMode:Zn,showDialogueUI:dt,hideDialogueUI:pt,toggleDialogueUI:er,showDialogueHistory:tr,hideDialogueHistory:nr,setCurrentLocalizationPackageId:rr,clearPendingEffects:or,appendPendingEffect:ir,addViewedLine:ht,addViewedResource:sr,setNextLineConfig:ar,saveSaveSlot:cr,loadSaveSlot:ur,setAutoplayDelay:lr,updateProjectData:fr,sectionTransition:br,jumpToLine:dr,addToHistorySequence:pr,nextLine:gr,nextLineFromCompleted:hr,markLineCompleted:yr,prevLine:mr,pushLayeredView:Jn,popLayeredView:Xn,replaceLastLayeredView:Gn,clearLayeredViews:qn,updateVariable:wr,nextLineFromSystem:Ir},{transformActionFirstArgument:r=>({state:r}),transformSelectorFirstArgument:r=>({state:r})})};function Ae(e){let t,{handlePendingEffects:n}=e,r=()=>{for(;t.selectPendingEffects().length>0;){let h=[...t.selectPendingEffects()];t.clearPendingEffects(),n(h)}},o=({initialState:h})=>{t=gt(h),t.appendPendingEffect({name:"render"}),d(),r()},i=()=>t.selectPresentationState(),a=()=>t.selectPresentationChanges(),c=h=>t.selectSectionLineChanges(h),l=()=>t.selectRenderState(),s=()=>t.selectSaveSlots(),u=(h,g)=>{t[h]&&(t[h](g),r())},f=h=>{Object.entries(h).forEach(([g,y])=>{u(g,y)})},d=()=>{let h=t.selectCurrentLine();h&&h.actions&&f(h.actions)};return{init:o,handleAction:u,handleActions:f,selectRenderState:l,selectPresentationState:i,selectPresentationChanges:a,selectSectionLineChanges:c,selectSaveSlots:s,handleLineActions:d}}var Le=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:n=>{e=n},addElapsed:n=>{e+=n},getCallback:()=>t,setCallback:n=>{t=n}}},_r=({engine:e,routeGraphics:t},n)=>{let r=e.selectRenderState();t.render(r)},vr=({engine:e},t)=>{e.handleLineActions()},Er=({engine:e,ticker:t,autoTimer:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=a=>{n.addElapsed(a.deltaMS);let c=r.delay??1e3;n.getElapsed()>=c&&(n.setElapsed(0),e.handleAction("nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},xr=({ticker:e,autoTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Ar=({engine:e,ticker:t,skipTimer:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=a=>{n.addElapsed(a.deltaMS),n.getElapsed()>=30&&(n.setElapsed(0),e.handleAction("nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},Lr=({ticker:e,skipTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},$r=({engine:e,ticker:t,nextLineConfigTimerState:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=a=>{n.addElapsed(a.deltaMS);let c=r.delay??1e3;n.getElapsed()>=c&&(n.setElapsed(0),e.handleAction("nextLineFromSystem",{}),t.remove(i),n.setCallback(null))};n.setCallback(i),t.add(i)},Cr=({ticker:e,nextLineConfigTimerState:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},kr=({},e)=>{localStorage.setItem("saveSlots",JSON.stringify(e.saveSlots))},Or=({},e)=>{localStorage.setItem("globalDeviceVariables",JSON.stringify(e.globalDeviceVariables))},Sr=({},e)=>{localStorage.setItem("globalAccountVariables",JSON.stringify(e.globalAccountVariables))},Rr={render:_r,saveSlots:kr,saveGlobalDeviceVariables:Or,saveGlobalAccountVariables:Sr,handleLineActions:vr,startAutoNextTimer:Er,clearAutoNextTimer:xr,startSkipNextTimer:Ar,clearSkipNextTimer:Lr,nextLineConfigTimer:$r,clearNextLineConfigTimer:Cr},Nr=({getEngine:e,routeGraphics:t,ticker:n})=>{let r=Le(),o=Le(),i=Le();return async a=>{let c=e(),l=a.reduce((f,d)=>(f[d.name]=d,f),{}),s=Object.values(l),u={engine:c,routeGraphics:t,ticker:n,autoTimer:r,skipTimer:o,nextLineConfigTimerState:i};for(let f of s){let d=Rr[f.name];d&&d(u,f.payload)}}},Pr=Nr;var ko=Ae;export{Pr as createEffectsHandler,ko as default};
1
+ var _t=Object.defineProperty;var vt=(e,t)=>{for(var n in t)_t(e,n,{get:t[n],enumerable:!0})};var Te=Symbol.for("immer-nothing"),ke=Symbol.for("immer-draftable"),S=Symbol.for("immer-state");function O(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var B=Object.getPrototypeOf;function j(e){return!!e&&!!e[S]}function V(e){return e?Ve(e)||Array.isArray(e)||!!e[ke]||!!e.constructor?.[ke]||ee(e)||te(e):!1}var Et=Object.prototype.constructor.toString();function Ve(e){if(!e||typeof e!="object")return!1;let t=B(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)===Et}function X(e,t){Z(e)===0?Reflect.ownKeys(e).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function Z(e){let t=e[S];return t?t.type_:Array.isArray(e)?1:ee(e)?2:te(e)?3:0}function ae(e,t){return Z(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function De(e,t,n){let r=Z(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function xt(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function ee(e){return e instanceof Map}function te(e){return e instanceof Set}function T(e){return e.copy_||e.base_}function le(e,t){if(ee(e))return new Map(e);if(te(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let n=Ve(e);if(t===!0||t==="class_only"&&!n){let r=Object.getOwnPropertyDescriptors(e);delete r[S];let o=Reflect.ownKeys(r);for(let i=0;i<o.length;i++){let l=o[i],c=r[l];c.writable===!1&&(c.writable=!0,c.configurable=!0),(c.get||c.set)&&(r[l]={configurable:!0,writable:!0,enumerable:c.enumerable,value:e[l]})}return Object.create(B(e),r)}else{let r=B(e);if(r!==null&&n)return{...e};let o=Object.create(r);return Object.assign(o,e)}}function pe(e,t=!1){return ne(e)||j(e)||!V(e)||(Z(e)>1&&(e.set=e.add=e.clear=e.delete=At),Object.freeze(e),t&&Object.entries(e).forEach(([n,r])=>pe(r,!0))),e}function At(){O(2)}function ne(e){return Object.isFrozen(e)}var Lt={};function D(e){let t=Lt[e];return t||O(0,e),t}var W;function Me(){return W}function $t(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function Oe(e,t){t&&(D("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function ce(e){ue(e),e.drafts_.forEach(Ct),e.drafts_=null}function ue(e){e===W&&(W=e.parent_)}function Re(e){return W=$t(W,e)}function Ct(e){let t=e[S];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function Ne(e,t){t.unfinalizedDrafts_=t.drafts_.length;let n=t.drafts_[0];return e!==void 0&&e!==n?(n[S].modified_&&(ce(t),O(4)),V(e)&&(e=G(t,e),t.parent_||Q(t,e)),t.patches_&&D("Patches").generateReplacementPatches_(n[S].base_,e,t.patches_,t.inversePatches_)):e=G(t,n,[]),ce(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Te?e:void 0}function G(e,t,n){if(ne(t))return t;let r=t[S];if(!r)return X(t,(o,i)=>Pe(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Q(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),X(i,(c,a)=>Pe(e,r,o,c,a,n,l)),Q(e,o,!1),n&&e.patches_&&D("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function Pe(e,t,n,r,o,i,l){if(j(o)){let c=i&&t&&t.type_!==3&&!ae(t.assigned_,r)?i.concat(r):void 0,a=G(e,o,c);if(De(n,r,a),j(a))e.canAutoFreeze_=!1;else return}else l&&n.add(o);if(V(o)&&!ne(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;G(e,o),(!t||!t.scope_.parent_)&&typeof r!="symbol"&&Object.prototype.propertyIsEnumerable.call(n,r)&&Q(e,o)}}function Q(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&pe(t,n)}function St(e,t){let n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:Me(),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=z);let{revoke:l,proxy:c}=Proxy.revocable(o,i);return r.draft_=c,r.revoke_=l,c}var he={get(e,t){if(t===S)return e;let n=T(e);if(!ae(n,t))return kt(e,n,t);let r=n[t];return e.finalized_||!V(r)?r:r===ie(e.base_,t)?(se(e),e.copy_[t]=de(r,e)):r},has(e,t){return t in T(e)},ownKeys(e){return Reflect.ownKeys(T(e))},set(e,t,n){let r=Be(T(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){let o=ie(T(e),t),i=o?.[S];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(xt(n,o)&&(n!==void 0||ae(e.base_,t)))return!0;se(e),fe(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 ie(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,se(e),fe(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let n=T(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){O(11)},getPrototypeOf(e){return B(e.base_)},setPrototypeOf(){O(12)}},z={};X(he,(e,t)=>{z[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});z.deleteProperty=function(e,t){return z.set.call(this,e,t,void 0)};z.set=function(e,t,n){return he.set.call(this,e[0],t,n,e[0])};function ie(e,t){let n=e[S];return(n?T(n):e)[t]}function kt(e,t,n){let r=Be(t,n);return r?"value"in r?r.value:r.get?.call(e.draft_):void 0}function Be(e,t){if(!(t in e))return;let n=B(e);for(;n;){let r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=B(n)}}function fe(e){e.modified_||(e.modified_=!0,e.parent_&&fe(e.parent_))}function se(e){e.copy_||(e.copy_=le(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Ot=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(a=i,...s){return l.produce(a,u=>n.call(this,u,...s))}}typeof n!="function"&&O(6),r!==void 0&&typeof r!="function"&&O(7);let o;if(V(t)){let i=Re(this),l=de(t,void 0),c=!0;try{o=n(l),c=!1}finally{c?ce(i):ue(i)}return Oe(i,r),Ne(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===Te&&(o=void 0),this.autoFreeze_&&pe(o,!0),r){let i=[],l=[];D("Patches").generateReplacementPatches_(t,o,i,l),r(i,l)}return o}else O(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(l,...c)=>this.produceWithPatches(l,a=>t(a,...c));let r,o;return[this.produce(t,n,(l,c)=>{r=l,o=c}),r,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){V(e)||O(8),j(e)&&(e=Rt(e));let t=Re(this),n=de(e,void 0);return n[S].isManual_=!0,ue(t),n}finishDraft(e,t){let n=e&&e[S];(!n||!n.isManual_)&&O(9);let{scope_:r}=n;return Oe(r,t),Ne(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=D("Patches").applyPatches_;return j(e)?r(e,t):this.produce(e,o=>r(o,t))}};function de(e,t){let n=ee(e)?D("MapSet").proxyMap_(e,t):te(e)?D("MapSet").proxySet_(e,t):St(e,t);return(t?t.scope_:Me()).drafts_.push(n),n}function Rt(e){return j(e)||O(10,e),je(e)}function je(e){if(!V(e)||ne(e))return e;let t=e[S],n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=le(e,t.scope_.immer_.useStrictShallowCopy_)}else n=le(e,!0);return X(n,(r,o)=>{De(n,r,je(o))}),t&&(t.finalized_=!1),n}var k=new Ot,ge=k.produce,Fr=k.produceWithPatches.bind(k),Ur=k.setAutoFreeze.bind(k),Wr=k.setUseStrictShallowCopy.bind(k),zr=k.applyPatches.bind(k),Yr=k.createDraft.bind(k),Hr=k.finishDraft.bind(k);var Fe=(e,t,n={})=>{let r=structuredClone(e),o={},i={},{transformSelectorFirstArgument:l=a=>a,transformActionFirstArgument:c=a=>a}=n;for(let[a,s]of Object.entries(t))a!=="createInitialState"&&(a.startsWith("select")?o[a]=(...u)=>s(l(r),...u):i[a]=(...u)=>{r=ge(r,d=>s(c(d),...u))});return{...o,...i}},re=(e,t)=>n=>{let r=e(),o=Array.isArray(n)?n:[n];return ge(r,i=>{o.forEach(l=>{t.forEach(c=>{c(i,l)})})})};var Nt=(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{}}},Ue=e=>{let t={},n={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([r,o])=>{let i=Nt(o,r);o.scope==="context"?t[r]=i:n[r]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}},We=(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(", ")}`)},ze=(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(", ")}`)},ye=(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}`)}},me=(e,t,n)=>Object.fromEntries(Object.entries(e).filter(([r])=>t?.[r]?.scope===n)),Ye=(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()))},Pt=(e,t)=>{let n=e?.gui,r=t?.gui;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},be=(e={},t={})=>{let n={},r=["sfx","voice"],o=l=>{let c=e[l],a=t[l];a&&!c?n[l]={changeType:"add",data:a}:c&&!a?r.includes(l)||(n[l]={changeType:"delete",data:c}):c&&a&&JSON.stringify(c)!==JSON.stringify(a)&&(n[l]={changeType:"update",data:a})};o("background"),o("base"),o("bgm"),o("voice");let i=Pt(e.dialogue,t.dialogue);return i&&(n.dialogue=i),o("choice"),o("layout"),o("animation"),o("keyboard"),o("character"),o("visual"),o("sfx"),n};var Tt=()=>({}),Vt=(e,t)=>{t.base&&(e.base={...t.base})},Dt=(e,t)=>{if(t.background){if(!t.background.resourceId){delete e.background;return}e.background=structuredClone(t.background)}else e.background?.animations&&(e.background.animations={})},Mt=(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.gui&&(e.dialogue.gui={...t.dialogue.gui}),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}),t.dialogue.clear){delete e.dialogue;return}t.dialogue?.mode==="nvl"&&t.dialogue.content!==void 0&&(t.dialogue.clear&&(e.dialogue.lines=[]),e.dialogue.lines.push({content:t.dialogue.content}))},Bt=(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},jt=(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}}},Ft=(e,t)=>{t.visual?e.visual=structuredClone(t.visual):e.visual?.items&&(e.visual.items=e.visual.items.map(n=>n.animations?{...n,animations:{}}:n))},Ut=(e,t)=>{if(!t.character){e.character?.items&&(e.character.items=e.character.items.map(n=>n.animations?{...n,animations:{}}:n));return}if(!t.character.items||t.character.items.length===0){delete e.character;return}e.character=structuredClone(t.character)},Wt=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},zt=(e,t)=>{t.layout?e.layout=t.layout:e.layout&&delete e.layout},Yt=(e,t)=>{t.choice?e.choice=t.choice:e.choice&&delete e.choice},Ht=(e,t)=>{t.keyboard&&(e.keyboard=t.keyboard)},Kt=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},Jt=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(n=>{delete e[n]})},Y=e=>re(Tt,[Jt,Vt,Dt,Bt,jt,Ft,Mt,Ut,Wt,zt,Yt,Ht,Kt])(e);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},E={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},H={NOT:0};var I=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},$=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var Ie=e=>{if(!e||e.trim()==="")throw new I("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let n=e.includes("===")?"==":"!=";throw new I(`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 I(`Incomplete comparison expression - missing right operand (got: '${e}')`)},He=e=>{if(e.trim().endsWith(" in"))throw new I(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new I(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,n]=e.split(" in ");if(!n||n.trim()==="")throw new I(`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 I(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new I(`Invalid loop syntax (got: '$for ${e}')`)}};var Ke=(e,t,n=!1)=>{if(t===null)return new $(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new $(`Cannot iterate over undefined value at '$for ${e}'`);let r=typeof t;return n?new $(`Cannot iterate over non-array value in loop '${e}' - got ${r} instead`):new $(`Cannot iterate over non-array value (got: ${r}) at '$for ${e}'`)},Je=(e,t)=>{let n=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new $(`Unknown function '${e}' (${n})`)};var qt=(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 A(e.var,n,r);if(e.type===p.LITERAL)return e.value;if(e.type===p.VARIABLE)return A(e.path,n,r);if(e.type===p.INTERPOLATION)return Gt(e.parts,t,n,r);switch(e.type){case p.FUNCTION:return Xe(e,t,n,r);case p.BINARY:return Ge(e,t,n,r);case p.UNARY:return Qe(e,t,n,r);case p.CONDITIONAL:return Zt(e,t,n,r);case p.LOOP:return on(e,t,n,r);case p.OBJECT:return an(e,t,n,r);case p.ARRAY:return ln(e,t,n,r);case p.PARTIAL:return cn(e,t,n,r);case p.PATH_REFERENCE:return un(e,t,n,r);default:throw new Error(`Unknown node type: ${e.type}`)}},qe=new Map,Xt=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 c=l.slice(1,-1);t.push({type:"property",value:c})}else t.push({type:"property",value:l});n=""}r=!1}else n+=i}return n&&t.push({type:"property",value:n}),t},A=(e,t,n)=>{if(!e)return;if(e in n)return n[e];let r=qe.get(e);if(!r){let i=[],l="",c=0;for(let a=0;a<e.length;a++){let s=e[a];s==="["?(c++,l+=s):s==="]"?(c--,l+=s):s==="."&&c===0?l&&(i.push(l),l=""):l+=s}l&&i.push(l),r=[];for(let a of i){let s=Xt(a.trim());r.push(...s)}qe.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},Gt=(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("")},Xe=(e,t,n,r)=>{let o=t.functions||t,i=o[e.name];if(!i)throw Je(e.name,o);let l=e.args.map(c=>_(c,t,n,r));return i(...l)},F=(e,t,n,r)=>{if(e.var&&!e.type)return A(e.var,n,r);switch(e.type){case p.VARIABLE:return A(e.path,n,r);case p.LITERAL:return e.value;case p.BINARY:return Ge(e,t,n,r);case p.UNARY:return Qe(e,t,n,r);case p.FUNCTION:return Xe(e,t,n,r);default:return _(e,t,n,r)}},Ge=(e,t,n,r)=>{if(e.op===E.AND||e.op===E.OR){let l=F(e.left,t,n,r),c=F(e.right,t,n,r);switch(e.op){case E.AND:return l&&c;case E.OR:return l||c}}let o=_(e.left,t,n,r),i=_(e.right,t,n,r);switch(e.op){case E.EQ:return o==i;case E.NEQ:return o!=i;case E.GT:return o>i;case E.LT:return o<i;case E.GTE:return o>=i;case E.LTE:return o<=i;case E.IN:return Array.isArray(i)?i.includes(o):!1;case E.ADD:if(typeof o!="number"||typeof i!="number")throw new $(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case E.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new $(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},Qe=(e,t,n,r)=>{let o=e.op===H.NOT?F(e.operand,t,n,r):_(e.operand,t,n,r);if(e.op===H.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},Qt=(e,t,n,r)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===p.VARIABLE)if(A(o.path,n,r)){let l=e.bodies[0];if(l.type===p.OBJECT&&l.properties.length<=5){let c={};for(let a of l.properties){let s=a.parsedKey?_(a.parsedKey,t,n,r):a.key,u=a.value;if(u.type===p.LITERAL)c[s]=u.value;else if(u.type===p.VARIABLE)c[s]=A(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=A(d.path,n,r);f.push(h!=null?String(h):"")}else{let h=_(d,t,n,r);f.push(h!=null?String(h):"")}c[s]=f.join("")}else c[s]=_(u,t,n,r)}return c}}else{let l=e.bodies[1];if(l.type===p.OBJECT&&l.properties.length<=5){let c={};for(let a of l.properties){let s=a.parsedKey?_(a.parsedKey,t,n,r):a.key,u=a.value;if(u.type===p.LITERAL)c[s]=u.value;else if(u.type===p.VARIABLE)c[s]=A(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=A(d.path,n,r);f.push(h!=null?String(h):"")}else{let h=_(d,t,n,r);f.push(h!=null?String(h):"")}c[s]=f.join("")}else c[s]=_(u,t,n,r)}return c}}}return null},Zt=(e,t,n,r)=>{let o=Qt(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||F(l,t,n,r))return _(e.bodies[i],t,n,r)}return Ze},en=(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 a of i.properties)if(a.parsedKey)return null;let c=[];for(let a=0;a<t.length;a++){let s=t[a];if(s[l]){let u={};for(let f of i.properties){let d=f.key,h=f.value;if(h.type===p.LITERAL)u[d]=h.value;else if(h.type===p.VARIABLE){let g=h.path;if(g===r)u[d]=s;else if(g.startsWith(r+".")){let y=g.substring(r.length+1);u[d]=s[y]}else return null}else if(h.type===p.INTERPOLATION){let g=[],y=!0;for(let b of h.parts)if(typeof b=="string")g.push(b);else if(b.type===p.VARIABLE){let m=b.path;if(m===r)g.push(s!=null?String(s):"");else if(m.startsWith(r+".")){let w=m.substring(r.length+1),v=s[w];g.push(v!=null?String(v):"")}else{y=!1;break}}else{y=!1;break}if(!y)return null;u[d]=g.join("")}else return null}c.push(u)}}return c}}}return null},tn=(e,t)=>{let n=e.body,r=e.itemVar,o=en(e,t);if(o!==null)return o;if(n.type===p.OBJECT&&n.properties.length<=5&&!n.whenCondition){for(let c of n.properties)if(c.parsedKey)return null;let i=[],l=!0;for(let c of n.properties){let a=c.key,s=c.value;if(s.type===p.LITERAL)i.push({key:a,type:"literal",value:s.value});else if(s.type===p.VARIABLE){let u=s.path;if(u===r)i.push({key:a,type:"item"});else if(u.startsWith(r+".")){let f=u.substring(r.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:a,type:"prop",prop:f});else{l=!1;break}}else{l=!1;break}}else if(s.type===p.INTERPOLATION&&s.parts.length===1){let u=s.parts[0];if(u.type===p.VARIABLE){let f=u.path;if(f===r)i.push({key:a,type:"item_string"});else if(f.startsWith(r+".")){let d=f.substring(r.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:a,type:"prop_string",prop:d});else{l=!1;break}}else{l=!1;break}}else{l=!1;break}}else{l=!1;break}}if(l){let c=new Array(t.length);if(i.length===3&&i[0].type==="prop"&&i[0].key==="id"&&i[1].type==="prop_string"&&i[1].key==="title"&&i[2].type==="prop"&&i[2].key==="completed")for(let a=0;a<t.length;a++){let s=t[a];c[a]={id:s.id,title:s.title!=null?String(s.title):"",completed:s.completed}}else for(let a=0;a<t.length;a++){let s=t[a],u={};for(let f of i)if(f.type==="literal")u[f.key]=f.value;else if(f.type==="item")u[f.key]=s;else if(f.type==="prop")u[f.key]=s[f.prop];else if(f.type==="item_string")u[f.key]=s!=null?String(s):"";else if(f.type==="prop_string"){let d=s[f.prop];u[f.key]=d!=null?String(d):""}c[a]=u}return c}}return null},nn=(e,t,n,r,o)=>{let i=[],l=e.body;if(l.type===p.OBJECT&&l.fast!==!1){let c=e.itemVar,a=e.indexVar;for(let s=0;s<o.length;s++){let u=o[s],f={},d={...r,[c]:u,...a&&{[a]:s}};d.__paths__||(d.__paths__=r.__paths__||{});let h=e.iterable.path||"";if(r&&r.__paths__&&h){let g=h.split("."),y=g[0];y in r.__paths__&&(h=r.__paths__[y],g.length>1&&(h+="."+g.slice(1).join(".")))}d.__paths__={...d.__paths__,[c]:`${h}[${s}]`,...a&&{[a]:s}};for(let g of l.properties){let y=g.parsedKey?_(g.parsedKey,t,n,d):g.key,b=g.value;if(b.type===p.LITERAL)f[y]=b.value;else if(b.type===p.VARIABLE){let m=b.path;if(m===c)f[y]=u;else if(m===a)f[y]=s;else if(m.startsWith(c+".")){let w=m.substring(c.length+1);!w.includes(".")&&!w.includes("[")?f[y]=u[w]:f[y]=A(m,n,{...r,[c]:u,...a&&{[a]:s}})}else f[y]=A(m,n,{...r,[c]:u,...a&&{[a]:s}})}else if(b.type===p.INTERPOLATION){let m=[];for(let w of b.parts)if(typeof w=="string")m.push(w);else if(w.type===p.VARIABLE){let v=w.path,x;if(v===c)x=u;else if(v===a)x=s;else if(v.startsWith(c+".")){let P=v.substring(c.length+1);!P.includes(".")&&!P.includes("[")?x=u[P]:x=A(v,n,{...r,[c]:u,...a&&{[a]:s}})}else x=A(v,n,{...r,[c]:u,...a&&{[a]:s}});m.push(x!=null?String(x):"")}else{let v={...r,[c]:u,...a&&{[a]:s}},x=_(w,t,n,v);m.push(x!=null?String(x):"")}f[y]=m.join("")}else{let m={...r,[c]:u,...a&&{[a]:s}};f[y]=_(b,t,n,m)}}i.push(f)}return i}return null},rn=(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 c=l.properties[0],a=l.properties[1];if(c.key==="id"&&c.value.type===p.VARIABLE&&c.value.path==="item.id"&&a.key==="$if item.highlighted"&&a.value.type===p.CONDITIONAL){let s=[];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),s.push(d)}}return s}}}}return null},on=(e,t,n,r)=>{let o=_(e.iterable,t,n,r);if(!Array.isArray(o)){let s,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(", ");s=`${e.iterable.name}(${d})`}else s=e.iterable.path||"undefined";let f=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${s}`;throw Ke(f,o,u)}if(!e.indexVar){let s=rn(e,o,e.itemVar);if(s!==null)return s}if(!e.indexVar){let s=tn(e,o);if(s!==null)return s}let i=nn(e,t,n,r,o);if(i!==null)return i;let l=[],c=e.iterable.path||"";if(r&&r.__paths__&&c){let s=c.split("."),u=s[0];u in r.__paths__&&(c=r.__paths__[u],s.length>1&&(c+="."+s.slice(1).join(".")))}let a=!1;e.body.type===p.ARRAY&&(e.body.items.length<=1?a=!1:a=e.body._shouldPreserveArray??=e.body.items.some(s=>s.type===p.OBJECT&&s.properties.some(u=>u.key.startsWith("$if ")||u.key.startsWith("$when "))));for(let s=0;s<o.length;s++){let u=e.indexVar?{...r,[e.itemVar]:o[s],[e.indexVar]:s}:{...r,[e.itemVar]:o[s]};u.__paths__||(u.__paths__=r.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${c}[${s}]`},e.indexVar&&(u.__paths__[e.indexVar]=s);let f=_(e.body,t,n,u);if(Array.isArray(f)&&f.length===1&&!a){let d=f[0];l.push(d===void 0?{}:d)}else l.push(f===void 0?{}:f)}return l},sn=(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 c={},a={},s=!0;for(let u of l.properties){let f=u.parsedKey?_(u.parsedKey,t,n,r):u.key,d=u.value;if(d.type===p.LITERAL)a[f]=d.value;else if(d.type===p.VARIABLE)a[f]=A(d.path,n,r);else if(d.type===p.INTERPOLATION){let h=[];for(let g of d.parts)if(typeof g=="string")h.push(g);else if(g.type===p.VARIABLE){let y=A(g.path,n,r);h.push(y!=null?String(y):"")}else{s=!1;break}if(!s)break;a[f]=h.join("")}else if(d.type===p.OBJECT&&d.properties.length<=5){let h={};for(let g of d.properties){let y=g.key,b=g.value;if(b.type===p.LITERAL)h[y]=b.value;else if(b.type===p.VARIABLE)h[y]=A(b.path,n,r);else if(b.type===p.INTERPOLATION){let m=[];for(let w of b.parts)if(typeof w=="string")m.push(w);else if(w.type===p.VARIABLE){let v=A(w.path,n,r);m.push(v!=null?String(v):"")}else{s=!1;break}if(!s)break;h[y]=m.join("")}else{s=!1;break}}if(!s)break;a[f]=h}else{s=!1;break}}if(s)return c[i]=a,c}}return null},an=(e,t,n,r)=>{let o=t.functions||t;if(e.whenCondition&&!F(e.whenCondition,o,n,r))return;let i=sn(e,t,n,r);if(i!==null)return i;if(e.fast){let s={};for(let u of e.properties){let f=u.parsedKey?_(u.parsedKey,t,n,r):u.key,d=u.value;if(d.type===p.LITERAL)s[f]=d.value;else if(d.type===p.VARIABLE)s[f]=A(d.path,n,r);else if(d.type===p.INTERPOLATION){let h=[];for(let g of d.parts)if(typeof g=="string")h.push(g);else if(g.type===p.VARIABLE){let y=A(g.path,n,r);h.push(y!=null?String(y):"")}else{let y=_(g,t,n,r);h.push(y!=null?String(y):"")}s[f]=h.join("")}else s[f]=_(d,t,n,r)}return s}let l={},c=null,a=!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 ")){a=!0;break}for(let s of e.properties)if(s.key.startsWith("$if ")||s.key.match(/^\$if\s+\w+.*:?$/)){let u=_(s.value,t,n,r);if(!a&&u!==null&&u!==void 0)return Array.isArray(u)&&u.length===1?u[0]:u;typeof u=="object"&&u!==null&&!Array.isArray(u)&&Object.assign(l,u)}else if(s.key.startsWith("$for ")){if(e.properties.length===1)return _(s.value,t,n,r)}else{let u=s.value;if(u&&u.type===p.OBJECT&&u.properties){let f=u.properties.find(d=>d.key.startsWith("$for "));if(f){let d=_(f.value,t,n,r);d!==void 0&&(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},Ze={},ln=(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!==Ze&&l!==void 0&&o.push(l)}return o},cn=(e,t,n,r)=>{let{name:o,data:i,whenCondition:l}=e,c=t.partials||{},a=t.functions||t;if(l&&!F(l,a,n,r))return;if(!c[o])throw new $(`Partial '${o}' is not defined`);let s=r._partialStack||[];if(s.includes(o))throw new $(`Circular partial reference detected: ${o}`);let u=c[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 _(u,t,f,d)},un=(e,t,n,r)=>{let{path:o}=e,i=o.split("."),l=i[0],c=i.slice(1);if(!r||!(l in r))throw new $(`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 $(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let a=r.__paths__[l];if(typeof a=="number"){if(c.length>0)throw new $(`Path reference '#{${o}}' - cannot access properties on index variable '${l}'`);return String(a)}return c.length>0&&(a+="."+c.join(".")),a},we=qt;var fn=/\$\{([^}]*)\}/g,dn=/#\{([^}]*)\}/g,tt=(e,t={})=>{let n=e.match(/^(\w+)\((.*)\)$/);if(!n)return{isFunction:!1};let[,r,o]=n,i=pn(o,t);return{isFunction:!0,type:p.FUNCTION,name:r,args:i}},pn=(e,t={})=>e.trim()?hn(e).map(r=>gn(r.trim(),t)):[],hn=e=>{let t=[],n="",r=0,o=!1,i="";for(let l=0;l<e.length;l++){let c=e[l],a=l>0?e[l-1]:"";!o&&(c==='"'||c==="'")?(o=!0,i=c,n+=c):o&&c===i&&a!=="\\"?(o=!1,i="",n+=c):!o&&c==="("?(r++,n+=c):!o&&c===")"?(r--,n+=c):!o&&c===","&&r===0?(t.push(n),n=""):n+=c}return n&&t.push(n),t},gn=(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=tt(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:c,type:a}of o){let s=0;for(;s<r.length;){let u=M(r.substring(s),c);if(u===-1)break;let f=s+u;f>i&&(i=f,l={op:c,type:a}),s=f+c.length}}if(i!==-1)try{return L(r,t)}catch{return{type:p.VARIABLE,path:r}}return{type:p.VARIABLE,path:r}},nt=/^\w+\(.*\)$/,yn=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,mn=e=>{if(!(!e||e.trim()===""||nt.test(e))&&yn.test(e))throw e.includes("?")&&e.includes(":")?new I(`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 I(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new I(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},et=e=>{let t=e.trim();if(nt.test(t))throw new I(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new I(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new I(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new I(`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 I(`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}},K=(e,t={})=>{let n=e.trim();mn(n);let r=tt(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}},_e=(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,u)=>{let f=`__ESCAPED_${r.length}__`;return r.push(u),f}),n=n.replace(/\\(#\{[^}]*\})/g,(s,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(fn)],i=[...n.matchAll(dn)],l=[...o.map(s=>({match:s,type:"variable"})),...i.map(s=>({match:s,type:"pathref"}))].sort((s,u)=>s.match.index-u.match.index);if(l.length===0){let s=n;for(let u=0;u<r.length;u++)s=s.replace(`__ESCAPED_${u}__`,r[u]);return{type:p.LITERAL,value:s}}if(l.length===1&&l[0].match[0]===n&&r.length===0){let{match:s,type:u}=l[0];try{return u==="variable"?K(s[1],t):et(s[1])}catch(f){if(f.message==="Invalid array index syntax")return{type:p.LITERAL,value:n};throw f}}let c=[],a=0;for(let{match:s,type:u}of l){let[f,d]=s,h=s.index;if(h>a){let g=n.substring(a,h);for(let y=0;y<r.length;y++)g=g.replace(`__ESCAPED_${y}__`,r[y]);g&&c.push(g)}try{let g;u==="variable"?g=K(d.trim(),t):g=et(d.trim()),c.push(g)}catch(g){if(g.message==="Invalid array index syntax")c.push(f);else throw g}a=h+f.length}if(a<n.length){let s=n.substring(a);for(let u=0;u<r.length;u++)s=s.replace(`__ESCAPED_${u}__`,r[u]);s&&c.push(s)}return{type:p.INTERPOLATION,parts:c}};var N=(e,t)=>typeof e=="string"?_e(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?In(e,t):wn(e,t):{type:p.LITERAL,value:e},bn=e=>{let{$each:t,...n}=e;if(typeof t!="string")throw new I("$each value must be a non-empty string");let r=t.trim();if(r==="")throw new I("$each value must be a non-empty string");if(Object.keys(n).length===0)throw new I("Empty $each body not allowed");if(n.$partial!==void 0)throw new I("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${r}`]:n}},In=(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 a=bn(i),s=Object.keys(a);if(s.length===1&&/^\$for(?::\w+)?\s/.test(s[0])){let u=rt(s[0],a[s[0]],t,!0);n.push(u),r=!0;continue}}catch(a){throw a instanceof I?a:new I(a.message)}let c=Object.keys(i);if(c.length===1&&/^\$for(?::\w+)?\s/.test(c[0])){let a=rt(c[0],i[c[0]],t);n.push(a),r=!0;continue}}let l=N(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}},wn=(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 I("$partial value must be a string");if(e.$partial.trim()==="")throw new I("$partial value cannot be an empty string");let a=["$if","$elif","$else","$for"],s=[];for(let[m]of i)for(let w of a)if(m===w||m.startsWith(w+" ")||m.startsWith(w+"#")){s.push(w);break}if(s.length>0)throw new I(`Cannot use $partial with ${s.join(", ")} at the same level. Wrap $partial in a parent object if you need conditionals.`);let{$partial:u,$when:f,...d}=e,h={},g=!1;for(let[m,w]of Object.entries(d)){let v=m;(m.startsWith("\\$")||m.startsWith("$$"))&&(v=m.slice(1)),h[v]=w,g=!0}let y=null;if(g&&(y=N(h,t),y.type===p.OBJECT)){let m=!1;for(let w of y.properties)if(w.value.type===p.VARIABLE||w.value.type===p.INTERPOLATION||w.value.type===p.FUNCTION||w.value.type===p.CONDITIONAL||w.value.type===p.OBJECT&&!w.value.fast||w.value.type===p.ARRAY&&!w.value.fast){m=!0;break}m&&(y.fast=!1)}let b={type:p.PARTIAL,name:u,data:y};if(f!==void 0){let m;if(typeof f=="string"){if(f.trim()==="")throw new I("Empty condition expression after '$when'");m=L(f,t)}else m={type:p.LITERAL,value:f};b.whenCondition=m}return b}for(let[a,s]of i)if(a==="$when"){if(o!==null)throw new I("Multiple '$when' directives on the same object are not allowed");if(s==null)throw new I("Missing condition expression after '$when'");let u=typeof s=="string"?s:JSON.stringify(s);if(u.trim()==="")throw new I("Empty condition expression after '$when'");o=L(u,t),r=!0}else if(a.startsWith("$when#")||a.startsWith("$when "))throw new I("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;l<i.length;){let[a,s]=i[l];if(a==="$when"){l++;continue}if(a==="$each")throw new I("$each can only be used inside arrays");if(a.startsWith("$if ")||a.match(/^\$if#\w+\s/)||a.match(/^\$if\s+\w+.*:$/)){let u=_n(i,l,t);n.push({key:a,value:u.node}),r=!0,l=u.nextIndex}else if(/^\$for(?::\w+)?\s/.test(a)){let u=a.match(/^\$for(?::(\w+))?\s/)?.[1]||"",f=u?`:${u}`:"";throw new I(`$for loops must be inside arrays - use '- $for${f} item in items:' instead of '$for${f} item in items:'. For cleaner object generation syntax, consider using $each.`)}else{if(a.startsWith("$elif ")||a.startsWith("$else"))throw new I(`'${a.split(" ")[0]}' without matching '$if'`);if(a==="$if"||a==="$if:")throw new I("Missing condition expression after '$if'");{let u=N(s,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=_e(a,t),d={key:a,value:u};(f.type!==p.LITERAL||f.value!==a)&&(d.parsedKey=f),n.push(d),l++}}}let c={type:p.OBJECT,properties:n,fast:!r};return o&&(c.whenCondition=o),c},_n=(e,t,n={})=>{let r=[],o=[],i=t,[l,c]=e[i],a=null,s;if(l.startsWith("$if#")){let f=l.match(/^\$if#(\w+)\s+(.+)$/);if(f)a=f[1],s=f[2];else throw new I(`Invalid conditional syntax: ${l}`)}else s=l.substring(4),s.endsWith(":")&&(s=s.slice(0,-1).trim());Ie(s);let u=L(s,n);for(r.push(u),o.push(N(c,n)),i++;i<e.length;){let[f,d]=e[i],h=!1,g;if(a?f.startsWith(`$elif#${a} `)?(g=f.substring(`$elif#${a} `.length),g.endsWith(":")&&(g=g.slice(0,-1).trim()),h=!0):(f===`$else#${a}`||f===`$else#${a}:`)&&(h=!0,g=null):f.startsWith("$elif ")?(g=f.substring(6),g.endsWith(":")&&(g=g.slice(0,-1).trim()),h=!0):(f==="$else"||f==="$else:")&&(h=!0,g=null),h){if(g===null)r.push(null);else{Ie(g);let y=L(g,n);r.push(y)}if(o.push(N(d,n)),i++,g===null)break}else break}return{node:{type:p.CONDITIONAL,conditions:r,bodies:o,id:a},nextIndex:i}},L=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let s=e.slice(1,-1),u=0,f=!0;for(let d=0;d<s.length;d++)if(s[d]==="("?u++:s[d]===")"&&u--,u<0){f=!1;break}if(f&&u===0)return L(s,t)}let n=M(e,"||");if(n!==-1)return{type:p.BINARY,op:E.OR,left:L(e.substring(0,n).trim(),t),right:L(e.substring(n+2).trim(),t)};let r=M(e,"&&");if(r!==-1)return{type:p.BINARY,op:E.AND,left:L(e.substring(0,r).trim(),t),right:L(e.substring(r+2).trim(),t)};let o=[{op:">=",type:E.GTE},{op:"<=",type:E.LTE},{op:"==",type:E.EQ},{op:"!=",type:E.NEQ},{op:">",type:E.GT},{op:"<",type:E.LT},{op:" in ",type:E.IN}];for(let{op:s,type:u}of o){let f=M(e,s);if(f!==-1)return{type:p.BINARY,op:u,left:L(e.substring(0,f).trim(),t),right:L(e.substring(f+s.length).trim(),t)}}let i=-1,l=null,c=[{op:" + ",type:E.ADD},{op:" - ",type:E.SUBTRACT}];for(let{op:s,type:u}of c){let f=0;for(;f<e.length;){let d=M(e.substring(f),s);if(d===-1)break;let h=f+d;h>i&&(i=h,l={op:s,type:u}),f=h+s.length}}if(i!==-1&&l)return{type:p.BINARY,op:l.type,left:L(e.substring(0,i).trim(),t),right:L(e.substring(i+l.op.length).trim(),t)};let a=[" * "," / "," % "];for(let s of a)if(M(e,s)!==-1)throw new I(`Arithmetic operations are not allowed in conditionals: "${s}"`);return e.startsWith("!")?{type:p.UNARY,op:H.NOT,operand:L(e.substring(1).trim(),t)}:ot(e,t)},M=(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},vn=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}},ot=(e,t)=>{let n=e.trim();if(n.match(/^(\w+)\((.*)\)$/))return K(n,t);let o=vn(n);if(o.type===p.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(n))return{type:p.VARIABLE,path:n};try{return K(n,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},En=(e,t=!1)=>{let n=t?"$each":"$for";try{He(e)}catch(r){if(r instanceof I&&t){let o=r.message.replace(/\$for/g,"$each");throw new I(o.replace("Parse Error: ",""))}throw r}},rt=(e,t,n,r=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let b=r?"$each":"$for";throw new I(`Invalid loop syntax (got: '${e.replace("$for",b)}')`)}let l=i[1],c=i[2].trim();En(c,r);let a=c.match(/^(.+?)\s+in\s+(.+)$/);if(!a){let b=r?"$each":"$for";throw new I(`Invalid loop syntax - missing 'in' keyword (got: '${b} ${c}')`)}let s=a[1].trim(),u=a[2].trim(),f,d=null;if(s.includes(",")){let b=s.split(",").map(m=>m.trim());if(b.length!==2)throw new I(`Invalid loop variables: ${s}. Expected format: "item" or "item, index"`);f=b[0],d=b[1]}else f=s;let h=["this","undefined","null","true","false"];if(h.includes(f))throw new I(`Reserved variable name: ${f}`);if(d&&h.includes(d))throw new I(`Reserved variable name: ${d}`);let g=ot(u,n),y=N(t,n);return{type:p.LOOP,itemVar:f,indexVar:d,iterable:g,body:y,flatten:l!=="nested"}};var xn=(e,t={})=>{let{functions:n={}}=t;return N(e,n)},oe=xn;var ve={};vt(ve,{now:()=>An});var An=()=>Date.now();var Ln=(e,t,n={})=>{let{functions:r={},partials:o={}}=n,i={...ve,...r},l=oe(e,{functions:i}),c={};for(let[a,s]of Object.entries(o))c[a]=oe(s,{functions:i});return we(l,t,{functions:i,partials:c})},R=Ln;var Ee={objectValues:e=>Object.entries(e).map(([t,n])=>({id:t,...n})),formatDate:Ye},$n=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),Cn=(e,{presentationState:t,resources:n})=>{let{elements:r}=e;if(t.base){let o=r.find(i=>i.id==="story");if(!o)return e;if(t.base.resourceId){let i=n?.layouts[t.base.resourceId];i&&o.children.unshift({id:"base",type:"container",children:i.elements})}}return e},Sn=(e,{presentationState:t,previousPresentationState:n,resources:r={},variables:o,autoMode:i,skipMode:l,currentLocalizationPackageId:c})=>{let{elements:a}=e,s=e.animations||[];if(t.background){let u=a.find(f=>f.id==="story");if(!u)return e;if(t.background.resourceId){let{images:f={},videos:d={}}=r,h=f[t.background.resourceId]||d[t.background.resourceId];if(h){let g=d[t.background.resourceId]!==void 0,y={id:`bg-cg-${t.background.resourceId}`,type:g?"video":"sprite",x:0,y:0,src:h.fileId,width:h.width,height:h.height};g&&(y.loop=h.loop??!1,y.volume=h.volume??500),u.children.push(y)}}if(t.background.resourceId){let{layouts:f={}}=r,d=f[t.background.resourceId];d&&u.children.push({id:`bg-cg-${t.background.resourceId}`,type:"container",children:d.elements})}if(t.background.animations){if(t.background.animations.in){let f=t.background.animations.in.resourceId,d=r?.tweens[f];d&&s.push({id:"bg-cg-animation-in",type:"tween",targetId:`bg-cg-${t.background.resourceId}`,properties:d.properties})}if(t.background.animations.out){let f=t.background.animations.out.resourceId,d=n?.background?.resourceId,h=r?.tweens[f];h&&d&&s.push({id:"bg-cg-animation-out",type:"tween",targetId:`bg-cg-${d}`,properties:h.properties})}if(t.background.animations.update){let f=t.background.animations.update.resourceId,d=r?.tweens[f];d&&s.push({id:"bg-cg-animation-update",type:"tween",targetId:`bg-cg-${t.background.resourceId}`,properties:d.properties})}}}return e},kn=(e,{presentationState:t,resources:n})=>{let{elements:r}=e,o=e.animations||[];if(t.character&&n){let i=r.find(c=>c.id==="story");if(!i)return e;let l=t.character.items||[];for(let c=0;c<l.length;c++){let a=l[c],{transformId:s,sprites:u}=a;if(a.animations&&a.animations.out&&!u&&!s){let y=a.animations.out.resourceId,b=n?.tweens[y];if(b){let m={id:"character-animation-out",type:"tween",targetId:`character-container-${a.id}`,properties:b.properties};o.push(m)}continue}if(!u||u.length===0||!s){console.warn("Character item missing sprites or transformId:",a);continue}let f=u.map(({resourceId:y})=>y),d=`character-container-${a.id}-${c}-${f.join("-")}`,h=n.transforms[s];if(!h){console.warn("Transform not found:",s);continue}let g={type:"container",id:d,x:a.x??h.x,y:a.y??h.y,anchorX:h.anchorX,anchorY:h.anchorY,rotation:h.rotation,scaleX:h.scaleX,scaleY:h.scaleY,children:[]};for(let y of u){let b=n.images[y.resourceId];if(!b){console.warn(`Image resource not found: ${y.resourceId}`);continue}g.children.push({type:"sprite",id:`${d}-${y.id}`,src:b.fileId,width:b.width,height:b.height,x:0,y:0})}if(i.children.push(g),a.animations){if(a.animations.in){let y=a.animations.in.resourceId,b=n?.tweens[y];b&&o.push({id:"character-animation-in",type:"tween",targetId:d,properties:b.properties})}if(a.animations.update){let y=a.animations.update.resourceId,b=n?.tweens[y];if(b){let m={id:"character-animation-update",type:"tween",targetId:d,properties:b.properties};o.push(m)}}}}}return e},On=(e,{presentationState:t,resources:n})=>{let{elements:r}=e,o=e.animations||[];if(t.visual&&n){let i=r.find(c=>c.id==="story");if(!i)return e;let l=t.visual.items;for(let c of l){if(c.resourceId){let{images:a={},videos:s={},spritesheets:u={}}=n,f=u[c.resourceId];if(f){let d=n.transforms?.[c.transformId]||{},h=c.animationName;if(h){let g=f.animations?.[h];if(!g)throw new Error(`Animation '${h}' not found in spritesheet resource '${c.resourceId}'`);let y={id:`visual-${c.id}`,type:"animated-sprite",x:c.x??d.x??0,y:c.y??d.y??0,width:c.width??100,height:c.height??100,alpha:c.alpha??1,anchorX:d.anchorX,anchorY:d.anchorY,rotation:d.rotation,scaleX:d.scaleX,scaleY:d.scaleY,spritesheetSrc:f.fileId,spritesheetData:f.jsonData,animation:{frames:g.frames,animationSpeed:c.animationSpeed??g.animationSpeed??.5,loop:c.loop??g.loop??!0}};i.children.push(structuredClone(y))}}else{let d=a[c.resourceId]||s[c.resourceId];if(d){let h=s[c.resourceId]!==void 0,g=n.transforms[c.transformId],y={id:`visual-${c.id}`,type:h?"video":"sprite",src:d.fileId,width:d.width,height:d.height,x:g.x,y:g.y,anchorX:g.anchorX,anchorY:g.anchorY,rotation:g.rotation,scaleX:g.scaleX,scaleY:g.scaleY};h&&(y.loop=d.loop??!1,y.volume=d.volume??500),i.children.push(y)}}}if(c.resourceId){let{layouts:a={}}=n,s=a[c.resourceId];if(s){let u=n.transforms[c.transformId];i.children.push({id:`visual-${c.id}`,type:"container",children:structuredClone(s.elements),x:u.x,y:u.y,anchorX:u.anchorX,anchorY:u.anchorY,rotation:u.rotation,scaleX:u.scaleX,scaleY:u.scaleY})}}if(c.animations){if(c.animations.in){let a=c.animations.in.resourceId||c.animations.in,s=n?.tweens[a];s&&o.push({id:`${c.id}-animation`,type:"tween",targetId:`visual-${c.id}`,properties:structuredClone(s.properties)})}if(c.animations.out){let a=c.animations.out.resourceId||c.animations.out,s=n?.tweens[a];s&&o.push({id:`${c.id}-animation-2`,type:"tween",targetId:`visual-${c.id}`,properties:structuredClone(s.properties)})}}}}return e},Rn=(e,{presentationState:t,resources:n={},dialogueUIHidden:r,autoMode:o,skipMode:i,canRollback:l,skipOnlyViewedLines:c,isLineCompleted:a,l10n:s,variables:u,saveSlots:f=[]})=>{let{elements:d}=e;if(!t.dialogue||r)return e;let h=d.find(g=>g.id==="story");if(!h)return e;if(t.dialogue.gui&&t.dialogue.gui.resourceId){let{layouts:g={}}=n,y=g[t.dialogue.gui.resourceId];if(y){let b;t.dialogue.characterId&&(b=n.characters[t.dialogue.characterId]),t.dialogue.character&&(b={...b,name:t.dialogue.character.name});let m={elements:y.elements},w={variables:u,autoMode:o,skipMode:i,canRollback:l,skipOnlyViewedLines:c,isLineCompleted:a,saveSlots:f,dialogue:{character:{name:b?.name||""},content:t.dialogue?.content||[{text:""}],lines:t.dialogue?.lines||[]},l10n:s},v=R(m,w,{functions:Ee});v=R(v,{l10n:s});let x=v?.elements;if(Array.isArray(x))for(let P of x)h.children.push(structuredClone(P));else x&&h.children.push(structuredClone(x))}}return e},Nn=(e,{presentationState:t,resources:n})=>{let{elements:r}=e;if(t.choice&&n){let o=r.find(s=>s.id==="story");if(!o)return e;o.children.push({id:"choice-blocker",type:"rect",fill:"transparent",width:1920,height:1080,x:0,y:0,click:{actionPayload:{actions:{}}}});let i=n?.layouts[t.choice.resourceId];if(!i||!i.elements)return e;let l={elements:i.elements},a=R(l,{choice:{items:t.choice?.items??[]}})?.elements;if(Array.isArray(a))for(let s of a)o.children.push(structuredClone(s));else a&&o.children.push(structuredClone(a))}return e},Pn=(e,{presentationState:t,resources:n})=>{if(t.keyboard?.resourceId){let r=n?.keyboards?.[t.keyboard.resourceId];r&&(e.global.keyboard=r)}return e},Tn=(e,{presentationState:t,resources:n})=>{let{elements:r,audio:o}=e;if(t.bgm&&n){if(!r.find(c=>c.id==="story"))return e;let l=n.sounds[t.bgm.resourceId];if(!l)return e;o.push({id:"bgm",type:"sound",src:l.fileId,loop:t.bgm.loop??!0,volume:t.bgm.volume??500,delay:t.bgm.delay??null})}return e},Vn=(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??!0,volume:i.volume??l.volume??500,delay:i.delay??l.delay??null})}}return e},Dn=(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},Mn=(e,{presentationState:t,resources:n={},variables:r,autoMode:o,skipMode:i,canRollback:l,currentLocalizationPackageId:c,saveSlots:a=[]})=>{let{elements:s}=e,u=e.animations||[];if(t.layout){let f=s.find(m=>m.id==="story");if(!f)return e;let d=n.layouts[t.layout.resourceId];if(!d)return e;Array.isArray(d.transitions)&&d.transitions.forEach(m=>{u.push(m)});let h={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:d.elements||[]},y=R(h,{variables:r,saveSlots:a,autoMode:o,skipMode:i,canRollback:l,currentLocalizationPackageId:c},{functions:Ee});y=R(y,{i18n:{}});let b=m=>{let w={...m};return m.src&&m.src.startsWith("file:")&&(w.src=m.src),m.children&&Array.isArray(m.children)&&(w.children=m.children.map(b)),w};f.children.push(b(y))}return e},Bn=(e,{resources:t={},variables:n,autoMode:r,skipMode:o,canRollback:i,currentLocalizationPackageId:l,layeredViews:c=[],dialogueHistory:a=[],saveSlots:s=[],l10n:u})=>{let{elements:f}=e,d=e.animations||[];return c&&c.length>0&&c.forEach((h,g)=>{let y=t.layouts[h.resourceId];if(!y){console.warn(`LayeredView layout not found: ${h.resourceId}`);return}Array.isArray(y.transitions)&&y.transitions.forEach(x=>{d.push(x)});let b={id:`layeredView-${g}`,type:"container",x:0,y:0,children:y.elements||[]},m=a.map(x=>{let P=t.characters?.[x.characterId];return{...x,characterName:P?.name||""}}),w={variables:n,autoMode:r,skipMode:o,canRollback:i,currentLocalizationPackageId:l,saveSlots:s,historyDialogue:m,characters:t.characters||{}},v=R(b,w,{functions:Ee});v=R(v,{i18n:{},l10n:u}),f.push(v)}),e},it=e=>re($n,[Cn,Sn,kn,On,Rn,Nn,Pn,Mn,Tn,Vn,Dn,Bn])(e);var jn=e=>{let{global:{currentLocalizationPackageId:t,saveSlots:n={},variables:r={}},projectData:o}=e,i={sceneId:o.story.initialSceneId,sectionId:o.story.scenes[o.story.initialSceneId].initialSectionId,lineId:o.story.scenes[o.story.initialSceneId].sections[o.story.scenes[o.story.initialSceneId].initialSectionId].lines[0].id},{contextVariableDefaultValues:l,globalVariablesDefaultValues:c}=Ue(o),a={...c,...r},s={projectData:o,global:{autoplayDelay:1e3,isLineCompleted:!1,pendingEffects:[],autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isDialogueHistoryShowing:!1,currentLocalizationPackageId:t,viewedRegistry:{sections:[],resources:[]},nextLineConfig:{manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1}},saveSlots:n,layeredViews:[],variables:a},contexts:[{currentPointerMode:"read",pointers:{read:i,history:{sectionId:void 0,lineId:void 0,historySequenceIndex:void 0}},historySequence:[{sectionId:i.sectionId,initialState:{...l},lines:[{id:i.lineId}]}],configuration:{},views:[],bgm:{resourceId:void 0},variables:l}]};return console.log("Initial State:",s),s},Fn=({state:e})=>e.global.layeredViews||[],Un=({state:e})=>e.global.pendingEffects,st=({state:e})=>e.global.skipMode,Wn=({state:e})=>e.global.autoMode,at=({state:e})=>e.global.dialogueUIHidden,zn=({state:e})=>e.global.autoplayDelay,xe=({state:e})=>{let t=e.contexts[e.contexts.length-1];if(!t)return[];let{sectionId:n,lineId:r}=t.pointers.read,o=C({state:e},{sectionId:n});if(!o?.lines||!Array.isArray(o.lines))return[];let i=o.lines.findIndex(a=>a.id===r);return o.lines.slice(0,i+1).filter(a=>a.actions?.dialogue).map(a=>{let s=a.actions.dialogue,u="";return s.characterId&&(u=e.projectData.resources?.characters?.[s.characterId]?.name||""),{content:s.content,characterId:s.characterId,characterName:u}})},Yn=({state:e})=>e.global.currentLocalizationPackageId,Ae=({state:e},t)=>{let{sectionId:n,lineId:r}=t,o=e.global.viewedRegistry.sections.find(a=>a.sectionId===n);if(!o)return!1;if(o.lastLineId===void 0||r===void 0)return!0;let i=C({state:e},{sectionId:n});if(!i||!i.lines||!Array.isArray(i.lines))return!1;let l=i.lines.findIndex(a=>a.id===o.lastLineId),c=i.lines.findIndex(a=>a.id===r);return l===-1||c===-1?o.lastLineId===r:c<l},Hn=({state:e},t)=>{let{resourceId:n}=t;return!!e.global.viewedRegistry.resources.find(o=>o.resourceId===n)},Kn=({state:e})=>e.global.nextLineConfig,Jn=({state:e})=>e.global.saveSlots,qn=({state:e},t)=>{let{slotKey:n}=t;return e.global.saveSlots[n]},U=({state:e})=>{let t=e.contexts[e.contexts.length-1];if(!t)return;let n=t.pointers?.[t.currentPointerMode];return{currentPointerMode:t.currentPointerMode,pointer:n}},C=({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]}},lt=({state:e})=>{let t=U({state:e});if(!t?.pointer)return;let{sectionId:n,lineId:r}=t.pointer,o=C({state:e},{sectionId:n});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===r)},ct=({state:e})=>{let{sectionId:t,lineId:n}=U({state:e}).pointer,o=C({state:e},{sectionId:t})?.lines||[],i=o.findIndex(s=>s.id===n),l=o.slice(0,i+1);console.log("currentLines",l);let c=l.map(s=>{let u=s.actions||{},f={};return Object.keys(u).forEach(d=>{f[d]=u[d]}),f});return Y(c)},Xn=({state:e})=>{let t=ut({state:e}),r=lt({state:e})?.actions??{},o=Y([t??{},r]);return be(t??{},o??{})},Gn=({state:e},{sectionId:t})=>{let n=C({state:e},{sectionId:t});if(!n?.lines)return{lines:[]};let r=[],o={};for(let i of n.lines){let l=i.actions||{},c=Y([o,l]),a=be(o,c);r.push({id:i.id,changes:a}),o=c}return{lines:r}},ut=({state:e})=>{let{sectionId:t,lineId:n}=U({state:e}).pointer,o=C({state:e},{sectionId:t})?.lines||[],i=o.findIndex(a=>a.id===n);if(i<=0)return null;let c=o.slice(0,i).map(a=>{let s=a.actions||{},u={};return Object.keys(s).forEach(f=>{u[f]=s[f]}),u});return Y(c)},ft=({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 c=o+l,a=e.global.saveSlots&&e.global.saveSlots[c]||{};i.push({slotNumber:c,...a})}return{saveSlots:i}},Qn=({state:e})=>{let t=ct({state:e}),n=ut({state:e});console.log("presentationState",t);let r={...e.global.variables,...e.contexts[e.contexts.length-1].variables},{saveSlots:o}=ft({state:e}),i=it({presentationState:t,previousPresentationState:n,resources:e.projectData.resources,l10n:e.projectData.l10n.packages[e.global.currentLocalizationPackageId],currentLocalizationPackageId:e.global.currentLocalizationPackageId,dialogueUIHidden:e.global.dialogueUIHidden,autoMode:e.global.autoMode,skipMode:e.global.skipMode,canRollback:bt({state:e}),skipOnlyViewedLines:!r._skipUnseenText,isLineCompleted:e.global.isLineCompleted,layeredViews:e.global.layeredViews,dialogueHistory:xe({state:e}),saveSlots:o,variables:r});return console.log("renderState",i),i},Zn=({state:e},t)=>(e.global.layeredViews.push(t),e.global.pendingEffects.push({name:"render"}),e),er=({state:e})=>(e.global.layeredViews.pop(),e.global.pendingEffects.push({name:"render"}),e),tr=({state:e},t)=>(e.global.layeredViews.length>0&&(e.global.layeredViews[e.global.layeredViews.length-1]=t),e.global.pendingEffects.push({name:"render"}),e),nr=({state:e})=>(e.global.layeredViews=[],e.global.pendingEffects.push({name:"render"}),e),dt=({state:e})=>(e.global.skipMode&&(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"})),e.global.autoMode=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:e.global.autoplayDelay}}),e.global.pendingEffects.push({name:"render"}),e),Le=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),rr=({state:e})=>(e.global.autoMode?Le({state:e}):dt({state:e}),e),pt=({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),J=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),or=({state:e})=>(st({state:e})?J({state:e}):pt({state:e}),e),ht=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),e),gt=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),e),ir=({state:e})=>(at({state:e})?ht({state:e}):gt({state:e}),e),sr=({state:e})=>{let t=xe({state:e});return e.global.isDialogueHistoryShowing=!0,e.global.pendingEffects.push({name:"render"}),e},ar=({state:e})=>(e.global.isDialogueHistoryShowing=!1,e.global.pendingEffects.push({name:"render"}),e),lr=({state:e},t)=>{let{localizationPackageId:n}=t;return e.global.currentLocalizationPackageId=n,e.global.pendingEffects.push({name:"render"}),e},cr=({state:e})=>(e.global.pendingEffects=[],e),ur=({state:e},t)=>(e.global.pendingEffects.push(t),e),yt=({state:e},t)=>{let{sectionId:n,lineId:r}=t,o=e.global.viewedRegistry.sections.find(i=>i.sectionId===n);if(o){let i=C({state:e},{sectionId:n});if(i?.lines&&o.lastLineId!==void 0){let l=i.lines.findIndex(a=>a.id===o.lastLineId),c=i.lines.findIndex(a=>a.id===r);(l===-1||c>l)&&(o.lastLineId=r)}else o.lastLineId=r}else e.global.viewedRegistry.sections.push({sectionId:n,lastLineId:r});return e.global.pendingEffects.push({name:"render"}),e},fr=({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},dr=({state:e},t)=>{let{manual:n,auto:r}=t,o=e.global.nextLineConfig.auto?.enabled,i=r?.enabled;return n&&r?e.global.nextLineConfig={manual:n,auto:r}:(n&&(e.global.nextLineConfig.manual=n),r&&(e.global.nextLineConfig.auto=r)),i===!0&&!o?e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):i===!1&&o&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),e},pr=({state:e},{delay:t})=>(e.global.autoplayDelay=t,e.global.autoMode&&(e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:e.global.autoplayDelay}})),e.global.pendingEffects.push({name:"render"}),e),hr=({state:e},t)=>{let{slot:n,thumbnailImage:r}=t,o=String(n),i={contexts:[...e.contexts],viewedRegistry:e.global.viewedRegistry},l={slotKey:o,date:Date.now(),image:r,state:i};return e.global.saveSlots[o]=l,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},gr=({state:e},t)=>{let{slot:n}=t,r=String(n),o=e.global.saveSlots[r];return o&&(e.global.viewedRegistry=o.state.viewedRegistry,e.contexts=o.state.contexts,e.global.pendingEffects.push({name:"render"})),e},yr=({state:e},t)=>{let{projectData:n}=t;return e.projectData=n,e.global.pendingEffects.push({name:"render"}),e},mr=({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&&!C({state:e},{sectionId:n}))return console.warn(`Section not found: ${n}`),e;let l=C({state:e},{sectionId:i});return!l?.lines||!Array.isArray(l.lines)?(console.warn(`Section ${i} has no lines`),e):l.lines.find(a=>a.id===r)?(o.pointers.read={sectionId:i,lineId:r},e.global.isLineCompleted=!1,q({state:e},{lineId:r}),e.global.pendingEffects.push({name:"render"}),e.global.pendingEffects.push({name:"handleLineActions"}),e):(console.warn(`Line not found: ${r} in section ${i}`),e)},mt=({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},q=({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},br=({state:e})=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(!e.global.isLineCompleted)return e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"render"}),e;let t=U({state:e})?.pointer,n=t?.sectionId,o=C({state:e},{sectionId:n})?.lines||[],l=o.findIndex(c=>c.id===t?.lineId)+1;if(l<o.length){let c=o[l],a=!e.global.variables?._skipUnseenText;if(e.global.skipMode&&a&&!Ae({state:e},{sectionId:n,lineId:c.id}))return J({state:e}),e;let s=e.contexts[e.contexts.length-1];if(s){let u=s.pointers.read.lineId;u&&n&&yt({state:e},{sectionId:n,lineId:u}),s.pointers.read={sectionId:n,lineId:c.id}}e.global.isLineCompleted=!1,q({state:e},{lineId:c.id}),e.global.pendingEffects.push({name:"render"}),e.global.pendingEffects.push({name:"handleLineActions"})}else e.global.autoMode&&Le({state:e}),e.global.skipMode&&J({state:e});return console.log("state",e),e},Ir=({state:e})=>(e.global.isLineCompleted||(e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"render"})),e),wr=({state:e},t)=>{let{sectionId:n}=t,r=C({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 u=o.findIndex(f=>f.id===l.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 a=o.findIndex(s=>s.id===i.pointers.history.lineId)-1;if(a>=0&&a<o.length){let s=o[a];i.pointers.history={sectionId:n,lineId:s.id},e.global.pendingEffects.push({name:"render"})}return e},_r=({state:e},t)=>{let{sectionId:n}=t,r=C({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;let i=e.contexts[e.contexts.length-1];return i&&(i.pointers.read={sectionId:n,lineId:o.id},mt({state:e},{item:{sectionId:n}}),q({state:e},{lineId:o.id})),e.global.isLineCompleted=!1,e.global.pendingEffects.push({name:"render"}),e.global.pendingEffects.push({name:"handleLineActions"}),e},vr=({state:e})=>{let t=U({state:e})?.pointer,n=t?.sectionId,o=C({state:e},{sectionId:n})?.lines||[],l=o.findIndex(c=>c.id===t?.lineId)+1;if(l<o.length){let c=o[l],a=!e.global.variables?._skipUnseenText;if(e.global.skipMode&&a&&!Ae({state:e},{sectionId:n,lineId:c.id}))return J({state:e}),e;let s=e.contexts[e.contexts.length-1];s&&(s.pointers.read={sectionId:n,lineId:c.id}),e.global.isLineCompleted=!1,q({state:e},{lineId:c.id}),e.global.pendingEffects.push({name:"render"}),e.global.pendingEffects.push({name:"handleLineActions"}),e.global.nextLineConfig.auto?.enabled&&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},Er=({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],i=!1,l=!1,c=!1;if(r.forEach(({variableId:a,op:s,value:u})=>{let f=e.projectData.resources?.variables?.[a],d=f?.scope,h=f?.type;We(d,a),ze(h,s,a);let g=d==="context"?o.variables:e.global.variables;d==="context"?i=!0:d==="global-device"?l=!0:d==="global-account"&&(c=!0),g[a]=ye(g[a],s,u)}),i){let a=o.historySequence;if(a&&a.length>0){let s=a[a.length-1];if(s.lines&&s.lines.length>0){let u=s.lines[s.lines.length-1];u.updateVariableIds||(u.updateVariableIds=[]),u.updateVariableIds.push(n)}}}if(l){let a=me(e.global.variables,e.projectData.resources?.variables,"global-device");e.global.pendingEffects.push({name:"saveGlobalDeviceVariables",payload:{globalDeviceVariables:a}})}if(c){let a=me(e.global.variables,e.projectData.resources?.variables,"global-account");e.global.pendingEffects.push({name:"saveGlobalAccountVariables",payload:{globalAccountVariables:a}})}return e.global.pendingEffects.push({name:"render"}),e},xr=(e,t)=>{let n=e?.story?.scenes||{};for(let r of Object.keys(n)){let i=n[r]?.sections||{};for(let l of Object.keys(i)){let a=i[l]?.lines||[];for(let s of a){if(s.actions?.updateVariable?.id===t)return s.actions.updateVariable;if(Array.isArray(s.actions?.updateVariables)){let u=s.actions.updateVariables.find(f=>f.id===t);if(u)return u}}}}},$e=({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.pointers.read?.sectionId,i=r.pointers.read?.lineId;if(!o||!i)return null;let c=r.historySequence?.find(f=>f.sectionId===o);if(!c?.lines||c.lines.length===0)return null;let a=c.lines.findLastIndex(f=>f.id===i);if(a===-1)return null;let s=a+n;if(s<0||s>=c.lines.length)return null;let u=c.lines[s];return{sectionId:o,lineId:u.id}},bt=({state:e})=>$e({state:e},{offset:-1})!==null,Ar=({state:e},t)=>{let{offset:n=-1}=t;if(n>=0)throw new Error("rollbackByOffset requires a negative offset");let r=$e({state:e},{offset:n});return r?It({state:e},{sectionId:r.sectionId,lineId:r.lineId}):e},It=({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 l=o.historySequence?.find(s=>s.sectionId===n);if(!l?.lines)throw new Error(`Section ${n} not found in history or has no lines`);let c=l.lines.findIndex(s=>s.id===r);if(c===-1)throw new Error(`Line ${r} not found in section ${n} history`);let a=l.initialState||{};o.variables={...a};for(let s=0;s<c;s++){let f=l.lines[s].updateVariableIds||[];for(let d of f){let h=xr(e.projectData,d);if(!h)throw new Error(`Action definition not found for ID: ${d}`);let g=h.operations||[];for(let{variableId:y,op:b,value:m}of g)e.projectData.resources?.variables?.[y]?.scope==="context"&&(o.variables[y]=ye(o.variables[y],b,m))}}return l.lines=l.lines.slice(0,c),l.lines.push({id:r}),o.pointers.read={sectionId:n,lineId:r},o.currentPointerMode="read",o.pointers.history={sectionId:null,lineId:null,historySequenceIndex:null},e.global.isLineCompleted=!1,e.global.pendingEffects.push({name:"render"}),e.global.pendingEffects.push({name:"handleLineActions"}),e},wt=e=>{let t=jn(e);return Fe(t,{selectPendingEffects:Un,selectSkipMode:st,selectAutoMode:Wn,selectDialogueUIHidden:at,selectDialogueHistory:xe,selectCurrentLocalizationPackageId:Yn,selectIsLineViewed:Ae,selectIsResourceViewed:Hn,selectNextLineConfig:Kn,selectSaveSlots:Jn,selectSaveSlot:qn,selectCurrentPointer:U,selectSection:C,selectCurrentLine:lt,selectPresentationState:ct,selectPresentationChanges:Xn,selectSectionLineChanges:Gn,selectAutoplayDelay:zn,selectCurrentPageSlots:ft,selectRenderState:Qn,selectLayeredViews:Fn,selectLineIdByOffset:$e,selectCanRollback:bt,startAutoMode:dt,stopAutoMode:Le,toggleAutoMode:rr,startSkipMode:pt,stopSkipMode:J,toggleSkipMode:or,showDialogueUI:ht,hideDialogueUI:gt,toggleDialogueUI:ir,showDialogueHistory:sr,hideDialogueHistory:ar,setCurrentLocalizationPackageId:lr,clearPendingEffects:cr,appendPendingEffect:ur,addViewedLine:yt,addViewedResource:fr,setNextLineConfig:dr,saveSaveSlot:hr,loadSaveSlot:gr,setAutoplayDelay:pr,updateProjectData:yr,sectionTransition:_r,jumpToLine:mr,addToHistorySequence:mt,addLineToHistory:q,nextLine:br,markLineCompleted:Ir,prevLine:wr,rollbackToLine:It,rollbackByOffset:Ar,pushLayeredView:Zn,popLayeredView:er,replaceLastLayeredView:tr,clearLayeredViews:nr,updateVariable:Er,nextLineFromSystem:vr},{transformActionFirstArgument:r=>({state:r}),transformSelectorFirstArgument:r=>({state:r})})};function Ce(e){let t,{handlePendingEffects:n}=e,r=()=>{for(;t.selectPendingEffects().length>0;){let h=[...t.selectPendingEffects()];t.clearPendingEffects(),n(h)}},o=({initialState:h})=>{t=wt(h),t.appendPendingEffect({name:"render"}),d(),r()},i=()=>t.selectPresentationState(),l=()=>t.selectPresentationChanges(),c=h=>t.selectSectionLineChanges(h),a=()=>t.selectRenderState(),s=()=>t.selectSaveSlots(),u=(h,g)=>{t[h]&&(t[h](g),r())},f=h=>{Object.entries(h).forEach(([g,y])=>{u(g,y)})},d=()=>{let h=t.selectCurrentLine();h?.actions&&f(h.actions)};return{init:o,handleAction:u,handleActions:f,selectRenderState:a,selectPresentationState:i,selectPresentationChanges:l,selectSectionLineChanges:c,selectSaveSlots:s,handleLineActions:d}}var Se=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:n=>{e=n},addElapsed:n=>{e+=n},getCallback:()=>t,setCallback:n=>{t=n}}},Lr=({engine:e,routeGraphics:t},n)=>{let r=e.selectRenderState();t.render(r)},$r=({engine:e},t)=>{e.handleLineActions()},Cr=({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 c=r.delay??1e3;n.getElapsed()>=c&&(n.setElapsed(0),e.handleAction("nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},Sr=({ticker:e,autoTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},kr=({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)},Or=({ticker:e,skipTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Rr=({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 c=r.delay??1e3;n.getElapsed()>=c&&(n.setElapsed(0),e.handleAction("nextLineFromSystem",{}),t.remove(i),n.setCallback(null))};n.setCallback(i),t.add(i)},Nr=({ticker:e,nextLineConfigTimerState:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Pr=({},e)=>{localStorage.setItem("saveSlots",JSON.stringify(e.saveSlots))},Tr=({},e)=>{localStorage.setItem("globalDeviceVariables",JSON.stringify(e.globalDeviceVariables))},Vr=({},e)=>{localStorage.setItem("globalAccountVariables",JSON.stringify(e.globalAccountVariables))},Dr={render:Lr,saveSlots:Pr,saveGlobalDeviceVariables:Tr,saveGlobalAccountVariables:Vr,handleLineActions:$r,startAutoNextTimer:Cr,clearAutoNextTimer:Sr,startSkipNextTimer:kr,clearSkipNextTimer:Or,nextLineConfigTimer:Rr,clearNextLineConfigTimer:Nr},Mr=({getEngine:e,routeGraphics:t,ticker:n})=>{let r=Se(),o=Se(),i=Se();return async l=>{let c=e(),a=l.reduce((f,d)=>(f[d.name]=d,f),{}),s=Object.values(a),u={engine:c,routeGraphics:t,ticker:n,autoTimer:r,skipTimer:o,nextLineConfigTimerState:i};for(let f of s){let d=Dr[f.name];d&&d(u,f.payload)}}},Br=Mr;var Po=Ce;export{Br as createEffectsHandler,Po as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "route-engine-js",
3
- "version": "0.1.24",
3
+ "version": "0.1.26",
4
4
  "description": "A lightweight Visual Novel engine built in JavaScript for creating interactive narrative games with branching storylines",
5
5
  "keywords": [
6
6
  "game-engine",