route-engine-js 0.1.21 → 0.1.22

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 Se=Symbol.for("immer-nothing"),Le=Symbol.for("immer-draftable"),C=Symbol.for("immer-state");function k(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[C]}function T(e){return e?Re(e)||Array.isArray(e)||!!e[Le]||!!e.constructor?.[Le]||q(e)||Q(e):!1}var bt=Object.prototype.constructor.toString();function Re(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 H(e,t){G(e)===0?Reflect.ownKeys(e).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function G(e){let t=e[C];return t?t.type_:Array.isArray(e)?1:q(e)?2:Q(e)?3:0}function se(e,t){return G(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Pe(e,t,n){let r=G(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 Q(e){return e instanceof Set}function N(e){return e.copy_||e.base_}function ae(e,t){if(q(e))return new Map(e);if(Q(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let n=Re(e);if(t===!0||t==="class_only"&&!n){let r=Object.getOwnPropertyDescriptors(e);delete r[C];let o=Reflect.ownKeys(r);for(let i=0;i<o.length;i++){let a=o[i],l=r[a];l.writable===!1&&(l.writable=!0,l.configurable=!0),(l.get||l.set)&&(r[a]={configurable:!0,writable:!0,enumerable:l.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 Z(e)||j(e)||!T(e)||(G(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(){k(2)}function Z(e){return Object.isFrozen(e)}var _t={};function V(e){let t=_t[e];return t||k(0,e),t}var U;function Ne(){return U}function vt(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function $e(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 Ce(e){return U=vt(U,e)}function Et(e){let t=e[C];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[C].modified_&&(le(t),k(4)),T(e)&&(e=J(t,e),t.parent_||X(t,e)),t.patches_&&V("Patches").generateReplacementPatches_(n[C].base_,e,t.patches_,t.inversePatches_)):e=J(t,n,[]),le(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Se?e:void 0}function J(e,t,n){if(Z(t))return t;let r=t[C];if(!r)return H(t,(o,i)=>ke(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return X(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),H(i,(l,c)=>ke(e,r,o,l,c,n,a)),X(e,o,!1),n&&e.patches_&&V("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function ke(e,t,n,r,o,i,a){if(j(o)){let l=i&&t&&t.type_!==3&&!se(t.assigned_,r)?i.concat(r):void 0,c=J(e,o,l);if(Pe(n,r,c),j(c))e.canAutoFreeze_=!1;else return}else a&&n.add(o);if(T(o)&&!Z(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;J(e,o),(!t||!t.scope_.parent_)&&typeof r!="symbol"&&Object.prototype.propertyIsEnumerable.call(n,r)&&X(e,o)}}function X(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&de(t,n)}function At(e,t){let n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:Ne(),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:l}=Proxy.revocable(o,i);return r.draft_=l,r.revoke_=a,l}var pe={get(e,t){if(t===C)return e;let n=N(e);if(!se(n,t))return xt(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 N(e)},ownKeys(e){return Reflect.ownKeys(N(e))},set(e,t,n){let r=Te(N(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){let o=oe(N(e),t),i=o?.[C];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=N(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){k(11)},getPrototypeOf(e){return B(e.base_)},setPrototypeOf(){k(12)}},W={};H(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[C];return(n?N(n):e)[t]}function xt(e,t,n){let r=Te(t,n);return r?"value"in r?r.value:r.get?.call(e.draft_):void 0}function Te(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(c=i,...s){return a.produce(c,u=>n.call(this,u,...s))}}typeof n!="function"&&k(6),r!==void 0&&typeof r!="function"&&k(7);let o;if(T(t)){let i=Ce(this),a=fe(t,void 0),l=!0;try{o=n(a),l=!1}finally{l?le(i):ce(i)}return $e(i,r),Oe(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===Se&&(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 k(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(a,...l)=>this.produceWithPatches(a,c=>t(c,...l));let r,o;return[this.produce(t,n,(a,l)=>{r=a,o=l}),r,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){T(e)||k(8),j(e)&&(e=$t(e));let t=Ce(this),n=fe(e,void 0);return n[C].isManual_=!0,ce(t),n}finishDraft(e,t){let n=e&&e[C];(!n||!n.isManual_)&&k(9);let{scope_:r}=n;return $e(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):Q(e)?V("MapSet").proxySet_(e,t):At(e,t);return(t?t.scope_:Ne()).drafts_.push(n),n}function $t(e){return j(e)||k(10,e),Ve(e)}function Ve(e){if(!T(e)||Z(e))return e;let t=e[C],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 H(n,(r,o)=>{Pe(n,r,Ve(o))}),t&&(t.finalized_=!1),n}var O=new Lt,he=O.produce,Mr=O.produceWithPatches.bind(O),Br=O.setAutoFreeze.bind(O),jr=O.setUseStrictShallowCopy.bind(O),Fr=O.applyPatches.bind(O),Ur=O.createDraft.bind(O),Wr=O.finishDraft.bind(O);var De=(e,t,n={})=>{let r=structuredClone(e),o={},i={},{transformSelectorFirstArgument:a=c=>c,transformActionFirstArgument:l=c=>c}=n;for(let[c,s]of Object.entries(t))c!=="createInitialState"&&(c.startsWith("select")?o[c]=(...u)=>s(a(r),...u):i[c]=(...u)=>{r=he(r,d=>s(l(d),...u))});return{...o,...i}},ee=(e,t)=>n=>{let r=e(),o=Array.isArray(n)?n:[n];return he(r,i=>{o.forEach(a=>{t.forEach(l=>{l(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{}}},Me=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}},Be=(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(", ")}`)},je=(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(", ")}`)},Fe=(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)),Ue=(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()))},ye=(e={},t={})=>{let n={},r=["sfx","voice"],o=i=>{let a=e[i],l=t[i];l&&!a?n[i]={changeType:"add",data:l}:a&&!l?r.includes(i)||(n[i]={changeType:"delete",data:a}):a&&l&&JSON.stringify(a)!==JSON.stringify(l)&&(n[i]={changeType:"update",data:l})};return o("background"),o("base"),o("bgm"),o("voice"),o("dialogue"),o("choice"),o("layout"),o("animation"),o("keyboard"),o("character"),o("visual"),o("sfx"),n};var Ot=()=>({}),kt=(e,t)=>{t.base&&(e.base={...t.base})},St=(e,t)=>{if(t.background){if(!t.background.resourceId){delete e.background;return}e.background={...t.background}}else e.background?.animations&&(e.background.animations={})},Rt=(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},Nt=(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}}},Tt=(e,t)=>{t.visual?e.visual=t.visual:e.visual?.items&&(e.visual.items=e.visual.items.map(n=>n.animations?{...n,animations:{}}:n))},Vt=(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)},Dt=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},Mt=(e,t)=>{t.layout?e.layout=t.layout:e.layout&&delete e.layout},Bt=(e,t)=>{t.choice?e.choice=t.choice:e.choice&&delete e.choice},jt=(e,t)=>{t.keyboard&&(e.keyboard=t.keyboard)},Ft=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},Ut=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(n=>{delete e[n]})},z=e=>ee(Ot,[Ut,kt,St,Pt,Nt,Tt,Rt,Vt,Dt,Mt,Bt,jt,Ft])(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},v={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}')`)},We=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 ze=(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}'`)},Ye=(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 Wt=(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 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 Yt(e.parts,t,n,r);switch(e.type){case p.FUNCTION:return He(e,t,n,r);case p.BINARY:return Je(e,t,n,r);case p.UNARY:return Xe(e,t,n,r);case p.CONDITIONAL:return Ht(e,t,n,r);case p.LOOP:return Qt(e,t,n,r);case p.OBJECT:return en(e,t,n,r);case p.ARRAY:return tn(e,t,n,r);case p.PARTIAL:return nn(e,t,n,r);case p.PATH_REFERENCE:return rn(e,t,n,r);default:throw new Error(`Unknown node type: ${e.type}`)}},Ke=new Map,zt=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 l=a.slice(1,-1);t.push({type:"property",value:l})}else t.push({type:"property",value:a});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=Ke.get(e);if(!r){let i=[],a="",l=0;for(let c=0;c<e.length;c++){let s=e[c];s==="["?(l++,a+=s):s==="]"?(l--,a+=s):s==="."&&l===0?a&&(i.push(a),a=""):a+=s}a&&i.push(a),r=[];for(let c of i){let s=zt(c.trim());r.push(...s)}Ke.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},Yt=(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("")},He=(e,t,n,r)=>{let o=t.functions||t,i=o[e.name];if(!i)throw Ye(e.name,o);let a=e.args.map(l=>_(l,t,n,r));return i(...a)},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 Je(e,t,n,r);case p.UNARY:return Xe(e,t,n,r);case p.FUNCTION:return He(e,t,n,r);default:return _(e,t,n,r)}},Je=(e,t,n,r)=>{if(e.op===v.AND||e.op===v.OR){let a=F(e.left,t,n,r),l=F(e.right,t,n,r);switch(e.op){case v.AND:return a&&l;case v.OR:return a||l}}let o=_(e.left,t,n,r),i=_(e.right,t,n,r);switch(e.op){case v.EQ:return o==i;case v.NEQ:return o!=i;case v.GT:return o>i;case v.LT:return o<i;case v.GTE:return o>=i;case v.LTE:return o<=i;case v.IN:return Array.isArray(i)?i.includes(o):!1;case v.ADD:if(typeof o!="number"||typeof i!="number")throw new L(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case v.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}`)}},Xe=(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}`)},Kt=(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 a=e.bodies[0];if(a.type===p.OBJECT&&a.properties.length<=5){let l={};for(let c of a.properties){let s=c.parsedKey?_(c.parsedKey,t,n,r):c.key,u=c.value;if(u.type===p.LITERAL)l[s]=u.value;else if(u.type===p.VARIABLE)l[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):"")}l[s]=f.join("")}else l[s]=_(u,t,n,r)}return l}}else{let a=e.bodies[1];if(a.type===p.OBJECT&&a.properties.length<=5){let l={};for(let c of a.properties){let s=c.parsedKey?_(c.parsedKey,t,n,r):c.key,u=c.value;if(u.type===p.LITERAL)l[s]=u.value;else if(u.type===p.VARIABLE)l[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):"")}l[s]=f.join("")}else l[s]=_(u,t,n,r)}return l}}}return null},Ht=(e,t,n,r)=>{let o=Kt(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 Ge},Jt=(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 c of i.properties)if(c.parsedKey)return null;let l=[];for(let c=0;c<t.length;c++){let s=t[c];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),E=s[w];g.push(E!=null?String(E):"")}else{y=!1;break}}else{y=!1;break}if(!y)return null;u[d]=g.join("")}else return null}l.push(u)}}return l}}}return null},Xt=(e,t)=>{let n=e.body,r=e.itemVar,o=Jt(e,t);if(o!==null)return o;if(n.type===p.OBJECT&&n.properties.length<=5&&!n.whenCondition){for(let l of n.properties)if(l.parsedKey)return null;let i=[],a=!0;for(let l of n.properties){let c=l.key,s=l.value;if(s.type===p.LITERAL)i.push({key:c,type:"literal",value:s.value});else if(s.type===p.VARIABLE){let u=s.path;if(u===r)i.push({key:c,type:"item"});else if(u.startsWith(r+".")){let f=u.substring(r.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:c,type:"prop",prop:f});else{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:c,type:"item_string"});else if(f.startsWith(r+".")){let d=f.substring(r.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:c,type:"prop_string",prop:d});else{a=!1;break}}else{a=!1;break}}else{a=!1;break}}else{a=!1;break}}if(a){let l=new Array(t.length);if(i.length===3&&i[0].type==="prop"&&i[0].key==="id"&&i[1].type==="prop_string"&&i[1].key==="title"&&i[2].type==="prop"&&i[2].key==="completed")for(let c=0;c<t.length;c++){let s=t[c];l[c]={id:s.id,title:s.title!=null?String(s.title):"",completed:s.completed}}else for(let c=0;c<t.length;c++){let s=t[c],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):""}l[c]=u}return l}}return null},Gt=(e,t,n,r,o)=>{let i=[],a=e.body;if(a.type===p.OBJECT&&a.fast!==!1){let l=e.itemVar,c=e.indexVar;for(let s=0;s<o.length;s++){let u=o[s],f={},d={...r,[l]:u,...c&&{[c]: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__,[l]:`${h}[${s}]`,...c&&{[c]: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===l)f[y]=u;else if(b===c)f[y]=s;else if(b.startsWith(l+".")){let w=b.substring(l.length+1);!w.includes(".")&&!w.includes("[")?f[y]=u[w]:f[y]=A(b,n,{...r,[l]:u,...c&&{[c]:s}})}else f[y]=A(b,n,{...r,[l]:u,...c&&{[c]: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 E=w.path,S;if(E===l)S=u;else if(E===c)S=s;else if(E.startsWith(l+".")){let re=E.substring(l.length+1);!re.includes(".")&&!re.includes("[")?S=u[re]:S=A(E,n,{...r,[l]:u,...c&&{[c]:s}})}else S=A(E,n,{...r,[l]:u,...c&&{[c]:s}});b.push(S!=null?String(S):"")}else{let E={...r,[l]:u,...c&&{[c]:s}},S=_(w,t,n,E);b.push(S!=null?String(S):"")}f[y]=b.join("")}else{let b={...r,[l]:u,...c&&{[c]: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 l=a.properties[0],c=a.properties[1];if(l.key==="id"&&l.value.type===p.VARIABLE&&l.value.path==="item.id"&&c.key==="$if item.highlighted"&&c.value.type===p.CONDITIONAL){let 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},Qt=(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 ze(f,o,u)}if(!e.indexVar){let s=qt(e,o,e.itemVar);if(s!==null)return s}if(!e.indexVar){let s=Xt(e,o);if(s!==null)return s}let i=Gt(e,t,n,r,o);if(i!==null)return i;let a=[],l=e.iterable.path||"";if(r&&r.__paths__&&l){let s=l.split("."),u=s[0];u in r.__paths__&&(l=r.__paths__[u],s.length>1&&(l+="."+s.slice(1).join(".")))}let c=!1;e.body.type===p.ARRAY&&(e.body.items.length<=1?c=!1:c=e.body._shouldPreserveArray??=e.body.items.some(s=>s.type===p.OBJECT&&s.properties.some(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]:`${l}[${s}]`},e.indexVar&&(u.__paths__[e.indexVar]=s);let f=_(e.body,t,n,u);if(Array.isArray(f)&&f.length===1&&!c){let d=f[0];a.push(d===void 0?{}:d)}else a.push(f===void 0?{}:f)}return a},Zt=(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 l={},c={},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)c[f]=d.value;else if(d.type===p.VARIABLE)c[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;c[f]=h.join("")}else if(d.type===p.OBJECT&&d.properties.length<=5){let h={};for(let g of d.properties){let y=g.key,m=g.value;if(m.type===p.LITERAL)h[y]=m.value;else if(m.type===p.VARIABLE)h[y]=A(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 E=A(w.path,n,r);b.push(E!=null?String(E):"")}else{s=!1;break}if(!s)break;h[y]=b.join("")}else{s=!1;break}}if(!s)break;c[f]=h}else{s=!1;break}}if(s)return l[i]=c,l}}return null},en=(e,t,n,r)=>{let o=t.functions||t;if(e.whenCondition&&!F(e.whenCondition,o,n,r))return;let i=Zt(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 a={},l=null,c=!1;for(let s of e.properties)if(!s.key.startsWith("$if ")&&!s.key.match(/^\$if\s+\w+.*:?$/)&&!s.key.startsWith("$elif")&&!s.key.startsWith("$else")&&!s.key.startsWith("$for ")){c=!0;break}for(let s of e.properties)if(s.key.startsWith("$if ")||s.key.match(/^\$if\s+\w+.*:?$/)){let u=_(s.value,t,n,r);if(!c&&u!==null&&u!==void 0)return Array.isArray(u)&&u.length===1?u[0]:u;typeof u=="object"&&u!==null&&!Array.isArray(u)&&Object.assign(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},Ge={},tn=(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!==Ge&&a!==void 0&&o.push(a)}return o},nn=(e,t,n,r)=>{let{name:o,data:i,whenCondition:a}=e,l=t.partials||{},c=t.functions||t;if(a&&!F(a,c,n,r))return;if(!l[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=l[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)},rn=(e,t,n,r)=>{let{path:o}=e,i=o.split("."),a=i[0],l=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 c=r.__paths__[a];if(typeof c=="number"){if(l.length>0)throw new L(`Path reference '#{${o}}' - cannot access properties on index variable '${a}'`);return String(c)}return l.length>0&&(c+="."+l.join(".")),c},be=Wt;var on=/\$\{([^}]*)\}/g,sn=/#\{([^}]*)\}/g,Qe=(e,t={})=>{let n=e.match(/^(\w+)\((.*)\)$/);if(!n)return{isFunction:!1};let[,r,o]=n,i=an(o,t);return{isFunction:!0,type:p.FUNCTION,name:r,args:i}},an=(e,t={})=>e.trim()?ln(e).map(r=>cn(r.trim(),t)):[],ln=e=>{let t=[],n="",r=0,o=!1,i="";for(let a=0;a<e.length;a++){let l=e[a],c=a>0?e[a-1]:"";!o&&(l==='"'||l==="'")?(o=!0,i=l,n+=l):o&&l===i&&c!=="\\"?(o=!1,i="",n+=l):!o&&l==="("?(r++,n+=l):!o&&l===")"?(r--,n+=l):!o&&l===","&&r===0?(t.push(n),n=""):n+=l}return n&&t.push(n),t},cn=(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=Qe(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:l,type:c}of o){let s=0;for(;s<r.length;){let u=D(r.substring(s),l);if(u===-1)break;let f=s+u;f>i&&(i=f,a={op:l,type:c}),s=f+l.length}}if(i!==-1)try{return x(r,t)}catch{return{type:p.VARIABLE,path:r}}return{type:p.VARIABLE,path:r}},Ze=/^\w+\(.*\)$/,un=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,fn=e=>{if(!(!e||e.trim()===""||Ze.test(e))&&un.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(Ze.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();fn(n);let r=Qe(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(on)],i=[...n.matchAll(sn)],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 l=[],c=0;for(let{match:s,type:u}of a){let[f,d]=s,h=s.index;if(h>c){let g=n.substring(c,h);for(let y=0;y<r.length;y++)g=g.replace(`__ESCAPED_${y}__`,r[y]);g&&l.push(g)}try{let g;u==="variable"?g=K(d.trim(),t):g=qe(d.trim()),l.push(g)}catch(g){if(g.message==="Invalid array index syntax")l.push(f);else throw g}c=h+f.length}if(c<n.length){let s=n.substring(c);for(let u=0;u<r.length;u++)s=s.replace(`__ESCAPED_${u}__`,r[u]);s&&l.push(s)}return{type:p.INTERPOLATION,parts:l}};var P=(e,t)=>typeof e=="string"?Ie(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?pn(e,t):hn(e,t):{type:p.LITERAL,value:e},dn=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}},pn=(e,t)=>{let n=[],r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(typeof i=="object"&&i!==null&&!Array.isArray(i)){if(i.$each!==void 0)try{let c=dn(i),s=Object.keys(c);if(s.length===1&&/^\$for(?::\w+)?\s/.test(s[0])){let u=et(s[0],c[s[0]],t,!0);n.push(u),r=!0;continue}}catch(c){throw c instanceof I?c:new I(c.message)}let l=Object.keys(i);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let c=et(l[0],i[l[0]],t);n.push(c),r=!0;continue}}let a=P(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}},hn=(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 c=["$if","$elif","$else","$for"],s=[];for(let[b]of i)for(let w of c)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 E=b;(b.startsWith("\\$")||b.startsWith("$$"))&&(E=b.slice(1)),h[E]=w,g=!0}let y=null;if(g&&(y=P(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=x(f,t)}else b={type:p.LITERAL,value:f};m.whenCondition=b}return m}for(let[c,s]of i)if(c==="$when"){if(o!==null)throw new 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=x(u,t),r=!0}else if(c.startsWith("$when#")||c.startsWith("$when "))throw new I("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;a<i.length;){let[c,s]=i[a];if(c==="$when"){a++;continue}if(c==="$each")throw new I("$each can only be used inside arrays");if(c.startsWith("$if ")||c.match(/^\$if#\w+\s/)||c.match(/^\$if\s+\w+.*:$/)){let u=gn(i,a,t);n.push({key:c,value:u.node}),r=!0,a=u.nextIndex}else if(/^\$for(?::\w+)?\s/.test(c)){let u=c.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(c.startsWith("$elif ")||c.startsWith("$else"))throw new I(`'${c.split(" ")[0]}' without matching '$if'`);if(c==="$if"||c==="$if:")throw new I("Missing condition expression after '$if'");{let u=P(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(c,t),d={key:c,value:u};(f.type!==p.LITERAL||f.value!==c)&&(d.parsedKey=f),n.push(d),a++}}}let l={type:p.OBJECT,properties:n,fast:!r};return o&&(l.whenCondition=o),l},gn=(e,t,n={})=>{let r=[],o=[],i=t,[a,l]=e[i],c=null,s;if(a.startsWith("$if#")){let f=a.match(/^\$if#(\w+)\s+(.+)$/);if(f)c=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=x(s,n);for(r.push(u),o.push(P(l,n)),i++;i<e.length;){let[f,d]=e[i],h=!1,g;if(c?f.startsWith(`$elif#${c} `)?(g=f.substring(`$elif#${c} `.length),g.endsWith(":")&&(g=g.slice(0,-1).trim()),h=!0):(f===`$else#${c}`||f===`$else#${c}:`)&&(h=!0,g=null):f.startsWith("$elif ")?(g=f.substring(6),g.endsWith(":")&&(g=g.slice(0,-1).trim()),h=!0):(f==="$else"||f==="$else:")&&(h=!0,g=null),h){if(g===null)r.push(null);else{me(g);let y=x(g,n);r.push(y)}if(o.push(P(d,n)),i++,g===null)break}else break}return{node:{type:p.CONDITIONAL,conditions:r,bodies:o,id:c},nextIndex:i}},x=(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 x(s,t)}let n=D(e,"||");if(n!==-1)return{type:p.BINARY,op:v.OR,left:x(e.substring(0,n).trim(),t),right:x(e.substring(n+2).trim(),t)};let r=D(e,"&&");if(r!==-1)return{type:p.BINARY,op:v.AND,left:x(e.substring(0,r).trim(),t),right:x(e.substring(r+2).trim(),t)};let o=[{op:">=",type:v.GTE},{op:"<=",type:v.LTE},{op:"==",type:v.EQ},{op:"!=",type:v.NEQ},{op:">",type:v.GT},{op:"<",type:v.LT},{op:" in ",type:v.IN}];for(let{op:s,type:u}of o){let f=D(e,s);if(f!==-1)return{type:p.BINARY,op:u,left:x(e.substring(0,f).trim(),t),right:x(e.substring(f+s.length).trim(),t)}}let i=-1,a=null,l=[{op:" + ",type:v.ADD},{op:" - ",type:v.SUBTRACT}];for(let{op:s,type:u}of l){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:x(e.substring(0,i).trim(),t),right:x(e.substring(i+a.op.length).trim(),t)};let c=[" * "," / "," % "];for(let s of c)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:x(e.substring(1).trim(),t)}:tt(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},yn=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}},tt=(e,t)=>{let n=e.trim();if(n.match(/^(\w+)\((.*)\)$/))return K(n,t);let o=yn(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}},mn=(e,t=!1)=>{let n=t?"$each":"$for";try{We(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}},et=(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],l=i[2].trim();mn(l,r);let c=l.match(/^(.+?)\s+in\s+(.+)$/);if(!c){let m=r?"$each":"$for";throw new I(`Invalid loop syntax - missing 'in' keyword (got: '${m} ${l}')`)}let s=c[1].trim(),u=c[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=tt(u,n),y=P(t,n);return{type:p.LOOP,itemVar:f,indexVar:d,iterable:g,body:y,flatten:a!=="nested"}};var bn=(e,t={})=>{let{functions:n={}}=t;return P(e,n)},te=bn;var we={};mt(we,{now:()=>In});var In=()=>Date.now();var wn=(e,t,n={})=>{let{functions:r={},partials:o={}}=n,i={...we,...r},a=te(e,{functions:i}),l={};for(let[c,s]of Object.entries(o))l[c]=te(s,{functions:i});return be(a,t,{functions:i,partials:l})},R=wn;var _e={objectValues:e=>Object.entries(e).map(([t,n])=>({id:t,...n})),formatDate:Ue},_n=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),vn=(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},En=(e,{presentationState:t,previousPresentationState:n,resources:r={},variables:o,autoMode:i,skipMode:a,currentLocalizationPackageId:l})=>{let{elements:c}=e,s=e.animations||[];if(t.background){let u=c.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(l=>l.id==="story");if(!i)return e;let a=t.character.items||[];for(let l=0;l<a.length;l++){let c=a[l],{transformId:s,sprites:u}=c;if(c.animations&&c.animations.out&&!u&&!s){let y=c.animations.out.resourceId,m=n?.tweens[y];if(m){let b={id:"character-animation-out",type:"tween",targetId:`character-container-${c.id}`,properties:m.properties};o.push(b)}continue}if(!u||u.length===0||!s){console.warn("Character item missing sprites or transformId:",c);continue}let f=u.map(({resourceId:y})=>y),d=`character-container-${c.id}-${l}-${f.join("-")}`,h=n.transforms[s];if(!h){console.warn("Transform not found:",s);continue}let g={type:"container",id:d,x:c.x??h.x,y:c.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),c.animations){if(c.animations.in){let y=c.animations.in.resourceId,m=n?.tweens[y];m&&o.push({id:"character-animation-in",type:"tween",targetId:d,properties:m.properties})}if(c.animations.update){let y=c.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},xn=(e,{presentationState:t,resources:n})=>{let{elements:r}=e,o=e.animations||[];if(t.visual&&n){let i=r.find(l=>l.id==="story");if(!i)return e;let a=t.visual.items;for(let l of a){if(l.resourceId){let{images:c={},videos:s={},spritesheets:u={}}=n,f=u[l.resourceId];if(f){let d=n.transforms?.[l.transformId]||{},h=l.animationName;if(h){let g=f.animations?.[h];if(!g)throw new Error(`Animation '${h}' not found in spritesheet resource '${l.resourceId}'`);let y={id:`visual-${l.id}`,type:"animated-sprite",x:l.x??d.x??0,y:l.y??d.y??0,width:l.width??100,height:l.height??100,alpha:l.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:l.animationSpeed??g.animationSpeed??.5,loop:l.loop??g.loop??!0}};i.children.push(y)}}else{let d=c[l.resourceId]||s[l.resourceId];if(d){let h=s[l.resourceId]!==void 0,g=n.transforms[l.transformId],y={id:`visual-${l.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(l.resourceId){let{layouts:c={}}=n,s=c[l.resourceId];if(s){let u=n.transforms[l.transformId];i.children.push({id:`visual-${l.id}`,type:"container",children:s.elements,x:u.x,y:u.y,anchorX:u.anchorX,anchorY:u.anchorY,rotation:u.rotation,scaleX:u.scaleX,scaleY:u.scaleY})}}if(l.animations){if(l.animations.in){let c=l.animations.in.resourceId||l.animations.in,s=n?.tweens[c];s&&o.push({id:`${l.id}-animation`,type:"tween",targetId:`visual-${l.id}`,properties:s.properties})}if(l.animations.out){let c=l.animations.out.resourceId||l.animations.out,s=n?.tweens[c];s&&o.push({id:`${l.id}-animation-2`,type:"tween",targetId:`visual-${l.id}`,properties:s.properties})}}}}return e},Ln=(e,{presentationState:t,resources:n={},dialogueUIHidden:r,autoMode:o,skipMode:i,skipOnlyViewedLines:a,l10n:l,variables:c,saveSlots:s=[]})=>{let{elements:u}=e;if(!t.dialogue||r)return e;let f=u.find(d=>d.id==="story");if(!f)return e;if(t.dialogue.gui&&t.dialogue.gui.resourceId){let{layouts:d={}}=n,h=d[t.dialogue.gui.resourceId];if(h){let g;t.dialogue.characterId&&(g=n.characters[t.dialogue.characterId]),t.dialogue.character&&(g={...g,name:t.dialogue.character.name});let y={elements:h.elements},m={variables:c,autoMode:o,skipMode:i,skipOnlyViewedLines:a,saveSlots:s,dialogue:{character:{name:g?.name||""},content:t.dialogue?.content||[{text:""}],lines:t.dialogue?.lines||[]},l10n:l},b=R(y,m,{functions:_e});b=R(b,{l10n:l});let w=b?.elements;if(Array.isArray(w))for(let E of w)f.children.push(structuredClone(E));else w&&f.children.push(structuredClone(w))}}return e},$n=(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},c=R(a,{choice:{items:t.choice?.items??[]}})?.elements;if(Array.isArray(c))for(let s of c)o.children.push(structuredClone(s));else c&&o.children.push(structuredClone(c))}return e},Cn=(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(l=>l.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},kn=(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},Sn=(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},Rn=(e,{presentationState:t,resources:n={},variables:r,autoMode:o,skipMode:i,currentLocalizationPackageId:a,saveSlots:l=[]})=>{let{elements:c}=e,s=e.animations||[];if(t.layout){let u=c.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:l,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:l=[],saveSlots:c=[]})=>{let{elements:s}=e,u=e.animations||[];return a&&a.length>0&&a.forEach((f,d)=>{let h=t.layouts[f.resourceId];if(!h){console.warn(`LayeredView layout not found: ${f.resourceId}`);return}Array.isArray(h.transitions)&&h.transitions.forEach(w=>{u.push(w)});let g={id:`layeredView-${d}`,type:"container",x:0,y:0,children:h.elements||[]},y=l.map(w=>{let E=t.characters?.[w.characterId];return{...w,characterName:E?.name||""}}),m={variables:n,autoMode:r,skipMode:o,currentLocalizationPackageId:i,saveSlots:c,historyDialogue:y,characters:t.characters||{}},b=R(g,m,{functions:_e});b=R(b,{i18n:{}}),s.push(b)}),e},nt=e=>ee(_n,[vn,En,An,xn,Ln,$n,Cn,Rn,On,kn,Sn,Pn])(e);var Nn=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:l}=Me(o),c={...l,...r},s={projectData:o,global:{autoplayDelay:1e3,isLineCompleted:!1,pendingEffects:[],autoMode:!1,skipMode:!1,skipOnlyViewedLines:!0,dialogueUIHidden:!1,isDialogueHistoryShowing:!1,currentLocalizationPackageId:t,viewedRegistry:{sections:[],resources:[]},nextLineConfig:{manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1}},saveSlots:n,layeredViews:[],variables:c},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},Tn=({state:e})=>e.global.layeredViews||[],Vn=({state:e})=>e.global.pendingEffects,rt=({state:e})=>e.global.skipMode,Dn=({state:e})=>e.global.skipOnlyViewedLines,Mn=({state:e})=>e.global.autoMode,ot=({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(c=>c.id===r);return o.lines.slice(0,i+1).filter(c=>c.actions?.dialogue).map(c=>{let s=c.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,it=({state:e},t)=>{let{sectionId:n,lineId:r}=t,o=e.global.viewedRegistry.sections.find(c=>c.sectionId===n);if(!o)return!1;if(o.lastLineId===void 0||r===void 0)return!0;let i=$({state:e},{sectionId:n});if(!i||!i.lines||!Array.isArray(i.lines))return!1;let a=i.lines.findIndex(c=>c.id===o.lastLineId),l=i.lines.findIndex(c=>c.id===r);return a===-1||l===-1?o.lastLineId===r:l<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 l=a.map(s=>{let u=s.actions||{},f={};return Object.keys(u).forEach(d=>{f[d]=u[d]}),f});return z(l)},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||{},l=z([o,a]),c=ye(o,l);r.push({id:i.id,changes:c}),o=l}return{lines:r}},lt=({state:e})=>{let{sectionId:t,lineId:n}=M({state:e}).pointer,o=$({state:e},{sectionId:t})?.lines||[],i=o.findIndex(c=>c.id===n);if(i<=0)return null;let l=o.slice(0,i).map(c=>{let s=c.actions||{},u={};return Object.keys(s).forEach(f=>{u[f]=s[f]}),u});return z(l)},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 l=o+a,c=e.global.saveSlots&&e.global.saveSlots[l]||{};i.push({slotNumber:l,...c})}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=nt({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:e.global.skipOnlyViewedLines,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),Ee=({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?Ee({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),ne=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Zn=({state:e})=>(rt({state:e})?ne({state:e}):ft({state:e}),e),er=({state:e},t)=>{let{skipOnlyViewedLines:n}=t;return e.global.skipOnlyViewedLines=n,e.global.pendingEffects.push({name:"render"}),e},tr=({state:e})=>(e.global.skipOnlyViewedLines=!e.global.skipOnlyViewedLines,e.global.pendingEffects.push({name:"render"}),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),nr=({state:e})=>(ot({state:e})?dt({state:e}):pt({state:e}),e),rr=({state:e})=>{let t=ve({state:e});return e.global.isDialogueHistoryShowing=!0,e.global.pendingEffects.push({name:"render"}),e},or=({state:e})=>(e.global.isDialogueHistoryShowing=!1,e.global.pendingEffects.push({name:"render"}),e),ir=({state:e},t)=>{let{localizationPackageId:n}=t;return e.global.currentLocalizationPackageId=n,e.global.pendingEffects.push({name:"render"}),e},sr=({state:e})=>(e.global.pendingEffects=[],e),ar=({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(c=>c.id===o.lastLineId),l=i.lines.findIndex(c=>c.id===r);(a===-1||l>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},lr=({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},cr=({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},ur=({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),fr=({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},dr=({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},pr=({state:e},t)=>{let{projectData:n}=t;return e.projectData=n,e.global.pendingEffects.push({name:"render"}),e},hr=({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(c=>c.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)},gr=({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},yr=({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(l=>l.id===t?.lineId)+1;if(a<o.length){let l=o[a],c=e.contexts[e.contexts.length-1];c&&(c.pointers.read={sectionId:n,lineId:l.id}),e.global.isLineCompleted=!1,e.global.nextLineConfig.auto={},e.global.pendingEffects.push({name:"render"}),e.global.pendingEffects.push({name:"handleLineActions"})}return e},mr=({state:e})=>{if(!e.global.nextLineConfig.manual.enabled)return e;let t=M({state:e})?.pointer,n=t?.sectionId,o=$({state:e},{sectionId:n})?.lines||[],a=o.findIndex(l=>l.id===t?.lineId)+1;if(a<o.length){let l=o[a];e.global.skipMode&&e.global.skipOnlyViewedLines&&(it({state:e},{sectionId:n,lineId:l.id})||ne({state:e}));let c=e.contexts[e.contexts.length-1];if(c){let s=c.pointers.read.lineId;s&&n&&ht({state:e},{sectionId:n,lineId:s}),c.pointers.read={sectionId:n,lineId:l.id}}e.global.isLineCompleted=!1,e.global.pendingEffects.push({name:"render"}),e.global.pendingEffects.push({name:"handleLineActions"})}else e.global.autoMode&&Ee({state:e}),e.global.skipMode&&ne({state:e});return console.log("state",e),e},br=({state:e})=>(e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"render"}),e),Ir=({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 c=o.findIndex(s=>s.id===i.pointers.history.lineId)-1;if(c>=0&&c<o.length){let s=o[c];i.pointers.history={sectionId:n,lineId:s.id},e.global.pendingEffects.push({name:"render"})}return e},wr=({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},_r=({state:e})=>{let t=M({state:e})?.pointer,n=t?.sectionId,o=$({state:e},{sectionId:n})?.lines||[],a=o.findIndex(l=>l.id===t?.lineId)+1;if(a<o.length){let l=o[a],c=e.contexts[e.contexts.length-1];c&&(c.pointers.read={sectionId:n,lineId:l.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},vr=({state:e},t)=>{let{operations:n=[]}=t,r=!1,o=!1;if(n.forEach(({variableId:i,op:a,value:l})=>{let c=e.projectData.resources?.variables?.[i],s=c?.scope,u=c?.type;Be(s,i),je(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]=Fe(f[i],a,l)}),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=Nn(e);return De(t,{selectPendingEffects:Vn,selectSkipMode:rt,selectSkipOnlyViewedLines:Dn,selectAutoMode:Mn,selectDialogueUIHidden:ot,selectDialogueHistory:ve,selectCurrentLocalizationPackageId:jn,selectIsLineViewed:it,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:Tn,startAutoMode:ut,stopAutoMode:Ee,toggleAutoMode:Qn,startSkipMode:ft,stopSkipMode:ne,toggleSkipMode:Zn,setSkipOnlyViewedLines:er,toggleSkipOnlyViewedLines:tr,showDialogueUI:dt,hideDialogueUI:pt,toggleDialogueUI:nr,showDialogueHistory:rr,hideDialogueHistory:or,setCurrentLocalizationPackageId:ir,clearPendingEffects:sr,appendPendingEffect:ar,addViewedLine:ht,addViewedResource:lr,setNextLineConfig:cr,saveSaveSlot:fr,loadSaveSlot:dr,setAutoplayDelay:ur,updateProjectData:pr,sectionTransition:wr,jumpToLine:hr,addToHistorySequence:gr,nextLine:mr,nextLineFromCompleted:yr,markLineCompleted:br,prevLine:Ir,pushLayeredView:Jn,popLayeredView:Xn,replaceLastLayeredView:Gn,clearLayeredViews:qn,updateVariable:vr,nextLineFromSystem:_r},{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(),l=h=>t.selectSectionLineChanges(h),c=()=>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:c,selectPresentationState:i,selectPresentationChanges:a,selectSectionLineChanges:l,selectSaveSlots:s,handleLineActions:d}}var xe=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:n=>{e=n},addElapsed:n=>{e+=n},getCallback:()=>t,setCallback:n=>{t=n}}},Er=({engine:e,routeGraphics:t},n)=>{let r=e.selectRenderState();t.render(r)},Ar=({engine:e},t)=>{e.handleLineActions()},xr=({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 l=r.delay??1e3;n.getElapsed()>=l&&(n.setElapsed(0),e.handleAction("nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},Lr=({ticker:e,autoTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},$r=({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)},Cr=({ticker:e,skipTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Or=({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 l=r.delay??1e3;n.getElapsed()>=l&&(n.setElapsed(0),e.handleAction("nextLineFromSystem",{}),t.remove(i),n.setCallback(null))};n.setCallback(i),t.add(i)},kr=({ticker:e,nextLineConfigTimerState:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Sr=({},e)=>{localStorage.setItem("saveSlots",JSON.stringify(e.saveSlots))},Rr=({},e)=>{localStorage.setItem("globalDeviceVariables",JSON.stringify(e.globalDeviceVariables))},Pr=({},e)=>{localStorage.setItem("globalAccountVariables",JSON.stringify(e.globalAccountVariables))},Nr={render:Er,saveSlots:Sr,saveGlobalDeviceVariables:Rr,saveGlobalAccountVariables:Pr,handleLineActions:Ar,startAutoNextTimer:xr,clearAutoNextTimer:Lr,startSkipNextTimer:$r,clearSkipNextTimer:Cr,nextLineConfigTimer:Or,clearNextLineConfigTimer:kr},Tr=({getEngine:e,routeGraphics:t,ticker:n})=>{let r=xe(),o=xe(),i=xe();return async a=>{let l=e(),c=a.reduce((f,d)=>(f[d.name]=d,f),{}),s=Object.values(c),u={engine:l,routeGraphics:t,ticker:n,autoTimer:r,skipTimer:o,nextLineConfigTimerState:i};for(let f of s){let d=Nr[f.name];d&&d(u,f.payload)}}},Vr=Tr;var So=Ae;export{Vr as createEffectsHandler,So as default};
1
+ var yt=Object.defineProperty;var mt=(e,t)=>{for(var n in t)yt(e,n,{get:t[n],enumerable:!0})};var Se=Symbol.for("immer-nothing"),Le=Symbol.for("immer-draftable"),C=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[C]}function T(e){return e?Re(e)||Array.isArray(e)||!!e[Le]||!!e.constructor?.[Le]||q(e)||Q(e):!1}var bt=Object.prototype.constructor.toString();function Re(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 H(e,t){G(e)===0?Reflect.ownKeys(e).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function G(e){let t=e[C];return t?t.type_:Array.isArray(e)?1:q(e)?2:Q(e)?3:0}function se(e,t){return G(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Pe(e,t,n){let r=G(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 Q(e){return e instanceof Set}function N(e){return e.copy_||e.base_}function ae(e,t){if(q(e))return new Map(e);if(Q(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let n=Re(e);if(t===!0||t==="class_only"&&!n){let r=Object.getOwnPropertyDescriptors(e);delete r[C];let o=Reflect.ownKeys(r);for(let i=0;i<o.length;i++){let a=o[i],l=r[a];l.writable===!1&&(l.writable=!0,l.configurable=!0),(l.get||l.set)&&(r[a]={configurable:!0,writable:!0,enumerable:l.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 Z(e)||j(e)||!T(e)||(G(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 Z(e){return Object.isFrozen(e)}var _t={};function V(e){let t=_t[e];return t||S(0,e),t}var U;function Ne(){return U}function vt(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function $e(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 Ce(e){return U=vt(U,e)}function Et(e){let t=e[C];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[C].modified_&&(le(t),S(4)),T(e)&&(e=J(t,e),t.parent_||X(t,e)),t.patches_&&V("Patches").generateReplacementPatches_(n[C].base_,e,t.patches_,t.inversePatches_)):e=J(t,n,[]),le(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Se?e:void 0}function J(e,t,n){if(Z(t))return t;let r=t[C];if(!r)return H(t,(o,i)=>ke(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return X(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),H(i,(l,c)=>ke(e,r,o,l,c,n,a)),X(e,o,!1),n&&e.patches_&&V("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function ke(e,t,n,r,o,i,a){if(j(o)){let l=i&&t&&t.type_!==3&&!se(t.assigned_,r)?i.concat(r):void 0,c=J(e,o,l);if(Pe(n,r,c),j(c))e.canAutoFreeze_=!1;else return}else a&&n.add(o);if(T(o)&&!Z(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;J(e,o),(!t||!t.scope_.parent_)&&typeof r!="symbol"&&Object.prototype.propertyIsEnumerable.call(n,r)&&X(e,o)}}function X(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&de(t,n)}function At(e,t){let n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:Ne(),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:l}=Proxy.revocable(o,i);return r.draft_=l,r.revoke_=a,l}var pe={get(e,t){if(t===C)return e;let n=N(e);if(!se(n,t))return xt(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 N(e)},ownKeys(e){return Reflect.ownKeys(N(e))},set(e,t,n){let r=Te(N(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){let o=oe(N(e),t),i=o?.[C];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=N(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={};H(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[C];return(n?N(n):e)[t]}function xt(e,t,n){let r=Te(t,n);return r?"value"in r?r.value:r.get?.call(e.draft_):void 0}function Te(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(c=i,...s){return a.produce(c,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=Ce(this),a=fe(t,void 0),l=!0;try{o=n(a),l=!1}finally{l?le(i):ce(i)}return $e(i,r),Oe(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===Se&&(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,...l)=>this.produceWithPatches(a,c=>t(c,...l));let r,o;return[this.produce(t,n,(a,l)=>{r=a,o=l}),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=Ce(this),n=fe(e,void 0);return n[C].isManual_=!0,ce(t),n}finishDraft(e,t){let n=e&&e[C];(!n||!n.isManual_)&&S(9);let{scope_:r}=n;return $e(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):Q(e)?V("MapSet").proxySet_(e,t):At(e,t);return(t?t.scope_:Ne()).drafts_.push(n),n}function $t(e){return j(e)||S(10,e),Ve(e)}function Ve(e){if(!T(e)||Z(e))return e;let t=e[C],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 H(n,(r,o)=>{Pe(n,r,Ve(o))}),t&&(t.finalized_=!1),n}var O=new Lt,he=O.produce,Mr=O.produceWithPatches.bind(O),Br=O.setAutoFreeze.bind(O),jr=O.setUseStrictShallowCopy.bind(O),Fr=O.applyPatches.bind(O),Ur=O.createDraft.bind(O),Wr=O.finishDraft.bind(O);var De=(e,t,n={})=>{let r=structuredClone(e),o={},i={},{transformSelectorFirstArgument:a=c=>c,transformActionFirstArgument:l=c=>c}=n;for(let[c,s]of Object.entries(t))c!=="createInitialState"&&(c.startsWith("select")?o[c]=(...u)=>s(a(r),...u):i[c]=(...u)=>{r=he(r,d=>s(l(d),...u))});return{...o,...i}},ee=(e,t)=>n=>{let r=e(),o=Array.isArray(n)?n:[n];return he(r,i=>{o.forEach(a=>{t.forEach(l=>{l(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{}}},Me=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}},Be=(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(", ")}`)},je=(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(", ")}`)},Fe=(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)),Ue=(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()))},ye=(e={},t={})=>{let n={},r=["sfx","voice"],o=i=>{let a=e[i],l=t[i];l&&!a?n[i]={changeType:"add",data:l}:a&&!l?r.includes(i)||(n[i]={changeType:"delete",data:a}):a&&l&&JSON.stringify(a)!==JSON.stringify(l)&&(n[i]={changeType:"update",data:l})};return o("background"),o("base"),o("bgm"),o("voice"),o("dialogue"),o("choice"),o("layout"),o("animation"),o("keyboard"),o("character"),o("visual"),o("sfx"),n};var Ot=()=>({}),kt=(e,t)=>{t.base&&(e.base={...t.base})},St=(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={})},Rt=(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},Nt=(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}}},Tt=(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))},Vt=(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)},Dt=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},Mt=(e,t)=>{t.layout?e.layout=t.layout:e.layout&&delete e.layout},Bt=(e,t)=>{t.choice?e.choice=t.choice:e.choice&&delete e.choice},jt=(e,t)=>{t.keyboard&&(e.keyboard=t.keyboard)},Ft=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},Ut=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(n=>{delete e[n]})},z=e=>ee(Ot,[Ut,kt,St,Pt,Nt,Tt,Rt,Vt,Dt,Mt,Bt,jt,Ft])(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},v={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}')`)},We=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 ze=(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}'`)},Ye=(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 Wt=(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 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 Yt(e.parts,t,n,r);switch(e.type){case p.FUNCTION:return He(e,t,n,r);case p.BINARY:return Je(e,t,n,r);case p.UNARY:return Xe(e,t,n,r);case p.CONDITIONAL:return Ht(e,t,n,r);case p.LOOP:return Qt(e,t,n,r);case p.OBJECT:return en(e,t,n,r);case p.ARRAY:return tn(e,t,n,r);case p.PARTIAL:return nn(e,t,n,r);case p.PATH_REFERENCE:return rn(e,t,n,r);default:throw new Error(`Unknown node type: ${e.type}`)}},Ke=new Map,zt=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 l=a.slice(1,-1);t.push({type:"property",value:l})}else t.push({type:"property",value:a});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=Ke.get(e);if(!r){let i=[],a="",l=0;for(let c=0;c<e.length;c++){let s=e[c];s==="["?(l++,a+=s):s==="]"?(l--,a+=s):s==="."&&l===0?a&&(i.push(a),a=""):a+=s}a&&i.push(a),r=[];for(let c of i){let s=zt(c.trim());r.push(...s)}Ke.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},Yt=(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("")},He=(e,t,n,r)=>{let o=t.functions||t,i=o[e.name];if(!i)throw Ye(e.name,o);let a=e.args.map(l=>_(l,t,n,r));return i(...a)},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 Je(e,t,n,r);case p.UNARY:return Xe(e,t,n,r);case p.FUNCTION:return He(e,t,n,r);default:return _(e,t,n,r)}},Je=(e,t,n,r)=>{if(e.op===v.AND||e.op===v.OR){let a=F(e.left,t,n,r),l=F(e.right,t,n,r);switch(e.op){case v.AND:return a&&l;case v.OR:return a||l}}let o=_(e.left,t,n,r),i=_(e.right,t,n,r);switch(e.op){case v.EQ:return o==i;case v.NEQ:return o!=i;case v.GT:return o>i;case v.LT:return o<i;case v.GTE:return o>=i;case v.LTE:return o<=i;case v.IN:return Array.isArray(i)?i.includes(o):!1;case v.ADD:if(typeof o!="number"||typeof i!="number")throw new L(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case v.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}`)}},Xe=(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}`)},Kt=(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 a=e.bodies[0];if(a.type===p.OBJECT&&a.properties.length<=5){let l={};for(let c of a.properties){let s=c.parsedKey?_(c.parsedKey,t,n,r):c.key,u=c.value;if(u.type===p.LITERAL)l[s]=u.value;else if(u.type===p.VARIABLE)l[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):"")}l[s]=f.join("")}else l[s]=_(u,t,n,r)}return l}}else{let a=e.bodies[1];if(a.type===p.OBJECT&&a.properties.length<=5){let l={};for(let c of a.properties){let s=c.parsedKey?_(c.parsedKey,t,n,r):c.key,u=c.value;if(u.type===p.LITERAL)l[s]=u.value;else if(u.type===p.VARIABLE)l[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):"")}l[s]=f.join("")}else l[s]=_(u,t,n,r)}return l}}}return null},Ht=(e,t,n,r)=>{let o=Kt(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 Ge},Jt=(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 c of i.properties)if(c.parsedKey)return null;let l=[];for(let c=0;c<t.length;c++){let s=t[c];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),E=s[w];g.push(E!=null?String(E):"")}else{y=!1;break}}else{y=!1;break}if(!y)return null;u[d]=g.join("")}else return null}l.push(u)}}return l}}}return null},Xt=(e,t)=>{let n=e.body,r=e.itemVar,o=Jt(e,t);if(o!==null)return o;if(n.type===p.OBJECT&&n.properties.length<=5&&!n.whenCondition){for(let l of n.properties)if(l.parsedKey)return null;let i=[],a=!0;for(let l of n.properties){let c=l.key,s=l.value;if(s.type===p.LITERAL)i.push({key:c,type:"literal",value:s.value});else if(s.type===p.VARIABLE){let u=s.path;if(u===r)i.push({key:c,type:"item"});else if(u.startsWith(r+".")){let f=u.substring(r.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:c,type:"prop",prop:f});else{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:c,type:"item_string"});else if(f.startsWith(r+".")){let d=f.substring(r.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:c,type:"prop_string",prop:d});else{a=!1;break}}else{a=!1;break}}else{a=!1;break}}else{a=!1;break}}if(a){let l=new Array(t.length);if(i.length===3&&i[0].type==="prop"&&i[0].key==="id"&&i[1].type==="prop_string"&&i[1].key==="title"&&i[2].type==="prop"&&i[2].key==="completed")for(let c=0;c<t.length;c++){let s=t[c];l[c]={id:s.id,title:s.title!=null?String(s.title):"",completed:s.completed}}else for(let c=0;c<t.length;c++){let s=t[c],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):""}l[c]=u}return l}}return null},Gt=(e,t,n,r,o)=>{let i=[],a=e.body;if(a.type===p.OBJECT&&a.fast!==!1){let l=e.itemVar,c=e.indexVar;for(let s=0;s<o.length;s++){let u=o[s],f={},d={...r,[l]:u,...c&&{[c]: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__,[l]:`${h}[${s}]`,...c&&{[c]: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===l)f[y]=u;else if(b===c)f[y]=s;else if(b.startsWith(l+".")){let w=b.substring(l.length+1);!w.includes(".")&&!w.includes("[")?f[y]=u[w]:f[y]=A(b,n,{...r,[l]:u,...c&&{[c]:s}})}else f[y]=A(b,n,{...r,[l]:u,...c&&{[c]: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 E=w.path,k;if(E===l)k=u;else if(E===c)k=s;else if(E.startsWith(l+".")){let re=E.substring(l.length+1);!re.includes(".")&&!re.includes("[")?k=u[re]:k=A(E,n,{...r,[l]:u,...c&&{[c]:s}})}else k=A(E,n,{...r,[l]:u,...c&&{[c]:s}});b.push(k!=null?String(k):"")}else{let E={...r,[l]:u,...c&&{[c]:s}},k=_(w,t,n,E);b.push(k!=null?String(k):"")}f[y]=b.join("")}else{let b={...r,[l]:u,...c&&{[c]: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 l=a.properties[0],c=a.properties[1];if(l.key==="id"&&l.value.type===p.VARIABLE&&l.value.path==="item.id"&&c.key==="$if item.highlighted"&&c.value.type===p.CONDITIONAL){let 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},Qt=(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 ze(f,o,u)}if(!e.indexVar){let s=qt(e,o,e.itemVar);if(s!==null)return s}if(!e.indexVar){let s=Xt(e,o);if(s!==null)return s}let i=Gt(e,t,n,r,o);if(i!==null)return i;let a=[],l=e.iterable.path||"";if(r&&r.__paths__&&l){let s=l.split("."),u=s[0];u in r.__paths__&&(l=r.__paths__[u],s.length>1&&(l+="."+s.slice(1).join(".")))}let c=!1;e.body.type===p.ARRAY&&(e.body.items.length<=1?c=!1:c=e.body._shouldPreserveArray??=e.body.items.some(s=>s.type===p.OBJECT&&s.properties.some(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]:`${l}[${s}]`},e.indexVar&&(u.__paths__[e.indexVar]=s);let f=_(e.body,t,n,u);if(Array.isArray(f)&&f.length===1&&!c){let d=f[0];a.push(d===void 0?{}:d)}else a.push(f===void 0?{}:f)}return a},Zt=(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 l={},c={},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)c[f]=d.value;else if(d.type===p.VARIABLE)c[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;c[f]=h.join("")}else if(d.type===p.OBJECT&&d.properties.length<=5){let h={};for(let g of d.properties){let y=g.key,m=g.value;if(m.type===p.LITERAL)h[y]=m.value;else if(m.type===p.VARIABLE)h[y]=A(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 E=A(w.path,n,r);b.push(E!=null?String(E):"")}else{s=!1;break}if(!s)break;h[y]=b.join("")}else{s=!1;break}}if(!s)break;c[f]=h}else{s=!1;break}}if(s)return l[i]=c,l}}return null},en=(e,t,n,r)=>{let o=t.functions||t;if(e.whenCondition&&!F(e.whenCondition,o,n,r))return;let i=Zt(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 a={},l=null,c=!1;for(let s of e.properties)if(!s.key.startsWith("$if ")&&!s.key.match(/^\$if\s+\w+.*:?$/)&&!s.key.startsWith("$elif")&&!s.key.startsWith("$else")&&!s.key.startsWith("$for ")){c=!0;break}for(let s of e.properties)if(s.key.startsWith("$if ")||s.key.match(/^\$if\s+\w+.*:?$/)){let u=_(s.value,t,n,r);if(!c&&u!==null&&u!==void 0)return Array.isArray(u)&&u.length===1?u[0]:u;typeof u=="object"&&u!==null&&!Array.isArray(u)&&Object.assign(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},Ge={},tn=(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!==Ge&&a!==void 0&&o.push(a)}return o},nn=(e,t,n,r)=>{let{name:o,data:i,whenCondition:a}=e,l=t.partials||{},c=t.functions||t;if(a&&!F(a,c,n,r))return;if(!l[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=l[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)},rn=(e,t,n,r)=>{let{path:o}=e,i=o.split("."),a=i[0],l=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 c=r.__paths__[a];if(typeof c=="number"){if(l.length>0)throw new L(`Path reference '#{${o}}' - cannot access properties on index variable '${a}'`);return String(c)}return l.length>0&&(c+="."+l.join(".")),c},be=Wt;var on=/\$\{([^}]*)\}/g,sn=/#\{([^}]*)\}/g,Qe=(e,t={})=>{let n=e.match(/^(\w+)\((.*)\)$/);if(!n)return{isFunction:!1};let[,r,o]=n,i=an(o,t);return{isFunction:!0,type:p.FUNCTION,name:r,args:i}},an=(e,t={})=>e.trim()?ln(e).map(r=>cn(r.trim(),t)):[],ln=e=>{let t=[],n="",r=0,o=!1,i="";for(let a=0;a<e.length;a++){let l=e[a],c=a>0?e[a-1]:"";!o&&(l==='"'||l==="'")?(o=!0,i=l,n+=l):o&&l===i&&c!=="\\"?(o=!1,i="",n+=l):!o&&l==="("?(r++,n+=l):!o&&l===")"?(r--,n+=l):!o&&l===","&&r===0?(t.push(n),n=""):n+=l}return n&&t.push(n),t},cn=(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=Qe(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:l,type:c}of o){let s=0;for(;s<r.length;){let u=D(r.substring(s),l);if(u===-1)break;let f=s+u;f>i&&(i=f,a={op:l,type:c}),s=f+l.length}}if(i!==-1)try{return x(r,t)}catch{return{type:p.VARIABLE,path:r}}return{type:p.VARIABLE,path:r}},Ze=/^\w+\(.*\)$/,un=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,fn=e=>{if(!(!e||e.trim()===""||Ze.test(e))&&un.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(Ze.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();fn(n);let r=Qe(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(on)],i=[...n.matchAll(sn)],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 l=[],c=0;for(let{match:s,type:u}of a){let[f,d]=s,h=s.index;if(h>c){let g=n.substring(c,h);for(let y=0;y<r.length;y++)g=g.replace(`__ESCAPED_${y}__`,r[y]);g&&l.push(g)}try{let g;u==="variable"?g=K(d.trim(),t):g=qe(d.trim()),l.push(g)}catch(g){if(g.message==="Invalid array index syntax")l.push(f);else throw g}c=h+f.length}if(c<n.length){let s=n.substring(c);for(let u=0;u<r.length;u++)s=s.replace(`__ESCAPED_${u}__`,r[u]);s&&l.push(s)}return{type:p.INTERPOLATION,parts:l}};var P=(e,t)=>typeof e=="string"?Ie(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?pn(e,t):hn(e,t):{type:p.LITERAL,value:e},dn=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}},pn=(e,t)=>{let n=[],r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(typeof i=="object"&&i!==null&&!Array.isArray(i)){if(i.$each!==void 0)try{let c=dn(i),s=Object.keys(c);if(s.length===1&&/^\$for(?::\w+)?\s/.test(s[0])){let u=et(s[0],c[s[0]],t,!0);n.push(u),r=!0;continue}}catch(c){throw c instanceof I?c:new I(c.message)}let l=Object.keys(i);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let c=et(l[0],i[l[0]],t);n.push(c),r=!0;continue}}let a=P(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}},hn=(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 c=["$if","$elif","$else","$for"],s=[];for(let[b]of i)for(let w of c)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 E=b;(b.startsWith("\\$")||b.startsWith("$$"))&&(E=b.slice(1)),h[E]=w,g=!0}let y=null;if(g&&(y=P(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=x(f,t)}else b={type:p.LITERAL,value:f};m.whenCondition=b}return m}for(let[c,s]of i)if(c==="$when"){if(o!==null)throw new 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=x(u,t),r=!0}else if(c.startsWith("$when#")||c.startsWith("$when "))throw new I("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;a<i.length;){let[c,s]=i[a];if(c==="$when"){a++;continue}if(c==="$each")throw new I("$each can only be used inside arrays");if(c.startsWith("$if ")||c.match(/^\$if#\w+\s/)||c.match(/^\$if\s+\w+.*:$/)){let u=gn(i,a,t);n.push({key:c,value:u.node}),r=!0,a=u.nextIndex}else if(/^\$for(?::\w+)?\s/.test(c)){let u=c.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(c.startsWith("$elif ")||c.startsWith("$else"))throw new I(`'${c.split(" ")[0]}' without matching '$if'`);if(c==="$if"||c==="$if:")throw new I("Missing condition expression after '$if'");{let u=P(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(c,t),d={key:c,value:u};(f.type!==p.LITERAL||f.value!==c)&&(d.parsedKey=f),n.push(d),a++}}}let l={type:p.OBJECT,properties:n,fast:!r};return o&&(l.whenCondition=o),l},gn=(e,t,n={})=>{let r=[],o=[],i=t,[a,l]=e[i],c=null,s;if(a.startsWith("$if#")){let f=a.match(/^\$if#(\w+)\s+(.+)$/);if(f)c=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=x(s,n);for(r.push(u),o.push(P(l,n)),i++;i<e.length;){let[f,d]=e[i],h=!1,g;if(c?f.startsWith(`$elif#${c} `)?(g=f.substring(`$elif#${c} `.length),g.endsWith(":")&&(g=g.slice(0,-1).trim()),h=!0):(f===`$else#${c}`||f===`$else#${c}:`)&&(h=!0,g=null):f.startsWith("$elif ")?(g=f.substring(6),g.endsWith(":")&&(g=g.slice(0,-1).trim()),h=!0):(f==="$else"||f==="$else:")&&(h=!0,g=null),h){if(g===null)r.push(null);else{me(g);let y=x(g,n);r.push(y)}if(o.push(P(d,n)),i++,g===null)break}else break}return{node:{type:p.CONDITIONAL,conditions:r,bodies:o,id:c},nextIndex:i}},x=(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 x(s,t)}let n=D(e,"||");if(n!==-1)return{type:p.BINARY,op:v.OR,left:x(e.substring(0,n).trim(),t),right:x(e.substring(n+2).trim(),t)};let r=D(e,"&&");if(r!==-1)return{type:p.BINARY,op:v.AND,left:x(e.substring(0,r).trim(),t),right:x(e.substring(r+2).trim(),t)};let o=[{op:">=",type:v.GTE},{op:"<=",type:v.LTE},{op:"==",type:v.EQ},{op:"!=",type:v.NEQ},{op:">",type:v.GT},{op:"<",type:v.LT},{op:" in ",type:v.IN}];for(let{op:s,type:u}of o){let f=D(e,s);if(f!==-1)return{type:p.BINARY,op:u,left:x(e.substring(0,f).trim(),t),right:x(e.substring(f+s.length).trim(),t)}}let i=-1,a=null,l=[{op:" + ",type:v.ADD},{op:" - ",type:v.SUBTRACT}];for(let{op:s,type:u}of l){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:x(e.substring(0,i).trim(),t),right:x(e.substring(i+a.op.length).trim(),t)};let c=[" * "," / "," % "];for(let s of c)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:x(e.substring(1).trim(),t)}:tt(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},yn=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}},tt=(e,t)=>{let n=e.trim();if(n.match(/^(\w+)\((.*)\)$/))return K(n,t);let o=yn(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}},mn=(e,t=!1)=>{let n=t?"$each":"$for";try{We(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}},et=(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],l=i[2].trim();mn(l,r);let c=l.match(/^(.+?)\s+in\s+(.+)$/);if(!c){let m=r?"$each":"$for";throw new I(`Invalid loop syntax - missing 'in' keyword (got: '${m} ${l}')`)}let s=c[1].trim(),u=c[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=tt(u,n),y=P(t,n);return{type:p.LOOP,itemVar:f,indexVar:d,iterable:g,body:y,flatten:a!=="nested"}};var bn=(e,t={})=>{let{functions:n={}}=t;return P(e,n)},te=bn;var we={};mt(we,{now:()=>In});var In=()=>Date.now();var wn=(e,t,n={})=>{let{functions:r={},partials:o={}}=n,i={...we,...r},a=te(e,{functions:i}),l={};for(let[c,s]of Object.entries(o))l[c]=te(s,{functions:i});return be(a,t,{functions:i,partials:l})},R=wn;var _e={objectValues:e=>Object.entries(e).map(([t,n])=>({id:t,...n})),formatDate:Ue},_n=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),vn=(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},En=(e,{presentationState:t,previousPresentationState:n,resources:r={},variables:o,autoMode:i,skipMode:a,currentLocalizationPackageId:l})=>{let{elements:c}=e,s=e.animations||[];if(t.background){let u=c.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(l=>l.id==="story");if(!i)return e;let a=t.character.items||[];for(let l=0;l<a.length;l++){let c=a[l],{transformId:s,sprites:u}=c;if(c.animations&&c.animations.out&&!u&&!s){let y=c.animations.out.resourceId,m=n?.tweens[y];if(m){let b={id:"character-animation-out",type:"tween",targetId:`character-container-${c.id}`,properties:m.properties};o.push(b)}continue}if(!u||u.length===0||!s){console.warn("Character item missing sprites or transformId:",c);continue}let f=u.map(({resourceId:y})=>y),d=`character-container-${c.id}-${l}-${f.join("-")}`,h=n.transforms[s];if(!h){console.warn("Transform not found:",s);continue}let g={type:"container",id:d,x:c.x??h.x,y:c.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),c.animations){if(c.animations.in){let y=c.animations.in.resourceId,m=n?.tweens[y];m&&o.push({id:"character-animation-in",type:"tween",targetId:d,properties:m.properties})}if(c.animations.update){let y=c.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},xn=(e,{presentationState:t,resources:n})=>{let{elements:r}=e,o=e.animations||[];if(t.visual&&n){let i=r.find(l=>l.id==="story");if(!i)return e;let a=t.visual.items;for(let l of a){if(l.resourceId){let{images:c={},videos:s={},spritesheets:u={}}=n,f=u[l.resourceId];if(f){let d=n.transforms?.[l.transformId]||{},h=l.animationName;if(h){let g=f.animations?.[h];if(!g)throw new Error(`Animation '${h}' not found in spritesheet resource '${l.resourceId}'`);let y={id:`visual-${l.id}`,type:"animated-sprite",x:l.x??d.x??0,y:l.y??d.y??0,width:l.width??100,height:l.height??100,alpha:l.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:l.animationSpeed??g.animationSpeed??.5,loop:l.loop??g.loop??!0}};i.children.push(structuredClone(y))}}else{let d=c[l.resourceId]||s[l.resourceId];if(d){let h=s[l.resourceId]!==void 0,g=n.transforms[l.transformId],y={id:`visual-${l.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(l.resourceId){let{layouts:c={}}=n,s=c[l.resourceId];if(s){let u=n.transforms[l.transformId];i.children.push({id:`visual-${l.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(l.animations){if(l.animations.in){let c=l.animations.in.resourceId||l.animations.in,s=n?.tweens[c];s&&o.push({id:`${l.id}-animation`,type:"tween",targetId:`visual-${l.id}`,properties:structuredClone(s.properties)})}if(l.animations.out){let c=l.animations.out.resourceId||l.animations.out,s=n?.tweens[c];s&&o.push({id:`${l.id}-animation-2`,type:"tween",targetId:`visual-${l.id}`,properties:structuredClone(s.properties)})}}}}return e},Ln=(e,{presentationState:t,resources:n={},dialogueUIHidden:r,autoMode:o,skipMode:i,skipOnlyViewedLines:a,l10n:l,variables:c,saveSlots:s=[]})=>{let{elements:u}=e;if(!t.dialogue||r)return e;let f=u.find(d=>d.id==="story");if(!f)return e;if(t.dialogue.gui&&t.dialogue.gui.resourceId){let{layouts:d={}}=n,h=d[t.dialogue.gui.resourceId];if(h){let g;t.dialogue.characterId&&(g=n.characters[t.dialogue.characterId]),t.dialogue.character&&(g={...g,name:t.dialogue.character.name});let y={elements:h.elements},m={variables:c,autoMode:o,skipMode:i,skipOnlyViewedLines:a,saveSlots:s,dialogue:{character:{name:g?.name||""},content:t.dialogue?.content||[{text:""}],lines:t.dialogue?.lines||[]},l10n:l},b=R(y,m,{functions:_e});b=R(b,{l10n:l});let w=b?.elements;if(Array.isArray(w))for(let E of w)f.children.push(structuredClone(E));else w&&f.children.push(structuredClone(w))}}return e},$n=(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},c=R(a,{choice:{items:t.choice?.items??[]}})?.elements;if(Array.isArray(c))for(let s of c)o.children.push(structuredClone(s));else c&&o.children.push(structuredClone(c))}return e},Cn=(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(l=>l.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},kn=(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},Sn=(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},Rn=(e,{presentationState:t,resources:n={},variables:r,autoMode:o,skipMode:i,currentLocalizationPackageId:a,saveSlots:l=[]})=>{let{elements:c}=e,s=e.animations||[];if(t.layout){let u=c.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:l,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:l=[],saveSlots:c=[],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(E=>{f.push(E)});let y={id:`layeredView-${h}`,type:"container",x:0,y:0,children:g.elements||[]},m=l.map(E=>{let k=t.characters?.[E.characterId];return{...E,characterName:k?.name||""}}),b={variables:n,autoMode:r,skipMode:o,currentLocalizationPackageId:i,saveSlots:c,historyDialogue:m,characters:t.characters||{}},w=R(y,b,{functions:_e});w=R(w,{i18n:{},l10n:s}),u.push(w)}),e},nt=e=>ee(_n,[vn,En,An,xn,Ln,$n,Cn,Rn,On,kn,Sn,Pn])(e);var Nn=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:l}=Me(o),c={...l,...r},s={projectData:o,global:{autoplayDelay:1e3,isLineCompleted:!1,pendingEffects:[],autoMode:!1,skipMode:!1,skipOnlyViewedLines:!0,dialogueUIHidden:!1,isDialogueHistoryShowing:!1,currentLocalizationPackageId:t,viewedRegistry:{sections:[],resources:[]},nextLineConfig:{manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1}},saveSlots:n,layeredViews:[],variables:c},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},Tn=({state:e})=>e.global.layeredViews||[],Vn=({state:e})=>e.global.pendingEffects,rt=({state:e})=>e.global.skipMode,Dn=({state:e})=>e.global.skipOnlyViewedLines,Mn=({state:e})=>e.global.autoMode,ot=({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(c=>c.id===r);return o.lines.slice(0,i+1).filter(c=>c.actions?.dialogue).map(c=>{let s=c.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,it=({state:e},t)=>{let{sectionId:n,lineId:r}=t,o=e.global.viewedRegistry.sections.find(c=>c.sectionId===n);if(!o)return!1;if(o.lastLineId===void 0||r===void 0)return!0;let i=$({state:e},{sectionId:n});if(!i||!i.lines||!Array.isArray(i.lines))return!1;let a=i.lines.findIndex(c=>c.id===o.lastLineId),l=i.lines.findIndex(c=>c.id===r);return a===-1||l===-1?o.lastLineId===r:l<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 l=a.map(s=>{let u=s.actions||{},f={};return Object.keys(u).forEach(d=>{f[d]=u[d]}),f});return z(l)},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||{},l=z([o,a]),c=ye(o,l);r.push({id:i.id,changes:c}),o=l}return{lines:r}},lt=({state:e})=>{let{sectionId:t,lineId:n}=M({state:e}).pointer,o=$({state:e},{sectionId:t})?.lines||[],i=o.findIndex(c=>c.id===n);if(i<=0)return null;let l=o.slice(0,i).map(c=>{let s=c.actions||{},u={};return Object.keys(s).forEach(f=>{u[f]=s[f]}),u});return z(l)},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 l=o+a,c=e.global.saveSlots&&e.global.saveSlots[l]||{};i.push({slotNumber:l,...c})}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=nt({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:e.global.skipOnlyViewedLines,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),Ee=({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?Ee({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),ne=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Zn=({state:e})=>(rt({state:e})?ne({state:e}):ft({state:e}),e),er=({state:e},t)=>{let{skipOnlyViewedLines:n}=t;return e.global.skipOnlyViewedLines=n,e.global.pendingEffects.push({name:"render"}),e},tr=({state:e})=>(e.global.skipOnlyViewedLines=!e.global.skipOnlyViewedLines,e.global.pendingEffects.push({name:"render"}),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),nr=({state:e})=>(ot({state:e})?dt({state:e}):pt({state:e}),e),rr=({state:e})=>{let t=ve({state:e});return e.global.isDialogueHistoryShowing=!0,e.global.pendingEffects.push({name:"render"}),e},or=({state:e})=>(e.global.isDialogueHistoryShowing=!1,e.global.pendingEffects.push({name:"render"}),e),ir=({state:e},t)=>{let{localizationPackageId:n}=t;return e.global.currentLocalizationPackageId=n,e.global.pendingEffects.push({name:"render"}),e},sr=({state:e})=>(e.global.pendingEffects=[],e),ar=({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(c=>c.id===o.lastLineId),l=i.lines.findIndex(c=>c.id===r);(a===-1||l>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},lr=({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},cr=({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},ur=({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),fr=({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},dr=({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},pr=({state:e},t)=>{let{projectData:n}=t;return e.projectData=n,e.global.pendingEffects.push({name:"render"}),e},hr=({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(c=>c.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)},gr=({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},yr=({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(l=>l.id===t?.lineId)+1;if(a<o.length){let l=o[a],c=e.contexts[e.contexts.length-1];c&&(c.pointers.read={sectionId:n,lineId:l.id}),e.global.isLineCompleted=!1,e.global.nextLineConfig.auto={},e.global.pendingEffects.push({name:"render"}),e.global.pendingEffects.push({name:"handleLineActions"})}return e},mr=({state:e})=>{if(!e.global.nextLineConfig.manual.enabled)return e;let t=M({state:e})?.pointer,n=t?.sectionId,o=$({state:e},{sectionId:n})?.lines||[],a=o.findIndex(l=>l.id===t?.lineId)+1;if(a<o.length){let l=o[a];e.global.skipMode&&e.global.skipOnlyViewedLines&&(it({state:e},{sectionId:n,lineId:l.id})||ne({state:e}));let c=e.contexts[e.contexts.length-1];if(c){let s=c.pointers.read.lineId;s&&n&&ht({state:e},{sectionId:n,lineId:s}),c.pointers.read={sectionId:n,lineId:l.id}}e.global.isLineCompleted=!1,e.global.pendingEffects.push({name:"render"}),e.global.pendingEffects.push({name:"handleLineActions"})}else e.global.autoMode&&Ee({state:e}),e.global.skipMode&&ne({state:e});return console.log("state",e),e},br=({state:e})=>(e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"render"}),e),Ir=({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 c=o.findIndex(s=>s.id===i.pointers.history.lineId)-1;if(c>=0&&c<o.length){let s=o[c];i.pointers.history={sectionId:n,lineId:s.id},e.global.pendingEffects.push({name:"render"})}return e},wr=({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},_r=({state:e})=>{let t=M({state:e})?.pointer,n=t?.sectionId,o=$({state:e},{sectionId:n})?.lines||[],a=o.findIndex(l=>l.id===t?.lineId)+1;if(a<o.length){let l=o[a],c=e.contexts[e.contexts.length-1];c&&(c.pointers.read={sectionId:n,lineId:l.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},vr=({state:e},t)=>{let{operations:n=[]}=t,r=!1,o=!1;if(n.forEach(({variableId:i,op:a,value:l})=>{let c=e.projectData.resources?.variables?.[i],s=c?.scope,u=c?.type;Be(s,i),je(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]=Fe(f[i],a,l)}),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=Nn(e);return De(t,{selectPendingEffects:Vn,selectSkipMode:rt,selectSkipOnlyViewedLines:Dn,selectAutoMode:Mn,selectDialogueUIHidden:ot,selectDialogueHistory:ve,selectCurrentLocalizationPackageId:jn,selectIsLineViewed:it,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:Tn,startAutoMode:ut,stopAutoMode:Ee,toggleAutoMode:Qn,startSkipMode:ft,stopSkipMode:ne,toggleSkipMode:Zn,setSkipOnlyViewedLines:er,toggleSkipOnlyViewedLines:tr,showDialogueUI:dt,hideDialogueUI:pt,toggleDialogueUI:nr,showDialogueHistory:rr,hideDialogueHistory:or,setCurrentLocalizationPackageId:ir,clearPendingEffects:sr,appendPendingEffect:ar,addViewedLine:ht,addViewedResource:lr,setNextLineConfig:cr,saveSaveSlot:fr,loadSaveSlot:dr,setAutoplayDelay:ur,updateProjectData:pr,sectionTransition:wr,jumpToLine:hr,addToHistorySequence:gr,nextLine:mr,nextLineFromCompleted:yr,markLineCompleted:br,prevLine:Ir,pushLayeredView:Jn,popLayeredView:Xn,replaceLastLayeredView:Gn,clearLayeredViews:qn,updateVariable:vr,nextLineFromSystem:_r},{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(),l=h=>t.selectSectionLineChanges(h),c=()=>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:c,selectPresentationState:i,selectPresentationChanges:a,selectSectionLineChanges:l,selectSaveSlots:s,handleLineActions:d}}var xe=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:n=>{e=n},addElapsed:n=>{e+=n},getCallback:()=>t,setCallback:n=>{t=n}}},Er=({engine:e,routeGraphics:t},n)=>{let r=e.selectRenderState();t.render(r)},Ar=({engine:e},t)=>{e.handleLineActions()},xr=({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 l=r.delay??1e3;n.getElapsed()>=l&&(n.setElapsed(0),e.handleAction("nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},Lr=({ticker:e,autoTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},$r=({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)},Cr=({ticker:e,skipTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Or=({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 l=r.delay??1e3;n.getElapsed()>=l&&(n.setElapsed(0),e.handleAction("nextLineFromSystem",{}),t.remove(i),n.setCallback(null))};n.setCallback(i),t.add(i)},kr=({ticker:e,nextLineConfigTimerState:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Sr=({},e)=>{localStorage.setItem("saveSlots",JSON.stringify(e.saveSlots))},Rr=({},e)=>{localStorage.setItem("globalDeviceVariables",JSON.stringify(e.globalDeviceVariables))},Pr=({},e)=>{localStorage.setItem("globalAccountVariables",JSON.stringify(e.globalAccountVariables))},Nr={render:Er,saveSlots:Sr,saveGlobalDeviceVariables:Rr,saveGlobalAccountVariables:Pr,handleLineActions:Ar,startAutoNextTimer:xr,clearAutoNextTimer:Lr,startSkipNextTimer:$r,clearSkipNextTimer:Cr,nextLineConfigTimer:Or,clearNextLineConfigTimer:kr},Tr=({getEngine:e,routeGraphics:t,ticker:n})=>{let r=xe(),o=xe(),i=xe();return async a=>{let l=e(),c=a.reduce((f,d)=>(f[d.name]=d,f),{}),s=Object.values(c),u={engine:l,routeGraphics:t,ticker:n,autoTimer:r,skipTimer:o,nextLineConfigTimerState:i};for(let f of s){let d=Nr[f.name];d&&d(u,f.payload)}}},Vr=Tr;var So=Ae;export{Vr as createEffectsHandler,So as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "route-engine-js",
3
- "version": "0.1.21",
3
+ "version": "0.1.22",
4
4
  "type": "module",
5
5
  "main": "dist/RouteEngine.js",
6
6
  "exports": {