route-engine-js 1.10.0 → 1.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/RouteEngine.js +1 -1
- package/package.json +2 -2
package/dist/RouteEngine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var Ro=Object.defineProperty;var Lo=(e,t)=>{for(var n in t)Ro(e,n,{get:t[n],enumerable:!0})};var Tn=Symbol.for("immer-nothing"),Ln=Symbol.for("immer-draftable"),X=Symbol.for("immer-state");function ee(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var Ce=Object.getPrototypeOf;function ue(e){return!!e&&!!e[X]}function ge(e){return e?Nn(e)||Array.isArray(e)||!!e[Ln]||!!e.constructor?.[Ln]||et(e)||tt(e):!1}var $o=Object.prototype.constructor.toString();function Nn(e){if(!e||typeof e!="object")return!1;let t=Ce(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)===$o}function Ge(e,t){Ze(e)===0?Reflect.ownKeys(e).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function Ze(e){let t=e[X];return t?t.type_:Array.isArray(e)?1:et(e)?2:tt(e)?3:0}function vt(e,t){return Ze(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Dn(e,t,n){let r=Ze(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function Oo(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function et(e){return e instanceof Map}function tt(e){return e instanceof Set}function he(e){return e.copy_||e.base_}function St(e,t){if(et(e))return new Map(e);if(tt(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let n=Nn(e);if(t===!0||t==="class_only"&&!n){let r=Object.getOwnPropertyDescriptors(e);delete r[X];let o=Reflect.ownKeys(r);for(let i=0;i<o.length;i++){let s=o[i],a=r[s];a.writable===!1&&(a.writable=!0,a.configurable=!0),(a.get||a.set)&&(r[s]={configurable:!0,writable:!0,enumerable:a.enumerable,value:e[s]})}return Object.create(Ce(e),r)}else{let r=Ce(e);if(r!==null&&n)return{...e};let o=Object.create(r);return Object.assign(o,e)}}function $t(e,t=!1){return nt(e)||ue(e)||!ge(e)||(Ze(e)>1&&(e.set=e.add=e.clear=e.delete=ko),Object.freeze(e),t&&Object.entries(e).forEach(([n,r])=>$t(r,!0))),e}function ko(){ee(2)}function nt(e){return Object.isFrozen(e)}var Po={};function me(e){let t=Po[e];return t||ee(0,e),t}var Te;function Vn(){return Te}function To(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function $n(e,t){t&&(me("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Ct(e){_t(e),e.drafts_.forEach(No),e.drafts_=null}function _t(e){e===Te&&(Te=e.parent_)}function On(e){return Te=To(Te,e)}function No(e){let t=e[X];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function kn(e,t){t.unfinalizedDrafts_=t.drafts_.length;let n=t.drafts_[0];return e!==void 0&&e!==n?(n[X].modified_&&(Ct(t),ee(4)),ge(e)&&(e=Xe(t,e),t.parent_||Qe(t,e)),t.patches_&&me("Patches").generateReplacementPatches_(n[X].base_,e,t.patches_,t.inversePatches_)):e=Xe(t,n,[]),Ct(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Tn?e:void 0}function Xe(e,t,n){if(nt(t))return t;let r=t[X];if(!r)return Ge(t,(o,i)=>Pn(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Qe(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;let o=r.copy_,i=o,s=!1;r.type_===3&&(i=new Set(o),o.clear(),s=!0),Ge(i,(a,l)=>Pn(e,r,o,a,l,n,s)),Qe(e,o,!1),n&&e.patches_&&me("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function Pn(e,t,n,r,o,i,s){if(ue(o)){let a=i&&t&&t.type_!==3&&!vt(t.assigned_,r)?i.concat(r):void 0,l=Xe(e,o,a);if(Dn(n,r,l),ue(l))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if(ge(o)&&!nt(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Xe(e,o),(!t||!t.scope_.parent_)&&typeof r!="symbol"&&Object.prototype.propertyIsEnumerable.call(n,r)&&Qe(e,o)}}function Qe(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&$t(t,n)}function Do(e,t){let n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:Vn(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=r,i=Ot;n&&(o=[r],i=Ne);let{revoke:s,proxy:a}=Proxy.revocable(o,i);return r.draft_=a,r.revoke_=s,a}var Ot={get(e,t){if(t===X)return e;let n=he(e);if(!vt(n,t))return Vo(e,n,t);let r=n[t];return e.finalized_||!ge(r)?r:r===xt(e.base_,t)?(Et(e),e.copy_[t]=Lt(r,e)):r},has(e,t){return t in he(e)},ownKeys(e){return Reflect.ownKeys(he(e))},set(e,t,n){let r=jn(he(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){let o=xt(he(e),t),i=o?.[X];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(Oo(n,o)&&(n!==void 0||vt(e.base_,t)))return!0;Et(e),Rt(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 xt(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,Et(e),Rt(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let n=he(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){ee(11)},getPrototypeOf(e){return Ce(e.base_)},setPrototypeOf(){ee(12)}},Ne={};Ge(Ot,(e,t)=>{Ne[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});Ne.deleteProperty=function(e,t){return Ne.set.call(this,e,t,void 0)};Ne.set=function(e,t,n){return Ot.set.call(this,e[0],t,n,e[0])};function xt(e,t){let n=e[X];return(n?he(n):e)[t]}function Vo(e,t,n){let r=jn(t,n);return r?"value"in r?r.value:r.get?.call(e.draft_):void 0}function jn(e,t){if(!(t in e))return;let n=Ce(e);for(;n;){let r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=Ce(n)}}function Rt(e){e.modified_||(e.modified_=!0,e.parent_&&Rt(e.parent_))}function Et(e){e.copy_||(e.copy_=St(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var jo=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){let i=n;n=t;let s=this;return function(l=i,...c){return s.produce(l,u=>n.call(this,u,...c))}}typeof n!="function"&&ee(6),r!==void 0&&typeof r!="function"&&ee(7);let o;if(ge(t)){let i=On(this),s=Lt(t,void 0),a=!0;try{o=n(s),a=!1}finally{a?Ct(i):_t(i)}return $n(i,r),kn(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===Tn&&(o=void 0),this.autoFreeze_&&$t(o,!0),r){let i=[],s=[];me("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else ee(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...a)=>this.produceWithPatches(s,l=>t(l,...a));let r,o;return[this.produce(t,n,(s,a)=>{r=s,o=a}),r,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){ge(e)||ee(8),ue(e)&&(e=kt(e));let t=On(this),n=Lt(e,void 0);return n[X].isManual_=!0,_t(t),n}finishDraft(e,t){let n=e&&e[X];(!n||!n.isManual_)&&ee(9);let{scope_:r}=n;return $n(r,t),kn(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=me("Patches").applyPatches_;return ue(e)?r(e,t):this.produce(e,o=>r(o,t))}};function Lt(e,t){let n=et(e)?me("MapSet").proxyMap_(e,t):tt(e)?me("MapSet").proxySet_(e,t):Do(e,t);return(t?t.scope_:Vn()).drafts_.push(n),n}function kt(e){return ue(e)||ee(10,e),Mn(e)}function Mn(e){if(!ge(e)||nt(e))return e;let t=e[X],n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=St(e,t.scope_.immer_.useStrictShallowCopy_)}else n=St(e,!0);return Ge(n,(r,o)=>{Dn(n,r,Mn(o))}),t&&(t.finalized_=!1),n}var Q=new jo,Pt=Q.produce,tl=Q.produceWithPatches.bind(Q),nl=Q.setAutoFreeze.bind(Q),rl=Q.setUseStrictShallowCopy.bind(Q),ol=Q.applyPatches.bind(Q),il=Q.createDraft.bind(Q),sl=Q.finishDraft.bind(Q);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},R={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},_e={NOT:0};var w=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},K=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var Tt=e=>{if(!e||e.trim()==="")throw new w("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let n=e.includes("===")?"==":"!=";throw new w(`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 w(`Incomplete comparison expression - missing right operand (got: '${e}')`)},Un=e=>{if(e.trim().endsWith(" in"))throw new w(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new w(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,n]=e.split(" in ");if(!n||n.trim()==="")throw new w(`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 w(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new w(`Invalid loop syntax (got: '$for ${e}')`)}};var Bn=(e,t,n=!1)=>{if(t===null)return new K(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new K(`Cannot iterate over undefined value at '$for ${e}'`);let r=typeof t;return n?new K(`Cannot iterate over non-array value in loop '${e}' - got ${r} instead`):new K(`Cannot iterate over non-array value (got: ${r}) at '$for ${e}'`)},Fn=(e,t)=>{let n=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new K(`Unknown function '${e}' (${n})`)};var Mo=(e,t,n={})=>{let r={},o={};n&&typeof n=="object"&&(n.functions!==void 0||n.partials!==void 0?(r=n.functions||{},o=n.partials||{}):typeof n=="object"&&(r=n));let s=L(e,{functions:r,partials:o},t,{});return s===void 0?{}:s},L=(e,t,n,r)=>{let o=t.functions||t;if(e.var&&!e.type)return B(e.var,n,r);if(e.type===p.LITERAL)return e.value;if(e.type===p.VARIABLE)return B(e.path,n,r);if(e.type===p.INTERPOLATION)return Bo(e.parts,t,n,r);switch(e.type){case p.FUNCTION:return Wn(e,t,n,r);case p.BINARY:return Yn(e,t,n,r);case p.UNARY:return qn(e,t,n,r);case p.CONDITIONAL:return zo(e,t,n,r);case p.LOOP:return Jo(e,t,n,r);case p.OBJECT:return Go(e,t,n,r);case p.ARRAY:return Xo(e,t,n,r);case p.PARTIAL:return Qo(e,t,n,r);case p.PATH_REFERENCE:return Zo(e,t,n,r);default:throw new Error(`Unknown node type: ${e.type}`)}},zn=new Map,Uo=e=>{let t=[],n="",r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(i==="[")n&&(t.push({type:"property",value:n}),n=""),r=!0;else if(i==="]"){if(r&&n){let s=n.trim();if(/^\d+$/.test(s))t.push({type:"index",value:parseInt(s,10)});else if(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'")){let a=s.slice(1,-1);t.push({type:"property",value:a})}else t.push({type:"property",value:s});n=""}r=!1}else n+=i}return n&&t.push({type:"property",value:n}),t},B=(e,t,n)=>{if(!e)return;if(e in n)return n[e];let r=zn.get(e);if(!r){let i=[],s="",a=0;for(let l=0;l<e.length;l++){let c=e[l];c==="["?(a++,s+=c):c==="]"?(a--,s+=c):c==="."&&a===0?s&&(i.push(s),s=""):s+=c}s&&i.push(s),r=[];for(let l of i){let c=Uo(l.trim());r.push(...c)}zn.set(e,r)}let o=t;for(let i=0;i<r.length;i++){let s=r[i];if(s.type==="property"&&s.value in n){o=n[s.value];continue}if(o==null)return;(s.type==="property"||s.type==="index")&&(o=o[s.value])}return o},Bo=(e,t,n,r)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=L(i,t,n,r);o.push(s!=null?String(s):"")}return o.join("")},Wn=(e,t,n,r)=>{let o=t.functions||t,i=o[e.name];if(!i)throw Fn(e.name,o);let s=e.args.map(a=>L(a,t,n,r));return i(...s)},fe=(e,t,n,r)=>{if(e.var&&!e.type)return B(e.var,n,r);switch(e.type){case p.VARIABLE:return B(e.path,n,r);case p.LITERAL:return e.value;case p.BINARY:return Yn(e,t,n,r);case p.UNARY:return qn(e,t,n,r);case p.FUNCTION:return Wn(e,t,n,r);default:return L(e,t,n,r)}},Yn=(e,t,n,r)=>{if(e.op===R.AND||e.op===R.OR){let s=fe(e.left,t,n,r),a=fe(e.right,t,n,r);switch(e.op){case R.AND:return s&&a;case R.OR:return s||a}}let o=L(e.left,t,n,r),i=L(e.right,t,n,r);switch(e.op){case R.EQ:return o==i;case R.NEQ:return o!=i;case R.GT:return o>i;case R.LT:return o<i;case R.GTE:return o>=i;case R.LTE:return o<=i;case R.IN:return Array.isArray(i)?i.includes(o):!1;case R.ADD:if(typeof o!="number"||typeof i!="number")throw new K(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case R.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new K(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},qn=(e,t,n,r)=>{let o=e.op===_e.NOT?fe(e.operand,t,n,r):L(e.operand,t,n,r);if(e.op===_e.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},Fo=(e,t,n,r)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===p.VARIABLE)if(B(o.path,n,r)){let s=e.bodies[0];if(s.type===p.OBJECT&&s.properties.length<=5){let a={};for(let l of s.properties){let c=l.parsedKey?L(l.parsedKey,t,n,r):l.key,u=l.value;if(u.type===p.LITERAL)a[c]=u.value;else if(u.type===p.VARIABLE)a[c]=B(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=B(d.path,n,r);f.push(h!=null?String(h):"")}else{let h=L(d,t,n,r);f.push(h!=null?String(h):"")}a[c]=f.join("")}else a[c]=L(u,t,n,r)}return a}}else{let s=e.bodies[1];if(s.type===p.OBJECT&&s.properties.length<=5){let a={};for(let l of s.properties){let c=l.parsedKey?L(l.parsedKey,t,n,r):l.key,u=l.value;if(u.type===p.LITERAL)a[c]=u.value;else if(u.type===p.VARIABLE)a[c]=B(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=B(d.path,n,r);f.push(h!=null?String(h):"")}else{let h=L(d,t,n,r);f.push(h!=null?String(h):"")}a[c]=f.join("")}else a[c]=L(u,t,n,r)}return a}}}return null},zo=(e,t,n,r)=>{let o=Fo(e,t,n,r);if(o!==null)return o;for(let i=0;i<e.conditions.length;i++){let s=e.conditions[i];if(s===null||fe(s,t,n,r))return L(e.bodies[i],t,n,r)}return Hn},Wo=(e,t)=>{let n=e.body,r=e.itemVar;if(n.type===p.CONDITIONAL&&n.conditions.length===1&&n.conditions[0].type===p.VARIABLE){let o=n.conditions[0].path,i=n.bodies[0];if(o.startsWith(r+".")){let s=o.substring(r.length+1);if(i.type===p.OBJECT&&i.properties.length<=5){for(let l of i.properties)if(l.parsedKey)return null;let a=[];for(let l=0;l<t.length;l++){let c=t[l];if(c[s]){let u={};for(let f of i.properties){let d=f.key,h=f.value;if(h.type===p.LITERAL)u[d]=h.value;else if(h.type===p.VARIABLE){let g=h.path;if(g===r)u[d]=c;else if(g.startsWith(r+".")){let y=g.substring(r.length+1);u[d]=c[y]}else return null}else if(h.type===p.INTERPOLATION){let g=[],y=!0;for(let I of h.parts)if(typeof I=="string")g.push(I);else if(I.type===p.VARIABLE){let b=I.path;if(b===r)g.push(c!=null?String(c):"");else if(b.startsWith(r+".")){let m=b.substring(r.length+1),E=c[m];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}a.push(u)}}return a}}}return null},Yo=(e,t)=>{let n=e.body,r=e.itemVar,o=Wo(e,t);if(o!==null)return o;if(n.type===p.OBJECT&&n.properties.length<=5&&!n.whenCondition){for(let a of n.properties)if(a.parsedKey)return null;let i=[],s=!0;for(let a of n.properties){let l=a.key,c=a.value;if(c.type===p.LITERAL)i.push({key:l,type:"literal",value:c.value});else if(c.type===p.VARIABLE){let u=c.path;if(u===r)i.push({key:l,type:"item"});else if(u.startsWith(r+".")){let f=u.substring(r.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:l,type:"prop",prop:f});else{s=!1;break}}else{s=!1;break}}else if(c.type===p.INTERPOLATION&&c.parts.length===1){let u=c.parts[0];if(u.type===p.VARIABLE){let f=u.path;if(f===r)i.push({key:l,type:"item_string"});else if(f.startsWith(r+".")){let d=f.substring(r.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:l,type:"prop_string",prop:d});else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}if(s){let a=new Array(t.length);if(i.length===3&&i[0].type==="prop"&&i[0].key==="id"&&i[1].type==="prop_string"&&i[1].key==="title"&&i[2].type==="prop"&&i[2].key==="completed")for(let l=0;l<t.length;l++){let c=t[l];a[l]={id:c.id,title:c.title!=null?String(c.title):"",completed:c.completed}}else for(let l=0;l<t.length;l++){let c=t[l],u={};for(let f of i)if(f.type==="literal")u[f.key]=f.value;else if(f.type==="item")u[f.key]=c;else if(f.type==="prop")u[f.key]=c[f.prop];else if(f.type==="item_string")u[f.key]=c!=null?String(c):"";else if(f.type==="prop_string"){let d=c[f.prop];u[f.key]=d!=null?String(d):""}a[l]=u}return a}}return null},qo=(e,t,n,r,o)=>{let i=[],s=e.body;if(s.type===p.OBJECT&&s.fast!==!1){let a=e.itemVar,l=e.indexVar;for(let c=0;c<o.length;c++){let u=o[c],f={},d={...r,[a]:u,...l&&{[l]:c}};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__,[a]:`${h}[${c}]`,...l&&{[l]:c}};for(let g of s.properties){let y=g.parsedKey?L(g.parsedKey,t,n,d):g.key,I=g.value;if(I.type===p.LITERAL)f[y]=I.value;else if(I.type===p.VARIABLE){let b=I.path;if(b===a)f[y]=u;else if(b===l)f[y]=c;else if(b.startsWith(a+".")){let m=b.substring(a.length+1);!m.includes(".")&&!m.includes("[")?f[y]=u[m]:f[y]=B(b,n,{...r,[a]:u,...l&&{[l]:c}})}else f[y]=B(b,n,{...r,[a]:u,...l&&{[l]:c}})}else if(I.type===p.INTERPOLATION){let b=[];for(let m of I.parts)if(typeof m=="string")b.push(m);else if(m.type===p.VARIABLE){let E=m.path,S;if(E===a)S=u;else if(E===l)S=c;else if(E.startsWith(a+".")){let $=E.substring(a.length+1);!$.includes(".")&&!$.includes("[")?S=u[$]:S=B(E,n,{...r,[a]:u,...l&&{[l]:c}})}else S=B(E,n,{...r,[a]:u,...l&&{[l]:c}});b.push(S!=null?String(S):"")}else{let E={...r,[a]:u,...l&&{[l]:c}},S=L(m,t,n,E);b.push(S!=null?String(S):"")}f[y]=b.join("")}else{let b={...r,[a]:u,...l&&{[l]:c}};f[y]=L(I,t,n,b)}}i.push(f)}return i}return null},Ho=(e,t,n)=>{let r=e.body;if(r.type===p.OBJECT&&r.properties.length===1&&r.properties[0].key==="$if item.visible"){let i=r.properties[0].value;if(i.type===p.CONDITIONAL&&i.conditions.length===1&&i.conditions[0].type===p.VARIABLE&&i.conditions[0].path==="item.visible"){let s=i.bodies[0];if(s.type===p.OBJECT&&s.properties.length===2){let a=s.properties[0],l=s.properties[1];if(a.key==="id"&&a.value.type===p.VARIABLE&&a.value.path==="item.id"&&l.key==="$if item.highlighted"&&l.value.type===p.CONDITIONAL){let c=[];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),c.push(d)}}return c}}}}return null},Jo=(e,t,n,r)=>{let o=L(e.iterable,t,n,r);if(!Array.isArray(o)){let c,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(", ");c=`${e.iterable.name}(${d})`}else c=e.iterable.path||"undefined";let f=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${c}`;throw Bn(f,o,u)}if(!e.indexVar){let c=Ho(e,o,e.itemVar);if(c!==null)return c}if(!e.indexVar){let c=Yo(e,o);if(c!==null)return c}let i=qo(e,t,n,r,o);if(i!==null)return i;let s=[],a=e.iterable.path||"";if(r&&r.__paths__&&a){let c=a.split("."),u=c[0];u in r.__paths__&&(a=r.__paths__[u],c.length>1&&(a+="."+c.slice(1).join(".")))}let l=!1;e.body.type===p.ARRAY&&(e.body.items.length<=1?l=!1:l=e.body._shouldPreserveArray??=e.body.items.some(c=>c.type===p.OBJECT&&c.properties.some(u=>u.key.startsWith("$if ")||u.key.startsWith("$when "))));for(let c=0;c<o.length;c++){let u=e.indexVar?{...r,[e.itemVar]:o[c],[e.indexVar]:c}:{...r,[e.itemVar]:o[c]};u.__paths__||(u.__paths__=r.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${a}[${c}]`},e.indexVar&&(u.__paths__[e.indexVar]=c);let f=L(e.body,t,n,u);if(Array.isArray(f)&&f.length===1&&!l){let d=f[0];s.push(d===void 0?{}:d)}else s.push(f===void 0?{}:f)}return s},Ko=(e,t,n,r)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?L(o.parsedKey,t,n,r):o.key,s=o.value;if(s.type===p.OBJECT&&s.properties.length<=10&&!s.whenCondition){let a={},l={},c=!0;for(let u of s.properties){let f=u.parsedKey?L(u.parsedKey,t,n,r):u.key,d=u.value;if(d.type===p.LITERAL)l[f]=d.value;else if(d.type===p.VARIABLE)l[f]=B(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=B(g.path,n,r);h.push(y!=null?String(y):"")}else{c=!1;break}if(!c)break;l[f]=h.join("")}else if(d.type===p.OBJECT&&d.properties.length<=5){let h={};for(let g of d.properties){let y=g.key,I=g.value;if(I.type===p.LITERAL)h[y]=I.value;else if(I.type===p.VARIABLE)h[y]=B(I.path,n,r);else if(I.type===p.INTERPOLATION){let b=[];for(let m of I.parts)if(typeof m=="string")b.push(m);else if(m.type===p.VARIABLE){let E=B(m.path,n,r);b.push(E!=null?String(E):"")}else{c=!1;break}if(!c)break;h[y]=b.join("")}else{c=!1;break}}if(!c)break;l[f]=h}else{c=!1;break}}if(c)return a[i]=l,a}}return null},Go=(e,t,n,r)=>{let o=t.functions||t;if(e.whenCondition&&!fe(e.whenCondition,o,n,r))return;let i=Ko(e,t,n,r);if(i!==null)return i;if(e.fast){let c={};for(let u of e.properties){let f=u.parsedKey?L(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]=B(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=B(g.path,n,r);h.push(y!=null?String(y):"")}else{let y=L(g,t,n,r);h.push(y!=null?String(y):"")}c[f]=h.join("")}else c[f]=L(d,t,n,r)}return c}let s={},a=null,l=!1;for(let c of e.properties)if(!c.key.startsWith("$if ")&&!c.key.match(/^\$if\s+\w+.*:?$/)&&!c.key.startsWith("$elif")&&!c.key.startsWith("$else")&&!c.key.startsWith("$for ")){l=!0;break}for(let c of e.properties)if(c.key.startsWith("$if ")||c.key.match(/^\$if\s+\w+.*:?$/)){let u=L(c.value,t,n,r);if(!l&&u!==null&&u!==void 0)return Array.isArray(u)&&u.length===1?u[0]:u;typeof u=="object"&&u!==null&&!Array.isArray(u)&&Object.assign(s,u)}else if(c.key.startsWith("$for ")){if(e.properties.length===1)return L(c.value,t,n,r)}else{let u=c.value;if(u&&u.type===p.OBJECT&&u.properties){let f=u.properties.find(d=>d.key.startsWith("$for "));if(f){let d=L(f.value,t,n,r);d!==void 0&&(s[c.key]=d)}else{let d=L(c.value,t,n,r);d!==void 0&&(s[c.key]=d)}}else{let f=c.parsedKey?L(c.parsedKey,t,n,r):c.key,d=L(c.value,t,n,r);d!==void 0&&(s[f]=d)}}return s},Hn={},Xo=(e,t,n,r)=>{let o=[];for(let i of e.items)if(i.type===p.LOOP){let s=L(i,t,n,r);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=L(i,t,n,r);s!==Hn&&s!==void 0&&o.push(s)}return o},Qo=(e,t,n,r)=>{let{name:o,data:i,whenCondition:s}=e,a=t.partials||{},l=t.functions||t;if(s&&!fe(s,l,n,r))return;if(!a[o])throw new K(`Partial '${o}' is not defined`);let c=r._partialStack||[];if(c.includes(o))throw new K(`Circular partial reference detected: ${o}`);let u=a[o],f=n,d={...r,_partialStack:[...c,o]};if(r){f={...n};for(let h of Object.keys(r))h.startsWith("_")||(f[h]=r[h])}if(i){let h=L(i,t,n,r);f={...f,...h}}return L(u,t,f,d)},Zo=(e,t,n,r)=>{let{path:o}=e,i=o.split("."),s=i[0],a=i.slice(1);if(!r||!(s in r))throw new K(`Path reference '#{${o}}' refers to '${s}' which is not a loop variable in the current scope`);if(r.__paths__||(r.__paths__={}),!(s in r.__paths__))throw new K(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let l=r.__paths__[s];if(typeof l=="number"){if(a.length>0)throw new K(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(l)}return a.length>0&&(l+="."+a.join(".")),l};var Nt=Mo;var ei=/\$\{([^}]*)\}/g,ti=/#\{([^}]*)\}/g,Kn=(e,t={})=>{let n=e.match(/^(\w+)\((.*)\)$/);if(!n)return{isFunction:!1};let[,r,o]=n,i=ni(o,t);return{isFunction:!0,type:p.FUNCTION,name:r,args:i}},ni=(e,t={})=>e.trim()?ri(e).map(r=>oi(r.trim(),t)):[],ri=e=>{let t=[],n="",r=0,o=!1,i="";for(let s=0;s<e.length;s++){let a=e[s],l=s>0?e[s-1]:"";!o&&(a==='"'||a==="'")?(o=!0,i=a,n+=a):o&&a===i&&l!=="\\"?(o=!1,i="",n+=a):!o&&a==="("?(r++,n+=a):!o&&a===")"?(r--,n+=a):!o&&a===","&&r===0?(t.push(n),n=""):n+=a}return n&&t.push(n),t},oi=(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=Kn(e,t);if(n.isFunction)return{type:n.type,name:n.name,args:n.args};let r=e.trim(),o=[{op:" + ",type:"ADD"},{op:" - ",type:"SUBTRACT"}],i=-1,s=null;for(let{op:a,type:l}of o){let c=0;for(;c<r.length;){let u=ye(r.substring(c),a);if(u===-1)break;let f=c+u;f>i&&(i=f,s={op:a,type:l}),c=f+a.length}}if(i!==-1)try{return W(r,t)}catch{return{type:p.VARIABLE,path:r}}return{type:p.VARIABLE,path:r}},Gn=/^\w+\(.*\)$/,ii=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,si=e=>{if(!(!e||e.trim()===""||Gn.test(e))&&ii.test(e))throw e.includes("?")&&e.includes(":")?new w(`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 w(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new w(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},Jn=e=>{let t=e.trim();if(Gn.test(t))throw new w(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new w(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new w(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new w(`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 w(`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}},De=(e,t={})=>{let n=e.trim();si(n);let r=Kn(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}},Dt=(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,(c,u)=>{let f=`__ESCAPED_${r.length}__`;return r.push(u),f}),n=n.replace(/\\(#\{[^}]*\})/g,(c,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(ei)],i=[...n.matchAll(ti)],s=[...o.map(c=>({match:c,type:"variable"})),...i.map(c=>({match:c,type:"pathref"}))].sort((c,u)=>c.match.index-u.match.index);if(s.length===0){let c=n;for(let u=0;u<r.length;u++)c=c.replace(`__ESCAPED_${u}__`,r[u]);return{type:p.LITERAL,value:c}}if(s.length===1&&s[0].match[0]===n&&r.length===0){let{match:c,type:u}=s[0];try{return u==="variable"?De(c[1],t):Jn(c[1])}catch(f){if(f.message==="Invalid array index syntax")return{type:p.LITERAL,value:n};throw f}}let a=[],l=0;for(let{match:c,type:u}of s){let[f,d]=c,h=c.index;if(h>l){let g=n.substring(l,h);for(let y=0;y<r.length;y++)g=g.replace(`__ESCAPED_${y}__`,r[y]);g&&a.push(g)}try{let g;u==="variable"?g=De(d.trim(),t):g=Jn(d.trim()),a.push(g)}catch(g){if(g.message==="Invalid array index syntax")a.push(f);else throw g}l=h+f.length}if(l<n.length){let c=n.substring(l);for(let u=0;u<r.length;u++)c=c.replace(`__ESCAPED_${u}__`,r[u]);c&&a.push(c)}return{type:p.INTERPOLATION,parts:a}};var Mt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Zn=e=>Object.keys(e),J=e=>e.join("."),de=(e,t,n)=>{let r=Zn(e).filter(o=>!t.has(o));if(r.length>0)throw new w(`Unexpected key '${r[0]}' in condition JSON at '${J(n)}'`)},pe=(e,t)=>typeof e=="string"?Dt(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?ci(e,t):li(e,t):{type:p.LITERAL,value:e},ai=e=>{let{$each:t,...n}=e;if(typeof t!="string")throw new w("$each value must be a non-empty string");let r=t.trim();if(r==="")throw new w("$each value must be a non-empty string");if(Object.keys(n).length===0)throw new w("Empty $each body not allowed");if(n.$partial!==void 0)throw new w("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${r}`]:n}},ci=(e,t)=>{let n=[],r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(typeof i=="object"&&i!==null&&!Array.isArray(i)){if(i.$each!==void 0)try{let l=ai(i),c=Object.keys(l);if(c.length===1&&/^\$for(?::\w+)?\s/.test(c[0])){let u=Qn(c[0],l[c[0]],t,!0);n.push(u),r=!0;continue}}catch(l){throw l instanceof w?l:new w(l.message)}let a=Object.keys(i);if(a.length===1&&/^\$for(?::\w+)?\s/.test(a[0])){let l=Qn(a[0],i[a[0]],t);n.push(l),r=!0;continue}}let s=pe(i,t);n.push(s),(s.type===p.FUNCTION||s.type===p.CONDITIONAL||s.type===p.LOOP||s.type===p.PARTIAL||s.type===p.OBJECT&&!s.fast||s.type===p.ARRAY&&!s.fast)&&(r=!0)}return{type:p.ARRAY,items:n,fast:!r}},li=(e,t)=>{let n=[],r=!1,o=null,i=Object.entries(e),s=0;if(e.$partial!==void 0){if(typeof e.$partial!="string")throw new w("$partial value must be a string");if(e.$partial.trim()==="")throw new w("$partial value cannot be an empty string");let l=["$if","$elif","$else","$for"],c=[];for(let[b]of i)for(let m of l)if(b===m||b.startsWith(m+" ")||b.startsWith(m+"#")){c.push(m);break}if(c.length>0)throw new w(`Cannot use $partial with ${c.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,m]of Object.entries(d)){let E=b;(b.startsWith("\\$")||b.startsWith("$$"))&&(E=b.slice(1)),h[E]=m,g=!0}let y=null;if(g&&(y=pe(h,t),y.type===p.OBJECT)){let b=!1;for(let m of y.properties)if(m.value.type===p.VARIABLE||m.value.type===p.INTERPOLATION||m.value.type===p.FUNCTION||m.value.type===p.CONDITIONAL||m.value.type===p.OBJECT&&!m.value.fast||m.value.type===p.ARRAY&&!m.value.fast){b=!0;break}b&&(y.fast=!1)}let I={type:p.PARTIAL,name:u,data:y};return f!==void 0&&(I.whenCondition=Xn(f,t)),I}for(let[l,c]of i)if(l==="$when"){if(o!==null)throw new w("Multiple '$when' directives on the same object are not allowed");if(c==null)throw new w("Missing condition expression after '$when'");o=Xn(c,t),r=!0}else if(l.startsWith("$when#")||l.startsWith("$when "))throw new w("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<i.length;){let[l,c]=i[s];if(l==="$when"){s++;continue}if(l==="$each")throw new w("$each can only be used inside arrays");if(l.startsWith("$if ")||l.match(/^\$if#\w+\s/)||l.match(/^\$if\s+\w+.*:$/)){let u=ui(i,s,t);n.push({key:l,value:u.node}),r=!0,s=u.nextIndex}else if(/^\$for(?::\w+)?\s/.test(l)){let u=l.match(/^\$for(?::(\w+))?\s/)?.[1]||"",f=u?`:${u}`:"";throw new w(`$for loops must be inside arrays - use '- $for${f} item in items:' instead of '$for${f} item in items:'. For cleaner object generation syntax, consider using $each.`)}else{if(l.startsWith("$elif ")||l.startsWith("$else"))throw new w(`'${l.split(" ")[0]}' without matching '$if'`);if(l==="$if"||l==="$if:")throw new w("Missing condition expression after '$if'");{let u=pe(c,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=Dt(l,t),d={key:l,value:u};(f.type!==p.LITERAL||f.value!==l)&&(d.parsedKey=f),n.push(d),s++}}}let a={type:p.OBJECT,properties:n,fast:!r};return o&&(a.whenCondition=o),a},ui=(e,t,n={})=>{let r=[],o=[],i=t,[s,a]=e[i],l=null,c;if(s.startsWith("$if#")){let f=s.match(/^\$if#(\w+)\s+(.+)$/);if(f)l=f[1],c=f[2];else throw new w(`Invalid conditional syntax: ${s}`)}else c=s.substring(4),c.endsWith(":")&&(c=c.slice(0,-1).trim());Tt(c);let u=W(c,n);for(r.push(u),o.push(pe(a,n)),i++;i<e.length;){let[f,d]=e[i],h=!1,g;if(l?f.startsWith(`$elif#${l} `)?(g=f.substring(`$elif#${l} `.length),g.endsWith(":")&&(g=g.slice(0,-1).trim()),h=!0):(f===`$else#${l}`||f===`$else#${l}:`)&&(h=!0,g=null):f.startsWith("$elif ")?(g=f.substring(6),g.endsWith(":")&&(g=g.slice(0,-1).trim()),h=!0):(f==="$else"||f==="$else:")&&(h=!0,g=null),h){if(g===null)r.push(null);else{Tt(g);let y=W(g,n);r.push(y)}if(o.push(pe(d,n)),i++,g===null)break}else break}return{node:{type:p.CONDITIONAL,conditions:r,bodies:o,id:l},nextIndex:i}},Vt={eq:R.EQ,neq:R.NEQ,gt:R.GT,gte:R.GTE,lt:R.LT,lte:R.LTE,in:R.IN,add:R.ADD,sub:R.SUBTRACT},jt={all:R.AND,any:R.OR},fi=new Set(["var","literal","call","not",...Object.keys(Vt),...Object.keys(jt)]),di=(e,t,n)=>{if(!Array.isArray(e))throw new w(`Condition JSON operator '${t}' at '${J(n)}' requires an array`);if(e.length!==2)throw new w(`Condition JSON operator '${t}' at '${J(n)}' requires exactly 2 operands`);return e},pi=(e,t,n,r,o)=>{if(!Array.isArray(e))throw new w(`Condition JSON operator '${t}' at '${J(o)}' requires an array`);if(e.length===0)throw new w(`Condition JSON operator '${t}' at '${J(o)}' requires at least 1 condition`);return e.map((s,a)=>ne(s,r,[...o,a])).reduce((s,a)=>({type:p.BINARY,op:n,left:s,right:a}))},hi=(e,t,n)=>{let r,o;if(typeof e.call=="string")r=e.call,o=e.args??[],de(e,new Set(["call","args"]),n);else if(Mt(e.call))r=e.call.name,o=e.call.args??[],de(e,new Set(["call"]),n),de(e.call,new Set(["name","args"]),[...n,"call"]);else throw new w(`Condition JSON call at '${J(n)}' requires a function name`);if(typeof r!="string"||r.trim()==="")throw new w(`Condition JSON call at '${J(n)}' requires a non-empty function name`);if(!/^\w+$/.test(r))throw new w(`Invalid condition JSON function name '${r}' at '${J(n)}'`);if(!Array.isArray(o))throw new w(`Condition JSON call '${r}' at '${J(n)}' requires args to be an array`);return{type:p.FUNCTION,name:r,args:o.map((i,s)=>ne(i,t,[...n,"args",s]))}},ne=(e,t={},n=["$when"])=>{if(typeof e=="string"||typeof e=="number"||typeof e=="boolean"||e===null)return{type:p.LITERAL,value:e};if(Array.isArray(e))throw new w(`Condition JSON array at '${J(n)}' must be wrapped in an operator or { literal: [...] }`);if(!Mt(e))throw new w(`Invalid condition JSON value at '${J(n)}'`);let r=Zn(e);if(r.length===0)throw new w(`Condition JSON object at '${J(n)}' must contain an operator`);let o=r.filter(s=>fi.has(s));if(o.length===0)throw new w(`Unknown condition JSON operator '${r[0]}' at '${J(n)}'`);if(o.length>1)throw new w(`Condition JSON at '${J(n)}' must contain exactly one operator`);let i=o.includes("call")?"call":o[0];if(i==="var"){if(de(e,new Set(["var"]),n),typeof e.var!="string"||e.var.trim()==="")throw new w(`Condition JSON var at '${J(n)}' requires a non-empty path`);return{type:p.VARIABLE,path:e.var}}if(i==="literal")return de(e,new Set(["literal"]),n),{type:p.LITERAL,value:e.literal};if(i==="call")return hi(e,t,n);if(i==="not")return de(e,new Set(["not"]),n),{type:p.UNARY,op:_e.NOT,operand:ne(e.not,t,[...n,"not"])};if(i in jt)return de(e,new Set([i]),n),pi(e[i],i,jt[i],t,[...n,i]);if(i in Vt){de(e,new Set([i]),n);let s=di(e[i],i,[...n,i]);return{type:p.BINARY,op:Vt[i],left:ne(s[0],t,[...n,i,0]),right:ne(s[1],t,[...n,i,1])}}throw new w(`Unknown condition JSON operator '${i}' at '${J(n)}'`)},Xn=(e,t={})=>{if(e==null)throw new w("Missing condition expression after '$when'");if(typeof e=="string"){if(e.trim()==="")throw new w("Empty condition expression after '$when'");return W(e,t)}return Mt(e)||Array.isArray(e)?ne(e,t):{type:p.LITERAL,value:e}},W=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let c=e.slice(1,-1),u=0,f=!0;for(let d=0;d<c.length;d++)if(c[d]==="("?u++:c[d]===")"&&u--,u<0){f=!1;break}if(f&&u===0)return W(c,t)}let n=ye(e,"||");if(n!==-1)return{type:p.BINARY,op:R.OR,left:W(e.substring(0,n).trim(),t),right:W(e.substring(n+2).trim(),t)};let r=ye(e,"&&");if(r!==-1)return{type:p.BINARY,op:R.AND,left:W(e.substring(0,r).trim(),t),right:W(e.substring(r+2).trim(),t)};let o=[{op:">=",type:R.GTE},{op:"<=",type:R.LTE},{op:"==",type:R.EQ},{op:"!=",type:R.NEQ},{op:">",type:R.GT},{op:"<",type:R.LT},{op:" in ",type:R.IN}];for(let{op:c,type:u}of o){let f=ye(e,c);if(f!==-1)return{type:p.BINARY,op:u,left:W(e.substring(0,f).trim(),t),right:W(e.substring(f+c.length).trim(),t)}}let i=-1,s=null,a=[{op:" + ",type:R.ADD},{op:" - ",type:R.SUBTRACT}];for(let{op:c,type:u}of a){let f=0;for(;f<e.length;){let d=ye(e.substring(f),c);if(d===-1)break;let h=f+d;h>i&&(i=h,s={op:c,type:u}),f=h+c.length}}if(i!==-1&&s)return{type:p.BINARY,op:s.type,left:W(e.substring(0,i).trim(),t),right:W(e.substring(i+s.op.length).trim(),t)};let l=[" * "," / "," % "];for(let c of l)if(ye(e,c)!==-1)throw new w(`Arithmetic operations are not allowed in conditionals: "${c}"`);return e.startsWith("!")?{type:p.UNARY,op:_e.NOT,operand:W(e.substring(1).trim(),t)}:er(e,t)},ye=(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},gi=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}},er=(e,t)=>{let n=e.trim();if(n.match(/^(\w+)\((.*)\)$/))return De(n,t);let o=gi(n);if(o.type===p.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(n))return{type:p.VARIABLE,path:n};try{return De(n,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},mi=(e,t=!1)=>{let n=t?"$each":"$for";try{Un(e)}catch(r){if(r instanceof w&&t){let o=r.message.replace(/\$for/g,"$each");throw new w(o.replace("Parse Error: ",""))}throw r}},Qn=(e,t,n,r=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let I=r?"$each":"$for";throw new w(`Invalid loop syntax (got: '${e.replace("$for",I)}')`)}let s=i[1],a=i[2].trim();mi(a,r);let l=a.match(/^(.+?)\s+in\s+(.+)$/);if(!l){let I=r?"$each":"$for";throw new w(`Invalid loop syntax - missing 'in' keyword (got: '${I} ${a}')`)}let c=l[1].trim(),u=l[2].trim(),f,d=null;if(c.includes(",")){let I=c.split(",").map(b=>b.trim());if(I.length!==2)throw new w(`Invalid loop variables: ${c}. Expected format: "item" or "item, index"`);f=I[0],d=I[1]}else f=c;let h=["this","undefined","null","true","false"];if(h.includes(f))throw new w(`Reserved variable name: ${f}`);if(d&&h.includes(d))throw new w(`Reserved variable name: ${d}`);let g=er(u,n),y=pe(t,n);return{type:p.LOOP,itemVar:f,indexVar:d,iterable:g,body:y,flatten:s!=="nested"}};var yi=(e,t={})=>{let{functions:n={}}=t;return pe(e,n)},rt=yi;var Ve={};Lo(Ve,{now:()=>bi});var bi=()=>Date.now();var Ii=(e,t,n={})=>{let{functions:r={},partials:o={}}=n,i={...Ve,...r},s=rt(e,{functions:i}),a={};for(let[l,c]of Object.entries(o))a[l]=rt(c,{functions:i});return Nt(s,t,{functions:i,partials:a})},Z=Ii;var Ai=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",wi=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,xi=(e,t)=>{if(Ai(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new w("Empty condition expression");return W(e,t)}return ne(e,t)},Ei=(e,t={},n={})=>{let r=wi(n),o={...Ve,...r},i=xi(e,o);return!!fe(i,{functions:o,partials:{}},t,{})},je=Ei;var tr=(e,t,n={})=>{let r=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=l=>l,transformActionFirstArgument:a=l=>l}=n;for(let[l,c]of Object.entries(t))l!=="createInitialState"&&(l.startsWith("select")?o[l]=(...u)=>c(s(r),...u):i[l]=(...u)=>{r=Pt(r,d=>c(a(d),...u))});return{...o,...i}},ot=(e,t)=>n=>{let r=e(),o=Array.isArray(n)?n:[n];return Pt(r,i=>{o.forEach(s=>{t.forEach(a=>{a(i,s)})})})};var vi=(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{}}},Ft=e=>{let t={},n={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([r,o])=>{let i=vi(o,r);o.scope==="context"?t[r]=i:n[r]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}},zt=(e,t)=>{let n=["context","device","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(", ")}`)},Wt=(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(", ")}`)},Yt=(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}`)}};var nr=(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()))},Si=(e,t)=>{let n=i=>{if(!i)return;let s={};i.ui&&(s.ui=i.ui);let a=i.character?.sprite;return a&&Object.keys(a).length>0&&(s.sprite=a),Object.keys(s).length>0?s:void 0},r=n(e),o=n(t);return JSON.stringify(r)===JSON.stringify(o)?null:r&&!o?{changeType:"delete",data:e}:o&&!r?{changeType:"add",data:t}:o&&r?{changeType:"update",data:t}:null},qt=(e={},t={})=>{let n={},r=["sfx","voice"],o=s=>{let a=e[s],l=t[s];l&&!a?n[s]={changeType:"add",data:l}:a&&!l?r.includes(s)||(n[s]={changeType:"delete",data:a}):a&&l&&JSON.stringify(a)!==JSON.stringify(l)&&(n[s]={changeType:"update",data:l})};o("background"),o("bgm"),o("voice");let i=Si(e.dialogue,t.dialogue);return i&&(n.dialogue=i),o("choice"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),n},Ht=(e={})=>{let t=structuredClone(e);t.background&&(t.background.animations?.playback?.continuity!=="persistent"&&delete t.background.animations,t.background.resourceId||delete t.background);let n=o=>{t[o]&&(delete t[o].animations,Object.keys(t[o]).length===0&&delete t[o])};n("layout"),n("choice"),t.dialogue?.ui&&(delete t.dialogue.ui.animations,Object.keys(t.dialogue.ui).length===0&&delete t.dialogue.ui,Object.keys(t.dialogue).length===0&&delete t.dialogue),t.dialogue?.character?.sprite&&(delete t.dialogue.character.sprite.animations,Object.keys(t.dialogue.character.sprite).length===0&&delete t.dialogue.character.sprite,Object.keys(t.dialogue.character).length===0&&delete t.dialogue.character,Object.keys(t.dialogue).length===0&&delete t.dialogue);let r=(o,i)=>{let s=t[o]?.items;Array.isArray(s)&&(t[o].items=s.map(a=>{let l={...a};return delete l.animations,i(l)?l:null}).filter(Boolean),t[o].items.length===0&&delete t[o])};return r("character",o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId),r("visual",o=>o.resourceId||o.transformId),t},Ci=(e,t)=>{if(!e||!t)return;let n=e;for(let r of t.split(".")){if(n==null||!(r in Object(n)))return;n=n[r]}return n},_i=(e,t)=>{if(typeof e!="string")return e;if(e==="_event"){if(t==null)throw new Error('Action template binding "_event" requires event context "_event".');return t}if(!e.startsWith("_event."))return e;if(t==null)throw new Error(`Action template binding "${e}" requires event context "_event".`);let n=e.slice(7),r=Ci(t,n);if(r===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return r},Ri={conditional:new Set(["branches"]),updateProjectData:new Set(["projectData"]),showConfirmDialog:new Set(["confirmActions","cancelActions"])},rr=(e,t)=>{let n=e[e.length-1];return n?Ri[n]?.has(t)===!0:!1},Ut=(e,t,n=[])=>Array.isArray(e)?e.map(r=>Ut(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,rr(n,r)?o:Ut(o,t,[...n,r])])):_i(e,t),Bt=(e,t,n=[])=>Array.isArray(e)?e.map(r=>Bt(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,rr(n,r)?o:Bt(o,t,[...n,r])])):typeof e=="string"?Z(e,t):e,Jt=(e,t)=>{if(!t)return e;if(Object.prototype.hasOwnProperty.call(t,"event"))throw new Error('Action template context key "event" is no longer supported. Use "_event".');let n=Ut(e,t._event);return Bt(n,t)};var it=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:structuredClone(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},sr=(e,t)=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let n=e.map(r=>structuredClone(r)).filter(r=>t(r)||r.animations);return{hasValidItems:n.length>0,processedItems:n}},Re=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),or=e=>e?.animations?.playback?.continuity==="persistent",Li=e=>{if(e){if(e.character&&Re(e.character,"name"))return e.character.name;if(Re(e,"characterName"))return e.characterName}},ar=e=>!!e?.character&&Re(e.character,"sprite"),$i=e=>{let t={},n=!1,r=Li(e);return r!==void 0&&(t.name=r,n=!0),ar(e)&&(t.sprite=structuredClone(e.character.sprite),n=!0),n?t:void 0},ir=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},Oi=()=>({}),ki=(e,t)=>{if(t.background){let{animationsOnly:n,state:r}=it(t.background,s=>!!s.resourceId);if(n){e.background=e.background?.resourceId?{...structuredClone(e.background),...r}:r;return}if(!t.background.resourceId){delete e.background;return}let o=structuredClone(t.background),i=e.background;i?.resourceId===o.resourceId&&i?.transformId===o.transformId&&!Re(o,"animations")&&or(i)&&(o.animations=structuredClone(i.animations)),e.background=o}else e.background?.animations&&!or(e.background)&&(e.background.animations={})},Pi=(e,t)=>{if(!t.dialogue){e.dialogue&&(ir(e.dialogue),e.dialogue.mode==="adv"&&(e.dialogue.content=void 0,e.dialogue.persistCharacter!==!0&&(delete e.dialogue.characterId,delete e.dialogue.character)));return}if(e.dialogue||(e.dialogue={}),t.dialogue.ui){let{animationsOnly:a,state:l}=it(t.dialogue.ui,c=>!!c.resourceId);a?e.dialogue.ui={...e.dialogue.ui,...l}:e.dialogue.ui={...t.dialogue.ui}}else e.dialogue?.ui?.animations&&(e.dialogue.ui.animations={});t.dialogue.mode==="adv"&&(e.dialogue.content=e.dialogue.content||void 0,e.dialogue.characterId=e.dialogue.characterId||void 0,e.dialogue.mode="adv"),t.dialogue.mode==="nvl"&&(e.dialogue?.mode!=="nvl"&&(e.dialogue.lines=[]),e.dialogue.mode="nvl"),t.dialogue.content!==void 0&&(e.dialogue.content=t.dialogue.content);let n=Re(t.dialogue,"persistCharacter")?t.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;n?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let r=Re(t.dialogue,"characterId"),o=$i(t.dialogue),i=o!==void 0,s=ar(t.dialogue);if(r?t.dialogue.characterId?e.dialogue.characterId=t.dialogue.characterId:delete e.dialogue.characterId:n||delete e.dialogue.characterId,i?e.dialogue.character=!r&&n&&e.dialogue.character?{...structuredClone(e.dialogue.character),...o}:o:(r||!n)&&delete e.dialogue.character,s||ir(e.dialogue),t.dialogue.clear){delete e.dialogue;return}if(t.dialogue?.clearPage&&e.dialogue?.mode==="nvl"&&(e.dialogue.lines=[]),e.dialogue?.mode==="nvl"&&t.dialogue.content!==void 0){let a={content:t.dialogue.content,characterId:e.dialogue.characterId??null};e.dialogue.character&&(a.character=structuredClone(e.dialogue.character)),e.dialogue.lines.push(a)}},Ti=(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},Ni=(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}}},Di=(e,t)=>{if(t.visual){let{hasValidItems:n,processedItems:r}=sr(t.visual.items,o=>!!o.resourceId);n?e.visual={items:r}:delete e.visual}else e.visual?.items&&(e.visual.items=e.visual.items.map(n=>n.animations?{...n,animations:{}}:n))},Vi=(e,t)=>{if(!t.character){e.character?.items&&(e.character.items=e.character.items.map(o=>o.animations?{...o,animations:{}}:o));return}let{hasValidItems:n,processedItems:r}=sr(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId);n?e.character={items:r}:delete e.character},ji=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},Mi=(e,t)=>{if(t.layout){let{animationsOnly:n,state:r}=it(t.layout,o=>!!o.resourceId);if(n){e.layout=r;return}if(!t.layout.resourceId){delete e.layout;return}e.layout=t.layout}else e.layout&&delete e.layout},Ui=(e,t)=>{if(t.choice){let{animationsOnly:n,state:r}=it(t.choice,o=>!!o.resourceId);if(n){e.choice={...e.choice,...r};return}if(!t.choice.resourceId){delete e.choice;return}e.choice=t.choice}else e.choice&&delete e.choice},Bi=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},Fi=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},zi=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(n=>{delete e[n]})},Le=e=>ot(Oi,[zi,ki,Ti,Ni,Di,Pi,Vi,ji,Mi,Ui,Bi,Fi])(e);var be={objectValues:e=>Object.entries(e).map(([t,n])=>({id:t,...n})),formatDate:nr},Wi=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,Yi=(e,t)=>{let n=String(t||"").trim();if(!n)return;let r=n.match(/[A-Za-z_][A-Za-z0-9_]*|\[\d+\]/g)||[],o=e;for(let i of r){if(i.startsWith("[")){let s=Number(i.slice(1,-1));o=Array.isArray(o)?o[s]:void 0;continue}o=o?.[i]}return o},ct=(e,t,n)=>{if(Array.isArray(e)){let o=[];for(let i of e){if(i&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===1){let[s]=Object.keys(i),a=Wi.exec(s);if(a){let[,l,c,u]=a,f=Yi(t,u);if(!Array.isArray(f))continue;let d=Array.isArray(i[s])?i[s]:[];f.forEach((h,g)=>{let y={...t,[l]:h};c&&(y[c]=g),d.forEach(I=>{let b=ct(I,y,n),m=Z(b,y,n);Array.isArray(m)?o.push(...m):o.push(m)})});continue}}o.push(ct(i,t,n))}return o}if(!e||typeof e!="object")return e;let r={};return Object.entries(e).forEach(([o,i])=>{r[o]=ct(i,t,n)}),r},sn=({animationType:e,animationId:t,animationPath:n})=>{if(e!==void 0&&!(e==="update"||e==="transition"))throw new Error(`[${n}] Animation "${t}" has unsupported type "${e}". Use "update" or "transition".`)},qi=({id:e,targetId:t,animation:n,playback:r,animationPath:o="animation"})=>{let i=structuredClone(n);return sn({animationType:i.type,animationId:e,animationPath:o}),delete i.name,delete i.playback,i.id=e,i.targetId=t,r&&(i.playback=structuredClone(r)),i},Hi=(e,{animationId:t="animation",animationPath:n="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return sn({animationType:e.type,animationId:t,animationPath:n}),e.type},Ji=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},Ki=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},Gi=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Ar=e=>e?.playback?.continuity==="persistent",en=e=>Array.isArray(e)?e.map(en):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((t,n)=>(t[n]=en(e[n]),t),{}),lt=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let t=structuredClone(e);return delete t.playback,JSON.stringify(en(t))},wr=(e=[])=>e.filter(t=>Ar(t)).map(t=>structuredClone(t)),xr=e=>Array.isArray(e?.keyframes)?e.keyframes.reduce((t,n)=>{let r=typeof n?.duration=="number"&&Number.isFinite(n.duration)?n.duration:0;return t+r},0):0,Kt=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((t,n)=>Math.max(t,xr(n)),0),Er=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max(Kt(e.tween),Kt(e.prev?.tween),Kt(e.next?.tween),xr(e.mask?.progress)),cr=({animationInstances:e,activePersistentAnimations:t})=>{if(!Array.isArray(e)||e.length===0||!Array.isArray(t)||t.length===0)return!1;let n=new Set(t.map(lt).filter(Boolean));return e.some(r=>{if(!Ar(r))return!1;let o=lt(r);return o?n.has(o):!1})},se=({animationInstances:e,isLineCompleted:t,skipTransitionsAndAnimations:n,activePersistentAnimations:r,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||n?!1:i&&!t||cr({animationInstances:e,activePersistentAnimations:r})?!0:i?!1:cr({animationInstances:e,activePersistentAnimations:o}),Xi=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),Qi=(e,t)=>{if(Xi(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},Zi=({resources:e,animationId:t,playback:n,instanceId:r,targetId:o,animationPath:i="animation"})=>{if(!t||!o)return!1;let s=e?.animations?.[t];return s?qi({id:r,targetId:o,animation:s,playback:n,animationPath:i}):null},es=({hasPrevious:e,hasCurrent:t,previousResourceId:n,currentResourceId:r,sharedTarget:o})=>!e&&t?"enter":e&&!t?"exit":e&&t?n===r&&o?"update":"replace":"none",ts=({animationType:e,animationId:t,animationPath:n,lifecycle:r})=>{if(!(e!=="update"||r==="update"))throw new Error(`[${n}] Animation "${t}" has type "update", but update animations can only be used when the same target persists across the state change. Use type "transition" for enter, exit, and replace.`)},ns=(e,{defaultTargetId:t,defaultId:n,animationPath:r="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return sn({animationType:o.type,animationId:o.id??n,animationPath:r}),o.id??=n,o.targetId??=t,o},an=({animations:e,transitions:t,defaultTargetId:n,idPrefix:r,animationPathPrefix:o=r})=>{t.forEach((i,s)=>{e.push(ns(i,{defaultTargetId:n,defaultId:`${r}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},lr=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let n=Z(e,t);return n&&typeof n=="object"?e:n},ur=(e,t)=>{if(e===void 0)return[];if(!Array.isArray(e)||e.some(n=>n===null||typeof n!="object"||Array.isArray(n)))throw new Error(`${t} must be an array of objects`);return e},fr=(e=[])=>{let t=new Map;for(let n of e)n?.id&&t.set(n.id,(t.get(n.id)??0)+1);return new Set(Array.from(t.entries()).filter(([,n])=>n>1).map(([n])=>n))},st=(e,t=0,n=new Set)=>{if(!n.has(e?.id))return`character-container-${e.id}`;let r=e?.sprites?.map(({resourceId:o})=>o)||[];return r.length===0?`character-container-${e.id}`:`character-container-${e.id}-${t}-${r.join("-")}`},Gt=(e,t)=>{if(!t.transformId)throw new Error(`Visual item "${t.id}" requires transformId`);let n=e.transforms?.[t.transformId];if(!n)throw new Error(`Transform "${t.transformId}" not found for visual item "${t.id}"`);return n},rs=(e,t={})=>{if(!t?.transformId)return;let n=e.transforms?.[t.transformId];if(!n)throw new Error(`Transform "${t.transformId}" not found for background`);return n},dr=(e={},t)=>{if(t){if(e.images?.[t])return"sprite";if(e.videos?.[t])return"video";if(e.layouts?.[t])return"container"}},at=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},os=(e={})=>e.textStyles||{},is=(e={})=>e.images||{},ss=(e={})=>e.colors||{},as=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,Me=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,Oe=(e,t,n)=>{if(typeof e!="string"||e.length===0)throw new Error(`${n} at "${t}" must resolve to a non-empty string`)},pr=(e,t,n)=>{if(e===void 0)return 1;if(typeof e!="number"||!Number.isFinite(e))throw new Error(`${t} for text style "${n}" must be a number between 0 and 1`);if(e<0||e>1)throw new Error(`${t} for text style "${n}" must be a number between 0 and 1`);return e},vr=(e,t)=>{if(typeof e!="string"||!as.test(e))throw new Error(`${t} must resolve to a hex color`);return e.length===4?`#${e.slice(1).split("").map(n=>n.repeat(2)).join("")}`:e},hr=(e,t,n)=>{let r=vr(e,n);if(t===1)return r;let o=Number.parseInt(r.slice(1,3),16),i=Number.parseInt(r.slice(3,5),16),s=Number.parseInt(r.slice(5,7),16);return`rgba(${o}, ${i}, ${s}, ${t})`},cs=(e={},t)=>{let n=os(e)?.[t];if(!n)throw new Error(`Text style "${t}" not found`);let r=e.fonts?.[n.fontId];if(!r)throw new Error(`Font "${n.fontId}" not found for text style "${t}"`);let o=e.colors?.[n.colorId];if(!o)throw new Error(`Color "${n.colorId}" not found for text style "${t}"`);let i=pr(n.colorAlpha,"colorAlpha",t),s={fontFamily:r.fileId,fontSize:n.fontSize??16,fontWeight:n.fontWeight??"400",fontStyle:n.fontStyle??"normal",lineHeight:n.lineHeight??1.2,fill:hr(o.hex,i,`Color "${n.colorId}" for text style "${t}"`)};if(n.align!==void 0&&(s.align=n.align),n.wordWrap!==void 0&&(s.wordWrap=n.wordWrap),n.breakWords!==void 0&&(s.breakWords=n.breakWords),n.wordWrapWidth!==void 0&&(s.wordWrapWidth=n.wordWrapWidth),n.strokeColorId){let a=e.colors?.[n.strokeColorId];if(!a)throw new Error(`Stroke color "${n.strokeColorId}" not found for text style "${t}"`);let l=pr(n.strokeAlpha,"strokeAlpha",t);s.strokeColor=hr(a.hex,l,`Stroke color "${n.strokeColorId}" for text style "${t}"`)}else if(n.strokeAlpha!==void 0)throw new Error(`strokeAlpha for text style "${t}" requires strokeColorId`);return n.strokeWidth!==void 0&&(s.strokeWidth=n.strokeWidth),s},tn=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>tn(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(Object.prototype.hasOwnProperty.call(e,"textStyle"))throw new Error(`Inline textStyle is not allowed in layout elements at "${n}". Use textStyleId instead`);let r={};for(let[o,i]of Object.entries(e))o!=="textStyleId"&&(r[o]=tn(i,t,Me(n,o)));return e.textStyleId!==void 0&&(Oe(e.textStyleId,n,"textStyleId"),r.textStyle=cs(t,e.textStyleId)),r},Sr=(e={},t)=>{let n=ss(e)?.[t];if(!n)throw new Error(`Color "${t}" not found`);return vr(n.hex,`Color "${t}"`)},Cr=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",Xt=(e,t,n)=>{let r=e?.[t];if(!(!r||typeof r!="object"||Array.isArray(r))&&Object.prototype.hasOwnProperty.call(r,"fill"))throw new Error(`Inline ${t}.fill is not allowed in rect layout elements at "${n}". Use ${Cr(`${t}.fill`)} instead`)},ls=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>Ue(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;let r={};for(let[o,i]of Object.entries(e))o!=="colorId"&&(r[o]=Ue(i,t,Me(n,o)));return e.colorId!==void 0&&(Oe(e.colorId,n,"colorId"),r.fill=Sr(t,e.colorId)),r},Ue=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>Ue(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="rect"){if(Object.prototype.hasOwnProperty.call(e,"fill"))throw new Error(`Inline fill is not allowed in rect layout elements at "${n}". Use ${Cr("fill")} instead`);Xt(e,"hover",n),Xt(e,"click",n),Xt(e,"rightClick",n)}let r={};for(let[o,i]of Object.entries(e))if(!(e.type==="rect"&&o==="colorId")){if(e.type==="rect"&&(o==="hover"||o==="click"||o==="rightClick")){r[o]=ls(i,t,Me(n,o));continue}r[o]=Ue(i,t,Me(n,o))}return e.type==="rect"&&e.colorId!==void 0&&(Oe(e.colorId,n,"colorId"),r.fill=Sr(t,e.colorId)),r},Qt=(e={},t)=>{let n=is(e)?.[t];return n||null},_r=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",gr=(e,t,n,r)=>{let o=e?.[t];if(!(!o||typeof o!="object"||Array.isArray(o))&&Object.prototype.hasOwnProperty.call(o,r))throw new Error(`Inline ${t}.${r} is not allowed in sprite layout elements at "${n}". Use ${_r(`${t}.${r}`)} instead`)},mr=(e,t,n)=>{let r=e[t];e[t]={...r&&typeof r=="object"&&!Array.isArray(r)?r:{},src:n}},nn=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>nn(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="sprite"){for(let o of["url","src","hoverUrl","hoverSrc","clickUrl","clickSrc"])if(Object.prototype.hasOwnProperty.call(e,o))throw new Error(`Inline ${o} is not allowed in sprite layout elements at "${n}". Use ${_r(o)} instead`);gr(e,"hover",n,"src"),gr(e,"click",n,"src")}let r={};for(let[o,i]of Object.entries(e))e.type==="sprite"&&(o==="imageId"||o==="hoverImageId"||o==="clickImageId")||(r[o]=nn(i,t,Me(n,o)));if(e.type==="sprite"&&e.imageId!==void 0){Oe(e.imageId,n,"imageId");let o=Qt(t,e.imageId),i=o?.fileId??e.imageId;r.src=i,r.width===void 0&&o?.width!==void 0&&(r.width=o.width),r.height===void 0&&o?.height!==void 0&&(r.height=o.height)}return e.type==="sprite"&&e.hoverImageId!==void 0&&(Oe(e.hoverImageId,n,"hoverImageId"),mr(r,"hover",Qt(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(Oe(e.clickImageId,n,"clickImageId"),mr(r,"click",Qt(t,e.clickImageId)?.fileId??e.clickImageId)),r},cn=(e,t={},n="root")=>nn(Ue(tn(e,t,n),t,n),t,n),Ie=cn,Be=(e=[])=>e.find(t=>t.id==="story");var us=(e={})=>e?.muteAll?0:e?.musicVolume??50,re=({variables:e,runtime:t,saveSlots:n=[],dialogueState:r,includeInactiveAdvDialogue:o=!1,isLineCompleted:i,autoMode:s,skipMode:a,isChoiceVisible:l,canRollback:c,confirmDialog:u,historyDialogue:f=[],characters:d={},dialogueUIHidden:h,skipOnlyViewedLines:g,skipTransitionsAndAnimations:y}={})=>{let I={dialogueTextSpeed:t?.dialogueTextSpeed??50,autoForwardDelay:t?.autoForwardDelay??1e3,skipUnseenText:t?.skipUnseenText??!1,skipTransitionsAndAnimations:t?.skipTransitionsAndAnimations??!1,soundVolume:t?.soundVolume??50,musicVolume:t?.musicVolume??50,muteAll:t?.muteAll??!1,saveLoadPagination:t?.saveLoadPagination??1,menuPage:t?.menuPage??"",menuEntryPoint:t?.menuEntryPoint??"",autoMode:t?.autoMode??s??!1,skipMode:t?.skipMode??a??!1,dialogueUIHidden:t?.dialogueUIHidden??h??!1,isLineCompleted:t?.isLineCompleted??i??!1},b=hs({dialogueState:r,includeInactiveAdvDialogue:o,characters:d,variables:e}),m={variables:e,runtime:I,saveSlots:n,isChoiceVisible:l,canRollback:c,confirmDialog:u,historyDialogue:f,characters:d};return b&&(m.dialogue=b,m.dialogueLines=b.lines),m},yr=100,ut=(e,t)=>{if(Array.isArray(e))return e.map(r=>ut(r,t));if(!e||typeof e!="object")return e;let n={...e};return Object.keys(n).forEach(r=>{n[r]=ut(n[r],t)}),n.type==="text-revealing"?t(n):n},fs=e=>ut(e,t=>({...t,revealEffect:"none"})),ds=e=>ut(e,t=>{let n=Number(t.speed??t.displaySpeed),r=Number.isFinite(n)?Math.max(n,yr):yr;return{...t,speed:r,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:r}:{}}}),Ae=(e,{isLineCompleted:t=!1,skipMode:n=!1,skipTransitionsAndAnimations:r=!1}={})=>t||r?fs(e):n?ds(e):e,Rr=({id:e,screen:t={width:1920,height:1080}})=>({id:e,type:"rect",fill:"transparent",width:t.width,height:t.height,x:0,y:0,click:{payload:{actions:{}}}}),rn=e=>{if(Array.isArray(e))return e.map(rn);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=rn(s);let n=t.click?.payload;if(!n||typeof n!="object"||Array.isArray(n))return t;let r=n.actions,o=r&&typeof r=="object"&&!Array.isArray(r)&&Object.prototype.hasOwnProperty.call(r,"nextLine")?{...r.nextLine,_interactionSource:"choice"}:void 0;return{...t,click:{...t.click,payload:{...n,_interactionSource:"choice",...o?{actions:{...r,nextLine:o}}:{}}}}},on=({characterId:e,character:t,characterName:n,characters:r={}}={})=>{let o=e?r?.[e]:void 0,i=t?.name!==void 0?t.name:n!==void 0?n:o?.name||"";return{...o||{},...t||{},name:i}},Lr=(e=[],t={})=>e.map(n=>{let r=on({characterId:n.characterId,character:n.character,characterName:n.characterName,characters:t}),o=typeof n.text=="string"?n.text:Array.isArray(n.content)?n.content.map(i=>i?.text??"").join(""):"";return{...n,text:o,character:r,characterName:r.name}}),ps=e=>!(!e||e.mode==="adv"&&e.content===void 0),hs=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:n={},variables:r}={})=>{if(!t&&!ps(e))return;let o=e.content===void 0?[{text:""}]:ur(e.content,"dialogue.content"),i=(e.lines||[]).map((a,l)=>{let c=ur(a.content,`dialogue.lines[${l}].content`),u=on({characterId:a.characterId,character:a.character,characterName:a.characterName,characters:n});return{...a,content:c.map(f=>({...f,text:lr(f.text,{variables:r})})),character:u,characterName:u.name}}),s=on({characterId:e.characterId,character:e.character,characters:n});return{characterId:e.characterId,persistCharacter:e.persistCharacter,character:s,content:o.map(a=>({...a,text:lr(a.text,{variables:r})})),lines:i}},$r=({container:e,resources:t,templateData:n,isLineCompleted:r=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=Z(e,n,{functions:be});return Ie(Ae(s,{isLineCompleted:r,skipMode:o,skipTransitionsAndAnimations:i}),t)},Zt=(e,t={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(t),br=({renderStateKeyboard:e,keyboard:t,phase:n})=>{!t||typeof t!="object"||Array.isArray(t)||Object.entries(t).forEach(([r,o])=>{let i=e[r]??{},s=n==="keydown"?o?.keydown:o?.keyup;if(n==="keydown"&&s&&typeof s=="object"){e[r]={...i,keydown:{payload:Zt(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[r].keyup={payload:Zt(o.keyup)});return}e[r]={...i,[n]:{payload:Zt(o)}}})},gs=(e={},t={})=>{let n={};return br({renderStateKeyboard:n,keyboard:e,phase:"keydown"}),br({renderStateKeyboard:n,keyboard:t,phase:"keyup"}),Object.keys(n).length>0?n:void 0},we=({animationsDef:e,resources:t,previousResourceId:n,currentResourceId:r,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:a,allowIncomingUpdateFallback:l=!1})=>{if(!e)return[];let c=[],u=({instanceId:S,targetId:$})=>{let O=Zi({resources:t,animationId:y,playback:I,instanceId:S,targetId:$,animationPath:s});O&&c.push(O)},f=n!=null&&n!==!1,d=r!=null&&r!==!1,h=o&&i&&o===i,g=es({hasPrevious:f,hasCurrent:d,previousResourceId:n,currentResourceId:r,sharedTarget:h});Qi(e,s);let y=Ji(e),I=Ki(e),b=t?.animations?.[y],m=Hi(b,{animationId:y,animationPath:s}),E=l&&m==="update"&&g!=="update"&&d&&i;if(E||ts({animationType:m,animationId:y,animationPath:s,lifecycle:g}),m==="update")return f&&d&&n===r&&h?u({instanceId:`${a}-animation-update`,targetId:i}):E&&u({instanceId:`${a}-animation-update`,targetId:i}),c;if(m==="transition"){let S=`${a}-animation-transition`,$=I?.continuity==="persistent"?S:`${a}-animation-in`;if(f&&d&&h)return u({instanceId:S,targetId:i}),c;f&&u({instanceId:`${a}-animation-out`,targetId:o}),d&&u({instanceId:$,targetId:i})}return c},ms=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),ys=(e,{presentationState:t,previousPresentationState:n,currentLineActions:r,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:a,variables:l,runtime:c,activePersistentAnimations:u,restoredPersistentAnimations:f,autoMode:d,skipMode:h,isChoiceVisible:g,canRollback:y,saveSlots:I=[]})=>{let{elements:b,animations:m}=e;if(t.background){let E=r===void 0?!0:Gi(r?.background??{},"animations"),S=b.find(P=>P.id==="story");if(!S)return e;let $=rs(o,t.background),O=n?.background?.resourceId,_=t.background.resourceId??(t.background.animations?O:void 0),D=dr(o,O),N=dr(o,_);if(_){let{images:P={},videos:x={}}=o,C=P[_]||x[_];if(C){let M=x[_]!==void 0,z={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...$},Y={id:at({resourceId:_,kind:M?"video":"sprite"}),type:M?"video":"sprite",x:z.x,y:z.y,src:C.fileId,width:C.width,height:C.height,alpha:1,anchorX:z.anchorX,anchorY:z.anchorY,rotation:z.rotation,scaleX:z.scaleX,scaleY:z.scaleY};M&&(Y.loop=t.background.loop??!1,Y.volume=C.volume??50),S.children.push(Y)}}if(_){let{layouts:P={}}=o,x=P[_];if(x){let C={id:at({resourceId:_,kind:"container"}),type:"container",children:x.elements};$&&Object.assign(C,{x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...$});let M=Z(C,re({variables:l,runtime:c,saveSlots:I,dialogueState:t.dialogue,isLineCompleted:s,autoMode:d,skipMode:h,isChoiceVisible:g,canRollback:y,characters:o.characters||{},skipTransitionsAndAnimations:a}),{functions:be});S.children.push(Ie(Ae(M,{isLineCompleted:s,skipMode:h,skipTransitionsAndAnimations:a}),o))}}let k=we({animationsDef:t.background.animations,resources:o,previousResourceId:O,currentResourceId:_,previousTargetId:at({resourceId:O,kind:D}),currentTargetId:at({resourceId:_,kind:N}),animationPath:"background.animations",idPrefix:"bg-cg",allowIncomingUpdateFallback:!0});se({animationInstances:k,isLineCompleted:s,skipTransitionsAndAnimations:a,activePersistentAnimations:u,restoredPersistentAnimations:f,isAuthoredOnCurrentLine:E})&&m.push(...k)}return e},bs=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:a,animations:l}=e;if(t.character&&r){let c=a.find(g=>g.id==="story");if(!c)return e;let u=t.character.items||[],f=n?.character?.items||[],d=fr(u),h=fr(f);for(let g=0;g<u.length;g++){let y=u[g],{transformId:I,sprites:b}=y,m=f.find(P=>P.id===y.id),E=f.findIndex(P=>P.id===y.id),S=m?.sprites&&m.sprites.length>0,$=b&&b.length>0,O=E>=0?st(m,E,h):void 0,_=we({animationsDef:y.animations,resources:r,previousResourceId:O,currentResourceId:$?st(y,g,d):void 0,previousTargetId:O,currentTargetId:$?st(y,g,d):void 0,animationPath:`character.items[${g}].animations`,idPrefix:"character"});if(y.animations&&!b&&!I&&S&&se({animationInstances:_,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){l.push(..._);continue}if(y.animations&&!b&&!I)continue;if(!b||b.length===0||!I){console.warn("Character item missing sprites or transformId:",y);continue}let D=st(y,g,d),N=r.transforms[I];if(!N){console.warn("Transform not found:",I);continue}let k={type:"container",id:D,x:y.x??N.x,y:y.y??N.y,anchorX:N.anchorX,anchorY:N.anchorY,rotation:N.rotation,scaleX:N.scaleX,scaleY:N.scaleY,children:[]};for(let P of b){let x=r.images[P.resourceId];if(!x){console.warn(`Image resource not found: ${P.resourceId}`);continue}k.children.push({type:"sprite",id:`${D}-${P.id}`,src:x.fileId,width:x.width,height:x.height,x:0,y:0})}c.children.push(k),se({animationInstances:_,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(..._)}}return e},Is=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,runtime:a,activePersistentAnimations:l,autoMode:c,skipMode:u,isChoiceVisible:f,canRollback:d,saveSlots:h=[]})=>{let{elements:g,animations:y}=e;if(t.visual&&r){let I=g.find(m=>m.id==="story");if(!I)return e;let b=t.visual.items;for(let m of b){if(m.resourceId){let{images:O={},videos:_={},spritesheets:D={}}=r,N=D[m.resourceId];if(N){let k=Gt(r,m),P=m.animationName;if(P){let x=N.animations?.[P];if(!x)throw new Error(`Animation '${P}' not found in spritesheet resource '${m.resourceId}'`);let C={id:`visual-${m.id}`,type:"animated-sprite",x:m.x??k.x,y:m.y??k.y,width:m.width??N.width,height:m.height??N.height,alpha:m.alpha??1,anchorX:k.anchorX,anchorY:k.anchorY,rotation:k.rotation,scaleX:k.scaleX,scaleY:k.scaleY,spritesheetSrc:N.fileId,spritesheetData:N.jsonData,animation:{frames:x.frames,animationSpeed:m.animationSpeed??x.animationSpeed??.5,loop:m.loop??x.loop??!0}};I.children.push(structuredClone(C))}}else{let k=O[m.resourceId]||_[m.resourceId];if(k){let P=_[m.resourceId]!==void 0,x=Gt(r,m),C={id:`visual-${m.id}`,type:P?"video":"sprite",src:k.fileId,width:k.width,height:k.height,x:x.x,y:x.y,anchorX:x.anchorX,anchorY:x.anchorY,rotation:x.rotation,scaleX:x.scaleX,scaleY:x.scaleY};P&&(C.loop=k.loop??!1,C.volume=k.volume??50),I.children.push(C)}}}if(m.resourceId){let{layouts:O={}}=r,_=O[m.resourceId];if(_){let D=Gt(r,m),N={id:`visual-${m.id}`,type:"container",children:structuredClone(_.elements),x:D.x,y:D.y,anchorX:D.anchorX,anchorY:D.anchorY,rotation:D.rotation,scaleX:D.scaleX,scaleY:D.scaleY},k=Z(N,re({variables:s,runtime:a,saveSlots:h,dialogueState:t.dialogue,isLineCompleted:o,autoMode:c,skipMode:u,isChoiceVisible:f,canRollback:d,characters:r.characters||{},skipTransitionsAndAnimations:i}),{functions:be});I.children.push(Ie(Ae(k,{isLineCompleted:o,skipMode:u,skipTransitionsAndAnimations:i}),r))}}let S=(n?.visual?.items||[]).find(O=>O.id===m.id),$=we({animationsDef:m.animations,resources:r,previousResourceId:S?.resourceId,currentResourceId:m.resourceId,previousTargetId:S?.resourceId?`visual-${m.id}`:void 0,currentTargetId:m.resourceId?`visual-${m.id}`:void 0,animationPath:`visual.items[${m.id}].animations`,idPrefix:m.id});se({animationInstances:$,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:l})&&y.push(...$)}}return e},$e="dialogue-character-sprite",Ir=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,As=(e,{presentationState:t,previousPresentationState:n,resources:r={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:a}=e,l=Be(e.elements);if(!l)return e;let c=t.dialogue?.character?.sprite,u=n?.dialogue?.character?.sprite,f=Ir(c),d=Ir(u),h=we({animationsDef:c?.animations,resources:r,previousResourceId:d?$e:void 0,currentResourceId:f?$e:void 0,previousTargetId:d?$e:void 0,currentTargetId:f?$e:void 0,animationPath:"dialogue.character.sprite.animations",idPrefix:"dialogue-character-sprite"});if(!f)return c?.animations&&d&&se({animationInstances:h,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...h),e;let g=r.transforms?.[c.transformId];if(!g)return console.warn("Transform not found:",c.transformId),e;let y={type:"container",id:$e,x:g.x,y:g.y,anchorX:g.anchorX,anchorY:g.anchorY,rotation:g.rotation,scaleX:g.scaleX,scaleY:g.scaleY,children:[]};for(let I of c.items){let b=r.images?.[I.resourceId];if(!b){console.warn(`Image resource not found: ${I.resourceId}`);continue}y.children.push({type:"sprite",id:`${$e}-${I.id}`,src:b.fileId,width:b.width,height:b.height,x:0,y:0})}return l.children.push(y),se({animationInstances:h,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...h),e},ws=(e,{presentationState:t,previousPresentationState:n,resources:r={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:l,skipOnlyViewedLines:c,isLineCompleted:u,skipTransitionsAndAnimations:f,variables:d,runtime:h,activePersistentAnimations:g,saveSlots:y=[]})=>{let{elements:I,animations:b}=e;if(!t.dialogue||o)return e;let m=I.find(S=>S.id==="story");if(!m)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:S={}}=r,$=S[t.dialogue.ui.resourceId];if($){let O={elements:$.elements},_=re({variables:d,runtime:h,saveSlots:y,dialogueState:t.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:u,autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:l,characters:r.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:c,skipTransitionsAndAnimations:f}),D={functions:be},N=ct(O,_,D),k=Z(N,_,D),P=Ie(Ae(k?.elements,{isLineCompleted:u,skipMode:s,skipTransitionsAndAnimations:f}),r);if(Array.isArray(P))for(let x of P)m.children.push(x);else P&&m.children.push(P)}}As(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:u,skipTransitionsAndAnimations:f,activePersistentAnimations:g});let E=we({animationsDef:t.dialogue.ui?.animations,resources:r,previousResourceId:n?.dialogue?.ui?.resourceId,currentResourceId:t.dialogue.ui?.resourceId,previousTargetId:n?.dialogue?.ui?.resourceId?"dialogue-container":void 0,currentTargetId:t.dialogue.ui?.resourceId?"dialogue-container":void 0,animationPath:"dialogue.ui.animations",idPrefix:"dialogue-ui"});return se({animationInstances:E,isLineCompleted:u,skipTransitionsAndAnimations:f,activePersistentAnimations:g})&&b.push(...E),e},xs=(e,{presentationState:t,previousPresentationState:n,resources:r,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:a,runtime:l,autoMode:c,skipMode:u,isChoiceVisible:f,canRollback:d,activePersistentAnimations:h,saveSlots:g=[]})=>{let{elements:y,animations:I}=e;if(t.choice&&r){let b=Be(y);if(!b)return e;let m=r?.layouts[t.choice.resourceId];if(m&&m.elements){let S={elements:m.elements},$=Z(S,{...re({variables:a,runtime:l,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:i,autoMode:c,skipMode:u,isChoiceVisible:f??!!t.choice,canRollback:d,characters:r.characters||{},skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}},{functions:be}),O=rn(Ie(Ae($?.elements,{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),r));if(Array.isArray(O))for(let _ of O)b.children.push(_);else O&&b.children.push(O)}let E=we({animationsDef:t.choice.animations,resources:r,previousResourceId:n?.choice?.resourceId,currentResourceId:t.choice.resourceId,previousTargetId:n?.choice?.resourceId?"choice-container":void 0,currentTargetId:t.choice.resourceId?"choice-container":void 0,animationPath:"choice.animations",idPrefix:"choice"});se({animationInstances:E,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:h})&&I.push(...E)}return e},Es=(e,{presentationState:t,resources:n={},variables:r,runtime:o,isLineCompleted:i,autoMode:s,skipMode:a,isChoiceVisible:l,canRollback:c,saveSlots:u=[],skipTransitionsAndAnimations:f})=>{if(!t.control?.resourceId)return e;let d=n.controls?.[t.control.resourceId];if(!d)return e;let h=gs(d.keyboard,d.keyup);if(h&&Object.keys(h).length>0&&(e.global.keyboard=h),!Array.isArray(d.elements)||d.elements.length===0)return e;let g=Be(e.elements);if(!g)return e;let y={id:`control-${t.control.resourceId}`,type:"container",x:0,y:0,children:d.elements};return g.children.push($r({container:y,resources:n,templateData:re({variables:r,runtime:o,saveSlots:u,dialogueState:t.dialogue,isLineCompleted:i,autoMode:s,skipMode:a,isChoiceVisible:l,canRollback:c,characters:n.characters||{},skipTransitionsAndAnimations:f}),isLineCompleted:i,skipMode:a,skipTransitionsAndAnimations:f})),e},vs=(e,{presentationState:t,resources:n,runtime:r,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&n){if(!Be(i))return e;let l=n.sounds[t.bgm.resourceId];if(!l)return e;let c=re({variables:o,runtime:r}).runtime;s.push({id:"bgm",type:"sound",src:l.fileId,loop:t.bgm.loop??!0,volume:us(c),delay:t.bgm.delay??null})}return e},Ss=(e,{presentationState:t,resources:n})=>{let{audio:r}=e;if(t.sfx&&n){let o=t.sfx.items;for(let i of o){let s=n.sounds?.[i.resourceId];s&&r.push({id:i.id,type:"sound",src:s.fileId,loop:i.loop??s.loop??!1,volume:i.volume??s.volume??50,delay:i.delay??s.delay??null})}}return e},Cs=(e,t,n)=>{if(!(!t||!n))return e?.voices?.[t]?.[n]},_s=(e={},t={})=>t.muteAll?0:e.volume??t.soundVolume??50,Rs=(e,{presentationState:t,resources:n,currentSceneId:r,runtime:o,variables:i})=>{let{audio:s}=e;if(!t?.voice)return e;let a=t.voice,{resourceId:l,loop:c,delay:u}=a,f=Cs(n,r,l);if(!f)return e;let d=re({variables:i,runtime:o}).runtime;return s.push({id:`voice-${r}-${l}`,type:"sound",src:f.fileId,volume:_s(a,d),loop:c??!1,delay:u??null}),e},Ls=(e,{presentationState:t,previousPresentationState:n,resources:r={},variables:o,runtime:i,autoMode:s,skipMode:a,isChoiceVisible:l,canRollback:c,saveSlots:u=[],isLineCompleted:f,skipTransitionsAndAnimations:d,activePersistentAnimations:h})=>{let{elements:g,animations:y}=e;if(t.layout){let E=Be(g);if(!E)return e;let S=r.layouts[t.layout.resourceId];if(!S)return e;Array.isArray(S.transitions)&&!f&&!d&&an({animations:y,transitions:S.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let $={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:S.elements||[]};E.children.push($r({container:$,resources:r,templateData:re({variables:o,runtime:i,saveSlots:u,dialogueState:t.dialogue,isLineCompleted:f,autoMode:s,skipMode:a,isChoiceVisible:l,canRollback:c,characters:r.characters||{},skipTransitionsAndAnimations:d}),isLineCompleted:f,skipMode:a,skipTransitionsAndAnimations:d}))}let I=n?.layout?.resourceId,b=t.layout?.resourceId,m=we({animationsDef:t.layout?.animations,resources:r,previousResourceId:I,currentResourceId:b,previousTargetId:I?`layout-${I}`:void 0,currentTargetId:b?`layout-${b}`:void 0,animationPath:"layout.animations",idPrefix:"layout"});return se({animationInstances:m,isLineCompleted:f,skipTransitionsAndAnimations:d,activePersistentAnimations:h})&&y.push(...m),e},$s=(e,{presentationState:t,resources:n={},variables:r,runtime:o,autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:l,overlayStack:c=[],dialogueHistory:u=[],saveSlots:f=[],screen:d,isLineCompleted:h,skipTransitionsAndAnimations:g})=>{let{elements:y,animations:I}=e;return c&&c.length>0&&c.forEach((b,m)=>{let E=n.layouts[b.resourceId];if(!E){console.warn(`Overlay layout not found: ${b.resourceId}`);return}Array.isArray(E.transitions)&&(g||an({animations:I,transitions:E.transitions,defaultTargetId:`overlayStack-${m}`,idPrefix:`overlayStack-${m}`,animationPathPrefix:`overlayStack[${m}]`}));let S={id:`overlayStack-${m}`,type:"container",x:0,y:0,children:[Rr({id:`overlayStack-${m}-blocker`,screen:d}),...E.elements||[]]},$=Lr(u,n.characters),O=re({variables:r,runtime:o,saveSlots:f,dialogueState:t?.dialogue,isLineCompleted:h,autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:l,historyDialogue:$,characters:n.characters||{},skipTransitionsAndAnimations:g}),_=Z(S,O,{functions:be}),[D,...N]=_.children||[],k=Ie(Ae({..._,children:N},{isLineCompleted:h,skipMode:s,skipTransitionsAndAnimations:g}),n);y.push({...k,children:D?[D,...k.children||[]]:k.children})}),e},Os=(e,{presentationState:t,resources:n={},variables:r,runtime:o,saveSlots:i=[],autoMode:s,skipMode:a,isChoiceVisible:l,canRollback:c,confirmDialog:u,dialogueHistory:f=[],screen:d,isLineCompleted:h,skipTransitionsAndAnimations:g})=>{let{elements:y,animations:I}=e;if(!u?.resourceId)return e;let b=n.layouts?.[u.resourceId];if(!b)return console.warn(`ConfirmDialog layout not found: ${u.resourceId}`),e;Array.isArray(b.transitions)&&!g&&an({animations:I,transitions:b.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let m={id:"confirmDialog",type:"container",x:0,y:0,children:[Rr({id:"confirmDialog-blocker",screen:d}),...b.elements||[]]},E=Lr(f,n.characters),S=Z(m,re({variables:r,runtime:o,saveSlots:i,dialogueState:t?.dialogue,isLineCompleted:h,autoMode:s,skipMode:a,isChoiceVisible:l,canRollback:c,confirmDialog:u,historyDialogue:E,characters:n.characters||{},skipTransitionsAndAnimations:g}),{functions:be}),[$,...O]=S.children||[],_=Ie(Ae({...S,children:O},{isLineCompleted:h,skipMode:a,skipTransitionsAndAnimations:g}),n);return y.push({..._,children:$?[$,..._.children||[]]:_.children}),e},Or=e=>ot(ms,[Es,ys,bs,Is,ws,xs,Ls,vs,Ss,Rs,$s,Os])(e);var ks=Object.freeze({dialogueTextSpeed:{source:"global.dialogueTextSpeed"},autoForwardDelay:{source:"global.autoForwardDelay"},skipUnseenText:{source:"global.skipUnseenText"},skipTransitionsAndAnimations:{source:"global.skipTransitionsAndAnimations"},soundVolume:{source:"global.soundVolume"},musicVolume:{source:"global.musicVolume"},muteAll:{source:"global.muteAll"},saveLoadPagination:{source:"context.runtime.saveLoadPagination"},menuPage:{source:"context.runtime.menuPage"},menuEntryPoint:{source:"context.runtime.menuEntryPoint"},autoMode:{source:"global.autoMode"},skipMode:{source:"global.skipMode"},dialogueUIHidden:{source:"global.dialogueUIHidden"},isLineCompleted:{source:"global.isLineCompleted"}}),ft=Object.freeze({dialogueTextSpeed:50,autoForwardDelay:1e3,skipUnseenText:!1,skipTransitionsAndAnimations:!1,soundVolume:50,musicVolume:50,muteAll:!1,autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isLineCompleted:!1}),Fe=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),kr=Object.freeze({dialogueTextSpeed:"number",autoForwardDelay:"number",skipUnseenText:"boolean",skipTransitionsAndAnimations:"boolean",soundVolume:"number",musicVolume:"number",muteAll:"boolean",saveLoadPagination:"number",menuPage:"string",menuEntryPoint:"string",autoMode:"boolean",skipMode:"boolean",dialogueUIHidden:"boolean",isLineCompleted:"boolean"}),ln=Object.freeze(["dialogueTextSpeed","autoForwardDelay","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),un=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),Ps=(e,t)=>{if(t.startsWith("global.")){let n=t.slice(7);return e?.global?.[n]}if(t.startsWith("context.runtime.")){let n=t.slice(16),r=Array.isArray(e?.contexts)?e.contexts:[];return r[r.length-1]?.runtime?.[n]}},dt=e=>Object.fromEntries(Object.entries(ks).map(([t,n])=>{let r=Ps(e,n.source),o=r!==void 0?r:ft[t]??Fe[t];return[t,o]})),ae=(e,t)=>dt(e)[t],Pr=(e={})=>Object.fromEntries(ln.map(t=>[t,e[t]??ft[t]]));var pt={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},jr=1,gt=()=>({manual:{...pt.manual},auto:{...pt.auto},applyMode:pt.applyMode}),fn=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let n=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...gt()},n&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},F=e=>{let t=ue(e)?kt(e):e;return structuredClone(t)},j=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),mt=e=>String(e),Mr=()=>({sections:[],resources:[]}),Ts=e=>j(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):Mr(),Ns=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",Ds=()=>({resourceId:void 0}),Vs=e=>{if(!j(e))return e;let t={...e};return Object.prototype.hasOwnProperty.call(t,"requireComplete")&&!Object.prototype.hasOwnProperty.call(t,"requireLineCompleted")&&(t.requireLineCompleted=t.requireComplete),delete t.requireComplete,t},dn=(e,t)=>{let n=e?.story?.scenes??{};for(let[r,o]of Object.entries(n))if(o?.sections?.[t])return{sceneId:r,section:o.sections[t]};return{sceneId:void 0,section:void 0}},Ur=e=>{let t=e?.story?.scenes??{},n=new Map;for(let[r,o]of Object.entries(t)){let i=o?.sections??{};for(let s of Object.keys(i)){let a=n.get(s);if(a!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${a}" and "${r}". Section IDs must be globally unique.`);n.set(s,r)}}},Br=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},Fr=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==jr)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},js=(e,t={})=>{let n;try{n=Fr(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let r={...t,formatVersion:n,slotId:Br(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete r.slotKey,delete r.date,r},Ms=(e={})=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,js(t,n)])),zr=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:n})=>gc(n));return t.length>0?t:void 0},Us=e=>{!j(e)||!Array.isArray(e.timeline)||e.timeline.forEach(t=>{if(!j(t))return;let n=zr(t.executedActions);if(n){t.executedActions=n;return}delete t.executedActions})},Tr=(e,t,n,r="viewedRegistry")=>{let o=t==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[o]:String(e)};if(!j(e))throw new Error(`Malformed ${r}.${t}[${n}] entry.`);if(typeof e[o]!="string"||e[o].length===0)throw new Error(`Malformed ${r}.${t}[${n}] entry: missing ${o}.`);if(t==="sections"){let i={sectionId:e.sectionId};if(e.lastLineId!==void 0&&e.lastLineId!==null&&typeof e.lastLineId!="string")throw new Error(`Malformed ${r}.sections[${n}] entry: invalid lastLineId.`);return typeof e.lastLineId=="string"&&e.lastLineId.length>0&&(i.lastLineId=e.lastLineId),i}return{resourceId:e.resourceId}},Bs=(e,t="viewedRegistry")=>{if(e===void 0)return Mr();if(!j(e))throw new Error(`Malformed ${t}.`);if(e.sections!==void 0&&!Array.isArray(e.sections))throw new Error(`Malformed ${t}.sections.`);if(e.resources!==void 0&&!Array.isArray(e.resources))throw new Error(`Malformed ${t}.resources.`);let n=e.sections??[],r=e.resources??[];return{sections:Object.values(Object.fromEntries(n.map((o,i)=>{let s=Tr(o,"sections",i,t);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(r.map((o,i)=>{let s=Tr(o,"resources",i,t);return[s.resourceId,s]})))}},Wr=(e,t,n)=>{if(!j(e))throw new Error(`Malformed save slot ${n}.`);let{sectionId:r,lineId:o}=e;if(typeof r!="string"||r.length===0)throw new Error(`Malformed save slot ${n}: missing sectionId.`);if(typeof o!="string"||o.length===0)throw new Error(`Malformed save slot ${n}: missing lineId.`);let{sceneId:i,section:s}=dn(t,r);if(!s)throw new Error(`Malformed save slot ${n}: section "${r}" does not exist in projectData.`);if(!s.lines?.some(l=>l.id===o))throw new Error(`Malformed save slot ${n}: line "${o}" does not exist in section "${r}".`);return{sceneId:i,sectionId:r,lineId:o}},Fs=(e,t,n)=>{if(!j(e)||!Array.isArray(e.timeline))return ze({pointer:t,replayStartIndex:1});let r=e.timeline.flatMap((a,l)=>{if(!j(a))return[];try{let c=Wr(a,n,`rollback.timeline[${l}]`),u=ht({sectionId:c.sectionId,lineId:c.lineId,rollbackPolicy:a.rollbackPolicy}),f=zr(F(a.executedActions));return f&&(u.executedActions=f),[u]}catch{return[]}});if(r.length===0)return ze({pointer:t,replayStartIndex:1});let o=typeof e.currentIndex=="number"?Math.trunc(e.currentIndex):r.length-1;(o<0||o>=r.length)&&(o=r.length-1);let i=r[o];if(i?.sectionId!==t.sectionId||i?.lineId!==t.lineId){let a=r.findLastIndex(l=>l.sectionId===t.sectionId&&l.lineId===t.lineId);a>=0?o=a:(r.push(ht({sectionId:t.sectionId,lineId:t.lineId})),o=r.length-1)}let s=typeof e.replayStartIndex=="number"?Math.min(Math.max(Math.trunc(e.replayStartIndex),0),o):0;return{currentIndex:o,isRestoring:!1,replayStartIndex:s,timeline:r}},zs=(e,t,n)=>{if(!j(e))throw new Error(`Malformed save slot contexts[${n}] entry.`);let r=hn(t),o=Wr(e.pointers?.read,t,`contexts[${n}].pointers.read`);if(e.variables!==void 0&&!j(e.variables))throw new Error(`Malformed save slot contexts[${n}].variables entry.`);if(e.runtime!==void 0&&!j(e.runtime))throw new Error(`Malformed save slot contexts[${n}].runtime entry.`);let i=e.variables?F(e.variables):{},s=Js({loadedContextRuntime:j(e.runtime)?F(e.runtime):{}}),a={currentPointerMode:"read",pointers:{read:o},configuration:j(e.configuration)?F(e.configuration):{},views:Array.isArray(e.views)?F(e.views):[],bgm:j(e.bgm)?F(e.bgm):{resourceId:void 0},variables:{...r,...i},rollback:Fs(e.rollback,o,t)};return s&&(a.runtime=s),a},Ws=(e,t)=>{if(!j(e))throw new Error("Malformed save slot state.");if(!Array.isArray(e.contexts)||e.contexts.length===0)throw new Error("Malformed save slot state: contexts must be a non-empty array.");return{contexts:e.contexts.map((n,r)=>zs(n,t,r))}},Ys=(e,t)=>{if(!j(e))throw new Error("Malformed save slot.");let n=Fr(e.formatVersion);return{...e,formatVersion:n,state:Ws(e.state,t)}},Nr=(e,t,{required:n=!1}={})=>{if(e===void 0){if(n)throw new Error(`showConfirmDialog requires ${t}`);return{hideConfirmDialog:{}}}if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`showConfirmDialog ${t} must be an action object`);let r=F(e);return Object.prototype.hasOwnProperty.call(r,"hideConfirmDialog")||(r.hideConfirmDialog={}),r},qs=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:Nr(e.confirmActions,"confirmActions",{required:!0}),cancelActions:Nr(e.cancelActions,"cancelActions")}},ke=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},xe=[],Dr="line",pn="interaction",ht=({sectionId:e,lineId:t,rollbackPolicy:n})=>({sectionId:e,lineId:t,rollbackPolicy:n??"free"}),hn=e=>{let{contextVariableDefaultValues:t}=Ft(e??{});return F(t)},Yr=()=>({...F(Fe)}),qr=({loadedRuntime:e,runtimeIds:t,defaults:n={},path:r})=>{if(e===void 0)return{runtimeState:F(n),hasLoadedValues:!1};if(!j(e))throw new Error(`Malformed ${r}.`);let o=F(n),i=!1;return t.forEach(s=>{e[s]!==void 0&&(o[s]=Hr(s,F(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},Hs=({loadedGlobalRuntime:e={}})=>qr({loadedRuntime:e,runtimeIds:ln,defaults:ft,path:"global.runtime"}).runtimeState,Js=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:n}=qr({loadedRuntime:e,runtimeIds:un,defaults:Yr(),path:"context.runtime"});return n?t:void 0},gn=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},Ks=e=>e.runtime?(un.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=F(Fe[t]))}),e.runtime):(e.runtime=Yr(),e.runtime),Gs=e=>Pr(e.global),Xs=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:Gs(e)}})},Qs=e=>kr[e],Zs=(e,t)=>{let n=Qs(e);if(n==="number"){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} requires a finite numeric value`);return}if(n==="boolean"){if(typeof t!="boolean")throw new Error(`${e} requires a boolean value`);return}if(n==="string"){if(typeof t!="string")throw new Error(`${e} requires a string value`);return}throw new Error(`Unsupported runtime field "${e}"`)},Hr=(e,t)=>(Zs(e,t),e==="saveLoadPagination"?Math.max(1,Math.trunc(t)):t),Jr=(e,t,n)=>{let r=Hr(t,n);if(t in Fe){let o=gn(e);if(!o)return r;let i=Ks(o);return i[t]=r,r}return e.global[t]=r,r},Kr=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:F(e)},configuration:{},views:[],bgm:Ds(),variables:hn(t),rollback:ze({pointer:e})}),Pe=e=>e?(e.currentPointerMode="read",j(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,ea=e=>{let t=e.contexts?.[e.contexts.length-1],n=t?.pointers?.read;if(!t||!n?.sectionId||!n?.lineId)return null;let r=Kr({pointer:n,projectData:e.projectData});return e.contexts[e.contexts.length-1]=r,ta(e),r},ta=e=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,ke(e),e.global.nextLineConfig=gt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})},Gr=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},ze=({pointer:e,replayStartIndex:t=0})=>{let n=e?.sectionId&&e?.lineId;return{currentIndex:n?0:-1,isRestoring:!1,replayStartIndex:t,timeline:n?[ht({sectionId:e.sectionId,lineId:e.lineId})]:[]}},ve=(e,t={})=>{if(e?.rollback)return Gr(e.rollback),Array.isArray(e.rollback.timeline)||(e.rollback.timeline=[]),typeof e.rollback.currentIndex!="number"&&(e.rollback.currentIndex=e.rollback.timeline.length>0?e.rollback.timeline.length-1:-1),typeof e.rollback.isRestoring!="boolean"&&(e.rollback.isRestoring=!1),typeof e.rollback.replayStartIndex!="number"&&(e.rollback.replayStartIndex=0),e.rollback;let n=e?.pointers?.read;return e.rollback=ze({pointer:n,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},mn=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return;let r=ve(n);if(r.isRestoring)return;r.currentIndex<r.timeline.length-1&&(r.timeline=r.timeline.slice(0,r.currentIndex+1));let o=r.timeline[r.timeline.length-1];if(o?.sectionId===t.sectionId&&o?.lineId===t.lineId&&(o?.rollbackPolicy??"free")===(t.rollbackPolicy??"free")){r.currentIndex=r.timeline.length-1;return}r.timeline.push(ht(t)),r.currentIndex=r.timeline.length-1},na=e=>{let n=e.contexts?.[e.contexts.length-1]?.rollback;if(!n||n.isRestoring||!Array.isArray(n.timeline)||typeof n.currentIndex!="number")return null;let r=xe[xe.length-1],o=typeof r?.checkpointIndex=="number"?r.checkpointIndex:n.currentIndex;return o<0||o>=n.timeline.length?null:(typeof r?.checkpointIndex!="number"&&o<n.timeline.length-1&&(n.timeline=n.timeline.slice(0,o+1)),n.timeline[o]??null)},ra=({state:e},t={})=>{let n=t?.source===Dr?Dr:pn,o=e.contexts?.[e.contexts.length-1]?.rollback;return!o||o.isRestoring||!Array.isArray(o.timeline)||typeof o.currentIndex!="number"||o.currentIndex<0||o.currentIndex>=o.timeline.length?(xe.push({checkpointIndex:null,source:n}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),xe.push({checkpointIndex:o.currentIndex,source:n}),e)},oa=({state:e})=>(xe.pop(),e),ce=(e,t,n)=>{let o=xe[xe.length-1]?.source??pn;if(!mc(t,o))return;let i=na(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:F(n)}))},Vr=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return;let r=t?.operations??[];for(let{variableId:o,op:i,value:s}of r){let a=e.projectData.resources?.variables?.[o],l=a?.scope,c=a?.type;zt(l,o),Wt(c,i,o),l==="context"&&(n.variables[o]=Yt(n.variables[o],i,s))}},ia=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:n,payload:r})=>{yc(e,n,r)})},sa=(e,t)=>{let{sectionId:n,lineId:r}=t,s=G({state:e},{sectionId:n})?.lines?.find(a=>a.id===r)?.actions;s&&Object.entries(s).forEach(([a,l])=>{go(e,a,l)})},Xr=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return e;let r=ve(n),o=r.timeline[t];if(!o)return e;e.global.autoMode&&Ye({state:e}),e.global.skipMode&&Ee({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),r.isRestoring=!0,r.currentIndex=t;try{n.variables=hn(e.projectData),delete n.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=F(pt),e.global.overlayStack=[],ke(e),e.global.isLineCompleted=!0;let i=r.replayStartIndex??0;for(let a=i;a<=t;a++)a>i&&fn(e),sa(e,r.timeline[a]),ia(e,r.timeline[a]);let s=Pe(n);s.read={sectionId:o.sectionId,lineId:o.lineId},e.global.pendingEffects=e.global.pendingEffects.filter(a=>a?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{r.isRestoring=!1}return e},aa=e=>{let{projectData:t}=e,n=e.global??{},{saveSlots:r={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=n;Ur(t);let a=t.story.initialSceneId,l=t.story.scenes[a],c=l.initialSectionId,u=l.sections[c],f={sceneId:a,sectionId:c,lineId:u.initialLineId??u.lines[0].id},{globalVariablesDefaultValues:d}=Ft(t),h={...d,...o};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,accountViewedRegistry:Bs(s,"accountViewedRegistry"),nextLineConfig:gt(),saveSlots:Ms(r),overlayStack:[],variables:h,...Hs({loadedGlobalRuntime:i})},contexts:[Kr({pointer:f,projectData:t})]}},ca=({state:e})=>e.global.overlayStack||[],la=({state:e})=>e.global.pendingEffects,Qr=({state:e})=>e.global.skipMode,ua=({state:e})=>e.global.autoMode,Zr=({state:e})=>e.global.dialogueUIHidden,eo=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],n=t[t.length-1];if(!n)return[];let{sectionId:r,lineId:o}=n.pointers.read,i=G({state:e},{sectionId:r});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(u=>u.id===o),a=i.lines.slice(0,s+1),l=[],c={};for(let u of a){let f=u.actions||{};if(c=Le([c,f]),!f.dialogue)continue;let d=c.dialogue||{},h="";d.character?.name!==void 0?h=d.character.name:d.characterId&&(h=e.projectData.resources?.characters?.[d.characterId]?.name||""),l.push({sectionId:r,lineId:u.id,content:f.dialogue.content,text:Ns(f.dialogue.content),characterId:d.characterId,character:{...d.character||{},name:h},characterName:h})}return l},fa=({state:e})=>e.global.confirmDialog??null,da=({state:e,registry:t},n)=>{let{sectionId:r,lineId:o}=n,s=(Array.isArray(t?.sections)?t.sections:[]).find(u=>u.sectionId===r);if(!s)return!1;if(s.lastLineId===void 0||o===void 0)return!0;let a=G({state:e},{sectionId:r});if(!a||!a.lines||!Array.isArray(a.lines))return s.lastLineId===o;let l=a.lines.findIndex(u=>u.id===s.lastLineId),c=a.lines.findIndex(u=>u.id===o);return l===-1||c===-1?s.lastLineId===o:c<=l},pa=({registry:e},t)=>{let{resourceId:n}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===n)},yn=({state:e},t)=>da({state:e,registry:e.global.accountViewedRegistry},t),ha=({state:e},t)=>pa({registry:e.global.accountViewedRegistry},t),ga=({state:e})=>e.global.nextLineConfig,to=({state:e,pointer:t}={})=>{let n=t??oe({state:e})?.pointer;if(!n)return;let r=n?.sectionId,o=n?.lineId,s=G({state:e},{sectionId:r})?.lines||[],a=s.findIndex(c=>c.id===o);if(a<0)return;let l;for(let c of s.slice(0,a+1)){let u=c?.actions;if(u?.cleanAll&&(l=void 0),!u||!Object.prototype.hasOwnProperty.call(u,"choice")){l=void 0;continue}let f=u.choice;if(f?.resourceId){l=f.resourceId;continue}f?.animations||(l=void 0)}return l},ie=({state:e})=>!!to({state:e}),ma=({state:e})=>structuredClone(e),no=({state:e})=>e.global.saveSlots,ya=({state:e},t)=>{let n=t?.slotId,r=mt(n);return e.global.saveSlots[r]},bn=({state:e})=>dt(e),ba=({state:e},t)=>ae(e,t?.runtimeId),ro=({state:e})=>({...e.global?.variables??{},...gn(e)?.variables??{}}),oe=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],n=t[t.length-1];if(n)return{currentPointerMode:"read",pointer:n.pointers?.read}},G=({state:e},t)=>{let{sectionId:n}=t;return dn(e.projectData,n).section},In=({state:e})=>{let t=oe({state:e});if(!t?.pointer)return;let{sectionId:n,lineId:r}=t.pointer,o=G({state:e},{sectionId:n});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===r)},oo=({state:e})=>{let{sectionId:t,lineId:n}=oe({state:e}).pointer,o=G({state:e},{sectionId:t})?.lines||[],i=o.findIndex(c=>c.id===n),a=o.slice(0,i+1).map(c=>{let u=c.actions||{},f={};return Object.keys(u).forEach(d=>{f[d]=u[d]}),f});return Le(a)},Ia=({state:e})=>{let t=io({state:e}),r=In({state:e})?.actions??{},o=Le([t??{},r]);return qt(t??{},o??{})},Aa=({state:e},{sectionId:t})=>{let n=G({state:e},{sectionId:t});if(!n?.lines)return[];let r=[],o={};for(let i of n.lines){let s=i.actions||{},a=Le([o,s]),l=qt(o,a);r.push({id:i.id,changes:l,presentationState:a}),o=Ht(a)}return r},wa=({state:e},{sectionId:t,includePresentationState:n=!1})=>{let r=Aa({state:e},{sectionId:t});return n?{lines:r}:{lines:r.map(({presentationState:o,...i})=>i)}},io=({state:e})=>{let{sectionId:t,lineId:n}=oe({state:e}).pointer,o=G({state:e},{sectionId:t})?.lines||[],i=o.findIndex(l=>l.id===n);if(i<=0)return null;let a=o.slice(0,i).map(l=>{let c=l.actions||{},u={};return Object.keys(c).forEach(f=>{u[f]=c[f]}),u});return Ht(Le(a))},An=({state:e},{slotsPerPage:t=6}={})=>{let o=((bn({state:e}).saveLoadPagination??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let a=o+s,l=e.global.saveSlots&&e.global.saveSlots[mt(a)]||{};i.push({...l,slotId:a})}return{saveSlots:i}},xa=no,Ea=An,va=e=>{let n=e.contexts?.[e.contexts.length-1]?.rollback;return!n||!Array.isArray(n.timeline)||typeof n.currentIndex!="number"?!1:n.currentIndex>=0&&n.currentIndex<n.timeline.length-1},Sa=({state:e},t={})=>{let n=oo({state:e}),r=io({state:e}),o=In({state:e})?.actions??{},{sectionId:i}=oe({state:e}).pointer,{sceneId:s}=dn(e.projectData,i),a=bn({state:e}),l=t?.activePersistentAnimations??[],c=t?.restoredPersistentAnimations??[],u=ro({state:e}),{saveSlots:f}=An({state:e}),d=va(e);return Or({presentationState:n,previousPresentationState:r,currentLineActions:o,resources:e.projectData.resources,currentSceneId:s,screen:e.projectData.screen,dialogueUIHidden:a.dialogueUIHidden,autoMode:a.autoMode,skipMode:a.skipMode,isChoiceVisible:ie({state:e}),canRollback:yo({state:e}),skipOnlyViewedLines:!a.skipUnseenText,isLineCompleted:a.isLineCompleted,skipTransitionsAndAnimations:!!a.skipTransitionsAndAnimations||d,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,dialogueHistory:eo({state:e}),saveSlots:f,variables:u,runtime:a,activePersistentAnimations:l,restoredPersistentAnimations:c})},Ca=({state:e},t)=>(e.global.confirmDialog=qs(t),e.global.pendingEffects.push({name:"render"}),e),_a=({state:e})=>(e.global.confirmDialog&&(ke(e),e.global.pendingEffects.push({name:"render"})),e),Ra=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),ce(e,"pushOverlay",t),e),La=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),ce(e,"popOverlay",void 0),e),$a=({state:e},t)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=t),e.global.pendingEffects.push({name:"render"}),ce(e,"replaceLastOverlay",t),e),Oa=({state:e})=>(e.global.overlayStack=[],ke(e),e.global.pendingEffects.push({name:"render"}),ce(e,"clearOverlays",void 0),e),ka=e=>{e.global.autoMode&&(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"})),e.global.skipMode&&(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"})),e.global.nextLineConfig?.auto?.enabled&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},yt=(e,t)=>{e.global.isLineCompleted=!1;let n=!!to({state:e,pointer:t});return n&&ka(e),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:n}},so=({state:e})=>(ie({state:e})||(e.global.skipMode&&(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"})),e.global.autoMode=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.isLineCompleted&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:ae(e,"autoForwardDelay")}}),e.global.pendingEffects.push({name:"render"})),e),Ye=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Pa=({state:e})=>{let t=e.global.autoMode;return ie({state:e})&&!t||(t?Ye({state:e}):so({state:e})),e},ao=({state:e})=>(ie({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),Ee=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Ta=({state:e})=>{let t=Qr({state:e});return ie({state:e})&&!t||(t?Ee({state:e}):ao({state:e})),e},bt=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),ce(e,"showDialogueUI",void 0),e),co=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),ce(e,"hideDialogueUI",void 0),e),Na=({state:e})=>(Zr({state:e})?bt({state:e}):co({state:e}),e),Se=(e,t,n)=>(Jr(e,t,n),Xs(e),e.global.pendingEffects.push({name:"render"}),e),qe=(e,t,n,r)=>{let o=Jr(e,t,n);return e.global.pendingEffects.push({name:"render"}),ce(e,r,{value:o}),e},Da=({state:e},t)=>Se(e,"dialogueTextSpeed",t?.value),Va=({state:e},t)=>Se(e,"autoForwardDelay",t?.value),ja=({state:e},t)=>Se(e,"skipUnseenText",t?.value),Ma=({state:e},t)=>Se(e,"skipTransitionsAndAnimations",t?.value),Ua=({state:e},t)=>Se(e,"soundVolume",t?.value),Ba=({state:e},t)=>Se(e,"musicVolume",t?.value),Fa=({state:e},t)=>Se(e,"muteAll",t?.value),za=({state:e},t)=>qe(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),Wa=({state:e})=>{let t=ae(e,"saveLoadPagination")+1;return qe(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},Ya=({state:e})=>{let t=ae(e,"saveLoadPagination")-1;return qe(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},qa=({state:e},t)=>qe(e,"menuPage",t?.value,"setMenuPage"),Ha=({state:e},t)=>qe(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),Ja=({state:e})=>(e.global.pendingEffects=[],e),Ka=({state:e},t)=>(e.global.pendingEffects.push(t),e),lo=(e,{sectionId:t,resetStoryState:n=!1})=>{let r=G({state:e},{sectionId:t});if(!r)return console.warn(`Section not found: ${t}`),e;let o=r.lines?.[0];if(!o)return console.warn(`Section ${t} has no lines`),e;if(n&&!ea(e))return e;e.global.autoMode&&Ye({state:e}),e.global.skipMode&&Ee({state:e});let i=e.contexts?.[e.contexts.length-1];if(i){let s=Pe(i);i.rollback||ve(i,{compatibilityAnchor:!0}),s.read={sectionId:t,lineId:o.id},n?i.rollback=ze({pointer:s.read}):mn(e,{sectionId:t,lineId:o.id})}return yt(e,i?.pointers?.read),e},Ga=({state:e},t)=>lo(e,{sectionId:t?.sectionId,resetStoryState:!0}),uo=e=>(e.global.accountViewedRegistry=Ts(e.global.accountViewedRegistry),e.global.accountViewedRegistry),fo=(e,t)=>{!Array.isArray(t)||t.length===0||e.global.pendingEffects.push({name:"applyScopedDataUpdates",payload:{updates:t.map(n=>({scope:n.scope,path:n.path,op:n.op,value:F(n.value)}))}})},po=(e,t)=>{fo(e,[{scope:"account",path:"viewedRegistry",op:"markViewed",value:{sections:(Array.isArray(t?.sections)?t.sections:[]).map(n=>({sectionId:n.sectionId,...n.lastLineId===void 0?{}:{lineId:n.lastLineId}})),resources:Array.isArray(t?.resources)?t.resources:[]}}])},Xa=(e,t,{sectionId:n,lineId:r})=>{if(!n||!r)return!1;let o=j(t)?t:{};Array.isArray(o.sections)||(o.sections=[]);let i=o.sections.find(s=>s.sectionId===n);if(i){if(i.lastLineId===void 0)return!1;let s=G({state:e},{sectionId:n});if(s?.lines){let a=s.lines.findIndex(c=>c.id===i.lastLineId),l=s.lines.findIndex(c=>c.id===r);if(a===-1||l>a)return i.lastLineId===r?!1:(i.lastLineId=r,!0)}else return i.lastLineId===r?!1:(i.lastLineId=r,!0);return!1}else return o.sections.push({sectionId:n,lastLineId:r}),!0},We=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;Xa(e,uo(e),t)&&po(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},Qa=({state:e},t)=>(We(e,t),e.global.pendingEffects.push({name:"render"}),e),Za=({state:e},t)=>{let{resourceId:n}=t;if(e.global.accountViewedRegistry!==void 0){let r=uo(e);r.resources.find(i=>i.resourceId===n)||(r.resources.push({resourceId:n}),po(e,{sections:[],resources:[{resourceId:n}]}))}return e.global.pendingEffects.push({name:"render"}),e},ho=({state:e},t)=>{let n=Vs(t.manual),{auto:r,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,a=e.contexts?.[e.contexts.length-1]?.rollback?.isRestoring===!0;n&&r?(e.global.nextLineConfig={manual:n,auto:r},o!==void 0?e.global.nextLineConfig.applyMode=o:s!==void 0&&(e.global.nextLineConfig.applyMode=s)):(n&&(e.global.nextLineConfig.manual=n),r&&(e.global.nextLineConfig.auto=r),o!==void 0&&(e.global.nextLineConfig.applyMode=o));let l=e.global.nextLineConfig.auto?.enabled,c=ie({state:e});return!a&&!c&&l===!0&&!i?e.global.nextLineConfig.auto?.trigger==="fromStart"?e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):e.global.isLineCompleted&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):!a&&l===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),ce(e,"setNextLineConfig",t),e},ec=({state:e},t)=>{let n=t?.slotId;if(n==null||n==="")throw new Error("saveSlot requires slotId");let{thumbnailImage:r}=t,o=t?.savedAt,i=mt(n),s=F(e.contexts);s?.forEach(c=>{Pe(c),Gr(c.rollback),Us(c.rollback)});let a={contexts:s},l={formatVersion:jr,slotId:Br(n),savedAt:typeof o=="number"?o:Date.now(),image:r,state:a};return e.global.saveSlots[i]=l,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},tc=({state:e},t)=>{let n=t?.slotId;if(n==null||n==="")throw new Error("loadSlot requires slotId");let r=mt(n),o=e.global.saveSlots[r];if(o){let i=Ys(o,e.projectData);e.contexts=i.state.contexts,e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=gt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,ke(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},nc=({state:e},t)=>{let{projectData:n}=t;return Ur(n),e.projectData=n,ke(e),e.global.pendingEffects.push({name:"render"}),e},rc=({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&&!G({state:e},{sectionId:n}))return console.warn(`Section not found: ${n}`),e;let s=G({state:e},{sectionId:i});if(!s?.lines||!Array.isArray(s.lines))return console.warn(`Section ${i} has no lines`),e;if(!s.lines.find(c=>c.id===r))return console.warn(`Line not found: ${r} in section ${i}`),e;let l=Pe(o);return l.read={sectionId:i,lineId:r},yt(e,l.read),e},oc=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return bt({state:e}),e;if(ie({state:e})&&t?._interactionSource!=="choice")return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0;let c=oe({state:e})?.pointer,u=c?.sectionId,f=c?.lineId;u&&f&&We(e,{sectionId:u,lineId:f}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:ae(e,"autoForwardDelay")}});let d=e.global.nextLineConfig;return d?.auto?.enabled&&d.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:d.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e}let n=oe({state:e})?.pointer,r=n?.sectionId,o=G({state:e},{sectionId:r}),i=e.contexts[e.contexts.length-1],s=o?.lines||[],l=s.findIndex(c=>c.id===n?.lineId)+1;if(l<s.length){let c=s[l],u=!ae(e,"skipUnseenText");if(e.global.skipMode&&u&&!yn({state:e},{sectionId:r,lineId:c.id}))return Ee({state:e}),e;if(i&&!i.rollback&&ve(i,{compatibilityAnchor:!0}),i){let h=Pe(i),g=h.read?.lineId;g&&r&&We(e,{sectionId:r,lineId:g}),h.read={sectionId:r,lineId:c.id}}mn(e,{sectionId:r,lineId:c.id}),fn(e);let{isChoiceVisible:f}=yt(e,{sectionId:r,lineId:c.id}),d=e.global.nextLineConfig;d?.auto?.enabled&&!f&&d.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:d.auto.delay}})}else e.global.autoMode&&Ye({state:e}),e.global.skipMode&&Ee({state:e});return e},ic=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0;let t=ie({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:ae(e,"autoForwardDelay")}});let n=oe({state:e})?.pointer,r=n?.sectionId,o=n?.lineId;r&&o&&We(e,{sectionId:r,lineId:o});let i=e.global.nextLineConfig;return i?.auto?.enabled&&!t&&i.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:i.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e},sc=({state:e},t)=>lo(e,{sectionId:t?.sectionId}),ac=({state:e})=>{if(e.global.dialogueUIHidden)return bt({state:e}),e;if(ie({state:e}))return e;let t=oe({state:e})?.pointer,n=t?.sectionId,r=G({state:e},{sectionId:n}),o=e.contexts[e.contexts.length-1],i=r?.lines||[],a=i.findIndex(l=>l.id===t?.lineId)+1;if(a<i.length){let l=i[a],c=!ae(e,"skipUnseenText");if(e.global.skipMode&&c&&!yn({state:e},{sectionId:n,lineId:l.id}))return Ee({state:e}),e;if(o&&!o.rollback&&ve(o,{compatibilityAnchor:!0}),o){let f=Pe(o),d=f.read?.lineId;d&&n&&We(e,{sectionId:n,lineId:d}),f.read={sectionId:n,lineId:l.id}}mn(e,{sectionId:n,lineId:l.id}),fn(e);let{isChoiceVisible:u}=yt(e,{sectionId:n,lineId:l.id});e.global.nextLineConfig.auto?.enabled&&!u&&e.global.nextLineConfig.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}})}else e.global.nextLineConfig.auto?.enabled&&(e.global.nextLineConfig.auto.enabled=!1,e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}));return e},cc=({state:e},t)=>{let{id:n,operations:r=[]}=t;if(!n)throw new Error("updateVariable requires an id field");if(typeof n!="string"||!/^[a-zA-Z0-9]+$/.test(n))throw new Error(`updateVariable id must be alphanumeric, got: "${n}"`);let o=e.contexts[e.contexts.length-1];if(o?.rollback?.isRestoring)return e;let i=!1,s=[],a=[];return r.forEach(({variableId:l,op:c,value:u})=>{let f=e.projectData.resources?.variables?.[l],d=f?.scope,h=f?.type;zt(d,l),Wt(h,c,l);let g=d==="context"?o.variables:e.global.variables;d==="context"&&(i=!0,a.push({variableId:l,op:c,value:u})),g[l]=Yt(g[l],c,u),(d==="device"||d==="account")&&s.push({scope:d,path:`variables.${l}`,op:"set",value:F(g[l])})}),i&&ce(e,"updateVariable",{id:n,operations:a}),fo(e,s),e.global.pendingEffects.push({name:"render"}),e},lc=e=>(t,n)=>e({state:t},n),uc=e=>({variables:{...e.global?.variables??{},...gn(e)?.variables??{}},runtime:dt(e)}),fc=e=>{if(!j(e))throw new Error("conditional action payload must be an object");if(!Array.isArray(e.branches))throw new Error("conditional action requires branches array");if(e.branches.length===0)throw new Error("conditional action requires at least one branch")},dc=(e,t,n)=>{if(!j(e))throw new Error(`conditional branch at index ${t} must be an object`);if(!j(e.actions))throw new Error(`conditional branch at index ${t} requires actions object`);if(!Object.prototype.hasOwnProperty.call(e,"when")&&t!==n-1)throw new Error("conditional else branch must be the last branch")},pc=(e,t)=>{fc(t);for(let n=0;n<t.branches.length;n+=1){let r=t.branches[n];if(dc(r,n,t.branches.length),!(Object.prototype.hasOwnProperty.call(r,"when")&&!je(r.when,uc(e)))){Object.entries(r.actions).forEach(([i,s])=>{go(e,i,s)});return}}},hc={conditional:{replayLine:pc},updateVariable:{recordSources:[pn],replayLine:Vr,replayRecorded:Vr,persistInSaveSlot:!0},setNextLineConfig:{replayLine:lc(ho)}},It=e=>hc[e]??null,gc=e=>It(e)?.persistInSaveSlot===!0,mc=(e,t)=>{let n=It(e)?.recordSources;return Array.isArray(n)&&n.includes(t)},yc=(e,t,n)=>{It(t)?.replayRecorded?.(e,n)},go=(e,t,n)=>{It(t)?.replayLine?.(e,n)},mo=({state:e},t)=>{let{offset:n}=t;if(n===void 0||typeof n!="number")return console.warn("selectLineIdByOffset requires a numeric offset"),null;let r=e.contexts[e.contexts.length-1];if(!r)return null;let o=r.rollback;if(!Array.isArray(o?.timeline)||typeof o?.currentIndex!="number")return null;let i=o.currentIndex+n;if(i<0||i>=o.timeline.length)return null;let s=o.timeline[i];return{sectionId:s.sectionId,lineId:s.lineId}},yo=({state:e})=>mo({state:e},{offset:-1})!==null,bc=({state:e},t)=>{let{offset:n=-1}=t;if(n>=0)throw new Error("rollbackByOffset requires a negative offset");let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let o=ve(r,{compatibilityAnchor:!r.rollback}),i=o.currentIndex+n;return i<0||i>=o.timeline.length?e:Xr(e,i)},Ic=({state:e},t)=>{let{sectionId:n,lineId:r}=t,o=e.contexts[e.contexts.length-1];if(!o)throw new Error("No context available for rollbackToLine");let i=ve(o,{compatibilityAnchor:!o.rollback}),a=i.timeline.slice(0,i.currentIndex+1).findLastIndex(l=>l.sectionId===n&&l.lineId===r);if(a===-1)throw new Error(`Line ${r} not found in section ${n} rollback timeline`);return a===i.currentIndex?e:Xr(e,a)},bo=e=>{let t=aa(e);return tr(t,{selectPendingEffects:la,selectSkipMode:Qr,selectAutoMode:ua,selectIsChoiceVisible:ie,selectDialogueUIHidden:Zr,selectDialogueHistory:eo,selectConfirmDialog:fa,selectIsLineAccountViewed:yn,selectIsResourceAccountViewed:ha,selectNextLineConfig:ga,selectSystemState:ma,selectSaveSlotMap:no,selectSaveSlots:xa,selectSaveSlot:ya,selectRuntime:bn,selectRuntimeValue:ba,selectAllVariables:ro,selectCurrentPointer:oe,selectSection:G,selectCurrentLine:In,selectPresentationState:oo,selectPresentationChanges:Ia,selectSectionLineChanges:wa,selectSaveSlotPage:An,selectCurrentPageSlots:Ea,selectRenderState:Sa,selectOverlayStack:ca,selectLineIdByOffset:mo,selectCanRollback:yo,startAutoMode:so,stopAutoMode:Ye,toggleAutoMode:Pa,startSkipMode:ao,stopSkipMode:Ee,toggleSkipMode:Ta,showDialogueUI:bt,hideDialogueUI:co,toggleDialogueUI:Na,setDialogueTextSpeed:Da,setAutoForwardDelay:Va,setSkipUnseenText:ja,setSkipTransitionsAndAnimations:Ma,setSoundVolume:Ua,setMusicVolume:Ba,setMuteAll:Fa,setSaveLoadPagination:za,incrementSaveLoadPagination:Wa,decrementSaveLoadPagination:Ya,setMenuPage:qa,setMenuEntryPoint:Ha,showConfirmDialog:Ca,hideConfirmDialog:_a,resetStoryAtSection:Ga,clearPendingEffects:Ja,appendPendingEffect:Ka,beginRollbackActionBatch:ra,endRollbackActionBatch:oa,addViewedLine:Qa,addViewedResource:Za,setNextLineConfig:ho,saveSlot:ec,loadSlot:tc,updateProjectData:nc,sectionTransition:sc,jumpToLine:rc,nextLine:oc,markLineCompleted:ic,rollbackToLine:Ic,rollbackByOffset:bc,pushOverlay:Ra,popOverlay:La,replaceLastOverlay:$a,clearOverlays:Oa,updateVariable:cc,nextLineFromSystem:ac},{transformActionFirstArgument:r=>({state:r}),transformSelectorFirstArgument:r=>({state:r})})};var Ac="route-engine",wc="projectPersistence";var Ao=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),H=e=>Object.prototype.toString.call(e)==="[object Object]",Io="variables.",xc=(e={})=>{let t=H(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(n=>typeof n=="string"||typeof n=="number"?{sectionId:String(n)}:!H(n)||typeof n.sectionId!="string"||n.sectionId.length===0?null:{sectionId:n.sectionId,...typeof n.lineId=="string"?{lineId:n.lineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(n=>typeof n=="string"||typeof n=="number"?{resourceId:String(n)}:!H(n)||typeof n.resourceId!="string"||n.resourceId.length===0?null:{resourceId:n.resourceId}).filter(Boolean)}},Ec=(e={})=>{let t=H(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(n=>typeof n=="string"||typeof n=="number"?{sectionId:String(n)}:!H(n)||typeof n.sectionId!="string"||n.sectionId.length===0?null:{sectionId:n.sectionId,...typeof n.lastLineId=="string"?{lastLineId:n.lastLineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(n=>typeof n=="string"||typeof n=="number"?{resourceId:String(n)}:!H(n)||typeof n.resourceId!="string"||n.resourceId.length===0?null:{resourceId:n.resourceId}).filter(Boolean)}},vc=(e,t)=>{let n=Ec(e),r=xc(t),o=n.sections.map(s=>({...s})),i=n.resources.map(s=>({...s}));return r.sections.forEach(s=>{let a=o.find(l=>l.sectionId===s.sectionId);if(!a){o.push({sectionId:s.sectionId,...s.lineId===void 0?{}:{lastLineId:s.lineId}});return}if(a.lastLineId!==void 0){if(s.lineId===void 0){delete a.lastLineId;return}a.lastLineId=s.lineId}}),r.resources.forEach(s=>{i.find(l=>l.resourceId===s.resourceId)||i.push({...s})}),{sections:o,resources:i}},wo=(e={})=>{let t=H(e)?e:{};return{saveSlots:H(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:H(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:H(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:H(t.globalRuntime)?t.globalRuntime:{},accountViewedRegistry:H(t.accountViewedRegistry)?t.accountViewedRegistry:{}}},Sc=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((t,n)=>{if(!H(t))throw new Error(`Malformed applyScopedDataUpdates.updates[${n}] entry.`);let r=t.path?.startsWith(Io)?t.path.slice(Io.length):null;if(r!==null){if(!["device","account"].includes(t.scope))throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${n}].`);if(r.length===0)throw new Error(`Malformed applyScopedDataUpdates path "${t.path}" at updates[${n}].`);if(t.op!=="set")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${n}].`);return{scope:t.scope,path:t.path,op:t.op,value:t.value,variableId:r}}if(t.path==="viewedRegistry"){if(t.scope!=="account")throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${n}].`);if(t.op!=="markViewed")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${n}].`);return t}throw typeof t.path!="string"?new Error(`Malformed applyScopedDataUpdates path at updates[${n}].`):new Error(`Unsupported applyScopedDataUpdates path "${t.path}" at updates[${n}].`)})},Cc=(e,t)=>{let n={};return Sc(t).forEach(r=>{if(r.path==="viewedRegistry"){n.accountViewedRegistry=vc(n.accountViewedRegistry??e.accountViewedRegistry,r.value);return}let o=r.scope==="device"?"globalDeviceVariables":"globalAccountVariables";n[o]={...e[o],...n[o],[r.variableId]:r.value}}),n},wn=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},_c=e=>{let t=wn(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},Rc=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},Lc=({indexedDB:e,databaseName:t,objectStoreName:n})=>new Promise((r,o)=>{let i=e.open(t,1);i.onupgradeneeded=()=>{let s=i.result;s.objectStoreNames.contains(n)||s.createObjectStore(n,{keyPath:"namespace"})},i.onsuccess=()=>{r(i.result)},i.onerror=()=>{o(i.error??new Error(`Failed to open IndexedDB database "${t}".`))}}),$c=async({databasePromise:e,objectStoreName:t,namespace:n})=>{let r=await e;return new Promise((o,i)=>{let l=r.transaction(t,"readonly").objectStore(t).get(n);l.onsuccess=()=>{o(l.result??null)},l.onerror=()=>{i(l.error??new Error(`Failed to read persisted namespace "${n}" from IndexedDB.`))}})},He=async({databasePromise:e,objectStoreName:t,namespace:n,patch:r})=>{let o=await e;return new Promise((i,s)=>{let a=o.transaction(t,"readwrite"),l=a.objectStore(t),c=l.get(n),u=!1,f=h=>{u||(u=!0,s(h))},d=()=>{u||(u=!0,i())};c.onerror=()=>{f(c.error??new Error(`Failed to read persisted namespace "${n}" before updating IndexedDB.`))},c.onsuccess=()=>{let h=wo(c.result),g=typeof r=="function"?r(h):r,y={namespace:n,version:1,...Ao(),...h,...g},I=l.put(y);I.onerror=()=>{f(I.error??new Error(`Failed to persist namespace "${n}" to IndexedDB.`))}},a.oncomplete=()=>{d()},a.onerror=()=>{f(a.error??new Error(`IndexedDB transaction failed while updating namespace "${n}".`))},a.onabort=()=>{f(a.error??new Error(`IndexedDB transaction aborted while updating namespace "${n}".`))}})},Oc=async({databasePromise:e,objectStoreName:t,namespace:n})=>{let r=await e;return new Promise((o,i)=>{let s=r.transaction(t,"readwrite"),l=s.objectStore(t).delete(n),c=!1,u=d=>{c||(c=!0,i(d))},f=()=>{c||(c=!0,o())};l.onerror=()=>{u(l.error??new Error(`Failed to clear persisted namespace "${n}" from IndexedDB.`))},s.oncomplete=()=>{f()},s.onerror=()=>{u(s.error??new Error(`IndexedDB transaction failed while clearing namespace "${n}".`))},s.onabort=()=>{u(s.error??new Error(`IndexedDB transaction aborted while clearing namespace "${n}".`))}})},xn=(e={})=>{let{indexedDB:t,databaseName:n=Ac,objectStoreName:r=wc,namespace:o}=e,i=Rc(t),s=_c(o),a=Lc({indexedDB:i,databaseName:n,objectStoreName:r});return{namespace:s,load:async()=>{let l=await $c({databasePromise:a,objectStoreName:r,namespace:s});return{...Ao(),...wo(l)}},clear:async()=>Oc({databasePromise:a,objectStoreName:r,namespace:s}),saveSlots:async l=>He({databasePromise:a,objectStoreName:r,namespace:s,patch:{saveSlots:H(l)?l:{}}}),saveGlobalDeviceVariables:async l=>He({databasePromise:a,objectStoreName:r,namespace:s,patch:{globalDeviceVariables:H(l)?l:{}}}),saveGlobalAccountVariables:async l=>He({databasePromise:a,objectStoreName:r,namespace:s,patch:{globalAccountVariables:H(l)?l:{}}}),saveGlobalRuntime:async l=>He({databasePromise:a,objectStoreName:r,namespace:s,patch:{globalRuntime:H(l)?l:{}}}),applyScopedDataUpdates:async l=>He({databasePromise:a,objectStoreName:r,namespace:s,patch:c=>Cc(c,l)})}},kc=xn;var Pc=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),Tc=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),xo="conditional",Eo="choice",At=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function En(e){let t,n=0,r=null,o=new Map,i=new Map,s=new Map,{handlePendingEffects:a}=e,l=(A=new Map,v=Date.now())=>new Map(Array.from(A.entries()).filter(([,T])=>v<T.expiresAt).map(([T,V])=>[T,{animation:structuredClone(V.animation),startedAt:V.startedAt,expiresAt:V.expiresAt}])),c=(A=new Map)=>Array.from(A.values()).map(v=>structuredClone(v.animation)),u=(A=Date.now())=>{o=new Map(Array.from(o.entries()).filter(([,v])=>A<v.expiresAt))},f=()=>{for(;t.selectPendingEffects().length>0;){let A=[...t.selectPendingEffects()];t.clearPendingEffects();try{a(A)}catch(v){throw t.clearPendingEffects(),A.forEach(T=>{t.appendPendingEffect(T)}),v}}},d=({initialState:A,namespace:v})=>{t=bo(A),n=0,r=wn(v),o=new Map,i=new Map,s=new Map,t.appendPendingEffect({name:"handleLineActions"}),f()},h=()=>r,g=()=>t.selectPresentationState(),y=()=>t.selectPresentationChanges(),I=A=>t.selectSectionLineChanges(A),b=(A={})=>{n+=1;let v=Date.now();u(v);let T=i.size>0,V=l(o,v),q=T?l(i,v):new Map,le={...t.selectRenderState({activePersistentAnimations:c(V),restoredPersistentAnimations:c(q)}),id:`render-${n}`};return s.set(le.id,{builtAt:v,persistentAnimationSessions:new Map([...q.entries(),...V.entries()]),usedRestoredPersistentAnimationSessions:T}),le},m=(A={})=>b(A),E=(A={})=>b(A),S=A=>{let v=typeof A?.id=="string"&&A.id.length>0?A.id:null,T=v?s.get(v):null;v&&s.delete(v);let V=new Map;wr(A?.animations).forEach(q=>{let te=lt(q);if(!te)return;let le=T?.persistentAnimationSessions?.get(te)??o.get(te),_o=Math.max(0,Er(q)),Rn=le?.startedAt??T?.builtAt??Date.now();V.set(te,{animation:structuredClone(q),startedAt:Rn,expiresAt:Rn+_o})}),o=V,T?.usedRestoredPersistentAnimationSessions&&(i=new Map)},$=()=>t.selectSystemState(),O=()=>t.selectSaveSlotMap(),_=A=>t.selectSaveSlot(A),D=A=>t.selectSaveSlotPage(A),N=()=>t.selectSkipMode(),k=()=>t.selectAutoMode(),P=()=>t.selectRuntime(),x=()=>t.selectIsChoiceVisible(),C=(A,v,T={})=>T.interactionSource!==Eo||A!=="nextLine"||!At(v)?v:{...v,_interactionSource:Eo},M=(A,v)=>{t[A]&&(Pc.has(A)&&(Tc.has(A)?i=l(o):i=new Map,o=new Map),t[A](v),f())},z=(A,v,T,V={})=>{if(A===xo){let q=U(T),te=Jt({[A]:v},q);Sn(te[A],T,V);return}M(A,v)},Y=(A,v)=>{z(A,v)},U=A=>{if(!A)return{variables:t.selectAllVariables?t.selectAllVariables():void 0,runtime:t.selectRuntime?t.selectRuntime():{}};if(Object.prototype.hasOwnProperty.call(A,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:v,...T}=A,V=t.selectAllVariables?t.selectAllVariables():void 0;return{...T,_event:v,variables:V,runtime:t.selectRuntime?t.selectRuntime():{}}},Je=A=>{if(!At(A))throw new Error("conditional action payload must be an object");if(!Array.isArray(A.branches))throw new Error("conditional action requires branches array");if(A.branches.length===0)throw new Error("conditional action requires at least one branch")},Ke=(A,v,T)=>{if(!At(A))throw new Error(`conditional branch at index ${v} must be an object`);if(!At(A.actions))throw new Error(`conditional branch at index ${v} requires actions object`);if(!Object.prototype.hasOwnProperty.call(A,"when")&&v!==T-1)throw new Error("conditional else branch must be the last branch")},Sn=(A,v,T)=>{Je(A);for(let V=0;V<A.branches.length;V+=1){let q=A.branches[V];Ke(q,V,A.branches.length);let te=U(v);if(!(Object.prototype.hasOwnProperty.call(q,"when")&&!je(q.when,te))){Cn(q.actions,v,T);return}}},Co=(A,v,T,V)=>{let q=U(T),le=Jt({[A]:v},q)[A];if(A===xo){Sn(le,T,V);return}M(A,C(A,le,V))},Cn=(A,v,T)=>{Object.entries(A).forEach(([V,q])=>{Co(V,q,v,T)})},_n=(A,v,T={})=>{t.beginRollbackActionBatch({source:T.rollbackSource});try{Cn(A,v,T)}finally{t.endRollbackActionBatch({})}};return{init:d,handleAction:z,handleInternalAction:Y,handleActions:_n,selectRenderState:m,prepareRenderState:E,commitRenderState:S,selectPresentationState:g,selectPresentationChanges:y,selectSectionLineChanges:I,selectSystemState:$,selectSaveSlotMap:O,selectSaveSlot:_,selectSaveSlotPage:D,selectSaveSlots:O,selectRuntime:P,selectIsChoiceVisible:x,handleLineActions:()=>{let A=t.selectCurrentLine();return A?.actions?(_n(A.actions,void 0,{rollbackSource:"line"}),!0):!1},getNamespace:h}}var vn=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:n=>{e=n},addElapsed:n=>{e+=n},getCallback:()=>t,setCallback:n=>{t=n}}},Nc=80,So=({engine:e,routeGraphics:t,trackRenderDispatch:n},r)=>{let o=e.prepareRenderState?.(r)??e.selectRenderState(r);n?.(o),t.render(o),e.commitRenderState?.(o)},Dc=({engine:e,routeGraphics:t,trackRenderDispatch:n,getRenderDispatchCount:r},o)=>{let i=r?.()??0,s=e.handleLineActions();(r?.()??0)===i&&So({engine:e,routeGraphics:t,trackRenderDispatch:n},o)},Vc=({engine:e,ticker:t,autoTimer:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let a=r.delay??1e3;n.getElapsed()>=a&&(t.remove(i),n.setCallback(null),n.setElapsed(0),wt(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},jc=({ticker:e,autoTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Mc=({engine:e,ticker:t,skipTimer:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let a=r?.delay??Nc;n.getElapsed()>=a&&(n.setElapsed(0),wt(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},Uc=({ticker:e,skipTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Bc=({engine:e,ticker:t,nextLineConfigTimerState:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let a=r.delay??1e3;n.getElapsed()>=a&&(n.setElapsed(0),wt(e,"nextLineFromSystem",{}),t.remove(i),n.setCallback(null))};n.setCallback(i),t.add(i)},Fc=({ticker:e,nextLineConfigTimerState:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},zc=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveSlots(t?.saveSlots))},Wc=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalDeviceVariables(t?.globalDeviceVariables))},Yc=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalAccountVariables(t?.globalAccountVariables))},qc=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalRuntime(t?.globalRuntime))},Hc=({enqueuePersistenceWrite:e},t)=>{e(n=>{if(typeof n.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return n.applyScopedDataUpdates(t?.updates)})},vo={render:So,saveSlots:zc,saveGlobalDeviceVariables:Wc,saveGlobalAccountVariables:Yc,saveGlobalRuntime:qc,applyScopedDataUpdates:Hc,handleLineActions:Dc,startAutoNextTimer:Vc,clearAutoNextTimer:jc,startSkipNextTimer:Mc,clearSkipNextTimer:Uc,nextLineConfigTimer:Bc,clearNextLineConfigTimer:Fc},Jc=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),wt=(e,t,n)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,n)},Kc=(e=[])=>{let t=new Set,n=[];for(let r=e.length-1;r>=0;r-=1){let o=e[r];if(typeof o?.name!="string"||o.name.length===0)throw new Error("Pending effect is missing a valid name.");if(!Jc.has(o.name)){n.unshift(o);continue}t.has(o.name)||(t.add(o.name),n.unshift(o))}return n},Gc=({getEngine:e,routeGraphics:t,ticker:n,handleUnhandledEffect:r,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:a})=>{let l=vn(),c=vn(),u=vn(),f=s??null,d=Promise.resolve(),h=null,g=null,y=!1,I=0,b=x=>{if(o){o(x);return}console.error("RouteEngine persistence write failed.",x)},m=()=>{if(f)return f;let x=e();return f=xn({indexedDB:i,namespace:a??x?.getNamespace?.()}),f},E=x=>{d=d.catch(()=>{}).then(()=>{let C=m();return x(C)}).catch(C=>{b(C)})},S=x=>{let C=typeof x?.id=="string"&&x.id.length>0?x.id:null;I+=1,h=C,y=!1},$=()=>I,O=(x={})=>{if(x?.aborted===!0)return!1;let C=typeof x?.id=="string"&&x.id.length>0?x.id:null;return C?C!==h||C===g?!1:(g=C,!0):h!==null||y?!1:(y=!0,!0)},_=(x,C={})=>{if(x!=="renderComplete"||!O(C))return!1;let M=e();return wt(M,"markLineCompleted",{}),!0},D=(x={})=>{if(x?._interactionSource==="choice")return!0;let C=x?.actions;return!C||typeof C!="object"||Array.isArray(C)?!1:Object.values(C).some(M=>M?._interactionSource==="choice")},N=(x,C={})=>!C?.actions||typeof x?.selectIsChoiceVisible!="function"||!x.selectIsChoiceVisible()?!1:!D(C),k=({preprocessPayload:x,onEvent:C}={})=>async(M,z={})=>{let Y=e();if(N(Y,z))return C?.(M,z);let U=await x?.(M,z)??z;if(N(Y,U))return C?.(M,U);if(_(M,U),U?.actions){let Je=U?._event?{_event:U._event}:U?.event?{_event:U.event}:void 0,Ke=U?._interactionSource?{interactionSource:U._interactionSource}:void 0;Ke?Y.handleActions(U.actions,Je,Ke):Y.handleActions(U.actions,Je)}return C?.(M,U)},P=x=>{let C=e(),M=Kc(x);M.forEach(Y=>{if(!vo[Y.name]&&!r)throw new Error(`Unhandled pending effect "${Y.name}".`)});let z={engine:C,routeGraphics:t,ticker:n,autoTimer:l,skipTimer:c,nextLineConfigTimerState:u,trackRenderDispatch:S,getRenderDispatchCount:$,enqueuePersistenceWrite:E};for(let Y of M){let U=vo[Y.name];if(U){U(z,Y.payload);continue}r(Y,z)}};return P.handleRouteGraphicsEvent=_,P.createRouteGraphicsEventHandler=k,P},Xc=Gc;var Qc=(e,t={})=>{let{resources:n={}}=t;return cn(e,n)};var hu=En;export{Xc as createEffectsHandler,kc as createIndexedDbPersistence,hu as default,Qc as resolveLayoutReferences};
|
|
1
|
+
var Ro=Object.defineProperty;var Lo=(e,t)=>{for(var n in t)Ro(e,n,{get:t[n],enumerable:!0})};var Dn=Symbol.for("immer-nothing"),On=Symbol.for("immer-draftable"),X=Symbol.for("immer-state");function ee(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var Ce=Object.getPrototypeOf;function ue(e){return!!e&&!!e[X]}function ge(e){return e?Vn(e)||Array.isArray(e)||!!e[On]||!!e.constructor?.[On]||et(e)||tt(e):!1}var $o=Object.prototype.constructor.toString();function Vn(e){if(!e||typeof e!="object")return!1;let t=Ce(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)===$o}function Ge(e,t){Ze(e)===0?Reflect.ownKeys(e).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function Ze(e){let t=e[X];return t?t.type_:Array.isArray(e)?1:et(e)?2:tt(e)?3:0}function vt(e,t){return Ze(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function jn(e,t,n){let r=Ze(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function Oo(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function et(e){return e instanceof Map}function tt(e){return e instanceof Set}function he(e){return e.copy_||e.base_}function St(e,t){if(et(e))return new Map(e);if(tt(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let n=Vn(e);if(t===!0||t==="class_only"&&!n){let r=Object.getOwnPropertyDescriptors(e);delete r[X];let o=Reflect.ownKeys(r);for(let i=0;i<o.length;i++){let s=o[i],l=r[s];l.writable===!1&&(l.writable=!0,l.configurable=!0),(l.get||l.set)&&(r[s]={configurable:!0,writable:!0,enumerable:l.enumerable,value:e[s]})}return Object.create(Ce(e),r)}else{let r=Ce(e);if(r!==null&&n)return{...e};let o=Object.create(r);return Object.assign(o,e)}}function $t(e,t=!1){return nt(e)||ue(e)||!ge(e)||(Ze(e)>1&&(e.set=e.add=e.clear=e.delete=ko),Object.freeze(e),t&&Object.entries(e).forEach(([n,r])=>$t(r,!0))),e}function ko(){ee(2)}function nt(e){return Object.isFrozen(e)}var Po={};function me(e){let t=Po[e];return t||ee(0,e),t}var Te;function Mn(){return Te}function To(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function kn(e,t){t&&(me("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Ct(e){_t(e),e.drafts_.forEach(No),e.drafts_=null}function _t(e){e===Te&&(Te=e.parent_)}function Pn(e){return Te=To(Te,e)}function No(e){let t=e[X];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function Tn(e,t){t.unfinalizedDrafts_=t.drafts_.length;let n=t.drafts_[0];return e!==void 0&&e!==n?(n[X].modified_&&(Ct(t),ee(4)),ge(e)&&(e=Xe(t,e),t.parent_||Qe(t,e)),t.patches_&&me("Patches").generateReplacementPatches_(n[X].base_,e,t.patches_,t.inversePatches_)):e=Xe(t,n,[]),Ct(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Dn?e:void 0}function Xe(e,t,n){if(nt(t))return t;let r=t[X];if(!r)return Ge(t,(o,i)=>Nn(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Qe(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;let o=r.copy_,i=o,s=!1;r.type_===3&&(i=new Set(o),o.clear(),s=!0),Ge(i,(l,c)=>Nn(e,r,o,l,c,n,s)),Qe(e,o,!1),n&&e.patches_&&me("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function Nn(e,t,n,r,o,i,s){if(ue(o)){let l=i&&t&&t.type_!==3&&!vt(t.assigned_,r)?i.concat(r):void 0,c=Xe(e,o,l);if(jn(n,r,c),ue(c))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if(ge(o)&&!nt(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Xe(e,o),(!t||!t.scope_.parent_)&&typeof r!="symbol"&&Object.prototype.propertyIsEnumerable.call(n,r)&&Qe(e,o)}}function Qe(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&$t(t,n)}function Do(e,t){let n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:Mn(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=r,i=Ot;n&&(o=[r],i=Ne);let{revoke:s,proxy:l}=Proxy.revocable(o,i);return r.draft_=l,r.revoke_=s,l}var Ot={get(e,t){if(t===X)return e;let n=he(e);if(!vt(n,t))return Vo(e,n,t);let r=n[t];return e.finalized_||!ge(r)?r:r===xt(e.base_,t)?(Et(e),e.copy_[t]=Lt(r,e)):r},has(e,t){return t in he(e)},ownKeys(e){return Reflect.ownKeys(he(e))},set(e,t,n){let r=Un(he(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){let o=xt(he(e),t),i=o?.[X];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(Oo(n,o)&&(n!==void 0||vt(e.base_,t)))return!0;Et(e),Rt(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 xt(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,Et(e),Rt(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let n=he(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){ee(11)},getPrototypeOf(e){return Ce(e.base_)},setPrototypeOf(){ee(12)}},Ne={};Ge(Ot,(e,t)=>{Ne[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});Ne.deleteProperty=function(e,t){return Ne.set.call(this,e,t,void 0)};Ne.set=function(e,t,n){return Ot.set.call(this,e[0],t,n,e[0])};function xt(e,t){let n=e[X];return(n?he(n):e)[t]}function Vo(e,t,n){let r=Un(t,n);return r?"value"in r?r.value:r.get?.call(e.draft_):void 0}function Un(e,t){if(!(t in e))return;let n=Ce(e);for(;n;){let r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=Ce(n)}}function Rt(e){e.modified_||(e.modified_=!0,e.parent_&&Rt(e.parent_))}function Et(e){e.copy_||(e.copy_=St(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var jo=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){let i=n;n=t;let s=this;return function(c=i,...a){return s.produce(c,u=>n.call(this,u,...a))}}typeof n!="function"&&ee(6),r!==void 0&&typeof r!="function"&&ee(7);let o;if(ge(t)){let i=Pn(this),s=Lt(t,void 0),l=!0;try{o=n(s),l=!1}finally{l?Ct(i):_t(i)}return kn(i,r),Tn(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===Dn&&(o=void 0),this.autoFreeze_&&$t(o,!0),r){let i=[],s=[];me("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else ee(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,c=>t(c,...l));let r,o;return[this.produce(t,n,(s,l)=>{r=s,o=l}),r,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){ge(e)||ee(8),ue(e)&&(e=kt(e));let t=Pn(this),n=Lt(e,void 0);return n[X].isManual_=!0,_t(t),n}finishDraft(e,t){let n=e&&e[X];(!n||!n.isManual_)&&ee(9);let{scope_:r}=n;return kn(r,t),Tn(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=me("Patches").applyPatches_;return ue(e)?r(e,t):this.produce(e,o=>r(o,t))}};function Lt(e,t){let n=et(e)?me("MapSet").proxyMap_(e,t):tt(e)?me("MapSet").proxySet_(e,t):Do(e,t);return(t?t.scope_:Mn()).drafts_.push(n),n}function kt(e){return ue(e)||ee(10,e),Bn(e)}function Bn(e){if(!ge(e)||nt(e))return e;let t=e[X],n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=St(e,t.scope_.immer_.useStrictShallowCopy_)}else n=St(e,!0);return Ge(n,(r,o)=>{jn(n,r,Bn(o))}),t&&(t.finalized_=!1),n}var Q=new jo,Pt=Q.produce,ol=Q.produceWithPatches.bind(Q),il=Q.setAutoFreeze.bind(Q),sl=Q.setUseStrictShallowCopy.bind(Q),al=Q.applyPatches.bind(Q),cl=Q.createDraft.bind(Q),ll=Q.finishDraft.bind(Q);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},R={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},_e={NOT:0};var w=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},K=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var Tt=e=>{if(!e||e.trim()==="")throw new w("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let n=e.includes("===")?"==":"!=";throw new w(`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 w(`Incomplete comparison expression - missing right operand (got: '${e}')`)},Fn=e=>{if(e.trim().endsWith(" in"))throw new w(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new w(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,n]=e.split(" in ");if(!n||n.trim()==="")throw new w(`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 w(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new w(`Invalid loop syntax (got: '$for ${e}')`)}};var zn=(e,t,n=!1)=>{if(t===null)return new K(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new K(`Cannot iterate over undefined value at '$for ${e}'`);let r=typeof t;return n?new K(`Cannot iterate over non-array value in loop '${e}' - got ${r} instead`):new K(`Cannot iterate over non-array value (got: ${r}) at '$for ${e}'`)},Wn=(e,t)=>{let n=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new K(`Unknown function '${e}' (${n})`)};var Mo=(e,t,n={})=>{let r={},o={};n&&typeof n=="object"&&(n.functions!==void 0||n.partials!==void 0?(r=n.functions||{},o=n.partials||{}):typeof n=="object"&&(r=n));let s=L(e,{functions:r,partials:o},t,{});return s===void 0?{}:s},L=(e,t,n,r)=>{let o=t.functions||t;if(e.var&&!e.type)return B(e.var,n,r);if(e.type===p.LITERAL)return e.value;if(e.type===p.VARIABLE)return B(e.path,n,r);if(e.type===p.INTERPOLATION)return Bo(e.parts,t,n,r);switch(e.type){case p.FUNCTION:return qn(e,t,n,r);case p.BINARY:return Hn(e,t,n,r);case p.UNARY:return Jn(e,t,n,r);case p.CONDITIONAL:return zo(e,t,n,r);case p.LOOP:return Jo(e,t,n,r);case p.OBJECT:return Go(e,t,n,r);case p.ARRAY:return Xo(e,t,n,r);case p.PARTIAL:return Qo(e,t,n,r);case p.PATH_REFERENCE:return Zo(e,t,n,r);default:throw new Error(`Unknown node type: ${e.type}`)}},Yn=new Map,Uo=e=>{let t=[],n="",r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(i==="[")n&&(t.push({type:"property",value:n}),n=""),r=!0;else if(i==="]"){if(r&&n){let s=n.trim();if(/^\d+$/.test(s))t.push({type:"index",value:parseInt(s,10)});else if(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'")){let l=s.slice(1,-1);t.push({type:"property",value:l})}else t.push({type:"property",value:s});n=""}r=!1}else n+=i}return n&&t.push({type:"property",value:n}),t},B=(e,t,n)=>{if(!e)return;if(e in n)return n[e];let r=Yn.get(e);if(!r){let i=[],s="",l=0;for(let c=0;c<e.length;c++){let a=e[c];a==="["?(l++,s+=a):a==="]"?(l--,s+=a):a==="."&&l===0?s&&(i.push(s),s=""):s+=a}s&&i.push(s),r=[];for(let c of i){let a=Uo(c.trim());r.push(...a)}Yn.set(e,r)}let o=t;for(let i=0;i<r.length;i++){let s=r[i];if(s.type==="property"&&s.value in n){o=n[s.value];continue}if(o==null)return;(s.type==="property"||s.type==="index")&&(o=o[s.value])}return o},Bo=(e,t,n,r)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=L(i,t,n,r);o.push(s!=null?String(s):"")}return o.join("")},qn=(e,t,n,r)=>{let o=t.functions||t,i=o[e.name];if(!i)throw Wn(e.name,o);let s=e.args.map(l=>L(l,t,n,r));return i(...s)},fe=(e,t,n,r)=>{if(e.var&&!e.type)return B(e.var,n,r);switch(e.type){case p.VARIABLE:return B(e.path,n,r);case p.LITERAL:return e.value;case p.BINARY:return Hn(e,t,n,r);case p.UNARY:return Jn(e,t,n,r);case p.FUNCTION:return qn(e,t,n,r);default:return L(e,t,n,r)}},Hn=(e,t,n,r)=>{if(e.op===R.AND||e.op===R.OR){let s=fe(e.left,t,n,r),l=fe(e.right,t,n,r);switch(e.op){case R.AND:return s&&l;case R.OR:return s||l}}let o=L(e.left,t,n,r),i=L(e.right,t,n,r);switch(e.op){case R.EQ:return o==i;case R.NEQ:return o!=i;case R.GT:return o>i;case R.LT:return o<i;case R.GTE:return o>=i;case R.LTE:return o<=i;case R.IN:return Array.isArray(i)?i.includes(o):!1;case R.ADD:if(typeof o!="number"||typeof i!="number")throw new K(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case R.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new K(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},Jn=(e,t,n,r)=>{let o=e.op===_e.NOT?fe(e.operand,t,n,r):L(e.operand,t,n,r);if(e.op===_e.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},Fo=(e,t,n,r)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===p.VARIABLE)if(B(o.path,n,r)){let s=e.bodies[0];if(s.type===p.OBJECT&&s.properties.length<=5){let l={};for(let c of s.properties){let a=c.parsedKey?L(c.parsedKey,t,n,r):c.key,u=c.value;if(u.type===p.LITERAL)l[a]=u.value;else if(u.type===p.VARIABLE)l[a]=B(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=B(d.path,n,r);f.push(h!=null?String(h):"")}else{let h=L(d,t,n,r);f.push(h!=null?String(h):"")}l[a]=f.join("")}else l[a]=L(u,t,n,r)}return l}}else{let s=e.bodies[1];if(s.type===p.OBJECT&&s.properties.length<=5){let l={};for(let c of s.properties){let a=c.parsedKey?L(c.parsedKey,t,n,r):c.key,u=c.value;if(u.type===p.LITERAL)l[a]=u.value;else if(u.type===p.VARIABLE)l[a]=B(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=B(d.path,n,r);f.push(h!=null?String(h):"")}else{let h=L(d,t,n,r);f.push(h!=null?String(h):"")}l[a]=f.join("")}else l[a]=L(u,t,n,r)}return l}}}return null},zo=(e,t,n,r)=>{let o=Fo(e,t,n,r);if(o!==null)return o;for(let i=0;i<e.conditions.length;i++){let s=e.conditions[i];if(s===null||fe(s,t,n,r))return L(e.bodies[i],t,n,r)}return Kn},Wo=(e,t)=>{let n=e.body,r=e.itemVar;if(n.type===p.CONDITIONAL&&n.conditions.length===1&&n.conditions[0].type===p.VARIABLE){let o=n.conditions[0].path,i=n.bodies[0];if(o.startsWith(r+".")){let s=o.substring(r.length+1);if(i.type===p.OBJECT&&i.properties.length<=5){for(let c of i.properties)if(c.parsedKey)return null;let l=[];for(let c=0;c<t.length;c++){let a=t[c];if(a[s]){let u={};for(let f of i.properties){let d=f.key,h=f.value;if(h.type===p.LITERAL)u[d]=h.value;else if(h.type===p.VARIABLE){let g=h.path;if(g===r)u[d]=a;else if(g.startsWith(r+".")){let y=g.substring(r.length+1);u[d]=a[y]}else return null}else if(h.type===p.INTERPOLATION){let g=[],y=!0;for(let I of h.parts)if(typeof I=="string")g.push(I);else if(I.type===p.VARIABLE){let b=I.path;if(b===r)g.push(a!=null?String(a):"");else if(b.startsWith(r+".")){let m=b.substring(r.length+1),E=a[m];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},Yo=(e,t)=>{let n=e.body,r=e.itemVar,o=Wo(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=[],s=!0;for(let l of n.properties){let c=l.key,a=l.value;if(a.type===p.LITERAL)i.push({key:c,type:"literal",value:a.value});else if(a.type===p.VARIABLE){let u=a.path;if(u===r)i.push({key:c,type:"item"});else if(u.startsWith(r+".")){let f=u.substring(r.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:c,type:"prop",prop:f});else{s=!1;break}}else{s=!1;break}}else if(a.type===p.INTERPOLATION&&a.parts.length===1){let u=a.parts[0];if(u.type===p.VARIABLE){let f=u.path;if(f===r)i.push({key:c,type:"item_string"});else if(f.startsWith(r+".")){let d=f.substring(r.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:c,type:"prop_string",prop:d});else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}if(s){let 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 a=t[c];l[c]={id:a.id,title:a.title!=null?String(a.title):"",completed:a.completed}}else for(let c=0;c<t.length;c++){let a=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]=a;else if(f.type==="prop")u[f.key]=a[f.prop];else if(f.type==="item_string")u[f.key]=a!=null?String(a):"";else if(f.type==="prop_string"){let d=a[f.prop];u[f.key]=d!=null?String(d):""}l[c]=u}return l}}return null},qo=(e,t,n,r,o)=>{let i=[],s=e.body;if(s.type===p.OBJECT&&s.fast!==!1){let l=e.itemVar,c=e.indexVar;for(let a=0;a<o.length;a++){let u=o[a],f={},d={...r,[l]:u,...c&&{[c]:a}};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}[${a}]`,...c&&{[c]:a}};for(let g of s.properties){let y=g.parsedKey?L(g.parsedKey,t,n,d):g.key,I=g.value;if(I.type===p.LITERAL)f[y]=I.value;else if(I.type===p.VARIABLE){let b=I.path;if(b===l)f[y]=u;else if(b===c)f[y]=a;else if(b.startsWith(l+".")){let m=b.substring(l.length+1);!m.includes(".")&&!m.includes("[")?f[y]=u[m]:f[y]=B(b,n,{...r,[l]:u,...c&&{[c]:a}})}else f[y]=B(b,n,{...r,[l]:u,...c&&{[c]:a}})}else if(I.type===p.INTERPOLATION){let b=[];for(let m of I.parts)if(typeof m=="string")b.push(m);else if(m.type===p.VARIABLE){let E=m.path,S;if(E===l)S=u;else if(E===c)S=a;else if(E.startsWith(l+".")){let $=E.substring(l.length+1);!$.includes(".")&&!$.includes("[")?S=u[$]:S=B(E,n,{...r,[l]:u,...c&&{[c]:a}})}else S=B(E,n,{...r,[l]:u,...c&&{[c]:a}});b.push(S!=null?String(S):"")}else{let E={...r,[l]:u,...c&&{[c]:a}},S=L(m,t,n,E);b.push(S!=null?String(S):"")}f[y]=b.join("")}else{let b={...r,[l]:u,...c&&{[c]:a}};f[y]=L(I,t,n,b)}}i.push(f)}return i}return null},Ho=(e,t,n)=>{let r=e.body;if(r.type===p.OBJECT&&r.properties.length===1&&r.properties[0].key==="$if item.visible"){let i=r.properties[0].value;if(i.type===p.CONDITIONAL&&i.conditions.length===1&&i.conditions[0].type===p.VARIABLE&&i.conditions[0].path==="item.visible"){let s=i.bodies[0];if(s.type===p.OBJECT&&s.properties.length===2){let l=s.properties[0],c=s.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 a=[];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),a.push(d)}}return a}}}}return null},Jo=(e,t,n,r)=>{let o=L(e.iterable,t,n,r);if(!Array.isArray(o)){let a,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(", ");a=`${e.iterable.name}(${d})`}else a=e.iterable.path||"undefined";let f=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${a}`;throw zn(f,o,u)}if(!e.indexVar){let a=Ho(e,o,e.itemVar);if(a!==null)return a}if(!e.indexVar){let a=Yo(e,o);if(a!==null)return a}let i=qo(e,t,n,r,o);if(i!==null)return i;let s=[],l=e.iterable.path||"";if(r&&r.__paths__&&l){let a=l.split("."),u=a[0];u in r.__paths__&&(l=r.__paths__[u],a.length>1&&(l+="."+a.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(a=>a.type===p.OBJECT&&a.properties.some(u=>u.key.startsWith("$if ")||u.key.startsWith("$when "))));for(let a=0;a<o.length;a++){let u=e.indexVar?{...r,[e.itemVar]:o[a],[e.indexVar]:a}:{...r,[e.itemVar]:o[a]};u.__paths__||(u.__paths__=r.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${l}[${a}]`},e.indexVar&&(u.__paths__[e.indexVar]=a);let f=L(e.body,t,n,u);if(Array.isArray(f)&&f.length===1&&!c){let d=f[0];s.push(d===void 0?{}:d)}else s.push(f===void 0?{}:f)}return s},Ko=(e,t,n,r)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?L(o.parsedKey,t,n,r):o.key,s=o.value;if(s.type===p.OBJECT&&s.properties.length<=10&&!s.whenCondition){let l={},c={},a=!0;for(let u of s.properties){let f=u.parsedKey?L(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]=B(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=B(g.path,n,r);h.push(y!=null?String(y):"")}else{a=!1;break}if(!a)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,I=g.value;if(I.type===p.LITERAL)h[y]=I.value;else if(I.type===p.VARIABLE)h[y]=B(I.path,n,r);else if(I.type===p.INTERPOLATION){let b=[];for(let m of I.parts)if(typeof m=="string")b.push(m);else if(m.type===p.VARIABLE){let E=B(m.path,n,r);b.push(E!=null?String(E):"")}else{a=!1;break}if(!a)break;h[y]=b.join("")}else{a=!1;break}}if(!a)break;c[f]=h}else{a=!1;break}}if(a)return l[i]=c,l}}return null},Go=(e,t,n,r)=>{let o=t.functions||t;if(e.whenCondition&&!fe(e.whenCondition,o,n,r))return;let i=Ko(e,t,n,r);if(i!==null)return i;if(e.fast){let a={};for(let u of e.properties){let f=u.parsedKey?L(u.parsedKey,t,n,r):u.key,d=u.value;if(d.type===p.LITERAL)a[f]=d.value;else if(d.type===p.VARIABLE)a[f]=B(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=B(g.path,n,r);h.push(y!=null?String(y):"")}else{let y=L(g,t,n,r);h.push(y!=null?String(y):"")}a[f]=h.join("")}else a[f]=L(d,t,n,r)}return a}let s={},l=null,c=!1;for(let a of e.properties)if(!a.key.startsWith("$if ")&&!a.key.match(/^\$if\s+\w+.*:?$/)&&!a.key.startsWith("$elif")&&!a.key.startsWith("$else")&&!a.key.startsWith("$for ")){c=!0;break}for(let a of e.properties)if(a.key.startsWith("$if ")||a.key.match(/^\$if\s+\w+.*:?$/)){let u=L(a.value,t,n,r);if(!c&&u!==null&&u!==void 0)return Array.isArray(u)&&u.length===1?u[0]:u;typeof u=="object"&&u!==null&&!Array.isArray(u)&&Object.assign(s,u)}else if(a.key.startsWith("$for ")){if(e.properties.length===1)return L(a.value,t,n,r)}else{let u=a.value;if(u&&u.type===p.OBJECT&&u.properties){let f=u.properties.find(d=>d.key.startsWith("$for "));if(f){let d=L(f.value,t,n,r);d!==void 0&&(s[a.key]=d)}else{let d=L(a.value,t,n,r);d!==void 0&&(s[a.key]=d)}}else{let f=a.parsedKey?L(a.parsedKey,t,n,r):a.key,d=L(a.value,t,n,r);d!==void 0&&(s[f]=d)}}return s},Kn={},Xo=(e,t,n,r)=>{let o=[];for(let i of e.items)if(i.type===p.LOOP){let s=L(i,t,n,r);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=L(i,t,n,r);s!==Kn&&s!==void 0&&o.push(s)}return o},Qo=(e,t,n,r)=>{let{name:o,data:i,whenCondition:s}=e,l=t.partials||{},c=t.functions||t;if(s&&!fe(s,c,n,r))return;if(!l[o])throw new K(`Partial '${o}' is not defined`);let a=r._partialStack||[];if(a.includes(o))throw new K(`Circular partial reference detected: ${o}`);let u=l[o],f=n,d={...r,_partialStack:[...a,o]};if(r){f={...n};for(let h of Object.keys(r))h.startsWith("_")||(f[h]=r[h])}if(i){let h=L(i,t,n,r);f={...f,...h}}return L(u,t,f,d)},Zo=(e,t,n,r)=>{let{path:o}=e,i=o.split("."),s=i[0],l=i.slice(1);if(!r||!(s in r))throw new K(`Path reference '#{${o}}' refers to '${s}' which is not a loop variable in the current scope`);if(r.__paths__||(r.__paths__={}),!(s in r.__paths__))throw new K(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let c=r.__paths__[s];if(typeof c=="number"){if(l.length>0)throw new K(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(c)}return l.length>0&&(c+="."+l.join(".")),c};var Nt=Mo;var ei=/\$\{([^}]*)\}/g,ti=/#\{([^}]*)\}/g,Xn=(e,t={})=>{let n=e.match(/^(\w+)\((.*)\)$/);if(!n)return{isFunction:!1};let[,r,o]=n,i=ni(o,t);return{isFunction:!0,type:p.FUNCTION,name:r,args:i}},ni=(e,t={})=>e.trim()?ri(e).map(r=>oi(r.trim(),t)):[],ri=e=>{let t=[],n="",r=0,o=!1,i="";for(let s=0;s<e.length;s++){let l=e[s],c=s>0?e[s-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},oi=(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=Xn(e,t);if(n.isFunction)return{type:n.type,name:n.name,args:n.args};let r=e.trim(),o=[{op:" + ",type:"ADD"},{op:" - ",type:"SUBTRACT"}],i=-1,s=null;for(let{op:l,type:c}of o){let a=0;for(;a<r.length;){let u=ye(r.substring(a),l);if(u===-1)break;let f=a+u;f>i&&(i=f,s={op:l,type:c}),a=f+l.length}}if(i!==-1)try{return W(r,t)}catch{return{type:p.VARIABLE,path:r}}return{type:p.VARIABLE,path:r}},Qn=/^\w+\(.*\)$/,ii=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,si=e=>{if(!(!e||e.trim()===""||Qn.test(e))&&ii.test(e))throw e.includes("?")&&e.includes(":")?new w(`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 w(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new w(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},Gn=e=>{let t=e.trim();if(Qn.test(t))throw new w(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new w(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new w(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new w(`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 w(`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}},De=(e,t={})=>{let n=e.trim();si(n);let r=Xn(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}},Dt=(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,(a,u)=>{let f=`__ESCAPED_${r.length}__`;return r.push(u),f}),n=n.replace(/\\(#\{[^}]*\})/g,(a,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(ei)],i=[...n.matchAll(ti)],s=[...o.map(a=>({match:a,type:"variable"})),...i.map(a=>({match:a,type:"pathref"}))].sort((a,u)=>a.match.index-u.match.index);if(s.length===0){let a=n;for(let u=0;u<r.length;u++)a=a.replace(`__ESCAPED_${u}__`,r[u]);return{type:p.LITERAL,value:a}}if(s.length===1&&s[0].match[0]===n&&r.length===0){let{match:a,type:u}=s[0];try{return u==="variable"?De(a[1],t):Gn(a[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:a,type:u}of s){let[f,d]=a,h=a.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=De(d.trim(),t):g=Gn(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 a=n.substring(c);for(let u=0;u<r.length;u++)a=a.replace(`__ESCAPED_${u}__`,r[u]);a&&l.push(a)}return{type:p.INTERPOLATION,parts:l}};var Mt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),tr=e=>Object.keys(e),J=e=>e.join("."),de=(e,t,n)=>{let r=tr(e).filter(o=>!t.has(o));if(r.length>0)throw new w(`Unexpected key '${r[0]}' in condition JSON at '${J(n)}'`)},pe=(e,t)=>typeof e=="string"?Dt(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?ci(e,t):li(e,t):{type:p.LITERAL,value:e},ai=e=>{let{$each:t,...n}=e;if(typeof t!="string")throw new w("$each value must be a non-empty string");let r=t.trim();if(r==="")throw new w("$each value must be a non-empty string");if(Object.keys(n).length===0)throw new w("Empty $each body not allowed");if(n.$partial!==void 0)throw new w("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${r}`]:n}},ci=(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=ai(i),a=Object.keys(c);if(a.length===1&&/^\$for(?::\w+)?\s/.test(a[0])){let u=er(a[0],c[a[0]],t,!0);n.push(u),r=!0;continue}}catch(c){throw c instanceof w?c:new w(c.message)}let l=Object.keys(i);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let c=er(l[0],i[l[0]],t);n.push(c),r=!0;continue}}let s=pe(i,t);n.push(s),(s.type===p.FUNCTION||s.type===p.CONDITIONAL||s.type===p.LOOP||s.type===p.PARTIAL||s.type===p.OBJECT&&!s.fast||s.type===p.ARRAY&&!s.fast)&&(r=!0)}return{type:p.ARRAY,items:n,fast:!r}},li=(e,t)=>{let n=[],r=!1,o=null,i=Object.entries(e),s=0;if(e.$partial!==void 0){if(typeof e.$partial!="string")throw new w("$partial value must be a string");if(e.$partial.trim()==="")throw new w("$partial value cannot be an empty string");let c=["$if","$elif","$else","$for"],a=[];for(let[b]of i)for(let m of c)if(b===m||b.startsWith(m+" ")||b.startsWith(m+"#")){a.push(m);break}if(a.length>0)throw new w(`Cannot use $partial with ${a.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,m]of Object.entries(d)){let E=b;(b.startsWith("\\$")||b.startsWith("$$"))&&(E=b.slice(1)),h[E]=m,g=!0}let y=null;if(g&&(y=pe(h,t),y.type===p.OBJECT)){let b=!1;for(let m of y.properties)if(m.value.type===p.VARIABLE||m.value.type===p.INTERPOLATION||m.value.type===p.FUNCTION||m.value.type===p.CONDITIONAL||m.value.type===p.OBJECT&&!m.value.fast||m.value.type===p.ARRAY&&!m.value.fast){b=!0;break}b&&(y.fast=!1)}let I={type:p.PARTIAL,name:u,data:y};return f!==void 0&&(I.whenCondition=Zn(f,t)),I}for(let[c,a]of i)if(c==="$when"){if(o!==null)throw new w("Multiple '$when' directives on the same object are not allowed");if(a==null)throw new w("Missing condition expression after '$when'");o=Zn(a,t),r=!0}else if(c.startsWith("$when#")||c.startsWith("$when "))throw new w("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<i.length;){let[c,a]=i[s];if(c==="$when"){s++;continue}if(c==="$each")throw new w("$each can only be used inside arrays");if(c.startsWith("$if ")||c.match(/^\$if#\w+\s/)||c.match(/^\$if\s+\w+.*:$/)){let u=ui(i,s,t);n.push({key:c,value:u.node}),r=!0,s=u.nextIndex}else if(/^\$for(?::\w+)?\s/.test(c)){let u=c.match(/^\$for(?::(\w+))?\s/)?.[1]||"",f=u?`:${u}`:"";throw new w(`$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 w(`'${c.split(" ")[0]}' without matching '$if'`);if(c==="$if"||c==="$if:")throw new w("Missing condition expression after '$if'");{let u=pe(a,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=Dt(c,t),d={key:c,value:u};(f.type!==p.LITERAL||f.value!==c)&&(d.parsedKey=f),n.push(d),s++}}}let l={type:p.OBJECT,properties:n,fast:!r};return o&&(l.whenCondition=o),l},ui=(e,t,n={})=>{let r=[],o=[],i=t,[s,l]=e[i],c=null,a;if(s.startsWith("$if#")){let f=s.match(/^\$if#(\w+)\s+(.+)$/);if(f)c=f[1],a=f[2];else throw new w(`Invalid conditional syntax: ${s}`)}else a=s.substring(4),a.endsWith(":")&&(a=a.slice(0,-1).trim());Tt(a);let u=W(a,n);for(r.push(u),o.push(pe(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{Tt(g);let y=W(g,n);r.push(y)}if(o.push(pe(d,n)),i++,g===null)break}else break}return{node:{type:p.CONDITIONAL,conditions:r,bodies:o,id:c},nextIndex:i}},Vt={eq:R.EQ,neq:R.NEQ,gt:R.GT,gte:R.GTE,lt:R.LT,lte:R.LTE,in:R.IN,add:R.ADD,sub:R.SUBTRACT},jt={all:R.AND,any:R.OR},fi=new Set(["var","literal","call","not",...Object.keys(Vt),...Object.keys(jt)]),di=(e,t,n)=>{if(!Array.isArray(e))throw new w(`Condition JSON operator '${t}' at '${J(n)}' requires an array`);if(e.length!==2)throw new w(`Condition JSON operator '${t}' at '${J(n)}' requires exactly 2 operands`);return e},pi=(e,t,n,r,o)=>{if(!Array.isArray(e))throw new w(`Condition JSON operator '${t}' at '${J(o)}' requires an array`);if(e.length===0)throw new w(`Condition JSON operator '${t}' at '${J(o)}' requires at least 1 condition`);return e.map((s,l)=>ne(s,r,[...o,l])).reduce((s,l)=>({type:p.BINARY,op:n,left:s,right:l}))},hi=(e,t,n)=>{let r,o;if(typeof e.call=="string")r=e.call,o=e.args??[],de(e,new Set(["call","args"]),n);else if(Mt(e.call))r=e.call.name,o=e.call.args??[],de(e,new Set(["call"]),n),de(e.call,new Set(["name","args"]),[...n,"call"]);else throw new w(`Condition JSON call at '${J(n)}' requires a function name`);if(typeof r!="string"||r.trim()==="")throw new w(`Condition JSON call at '${J(n)}' requires a non-empty function name`);if(!/^\w+$/.test(r))throw new w(`Invalid condition JSON function name '${r}' at '${J(n)}'`);if(!Array.isArray(o))throw new w(`Condition JSON call '${r}' at '${J(n)}' requires args to be an array`);return{type:p.FUNCTION,name:r,args:o.map((i,s)=>ne(i,t,[...n,"args",s]))}},ne=(e,t={},n=["$when"])=>{if(typeof e=="string"||typeof e=="number"||typeof e=="boolean"||e===null)return{type:p.LITERAL,value:e};if(Array.isArray(e))throw new w(`Condition JSON array at '${J(n)}' must be wrapped in an operator or { literal: [...] }`);if(!Mt(e))throw new w(`Invalid condition JSON value at '${J(n)}'`);let r=tr(e);if(r.length===0)throw new w(`Condition JSON object at '${J(n)}' must contain an operator`);let o=r.filter(s=>fi.has(s));if(o.length===0)throw new w(`Unknown condition JSON operator '${r[0]}' at '${J(n)}'`);if(o.length>1)throw new w(`Condition JSON at '${J(n)}' must contain exactly one operator`);let i=o.includes("call")?"call":o[0];if(i==="var"){if(de(e,new Set(["var"]),n),typeof e.var!="string"||e.var.trim()==="")throw new w(`Condition JSON var at '${J(n)}' requires a non-empty path`);return{type:p.VARIABLE,path:e.var}}if(i==="literal")return de(e,new Set(["literal"]),n),{type:p.LITERAL,value:e.literal};if(i==="call")return hi(e,t,n);if(i==="not")return de(e,new Set(["not"]),n),{type:p.UNARY,op:_e.NOT,operand:ne(e.not,t,[...n,"not"])};if(i in jt)return de(e,new Set([i]),n),pi(e[i],i,jt[i],t,[...n,i]);if(i in Vt){de(e,new Set([i]),n);let s=di(e[i],i,[...n,i]);return{type:p.BINARY,op:Vt[i],left:ne(s[0],t,[...n,i,0]),right:ne(s[1],t,[...n,i,1])}}throw new w(`Unknown condition JSON operator '${i}' at '${J(n)}'`)},Zn=(e,t={})=>{if(e==null)throw new w("Missing condition expression after '$when'");if(typeof e=="string"){if(e.trim()==="")throw new w("Empty condition expression after '$when'");return W(e,t)}return Mt(e)||Array.isArray(e)?ne(e,t):{type:p.LITERAL,value:e}},W=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let a=e.slice(1,-1),u=0,f=!0;for(let d=0;d<a.length;d++)if(a[d]==="("?u++:a[d]===")"&&u--,u<0){f=!1;break}if(f&&u===0)return W(a,t)}let n=ye(e,"||");if(n!==-1)return{type:p.BINARY,op:R.OR,left:W(e.substring(0,n).trim(),t),right:W(e.substring(n+2).trim(),t)};let r=ye(e,"&&");if(r!==-1)return{type:p.BINARY,op:R.AND,left:W(e.substring(0,r).trim(),t),right:W(e.substring(r+2).trim(),t)};let o=[{op:">=",type:R.GTE},{op:"<=",type:R.LTE},{op:"==",type:R.EQ},{op:"!=",type:R.NEQ},{op:">",type:R.GT},{op:"<",type:R.LT},{op:" in ",type:R.IN}];for(let{op:a,type:u}of o){let f=ye(e,a);if(f!==-1)return{type:p.BINARY,op:u,left:W(e.substring(0,f).trim(),t),right:W(e.substring(f+a.length).trim(),t)}}let i=-1,s=null,l=[{op:" + ",type:R.ADD},{op:" - ",type:R.SUBTRACT}];for(let{op:a,type:u}of l){let f=0;for(;f<e.length;){let d=ye(e.substring(f),a);if(d===-1)break;let h=f+d;h>i&&(i=h,s={op:a,type:u}),f=h+a.length}}if(i!==-1&&s)return{type:p.BINARY,op:s.type,left:W(e.substring(0,i).trim(),t),right:W(e.substring(i+s.op.length).trim(),t)};let c=[" * "," / "," % "];for(let a of c)if(ye(e,a)!==-1)throw new w(`Arithmetic operations are not allowed in conditionals: "${a}"`);return e.startsWith("!")?{type:p.UNARY,op:_e.NOT,operand:W(e.substring(1).trim(),t)}:nr(e,t)},ye=(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},gi=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}},nr=(e,t)=>{let n=e.trim();if(n.match(/^(\w+)\((.*)\)$/))return De(n,t);let o=gi(n);if(o.type===p.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(n))return{type:p.VARIABLE,path:n};try{return De(n,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},mi=(e,t=!1)=>{let n=t?"$each":"$for";try{Fn(e)}catch(r){if(r instanceof w&&t){let o=r.message.replace(/\$for/g,"$each");throw new w(o.replace("Parse Error: ",""))}throw r}},er=(e,t,n,r=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let I=r?"$each":"$for";throw new w(`Invalid loop syntax (got: '${e.replace("$for",I)}')`)}let s=i[1],l=i[2].trim();mi(l,r);let c=l.match(/^(.+?)\s+in\s+(.+)$/);if(!c){let I=r?"$each":"$for";throw new w(`Invalid loop syntax - missing 'in' keyword (got: '${I} ${l}')`)}let a=c[1].trim(),u=c[2].trim(),f,d=null;if(a.includes(",")){let I=a.split(",").map(b=>b.trim());if(I.length!==2)throw new w(`Invalid loop variables: ${a}. Expected format: "item" or "item, index"`);f=I[0],d=I[1]}else f=a;let h=["this","undefined","null","true","false"];if(h.includes(f))throw new w(`Reserved variable name: ${f}`);if(d&&h.includes(d))throw new w(`Reserved variable name: ${d}`);let g=nr(u,n),y=pe(t,n);return{type:p.LOOP,itemVar:f,indexVar:d,iterable:g,body:y,flatten:s!=="nested"}};var yi=(e,t={})=>{let{functions:n={}}=t;return pe(e,n)},rt=yi;var Ve={};Lo(Ve,{now:()=>bi});var bi=()=>Date.now();var Ii=(e,t,n={})=>{let{functions:r={},partials:o={}}=n,i={...Ve,...r},s=rt(e,{functions:i}),l={};for(let[c,a]of Object.entries(o))l[c]=rt(a,{functions:i});return Nt(s,t,{functions:i,partials:l})},Z=Ii;var Ai=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",wi=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,xi=(e,t)=>{if(Ai(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new w("Empty condition expression");return W(e,t)}return ne(e,t)},Ei=(e,t={},n={})=>{let r=wi(n),o={...Ve,...r},i=xi(e,o);return!!fe(i,{functions:o,partials:{}},t,{})},je=Ei;var rr=(e,t,n={})=>{let r=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=c=>c,transformActionFirstArgument:l=c=>c}=n;for(let[c,a]of Object.entries(t))c!=="createInitialState"&&(c.startsWith("select")?o[c]=(...u)=>a(s(r),...u):i[c]=(...u)=>{r=Pt(r,d=>a(l(d),...u))});return{...o,...i}},ot=(e,t)=>n=>{let r=e(),o=Array.isArray(n)?n:[n];return Pt(r,i=>{o.forEach(s=>{t.forEach(l=>{l(i,s)})})})};var vi=(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{}}},Ft=e=>{let t={},n={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([r,o])=>{let i=vi(o,r);o.scope==="context"?t[r]=i:n[r]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}},zt=(e,t)=>{let n=["context","device","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(", ")}`)},Wt=(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(", ")}`)},Yt=(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}`)}};var or=(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()))},Si=(e,t)=>{let n=i=>{if(!i)return;let s={};i.ui&&(s.ui=i.ui);let l=i.character?.sprite;return l&&Object.keys(l).length>0&&(s.sprite=l),Object.keys(s).length>0?s:void 0},r=n(e),o=n(t);return JSON.stringify(r)===JSON.stringify(o)?null:r&&!o?{changeType:"delete",data:e}:o&&!r?{changeType:"add",data:t}:o&&r?{changeType:"update",data:t}:null},qt=(e={},t={})=>{let n={},r=["sfx","voice"],o=s=>{let l=e[s],c=t[s];c&&!l?n[s]={changeType:"add",data:c}:l&&!c?r.includes(s)||(n[s]={changeType:"delete",data:l}):l&&c&&JSON.stringify(l)!==JSON.stringify(c)&&(n[s]={changeType:"update",data:c})};o("background"),o("bgm"),o("voice");let i=Si(e.dialogue,t.dialogue);return i&&(n.dialogue=i),o("choice"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),n},Ht=(e={})=>{let t=structuredClone(e);t.background&&(t.background.animations?.playback?.continuity!=="persistent"&&delete t.background.animations,t.background.resourceId||delete t.background);let n=o=>{t[o]&&(delete t[o].animations,Object.keys(t[o]).length===0&&delete t[o])};n("layout"),n("choice"),t.dialogue?.ui&&(delete t.dialogue.ui.animations,Object.keys(t.dialogue.ui).length===0&&delete t.dialogue.ui,Object.keys(t.dialogue).length===0&&delete t.dialogue),t.dialogue?.character?.sprite&&(delete t.dialogue.character.sprite.animations,Object.keys(t.dialogue.character.sprite).length===0&&delete t.dialogue.character.sprite,Object.keys(t.dialogue.character).length===0&&delete t.dialogue.character,Object.keys(t.dialogue).length===0&&delete t.dialogue);let r=(o,i)=>{let s=t[o]?.items;Array.isArray(s)&&(t[o].items=s.map(l=>{let c={...l};return delete c.animations,i(c)?c:null}).filter(Boolean),t[o].items.length===0&&delete t[o])};return r("character",o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId),r("visual",o=>o.resourceId||o.transformId),t},Ci=(e,t)=>{if(!e||!t)return;let n=e;for(let r of t.split(".")){if(n==null||!(r in Object(n)))return;n=n[r]}return n},_i=(e,t)=>{if(typeof e!="string")return e;if(e==="_event"){if(t==null)throw new Error('Action template binding "_event" requires event context "_event".');return t}if(!e.startsWith("_event."))return e;if(t==null)throw new Error(`Action template binding "${e}" requires event context "_event".`);let n=e.slice(7),r=Ci(t,n);if(r===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return r},Ri={conditional:new Set(["branches"]),updateProjectData:new Set(["projectData"]),showConfirmDialog:new Set(["confirmActions","cancelActions"])},ir=(e,t)=>{let n=e[e.length-1];return n?Ri[n]?.has(t)===!0:!1},Ut=(e,t,n=[])=>Array.isArray(e)?e.map(r=>Ut(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,ir(n,r)?o:Ut(o,t,[...n,r])])):_i(e,t),Bt=(e,t,n=[])=>Array.isArray(e)?e.map(r=>Bt(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,ir(n,r)?o:Bt(o,t,[...n,r])])):typeof e=="string"?Z(e,t):e,Jt=(e,t)=>{if(!t)return e;if(Object.prototype.hasOwnProperty.call(t,"event"))throw new Error('Action template context key "event" is no longer supported. Use "_event".');let n=Ut(e,t._event);return Bt(n,t)};var it=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:structuredClone(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},cr=(e,t)=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let n=e.map(r=>structuredClone(r)).filter(r=>t(r)||r.animations);return{hasValidItems:n.length>0,processedItems:n}},Re=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),sr=e=>e?.animations?.playback?.continuity==="persistent",Li=e=>{if(e){if(e.character&&Re(e.character,"name"))return e.character.name;if(Re(e,"characterName"))return e.characterName}},lr=e=>!!e?.character&&Re(e.character,"sprite"),$i=e=>{let t={},n=!1,r=Li(e);return r!==void 0&&(t.name=r,n=!0),lr(e)&&(t.sprite=structuredClone(e.character.sprite),n=!0),n?t:void 0},ar=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},Oi=({dialogueState:e,content:t,append:n=!1})=>{if(!n||!Array.isArray(t)){e.content=t,delete e.initialRevealedContent;return}let r=Array.isArray(e.content)?e.content:[];r.length>0?e.initialRevealedContent=r.map(o=>structuredClone(o)):delete e.initialRevealedContent,e.content=[...r,...t]},ki=()=>({}),Pi=(e,t)=>{if(t.background){let{animationsOnly:n,state:r}=it(t.background,s=>!!s.resourceId);if(n){e.background=e.background?.resourceId?{...structuredClone(e.background),...r}:r;return}if(!t.background.resourceId){delete e.background;return}let o=structuredClone(t.background),i=e.background;i?.resourceId===o.resourceId&&i?.transformId===o.transformId&&!Re(o,"animations")&&sr(i)&&(o.animations=structuredClone(i.animations)),e.background=o}else e.background?.animations&&!sr(e.background)&&(e.background.animations={})},Ti=(e,t)=>{if(!t.dialogue){e.dialogue&&(ar(e.dialogue),e.dialogue.mode==="adv"&&(e.dialogue.content=void 0,delete e.dialogue.initialRevealedContent,e.dialogue.persistCharacter!==!0&&(delete e.dialogue.characterId,delete e.dialogue.character)));return}e.dialogue||(e.dialogue={});let n=e.dialogue.mode;if(t.dialogue.ui){let{animationsOnly:a,state:u}=it(t.dialogue.ui,f=>!!f.resourceId);a?e.dialogue.ui={...e.dialogue.ui,...u}:e.dialogue.ui={...t.dialogue.ui}}else e.dialogue?.ui?.animations&&(e.dialogue.ui.animations={});t.dialogue.mode==="adv"&&(e.dialogue.content=e.dialogue.content||void 0,e.dialogue.characterId=e.dialogue.characterId||void 0,e.dialogue.mode="adv"),t.dialogue.mode==="nvl"&&(e.dialogue?.mode!=="nvl"&&(e.dialogue.lines=[]),e.dialogue.mode="nvl");let r=t.dialogue.append===!0&&n!=="nvl"&&e.dialogue?.mode!=="nvl"&&Array.isArray(t.dialogue.content);t.dialogue.content!==void 0&&Oi({dialogueState:e.dialogue,content:t.dialogue.content,append:r});let o=Re(t.dialogue,"persistCharacter")?t.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;o?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let i=Re(t.dialogue,"characterId"),s=$i(t.dialogue),l=s!==void 0,c=lr(t.dialogue);if(i?t.dialogue.characterId?e.dialogue.characterId=t.dialogue.characterId:delete e.dialogue.characterId:!o&&!r&&delete e.dialogue.characterId,l?e.dialogue.character=!i&&o&&e.dialogue.character?{...structuredClone(e.dialogue.character),...s}:s:(i||!o&&!r)&&delete e.dialogue.character,c||ar(e.dialogue),t.dialogue.clear){delete e.dialogue;return}if(t.dialogue?.clearPage&&e.dialogue?.mode==="nvl"&&(e.dialogue.lines=[]),e.dialogue?.mode==="nvl"&&t.dialogue.content!==void 0){let a={content:t.dialogue.content,characterId:e.dialogue.characterId??null};e.dialogue.character&&(a.character=structuredClone(e.dialogue.character)),e.dialogue.lines.push(a)}},Ni=(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},Di=(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}}},Vi=(e,t)=>{if(t.visual){let{hasValidItems:n,processedItems:r}=cr(t.visual.items,o=>!!o.resourceId);n?e.visual={items:r}:delete e.visual}else e.visual?.items&&(e.visual.items=e.visual.items.map(n=>n.animations?{...n,animations:{}}:n))},ji=(e,t)=>{if(!t.character){e.character?.items&&(e.character.items=e.character.items.map(o=>o.animations?{...o,animations:{}}:o));return}let{hasValidItems:n,processedItems:r}=cr(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId);n?e.character={items:r}:delete e.character},Mi=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},Ui=(e,t)=>{if(t.layout){let{animationsOnly:n,state:r}=it(t.layout,o=>!!o.resourceId);if(n){e.layout=r;return}if(!t.layout.resourceId){delete e.layout;return}e.layout=t.layout}else e.layout&&delete e.layout},Bi=(e,t)=>{if(t.choice){let{animationsOnly:n,state:r}=it(t.choice,o=>!!o.resourceId);if(n){e.choice={...e.choice,...r};return}if(!t.choice.resourceId){delete e.choice;return}e.choice=t.choice}else e.choice&&delete e.choice},Fi=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},zi=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},Wi=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(n=>{delete e[n]})},Le=e=>ot(ki,[Wi,Pi,Ni,Di,Vi,Ti,ji,Mi,Ui,Bi,Fi,zi])(e);var be={objectValues:e=>Object.entries(e).map(([t,n])=>({id:t,...n})),formatDate:or},Yi=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,qi=(e,t)=>{let n=String(t||"").trim();if(!n)return;let r=n.match(/[A-Za-z_][A-Za-z0-9_]*|\[\d+\]/g)||[],o=e;for(let i of r){if(i.startsWith("[")){let s=Number(i.slice(1,-1));o=Array.isArray(o)?o[s]:void 0;continue}o=o?.[i]}return o},ct=(e,t,n)=>{if(Array.isArray(e)){let o=[];for(let i of e){if(i&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===1){let[s]=Object.keys(i),l=Yi.exec(s);if(l){let[,c,a,u]=l,f=qi(t,u);if(!Array.isArray(f))continue;let d=Array.isArray(i[s])?i[s]:[];f.forEach((h,g)=>{let y={...t,[c]:h};a&&(y[a]=g),d.forEach(I=>{let b=ct(I,y,n),m=Z(b,y,n);Array.isArray(m)?o.push(...m):o.push(m)})});continue}}o.push(ct(i,t,n))}return o}if(!e||typeof e!="object")return e;let r={};return Object.entries(e).forEach(([o,i])=>{r[o]=ct(i,t,n)}),r},cn=({animationType:e,animationId:t,animationPath:n})=>{if(e!==void 0&&!(e==="update"||e==="transition"))throw new Error(`[${n}] Animation "${t}" has unsupported type "${e}". Use "update" or "transition".`)},Hi=({id:e,targetId:t,animation:n,playback:r,animationPath:o="animation"})=>{let i=structuredClone(n);return cn({animationType:i.type,animationId:e,animationPath:o}),delete i.name,delete i.playback,i.id=e,i.targetId=t,r&&(i.playback=structuredClone(r)),i},Ji=(e,{animationId:t="animation",animationPath:n="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return cn({animationType:e.type,animationId:t,animationPath:n}),e.type},Ki=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},Gi=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},Xi=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Ar=e=>e?.playback?.continuity==="persistent",en=e=>Array.isArray(e)?e.map(en):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((t,n)=>(t[n]=en(e[n]),t),{}),lt=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let t=structuredClone(e);return delete t.playback,JSON.stringify(en(t))},wr=(e=[])=>e.filter(t=>Ar(t)).map(t=>structuredClone(t)),xr=e=>Array.isArray(e?.keyframes)?e.keyframes.reduce((t,n)=>{let r=typeof n?.duration=="number"&&Number.isFinite(n.duration)?n.duration:0;return t+r},0):0,Kt=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((t,n)=>Math.max(t,xr(n)),0),Er=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max(Kt(e.tween),Kt(e.prev?.tween),Kt(e.next?.tween),xr(e.mask?.progress)),ur=({animationInstances:e,activePersistentAnimations:t})=>{if(!Array.isArray(e)||e.length===0||!Array.isArray(t)||t.length===0)return!1;let n=new Set(t.map(lt).filter(Boolean));return e.some(r=>{if(!Ar(r))return!1;let o=lt(r);return o?n.has(o):!1})},se=({animationInstances:e,isLineCompleted:t,skipTransitionsAndAnimations:n,activePersistentAnimations:r,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||n?!1:i&&!t||ur({animationInstances:e,activePersistentAnimations:r})?!0:i?!1:ur({animationInstances:e,activePersistentAnimations:o}),Qi=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),Zi=(e,t)=>{if(Qi(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},es=({resources:e,animationId:t,playback:n,instanceId:r,targetId:o,animationPath:i="animation"})=>{if(!t||!o)return!1;let s=e?.animations?.[t];return s?Hi({id:r,targetId:o,animation:s,playback:n,animationPath:i}):null},ts=({hasPrevious:e,hasCurrent:t,previousResourceId:n,currentResourceId:r,sharedTarget:o})=>!e&&t?"enter":e&&!t?"exit":e&&t?n===r&&o?"update":"replace":"none",ns=({animationType:e,animationId:t,animationPath:n,lifecycle:r})=>{if(!(e!=="update"||r==="update"))throw new Error(`[${n}] Animation "${t}" has type "update", but update animations can only be used when the same target persists across the state change. Use type "transition" for enter, exit, and replace.`)},rs=(e,{defaultTargetId:t,defaultId:n,animationPath:r="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return cn({animationType:o.type,animationId:o.id??n,animationPath:r}),o.id??=n,o.targetId??=t,o},ln=({animations:e,transitions:t,defaultTargetId:n,idPrefix:r,animationPathPrefix:o=r})=>{t.forEach((i,s)=>{e.push(rs(i,{defaultTargetId:n,defaultId:`${r}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},tn=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let n=Z(e,t);return n&&typeof n=="object"?e:n},nn=(e,t)=>{if(e===void 0)return[];if(!Array.isArray(e)||e.some(n=>n===null||typeof n!="object"||Array.isArray(n)))throw new Error(`${t} must be an array of objects`);return e},os=({content:e,path:t,variables:n})=>nn(e,t).reduce((r,o)=>{let i=tn(o.text,{variables:n});return r+`${i??""}`.length},0),fr=(e=[])=>{let t=new Map;for(let n of e)n?.id&&t.set(n.id,(t.get(n.id)??0)+1);return new Set(Array.from(t.entries()).filter(([,n])=>n>1).map(([n])=>n))},st=(e,t=0,n=new Set)=>{if(!n.has(e?.id))return`character-container-${e.id}`;let r=e?.sprites?.map(({resourceId:o})=>o)||[];return r.length===0?`character-container-${e.id}`:`character-container-${e.id}-${t}-${r.join("-")}`},Gt=(e,t)=>{if(!t.transformId)throw new Error(`Visual item "${t.id}" requires transformId`);let n=e.transforms?.[t.transformId];if(!n)throw new Error(`Transform "${t.transformId}" not found for visual item "${t.id}"`);return n},is=(e,t={})=>{if(!t?.transformId)return;let n=e.transforms?.[t.transformId];if(!n)throw new Error(`Transform "${t.transformId}" not found for background`);return n},dr=(e={},t)=>{if(t){if(e.images?.[t])return"sprite";if(e.videos?.[t])return"video";if(e.layouts?.[t])return"container"}},at=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},ss=(e={})=>e.textStyles||{},as=(e={})=>e.images||{},cs=(e={})=>e.colors||{},ls=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,Me=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,Oe=(e,t,n)=>{if(typeof e!="string"||e.length===0)throw new Error(`${n} at "${t}" must resolve to a non-empty string`)},pr=(e,t,n)=>{if(e===void 0)return 1;if(typeof e!="number"||!Number.isFinite(e))throw new Error(`${t} for text style "${n}" must be a number between 0 and 1`);if(e<0||e>1)throw new Error(`${t} for text style "${n}" must be a number between 0 and 1`);return e},vr=(e,t)=>{if(typeof e!="string"||!ls.test(e))throw new Error(`${t} must resolve to a hex color`);return e.length===4?`#${e.slice(1).split("").map(n=>n.repeat(2)).join("")}`:e},hr=(e,t,n)=>{let r=vr(e,n);if(t===1)return r;let o=Number.parseInt(r.slice(1,3),16),i=Number.parseInt(r.slice(3,5),16),s=Number.parseInt(r.slice(5,7),16);return`rgba(${o}, ${i}, ${s}, ${t})`},us=(e={},t)=>{let n=ss(e)?.[t];if(!n)throw new Error(`Text style "${t}" not found`);let r=e.fonts?.[n.fontId];if(!r)throw new Error(`Font "${n.fontId}" not found for text style "${t}"`);let o=e.colors?.[n.colorId];if(!o)throw new Error(`Color "${n.colorId}" not found for text style "${t}"`);let i=pr(n.colorAlpha,"colorAlpha",t),s={fontFamily:r.fileId,fontSize:n.fontSize??16,fontWeight:n.fontWeight??"400",fontStyle:n.fontStyle??"normal",lineHeight:n.lineHeight??1.2,fill:hr(o.hex,i,`Color "${n.colorId}" for text style "${t}"`)};if(n.align!==void 0&&(s.align=n.align),n.wordWrap!==void 0&&(s.wordWrap=n.wordWrap),n.breakWords!==void 0&&(s.breakWords=n.breakWords),n.wordWrapWidth!==void 0&&(s.wordWrapWidth=n.wordWrapWidth),n.strokeColorId){let l=e.colors?.[n.strokeColorId];if(!l)throw new Error(`Stroke color "${n.strokeColorId}" not found for text style "${t}"`);let c=pr(n.strokeAlpha,"strokeAlpha",t);s.strokeColor=hr(l.hex,c,`Stroke color "${n.strokeColorId}" for text style "${t}"`)}else if(n.strokeAlpha!==void 0)throw new Error(`strokeAlpha for text style "${t}" requires strokeColorId`);return n.strokeWidth!==void 0&&(s.strokeWidth=n.strokeWidth),s},rn=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>rn(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(Object.prototype.hasOwnProperty.call(e,"textStyle"))throw new Error(`Inline textStyle is not allowed in layout elements at "${n}". Use textStyleId instead`);let r={};for(let[o,i]of Object.entries(e))o!=="textStyleId"&&(r[o]=rn(i,t,Me(n,o)));return e.textStyleId!==void 0&&(Oe(e.textStyleId,n,"textStyleId"),r.textStyle=us(t,e.textStyleId)),r},Sr=(e={},t)=>{let n=cs(e)?.[t];if(!n)throw new Error(`Color "${t}" not found`);return vr(n.hex,`Color "${t}"`)},Cr=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",Xt=(e,t,n)=>{let r=e?.[t];if(!(!r||typeof r!="object"||Array.isArray(r))&&Object.prototype.hasOwnProperty.call(r,"fill"))throw new Error(`Inline ${t}.fill is not allowed in rect layout elements at "${n}". Use ${Cr(`${t}.fill`)} instead`)},fs=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>Ue(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;let r={};for(let[o,i]of Object.entries(e))o!=="colorId"&&(r[o]=Ue(i,t,Me(n,o)));return e.colorId!==void 0&&(Oe(e.colorId,n,"colorId"),r.fill=Sr(t,e.colorId)),r},Ue=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>Ue(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="rect"){if(Object.prototype.hasOwnProperty.call(e,"fill"))throw new Error(`Inline fill is not allowed in rect layout elements at "${n}". Use ${Cr("fill")} instead`);Xt(e,"hover",n),Xt(e,"click",n),Xt(e,"rightClick",n)}let r={};for(let[o,i]of Object.entries(e))if(!(e.type==="rect"&&o==="colorId")){if(e.type==="rect"&&(o==="hover"||o==="click"||o==="rightClick")){r[o]=fs(i,t,Me(n,o));continue}r[o]=Ue(i,t,Me(n,o))}return e.type==="rect"&&e.colorId!==void 0&&(Oe(e.colorId,n,"colorId"),r.fill=Sr(t,e.colorId)),r},Qt=(e={},t)=>{let n=as(e)?.[t];return n||null},_r=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",gr=(e,t,n,r)=>{let o=e?.[t];if(!(!o||typeof o!="object"||Array.isArray(o))&&Object.prototype.hasOwnProperty.call(o,r))throw new Error(`Inline ${t}.${r} is not allowed in sprite layout elements at "${n}". Use ${_r(`${t}.${r}`)} instead`)},mr=(e,t,n)=>{let r=e[t];e[t]={...r&&typeof r=="object"&&!Array.isArray(r)?r:{},src:n}},on=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>on(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="sprite"){for(let o of["url","src","hoverUrl","hoverSrc","clickUrl","clickSrc"])if(Object.prototype.hasOwnProperty.call(e,o))throw new Error(`Inline ${o} is not allowed in sprite layout elements at "${n}". Use ${_r(o)} instead`);gr(e,"hover",n,"src"),gr(e,"click",n,"src")}let r={};for(let[o,i]of Object.entries(e))e.type==="sprite"&&(o==="imageId"||o==="hoverImageId"||o==="clickImageId")||(r[o]=on(i,t,Me(n,o)));if(e.type==="sprite"&&e.imageId!==void 0){Oe(e.imageId,n,"imageId");let o=Qt(t,e.imageId),i=o?.fileId??e.imageId;r.src=i,r.width===void 0&&o?.width!==void 0&&(r.width=o.width),r.height===void 0&&o?.height!==void 0&&(r.height=o.height)}return e.type==="sprite"&&e.hoverImageId!==void 0&&(Oe(e.hoverImageId,n,"hoverImageId"),mr(r,"hover",Qt(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(Oe(e.clickImageId,n,"clickImageId"),mr(r,"click",Qt(t,e.clickImageId)?.fileId??e.clickImageId)),r},un=(e,t={},n="root")=>on(Ue(rn(e,t,n),t,n),t,n),Ie=un,Be=(e=[])=>e.find(t=>t.id==="story");var ds=(e={})=>e?.muteAll?0:e?.musicVolume??50,re=({variables:e,runtime:t,saveSlots:n=[],dialogueState:r,includeInactiveAdvDialogue:o=!1,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:c,canRollback:a,confirmDialog:u,historyDialogue:f=[],characters:d={},dialogueUIHidden:h,skipOnlyViewedLines:g,skipTransitionsAndAnimations:y}={})=>{let I={dialogueTextSpeed:t?.dialogueTextSpeed??50,autoForwardDelay:t?.autoForwardDelay??1e3,skipUnseenText:t?.skipUnseenText??!1,skipTransitionsAndAnimations:t?.skipTransitionsAndAnimations??!1,soundVolume:t?.soundVolume??50,musicVolume:t?.musicVolume??50,muteAll:t?.muteAll??!1,saveLoadPagination:t?.saveLoadPagination??1,menuPage:t?.menuPage??"",menuEntryPoint:t?.menuEntryPoint??"",autoMode:t?.autoMode??s??!1,skipMode:t?.skipMode??l??!1,dialogueUIHidden:t?.dialogueUIHidden??h??!1,isLineCompleted:t?.isLineCompleted??i??!1},b=ms({dialogueState:r,includeInactiveAdvDialogue:o,characters:d,variables:e}),m={variables:e,runtime:I,saveSlots:n,isChoiceVisible:c,canRollback:a,confirmDialog:u,historyDialogue:f,characters:d};return b&&(m.dialogue=b,m.dialogueLines=b.lines),m},yr=100,ut=(e,t)=>{if(Array.isArray(e))return e.map(r=>ut(r,t));if(!e||typeof e!="object")return e;let n={...e};return Object.keys(n).forEach(r=>{n[r]=ut(n[r],t)}),n.type==="text-revealing"?t(n):n},ps=e=>ut(e,t=>({...t,revealEffect:"none"})),hs=e=>ut(e,t=>{let n=Number(t.speed??t.displaySpeed),r=Number.isFinite(n)?Math.max(n,yr):yr;return{...t,speed:r,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:r}:{}}}),Ae=(e,{isLineCompleted:t=!1,skipMode:n=!1,skipTransitionsAndAnimations:r=!1}={})=>t||r?ps(e):n?hs(e):e,Rr=({id:e,screen:t={width:1920,height:1080}})=>({id:e,type:"rect",fill:"transparent",width:t.width,height:t.height,x:0,y:0,click:{payload:{actions:{}}}}),sn=e=>{if(Array.isArray(e))return e.map(sn);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=sn(s);let n=t.click?.payload;if(!n||typeof n!="object"||Array.isArray(n))return t;let r=n.actions,o=r&&typeof r=="object"&&!Array.isArray(r)&&Object.prototype.hasOwnProperty.call(r,"nextLine")?{...r.nextLine,_interactionSource:"choice"}:void 0;return{...t,click:{...t.click,payload:{...n,_interactionSource:"choice",...o?{actions:{...r,nextLine:o}}:{}}}}},an=({characterId:e,character:t,characterName:n,characters:r={}}={})=>{let o=e?r?.[e]:void 0,i=t?.name!==void 0?t.name:n!==void 0?n:o?.name||"";return{...o||{},...t||{},name:i}},Lr=(e=[],t={})=>e.map(n=>{let r=an({characterId:n.characterId,character:n.character,characterName:n.characterName,characters:t}),o=typeof n.text=="string"?n.text:Array.isArray(n.content)?n.content.map(i=>i?.text??"").join(""):"";return{...n,text:o,character:r,characterName:r.name}}),gs=e=>!(!e||e.mode==="adv"&&e.content===void 0),ms=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:n={},variables:r}={})=>{if(!t&&!gs(e))return;let o=e.content===void 0?[{text:""}]:nn(e.content,"dialogue.content"),i=e.content===void 0?0:os({content:e.initialRevealedContent,path:"dialogue.initialRevealedContent",variables:r}),s=(e.lines||[]).map((c,a)=>{let u=nn(c.content,`dialogue.lines[${a}].content`),f=an({characterId:c.characterId,character:c.character,characterName:c.characterName,characters:n});return{...c,content:u.map(d=>({...d,text:tn(d.text,{variables:r})})),character:f,characterName:f.name}}),l=an({characterId:e.characterId,character:e.character,characters:n});return{characterId:e.characterId,persistCharacter:e.persistCharacter,character:l,content:o.map(c=>({...c,text:tn(c.text,{variables:r})})),initialRevealedCharacters:i,lines:s}},$r=({container:e,resources:t,templateData:n,isLineCompleted:r=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=Z(e,n,{functions:be});return Ie(Ae(s,{isLineCompleted:r,skipMode:o,skipTransitionsAndAnimations:i}),t)},Zt=(e,t={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(t),br=({renderStateKeyboard:e,keyboard:t,phase:n})=>{!t||typeof t!="object"||Array.isArray(t)||Object.entries(t).forEach(([r,o])=>{let i=e[r]??{},s=n==="keydown"?o?.keydown:o?.keyup;if(n==="keydown"&&s&&typeof s=="object"){e[r]={...i,keydown:{payload:Zt(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[r].keyup={payload:Zt(o.keyup)});return}e[r]={...i,[n]:{payload:Zt(o)}}})},ys=(e={},t={})=>{let n={};return br({renderStateKeyboard:n,keyboard:e,phase:"keydown"}),br({renderStateKeyboard:n,keyboard:t,phase:"keyup"}),Object.keys(n).length>0?n:void 0},we=({animationsDef:e,resources:t,previousResourceId:n,currentResourceId:r,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:l,allowIncomingUpdateFallback:c=!1})=>{if(!e)return[];let a=[],u=({instanceId:S,targetId:$})=>{let O=es({resources:t,animationId:y,playback:I,instanceId:S,targetId:$,animationPath:s});O&&a.push(O)},f=n!=null&&n!==!1,d=r!=null&&r!==!1,h=o&&i&&o===i,g=ts({hasPrevious:f,hasCurrent:d,previousResourceId:n,currentResourceId:r,sharedTarget:h});Zi(e,s);let y=Ki(e),I=Gi(e),b=t?.animations?.[y],m=Ji(b,{animationId:y,animationPath:s}),E=c&&m==="update"&&g!=="update"&&d&&i;if(E||ns({animationType:m,animationId:y,animationPath:s,lifecycle:g}),m==="update")return f&&d&&n===r&&h?u({instanceId:`${l}-animation-update`,targetId:i}):E&&u({instanceId:`${l}-animation-update`,targetId:i}),a;if(m==="transition"){let S=`${l}-animation-transition`,$=I?.continuity==="persistent"?S:`${l}-animation-in`;if(f&&d&&h)return u({instanceId:S,targetId:i}),a;f&&u({instanceId:`${l}-animation-out`,targetId:o}),d&&u({instanceId:$,targetId:i})}return a},bs=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),Is=(e,{presentationState:t,previousPresentationState:n,currentLineActions:r,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:l,variables:c,runtime:a,activePersistentAnimations:u,restoredPersistentAnimations:f,autoMode:d,skipMode:h,isChoiceVisible:g,canRollback:y,saveSlots:I=[]})=>{let{elements:b,animations:m}=e;if(t.background){let E=r===void 0?!0:Xi(r?.background??{},"animations"),S=b.find(P=>P.id==="story");if(!S)return e;let $=is(o,t.background),O=n?.background?.resourceId,_=t.background.resourceId??(t.background.animations?O:void 0),D=dr(o,O),N=dr(o,_);if(_){let{images:P={},videos:x={}}=o,C=P[_]||x[_];if(C){let M=x[_]!==void 0,z={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...$},Y={id:at({resourceId:_,kind:M?"video":"sprite"}),type:M?"video":"sprite",x:z.x,y:z.y,src:C.fileId,width:C.width,height:C.height,alpha:1,anchorX:z.anchorX,anchorY:z.anchorY,rotation:z.rotation,scaleX:z.scaleX,scaleY:z.scaleY};M&&(Y.loop=t.background.loop??!1,Y.volume=C.volume??50),S.children.push(Y)}}if(_){let{layouts:P={}}=o,x=P[_];if(x){let C={id:at({resourceId:_,kind:"container"}),type:"container",children:x.elements};$&&Object.assign(C,{x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...$});let M=Z(C,re({variables:c,runtime:a,saveSlots:I,dialogueState:t.dialogue,isLineCompleted:s,autoMode:d,skipMode:h,isChoiceVisible:g,canRollback:y,characters:o.characters||{},skipTransitionsAndAnimations:l}),{functions:be});S.children.push(Ie(Ae(M,{isLineCompleted:s,skipMode:h,skipTransitionsAndAnimations:l}),o))}}let k=we({animationsDef:t.background.animations,resources:o,previousResourceId:O,currentResourceId:_,previousTargetId:at({resourceId:O,kind:D}),currentTargetId:at({resourceId:_,kind:N}),animationPath:"background.animations",idPrefix:"bg-cg",allowIncomingUpdateFallback:!0});se({animationInstances:k,isLineCompleted:s,skipTransitionsAndAnimations:l,activePersistentAnimations:u,restoredPersistentAnimations:f,isAuthoredOnCurrentLine:E})&&m.push(...k)}return e},As=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:l,animations:c}=e;if(t.character&&r){let a=l.find(g=>g.id==="story");if(!a)return e;let u=t.character.items||[],f=n?.character?.items||[],d=fr(u),h=fr(f);for(let g=0;g<u.length;g++){let y=u[g],{transformId:I,sprites:b}=y,m=f.find(P=>P.id===y.id),E=f.findIndex(P=>P.id===y.id),S=m?.sprites&&m.sprites.length>0,$=b&&b.length>0,O=E>=0?st(m,E,h):void 0,_=we({animationsDef:y.animations,resources:r,previousResourceId:O,currentResourceId:$?st(y,g,d):void 0,previousTargetId:O,currentTargetId:$?st(y,g,d):void 0,animationPath:`character.items[${g}].animations`,idPrefix:"character"});if(y.animations&&!b&&!I&&S&&se({animationInstances:_,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){c.push(..._);continue}if(y.animations&&!b&&!I)continue;if(!b||b.length===0||!I){console.warn("Character item missing sprites or transformId:",y);continue}let D=st(y,g,d),N=r.transforms[I];if(!N){console.warn("Transform not found:",I);continue}let k={type:"container",id:D,x:y.x??N.x,y:y.y??N.y,anchorX:N.anchorX,anchorY:N.anchorY,rotation:N.rotation,scaleX:N.scaleX,scaleY:N.scaleY,children:[]};for(let P of b){let x=r.images[P.resourceId];if(!x){console.warn(`Image resource not found: ${P.resourceId}`);continue}k.children.push({type:"sprite",id:`${D}-${P.id}`,src:x.fileId,width:x.width,height:x.height,x:0,y:0})}a.children.push(k),se({animationInstances:_,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(..._)}}return e},ws=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,runtime:l,activePersistentAnimations:c,autoMode:a,skipMode:u,isChoiceVisible:f,canRollback:d,saveSlots:h=[]})=>{let{elements:g,animations:y}=e;if(t.visual&&r){let I=g.find(m=>m.id==="story");if(!I)return e;let b=t.visual.items;for(let m of b){if(m.resourceId){let{images:O={},videos:_={},spritesheets:D={}}=r,N=D[m.resourceId];if(N){let k=Gt(r,m),P=m.animationName;if(P){let x=N.animations?.[P];if(!x)throw new Error(`Animation '${P}' not found in spritesheet resource '${m.resourceId}'`);let C={id:`visual-${m.id}`,type:"animated-sprite",x:m.x??k.x,y:m.y??k.y,width:m.width??N.width,height:m.height??N.height,alpha:m.alpha??1,anchorX:k.anchorX,anchorY:k.anchorY,rotation:k.rotation,scaleX:k.scaleX,scaleY:k.scaleY,spritesheetSrc:N.fileId,spritesheetData:N.jsonData,animation:{frames:x.frames,animationSpeed:m.animationSpeed??x.animationSpeed??.5,loop:m.loop??x.loop??!0}};I.children.push(structuredClone(C))}}else{let k=O[m.resourceId]||_[m.resourceId];if(k){let P=_[m.resourceId]!==void 0,x=Gt(r,m),C={id:`visual-${m.id}`,type:P?"video":"sprite",src:k.fileId,width:k.width,height:k.height,x:x.x,y:x.y,anchorX:x.anchorX,anchorY:x.anchorY,rotation:x.rotation,scaleX:x.scaleX,scaleY:x.scaleY};P&&(C.loop=k.loop??!1,C.volume=k.volume??50),I.children.push(C)}}}if(m.resourceId){let{layouts:O={}}=r,_=O[m.resourceId];if(_){let D=Gt(r,m),N={id:`visual-${m.id}`,type:"container",children:structuredClone(_.elements),x:D.x,y:D.y,anchorX:D.anchorX,anchorY:D.anchorY,rotation:D.rotation,scaleX:D.scaleX,scaleY:D.scaleY},k=Z(N,re({variables:s,runtime:l,saveSlots:h,dialogueState:t.dialogue,isLineCompleted:o,autoMode:a,skipMode:u,isChoiceVisible:f,canRollback:d,characters:r.characters||{},skipTransitionsAndAnimations:i}),{functions:be});I.children.push(Ie(Ae(k,{isLineCompleted:o,skipMode:u,skipTransitionsAndAnimations:i}),r))}}let S=(n?.visual?.items||[]).find(O=>O.id===m.id),$=we({animationsDef:m.animations,resources:r,previousResourceId:S?.resourceId,currentResourceId:m.resourceId,previousTargetId:S?.resourceId?`visual-${m.id}`:void 0,currentTargetId:m.resourceId?`visual-${m.id}`:void 0,animationPath:`visual.items[${m.id}].animations`,idPrefix:m.id});se({animationInstances:$,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:c})&&y.push(...$)}}return e},$e="dialogue-character-sprite",Ir=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,xs=(e,{presentationState:t,previousPresentationState:n,resources:r={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:l}=e,c=Be(e.elements);if(!c)return e;let a=t.dialogue?.character?.sprite,u=n?.dialogue?.character?.sprite,f=Ir(a),d=Ir(u),h=we({animationsDef:a?.animations,resources:r,previousResourceId:d?$e:void 0,currentResourceId:f?$e:void 0,previousTargetId:d?$e:void 0,currentTargetId:f?$e:void 0,animationPath:"dialogue.character.sprite.animations",idPrefix:"dialogue-character-sprite"});if(!f)return a?.animations&&d&&se({animationInstances:h,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...h),e;let g=r.transforms?.[a.transformId];if(!g)return console.warn("Transform not found:",a.transformId),e;let y={type:"container",id:$e,x:g.x,y:g.y,anchorX:g.anchorX,anchorY:g.anchorY,rotation:g.rotation,scaleX:g.scaleX,scaleY:g.scaleY,children:[]};for(let I of a.items){let b=r.images?.[I.resourceId];if(!b){console.warn(`Image resource not found: ${I.resourceId}`);continue}y.children.push({type:"sprite",id:`${$e}-${I.id}`,src:b.fileId,width:b.width,height:b.height,x:0,y:0})}return c.children.push(y),se({animationInstances:h,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...h),e},Es=(e,{presentationState:t,previousPresentationState:n,resources:r={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:l,canRollback:c,skipOnlyViewedLines:a,isLineCompleted:u,skipTransitionsAndAnimations:f,variables:d,runtime:h,activePersistentAnimations:g,saveSlots:y=[]})=>{let{elements:I,animations:b}=e;if(!t.dialogue||o)return e;let m=I.find(S=>S.id==="story");if(!m)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:S={}}=r,$=S[t.dialogue.ui.resourceId];if($){let O={elements:$.elements},_=re({variables:d,runtime:h,saveSlots:y,dialogueState:t.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:u,autoMode:i,skipMode:s,isChoiceVisible:l,canRollback:c,characters:r.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:a,skipTransitionsAndAnimations:f}),D={functions:be},N=ct(O,_,D),k=Z(N,_,D),P=Ie(Ae(k?.elements,{isLineCompleted:u,skipMode:s,skipTransitionsAndAnimations:f}),r);if(Array.isArray(P))for(let x of P)m.children.push(x);else P&&m.children.push(P)}}xs(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:u,skipTransitionsAndAnimations:f,activePersistentAnimations:g});let E=we({animationsDef:t.dialogue.ui?.animations,resources:r,previousResourceId:n?.dialogue?.ui?.resourceId,currentResourceId:t.dialogue.ui?.resourceId,previousTargetId:n?.dialogue?.ui?.resourceId?"dialogue-container":void 0,currentTargetId:t.dialogue.ui?.resourceId?"dialogue-container":void 0,animationPath:"dialogue.ui.animations",idPrefix:"dialogue-ui"});return se({animationInstances:E,isLineCompleted:u,skipTransitionsAndAnimations:f,activePersistentAnimations:g})&&b.push(...E),e},vs=(e,{presentationState:t,previousPresentationState:n,resources:r,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,runtime:c,autoMode:a,skipMode:u,isChoiceVisible:f,canRollback:d,activePersistentAnimations:h,saveSlots:g=[]})=>{let{elements:y,animations:I}=e;if(t.choice&&r){let b=Be(y);if(!b)return e;let m=r?.layouts[t.choice.resourceId];if(m&&m.elements){let S={elements:m.elements},$=Z(S,{...re({variables:l,runtime:c,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:i,autoMode:a,skipMode:u,isChoiceVisible:f??!!t.choice,canRollback:d,characters:r.characters||{},skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}},{functions:be}),O=sn(Ie(Ae($?.elements,{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),r));if(Array.isArray(O))for(let _ of O)b.children.push(_);else O&&b.children.push(O)}let E=we({animationsDef:t.choice.animations,resources:r,previousResourceId:n?.choice?.resourceId,currentResourceId:t.choice.resourceId,previousTargetId:n?.choice?.resourceId?"choice-container":void 0,currentTargetId:t.choice.resourceId?"choice-container":void 0,animationPath:"choice.animations",idPrefix:"choice"});se({animationInstances:E,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:h})&&I.push(...E)}return e},Ss=(e,{presentationState:t,resources:n={},variables:r,runtime:o,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:c,canRollback:a,saveSlots:u=[],skipTransitionsAndAnimations:f})=>{if(!t.control?.resourceId)return e;let d=n.controls?.[t.control.resourceId];if(!d)return e;let h=ys(d.keyboard,d.keyup);if(h&&Object.keys(h).length>0&&(e.global.keyboard=h),!Array.isArray(d.elements)||d.elements.length===0)return e;let g=Be(e.elements);if(!g)return e;let y={id:`control-${t.control.resourceId}`,type:"container",x:0,y:0,children:d.elements};return g.children.push($r({container:y,resources:n,templateData:re({variables:r,runtime:o,saveSlots:u,dialogueState:t.dialogue,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:c,canRollback:a,characters:n.characters||{},skipTransitionsAndAnimations:f}),isLineCompleted:i,skipMode:l,skipTransitionsAndAnimations:f})),e},Cs=(e,{presentationState:t,resources:n,runtime:r,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&n){if(!Be(i))return e;let c=n.sounds[t.bgm.resourceId];if(!c)return e;let a=re({variables:o,runtime:r}).runtime;s.push({id:"bgm",type:"sound",src:c.fileId,loop:t.bgm.loop??!0,volume:ds(a),delay:t.bgm.delay??null})}return e},_s=(e,{presentationState:t,resources:n})=>{let{audio:r}=e;if(t.sfx&&n){let o=t.sfx.items;for(let i of o){let s=n.sounds?.[i.resourceId];s&&r.push({id:i.id,type:"sound",src:s.fileId,loop:i.loop??s.loop??!1,volume:i.volume??s.volume??50,delay:i.delay??s.delay??null})}}return e},Rs=(e,t,n)=>{if(!(!t||!n))return e?.voices?.[t]?.[n]},Ls=(e={},t={})=>t.muteAll?0:e.volume??t.soundVolume??50,$s=(e,{presentationState:t,resources:n,currentSceneId:r,runtime:o,variables:i})=>{let{audio:s}=e;if(!t?.voice)return e;let l=t.voice,{resourceId:c,loop:a,delay:u}=l,f=Rs(n,r,c);if(!f)return e;let d=re({variables:i,runtime:o}).runtime;return s.push({id:`voice-${r}-${c}`,type:"sound",src:f.fileId,volume:Ls(l,d),loop:a??!1,delay:u??null}),e},Os=(e,{presentationState:t,previousPresentationState:n,resources:r={},variables:o,runtime:i,autoMode:s,skipMode:l,isChoiceVisible:c,canRollback:a,saveSlots:u=[],isLineCompleted:f,skipTransitionsAndAnimations:d,activePersistentAnimations:h})=>{let{elements:g,animations:y}=e;if(t.layout){let E=Be(g);if(!E)return e;let S=r.layouts[t.layout.resourceId];if(!S)return e;Array.isArray(S.transitions)&&!f&&!d&&ln({animations:y,transitions:S.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let $={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:S.elements||[]};E.children.push($r({container:$,resources:r,templateData:re({variables:o,runtime:i,saveSlots:u,dialogueState:t.dialogue,isLineCompleted:f,autoMode:s,skipMode:l,isChoiceVisible:c,canRollback:a,characters:r.characters||{},skipTransitionsAndAnimations:d}),isLineCompleted:f,skipMode:l,skipTransitionsAndAnimations:d}))}let I=n?.layout?.resourceId,b=t.layout?.resourceId,m=we({animationsDef:t.layout?.animations,resources:r,previousResourceId:I,currentResourceId:b,previousTargetId:I?`layout-${I}`:void 0,currentTargetId:b?`layout-${b}`:void 0,animationPath:"layout.animations",idPrefix:"layout"});return se({animationInstances:m,isLineCompleted:f,skipTransitionsAndAnimations:d,activePersistentAnimations:h})&&y.push(...m),e},ks=(e,{presentationState:t,resources:n={},variables:r,runtime:o,autoMode:i,skipMode:s,isChoiceVisible:l,canRollback:c,overlayStack:a=[],dialogueHistory:u=[],saveSlots:f=[],screen:d,isLineCompleted:h,skipTransitionsAndAnimations:g})=>{let{elements:y,animations:I}=e;return a&&a.length>0&&a.forEach((b,m)=>{let E=n.layouts[b.resourceId];if(!E){console.warn(`Overlay layout not found: ${b.resourceId}`);return}Array.isArray(E.transitions)&&(g||ln({animations:I,transitions:E.transitions,defaultTargetId:`overlayStack-${m}`,idPrefix:`overlayStack-${m}`,animationPathPrefix:`overlayStack[${m}]`}));let S={id:`overlayStack-${m}`,type:"container",x:0,y:0,children:[Rr({id:`overlayStack-${m}-blocker`,screen:d}),...E.elements||[]]},$=Lr(u,n.characters),O=re({variables:r,runtime:o,saveSlots:f,dialogueState:t?.dialogue,isLineCompleted:h,autoMode:i,skipMode:s,isChoiceVisible:l,canRollback:c,historyDialogue:$,characters:n.characters||{},skipTransitionsAndAnimations:g}),_=Z(S,O,{functions:be}),[D,...N]=_.children||[],k=Ie(Ae({..._,children:N},{isLineCompleted:h,skipMode:s,skipTransitionsAndAnimations:g}),n);y.push({...k,children:D?[D,...k.children||[]]:k.children})}),e},Ps=(e,{presentationState:t,resources:n={},variables:r,runtime:o,saveSlots:i=[],autoMode:s,skipMode:l,isChoiceVisible:c,canRollback:a,confirmDialog:u,dialogueHistory:f=[],screen:d,isLineCompleted:h,skipTransitionsAndAnimations:g})=>{let{elements:y,animations:I}=e;if(!u?.resourceId)return e;let b=n.layouts?.[u.resourceId];if(!b)return console.warn(`ConfirmDialog layout not found: ${u.resourceId}`),e;Array.isArray(b.transitions)&&!g&&ln({animations:I,transitions:b.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let m={id:"confirmDialog",type:"container",x:0,y:0,children:[Rr({id:"confirmDialog-blocker",screen:d}),...b.elements||[]]},E=Lr(f,n.characters),S=Z(m,re({variables:r,runtime:o,saveSlots:i,dialogueState:t?.dialogue,isLineCompleted:h,autoMode:s,skipMode:l,isChoiceVisible:c,canRollback:a,confirmDialog:u,historyDialogue:E,characters:n.characters||{},skipTransitionsAndAnimations:g}),{functions:be}),[$,...O]=S.children||[],_=Ie(Ae({...S,children:O},{isLineCompleted:h,skipMode:l,skipTransitionsAndAnimations:g}),n);return y.push({..._,children:$?[$,..._.children||[]]:_.children}),e},Or=e=>ot(bs,[Ss,Is,As,ws,Es,vs,Os,Cs,_s,$s,ks,Ps])(e);var Ts=Object.freeze({dialogueTextSpeed:{source:"global.dialogueTextSpeed"},autoForwardDelay:{source:"global.autoForwardDelay"},skipUnseenText:{source:"global.skipUnseenText"},skipTransitionsAndAnimations:{source:"global.skipTransitionsAndAnimations"},soundVolume:{source:"global.soundVolume"},musicVolume:{source:"global.musicVolume"},muteAll:{source:"global.muteAll"},saveLoadPagination:{source:"context.runtime.saveLoadPagination"},menuPage:{source:"context.runtime.menuPage"},menuEntryPoint:{source:"context.runtime.menuEntryPoint"},autoMode:{source:"global.autoMode"},skipMode:{source:"global.skipMode"},dialogueUIHidden:{source:"global.dialogueUIHidden"},isLineCompleted:{source:"global.isLineCompleted"}}),ft=Object.freeze({dialogueTextSpeed:50,autoForwardDelay:1e3,skipUnseenText:!1,skipTransitionsAndAnimations:!1,soundVolume:50,musicVolume:50,muteAll:!1,autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isLineCompleted:!1}),Fe=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),kr=Object.freeze({dialogueTextSpeed:"number",autoForwardDelay:"number",skipUnseenText:"boolean",skipTransitionsAndAnimations:"boolean",soundVolume:"number",musicVolume:"number",muteAll:"boolean",saveLoadPagination:"number",menuPage:"string",menuEntryPoint:"string",autoMode:"boolean",skipMode:"boolean",dialogueUIHidden:"boolean",isLineCompleted:"boolean"}),fn=Object.freeze(["dialogueTextSpeed","autoForwardDelay","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),dn=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),Ns=(e,t)=>{if(t.startsWith("global.")){let n=t.slice(7);return e?.global?.[n]}if(t.startsWith("context.runtime.")){let n=t.slice(16),r=Array.isArray(e?.contexts)?e.contexts:[];return r[r.length-1]?.runtime?.[n]}},dt=e=>Object.fromEntries(Object.entries(Ts).map(([t,n])=>{let r=Ns(e,n.source),o=r!==void 0?r:ft[t]??Fe[t];return[t,o]})),ae=(e,t)=>dt(e)[t],Pr=(e={})=>Object.fromEntries(fn.map(t=>[t,e[t]??ft[t]]));var pt={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},jr=1,gt=()=>({manual:{...pt.manual},auto:{...pt.auto},applyMode:pt.applyMode}),pn=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let n=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...gt()},n&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},F=e=>{let t=ue(e)?kt(e):e;return structuredClone(t)},j=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),mt=e=>String(e),Mr=()=>({sections:[],resources:[]}),Ds=e=>j(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):Mr(),Vs=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",js=({sectionId:e,lineId:t,content:n,dialogueState:r,characterName:o})=>({sectionId:e,lineId:t,content:n,text:Vs(n),characterId:r.characterId,character:{...r.character||{},name:o},characterName:o}),Ms=()=>({resourceId:void 0}),Us=e=>{if(!j(e))return e;let t={...e};return Object.prototype.hasOwnProperty.call(t,"requireComplete")&&!Object.prototype.hasOwnProperty.call(t,"requireLineCompleted")&&(t.requireLineCompleted=t.requireComplete),delete t.requireComplete,t},hn=(e,t)=>{let n=e?.story?.scenes??{};for(let[r,o]of Object.entries(n))if(o?.sections?.[t])return{sceneId:r,section:o.sections[t]};return{sceneId:void 0,section:void 0}},Ur=e=>{let t=e?.story?.scenes??{},n=new Map;for(let[r,o]of Object.entries(t)){let i=o?.sections??{};for(let s of Object.keys(i)){let l=n.get(s);if(l!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${l}" and "${r}". Section IDs must be globally unique.`);n.set(s,r)}}},Br=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},Fr=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==jr)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},Bs=(e,t={})=>{let n;try{n=Fr(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let r={...t,formatVersion:n,slotId:Br(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete r.slotKey,delete r.date,r},Fs=(e={})=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Bs(t,n)])),zr=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:n})=>bc(n));return t.length>0?t:void 0},zs=e=>{!j(e)||!Array.isArray(e.timeline)||e.timeline.forEach(t=>{if(!j(t))return;let n=zr(t.executedActions);if(n){t.executedActions=n;return}delete t.executedActions})},Tr=(e,t,n,r="viewedRegistry")=>{let o=t==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[o]:String(e)};if(!j(e))throw new Error(`Malformed ${r}.${t}[${n}] entry.`);if(typeof e[o]!="string"||e[o].length===0)throw new Error(`Malformed ${r}.${t}[${n}] entry: missing ${o}.`);if(t==="sections"){let i={sectionId:e.sectionId};if(e.lastLineId!==void 0&&e.lastLineId!==null&&typeof e.lastLineId!="string")throw new Error(`Malformed ${r}.sections[${n}] entry: invalid lastLineId.`);return typeof e.lastLineId=="string"&&e.lastLineId.length>0&&(i.lastLineId=e.lastLineId),i}return{resourceId:e.resourceId}},Ws=(e,t="viewedRegistry")=>{if(e===void 0)return Mr();if(!j(e))throw new Error(`Malformed ${t}.`);if(e.sections!==void 0&&!Array.isArray(e.sections))throw new Error(`Malformed ${t}.sections.`);if(e.resources!==void 0&&!Array.isArray(e.resources))throw new Error(`Malformed ${t}.resources.`);let n=e.sections??[],r=e.resources??[];return{sections:Object.values(Object.fromEntries(n.map((o,i)=>{let s=Tr(o,"sections",i,t);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(r.map((o,i)=>{let s=Tr(o,"resources",i,t);return[s.resourceId,s]})))}},Wr=(e,t,n)=>{if(!j(e))throw new Error(`Malformed save slot ${n}.`);let{sectionId:r,lineId:o}=e;if(typeof r!="string"||r.length===0)throw new Error(`Malformed save slot ${n}: missing sectionId.`);if(typeof o!="string"||o.length===0)throw new Error(`Malformed save slot ${n}: missing lineId.`);let{sceneId:i,section:s}=hn(t,r);if(!s)throw new Error(`Malformed save slot ${n}: section "${r}" does not exist in projectData.`);if(!s.lines?.some(c=>c.id===o))throw new Error(`Malformed save slot ${n}: line "${o}" does not exist in section "${r}".`);return{sceneId:i,sectionId:r,lineId:o}},Ys=(e,t,n)=>{if(!j(e)||!Array.isArray(e.timeline))return ze({pointer:t,replayStartIndex:1});let r=e.timeline.flatMap((l,c)=>{if(!j(l))return[];try{let a=Wr(l,n,`rollback.timeline[${c}]`),u=ht({sectionId:a.sectionId,lineId:a.lineId,rollbackPolicy:l.rollbackPolicy}),f=zr(F(l.executedActions));return f&&(u.executedActions=f),[u]}catch{return[]}});if(r.length===0)return ze({pointer:t,replayStartIndex:1});let o=typeof e.currentIndex=="number"?Math.trunc(e.currentIndex):r.length-1;(o<0||o>=r.length)&&(o=r.length-1);let i=r[o];if(i?.sectionId!==t.sectionId||i?.lineId!==t.lineId){let l=r.findLastIndex(c=>c.sectionId===t.sectionId&&c.lineId===t.lineId);l>=0?o=l:(r.push(ht({sectionId:t.sectionId,lineId:t.lineId})),o=r.length-1)}let s=typeof e.replayStartIndex=="number"?Math.min(Math.max(Math.trunc(e.replayStartIndex),0),o):0;return{currentIndex:o,isRestoring:!1,replayStartIndex:s,timeline:r}},qs=(e,t,n)=>{if(!j(e))throw new Error(`Malformed save slot contexts[${n}] entry.`);let r=mn(t),o=Wr(e.pointers?.read,t,`contexts[${n}].pointers.read`);if(e.variables!==void 0&&!j(e.variables))throw new Error(`Malformed save slot contexts[${n}].variables entry.`);if(e.runtime!==void 0&&!j(e.runtime))throw new Error(`Malformed save slot contexts[${n}].runtime entry.`);let i=e.variables?F(e.variables):{},s=Xs({loadedContextRuntime:j(e.runtime)?F(e.runtime):{}}),l={currentPointerMode:"read",pointers:{read:o},configuration:j(e.configuration)?F(e.configuration):{},views:Array.isArray(e.views)?F(e.views):[],bgm:j(e.bgm)?F(e.bgm):{resourceId:void 0},variables:{...r,...i},rollback:Ys(e.rollback,o,t)};return s&&(l.runtime=s),l},Hs=(e,t)=>{if(!j(e))throw new Error("Malformed save slot state.");if(!Array.isArray(e.contexts)||e.contexts.length===0)throw new Error("Malformed save slot state: contexts must be a non-empty array.");return{contexts:e.contexts.map((n,r)=>qs(n,t,r))}},Js=(e,t)=>{if(!j(e))throw new Error("Malformed save slot.");let n=Fr(e.formatVersion);return{...e,formatVersion:n,state:Hs(e.state,t)}},Nr=(e,t,{required:n=!1}={})=>{if(e===void 0){if(n)throw new Error(`showConfirmDialog requires ${t}`);return{hideConfirmDialog:{}}}if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`showConfirmDialog ${t} must be an action object`);let r=F(e);return Object.prototype.hasOwnProperty.call(r,"hideConfirmDialog")||(r.hideConfirmDialog={}),r},Ks=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:Nr(e.confirmActions,"confirmActions",{required:!0}),cancelActions:Nr(e.cancelActions,"cancelActions")}},ke=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},xe=[],Dr="line",gn="interaction",ht=({sectionId:e,lineId:t,rollbackPolicy:n})=>({sectionId:e,lineId:t,rollbackPolicy:n??"free"}),mn=e=>{let{contextVariableDefaultValues:t}=Ft(e??{});return F(t)},Yr=()=>({...F(Fe)}),qr=({loadedRuntime:e,runtimeIds:t,defaults:n={},path:r})=>{if(e===void 0)return{runtimeState:F(n),hasLoadedValues:!1};if(!j(e))throw new Error(`Malformed ${r}.`);let o=F(n),i=!1;return t.forEach(s=>{e[s]!==void 0&&(o[s]=Hr(s,F(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},Gs=({loadedGlobalRuntime:e={}})=>qr({loadedRuntime:e,runtimeIds:fn,defaults:ft,path:"global.runtime"}).runtimeState,Xs=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:n}=qr({loadedRuntime:e,runtimeIds:dn,defaults:Yr(),path:"context.runtime"});return n?t:void 0},yn=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},Qs=e=>e.runtime?(dn.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=F(Fe[t]))}),e.runtime):(e.runtime=Yr(),e.runtime),Zs=e=>Pr(e.global),ea=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:Zs(e)}})},ta=e=>kr[e],na=(e,t)=>{let n=ta(e);if(n==="number"){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} requires a finite numeric value`);return}if(n==="boolean"){if(typeof t!="boolean")throw new Error(`${e} requires a boolean value`);return}if(n==="string"){if(typeof t!="string")throw new Error(`${e} requires a string value`);return}throw new Error(`Unsupported runtime field "${e}"`)},Hr=(e,t)=>(na(e,t),e==="saveLoadPagination"?Math.max(1,Math.trunc(t)):t),Jr=(e,t,n)=>{let r=Hr(t,n);if(t in Fe){let o=yn(e);if(!o)return r;let i=Qs(o);return i[t]=r,r}return e.global[t]=r,r},Kr=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:F(e)},configuration:{},views:[],bgm:Ms(),variables:mn(t),rollback:ze({pointer:e})}),Pe=e=>e?(e.currentPointerMode="read",j(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,ra=e=>{let t=e.contexts?.[e.contexts.length-1],n=t?.pointers?.read;if(!t||!n?.sectionId||!n?.lineId)return null;let r=Kr({pointer:n,projectData:e.projectData});return e.contexts[e.contexts.length-1]=r,oa(e),r},oa=e=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,ke(e),e.global.nextLineConfig=gt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})},Gr=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},ze=({pointer:e,replayStartIndex:t=0})=>{let n=e?.sectionId&&e?.lineId;return{currentIndex:n?0:-1,isRestoring:!1,replayStartIndex:t,timeline:n?[ht({sectionId:e.sectionId,lineId:e.lineId})]:[]}},ve=(e,t={})=>{if(e?.rollback)return Gr(e.rollback),Array.isArray(e.rollback.timeline)||(e.rollback.timeline=[]),typeof e.rollback.currentIndex!="number"&&(e.rollback.currentIndex=e.rollback.timeline.length>0?e.rollback.timeline.length-1:-1),typeof e.rollback.isRestoring!="boolean"&&(e.rollback.isRestoring=!1),typeof e.rollback.replayStartIndex!="number"&&(e.rollback.replayStartIndex=0),e.rollback;let n=e?.pointers?.read;return e.rollback=ze({pointer:n,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},bn=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return;let r=ve(n);if(r.isRestoring)return;r.currentIndex<r.timeline.length-1&&(r.timeline=r.timeline.slice(0,r.currentIndex+1));let o=r.timeline[r.timeline.length-1];if(o?.sectionId===t.sectionId&&o?.lineId===t.lineId&&(o?.rollbackPolicy??"free")===(t.rollbackPolicy??"free")){r.currentIndex=r.timeline.length-1;return}r.timeline.push(ht(t)),r.currentIndex=r.timeline.length-1},ia=e=>{let n=e.contexts?.[e.contexts.length-1]?.rollback;if(!n||n.isRestoring||!Array.isArray(n.timeline)||typeof n.currentIndex!="number")return null;let r=xe[xe.length-1],o=typeof r?.checkpointIndex=="number"?r.checkpointIndex:n.currentIndex;return o<0||o>=n.timeline.length?null:(typeof r?.checkpointIndex!="number"&&o<n.timeline.length-1&&(n.timeline=n.timeline.slice(0,o+1)),n.timeline[o]??null)},sa=({state:e},t={})=>{let n=t?.source===Dr?Dr:gn,o=e.contexts?.[e.contexts.length-1]?.rollback;return!o||o.isRestoring||!Array.isArray(o.timeline)||typeof o.currentIndex!="number"||o.currentIndex<0||o.currentIndex>=o.timeline.length?(xe.push({checkpointIndex:null,source:n}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),xe.push({checkpointIndex:o.currentIndex,source:n}),e)},aa=({state:e})=>(xe.pop(),e),ce=(e,t,n)=>{let o=xe[xe.length-1]?.source??gn;if(!Ic(t,o))return;let i=ia(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:F(n)}))},Vr=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return;let r=t?.operations??[];for(let{variableId:o,op:i,value:s}of r){let l=e.projectData.resources?.variables?.[o],c=l?.scope,a=l?.type;zt(c,o),Wt(a,i,o),c==="context"&&(n.variables[o]=Yt(n.variables[o],i,s))}},ca=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:n,payload:r})=>{Ac(e,n,r)})},la=(e,t)=>{let{sectionId:n,lineId:r}=t,s=G({state:e},{sectionId:n})?.lines?.find(l=>l.id===r)?.actions;s&&Object.entries(s).forEach(([l,c])=>{go(e,l,c)})},Xr=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return e;let r=ve(n),o=r.timeline[t];if(!o)return e;e.global.autoMode&&Ye({state:e}),e.global.skipMode&&Ee({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),r.isRestoring=!0,r.currentIndex=t;try{n.variables=mn(e.projectData),delete n.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=F(pt),e.global.overlayStack=[],ke(e),e.global.isLineCompleted=!0;let i=r.replayStartIndex??0;for(let l=i;l<=t;l++)l>i&&pn(e),la(e,r.timeline[l]),ca(e,r.timeline[l]);let s=Pe(n);s.read={sectionId:o.sectionId,lineId:o.lineId},e.global.pendingEffects=e.global.pendingEffects.filter(l=>l?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{r.isRestoring=!1}return e},ua=e=>{let{projectData:t}=e,n=e.global??{},{saveSlots:r={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=n;Ur(t);let l=t.story.initialSceneId,c=t.story.scenes[l],a=c.initialSectionId,u=c.sections[a],f={sceneId:l,sectionId:a,lineId:u.initialLineId??u.lines[0].id},{globalVariablesDefaultValues:d}=Ft(t),h={...d,...o};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,accountViewedRegistry:Ws(s,"accountViewedRegistry"),nextLineConfig:gt(),saveSlots:Fs(r),overlayStack:[],variables:h,...Gs({loadedGlobalRuntime:i})},contexts:[Kr({pointer:f,projectData:t})]}},fa=({state:e})=>e.global.overlayStack||[],da=({state:e})=>e.global.pendingEffects,Qr=({state:e})=>e.global.skipMode,pa=({state:e})=>e.global.autoMode,Zr=({state:e})=>e.global.dialogueUIHidden,eo=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],n=t[t.length-1];if(!n)return[];let{sectionId:r,lineId:o}=n.pointers.read,i=G({state:e},{sectionId:r});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(u=>u.id===o),l=i.lines.slice(0,s+1),c=[],a={};for(let u of l){let f=u.actions||{};if(a=Le([a,f]),!f.dialogue)continue;let d=a.dialogue||{},h="";d.character?.name!==void 0?h=d.character.name:d.characterId&&(h=e.projectData.resources?.characters?.[d.characterId]?.name||"");let g=js({sectionId:r,lineId:u.id,content:f.dialogue.append===!0?d.content:f.dialogue.content,dialogueState:d,characterName:h});if(f.dialogue.append===!0&&c.length>0){c[c.length-1]={...c[c.length-1],content:g.content,text:g.text,characterId:g.characterId,character:g.character,characterName:g.characterName};continue}c.push(g)}return c},ha=({state:e})=>e.global.confirmDialog??null,ga=({state:e,registry:t},n)=>{let{sectionId:r,lineId:o}=n,s=(Array.isArray(t?.sections)?t.sections:[]).find(u=>u.sectionId===r);if(!s)return!1;if(s.lastLineId===void 0||o===void 0)return!0;let l=G({state:e},{sectionId:r});if(!l||!l.lines||!Array.isArray(l.lines))return s.lastLineId===o;let c=l.lines.findIndex(u=>u.id===s.lastLineId),a=l.lines.findIndex(u=>u.id===o);return c===-1||a===-1?s.lastLineId===o:a<=c},ma=({registry:e},t)=>{let{resourceId:n}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===n)},In=({state:e},t)=>ga({state:e,registry:e.global.accountViewedRegistry},t),ya=({state:e},t)=>ma({registry:e.global.accountViewedRegistry},t),ba=({state:e})=>e.global.nextLineConfig,to=({state:e,pointer:t}={})=>{let n=t??oe({state:e})?.pointer;if(!n)return;let r=n?.sectionId,o=n?.lineId,s=G({state:e},{sectionId:r})?.lines||[],l=s.findIndex(a=>a.id===o);if(l<0)return;let c;for(let a of s.slice(0,l+1)){let u=a?.actions;if(u?.cleanAll&&(c=void 0),!u||!Object.prototype.hasOwnProperty.call(u,"choice")){c=void 0;continue}let f=u.choice;if(f?.resourceId){c=f.resourceId;continue}f?.animations||(c=void 0)}return c},ie=({state:e})=>!!to({state:e}),Ia=({state:e})=>structuredClone(e),no=({state:e})=>e.global.saveSlots,Aa=({state:e},t)=>{let n=t?.slotId,r=mt(n);return e.global.saveSlots[r]},An=({state:e})=>dt(e),wa=({state:e},t)=>ae(e,t?.runtimeId),ro=({state:e})=>({...e.global?.variables??{},...yn(e)?.variables??{}}),oe=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],n=t[t.length-1];if(n)return{currentPointerMode:"read",pointer:n.pointers?.read}},G=({state:e},t)=>{let{sectionId:n}=t;return hn(e.projectData,n).section},wn=({state:e})=>{let t=oe({state:e});if(!t?.pointer)return;let{sectionId:n,lineId:r}=t.pointer,o=G({state:e},{sectionId:n});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===r)},oo=({state:e})=>{let{sectionId:t,lineId:n}=oe({state:e}).pointer,o=G({state:e},{sectionId:t})?.lines||[],i=o.findIndex(a=>a.id===n),l=o.slice(0,i+1).map(a=>{let u=a.actions||{},f={};return Object.keys(u).forEach(d=>{f[d]=u[d]}),f});return Le(l)},xa=({state:e})=>{let t=io({state:e}),r=wn({state:e})?.actions??{},o=Le([t??{},r]);return qt(t??{},o??{})},Ea=({state:e},{sectionId:t})=>{let n=G({state:e},{sectionId:t});if(!n?.lines)return[];let r=[],o={};for(let i of n.lines){let s=i.actions||{},l=Le([o,s]),c=qt(o,l);r.push({id:i.id,changes:c,presentationState:l}),o=Ht(l)}return r},va=({state:e},{sectionId:t,includePresentationState:n=!1})=>{let r=Ea({state:e},{sectionId:t});return n?{lines:r}:{lines:r.map(({presentationState:o,...i})=>i)}},io=({state:e})=>{let{sectionId:t,lineId:n}=oe({state:e}).pointer,o=G({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 a=c.actions||{},u={};return Object.keys(a).forEach(f=>{u[f]=a[f]}),u});return Ht(Le(l))},xn=({state:e},{slotsPerPage:t=6}={})=>{let o=((An({state:e}).saveLoadPagination??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let l=o+s,c=e.global.saveSlots&&e.global.saveSlots[mt(l)]||{};i.push({...c,slotId:l})}return{saveSlots:i}},Sa=no,Ca=xn,_a=e=>{let n=e.contexts?.[e.contexts.length-1]?.rollback;return!n||!Array.isArray(n.timeline)||typeof n.currentIndex!="number"?!1:n.currentIndex>=0&&n.currentIndex<n.timeline.length-1},Ra=({state:e},t={})=>{let n=oo({state:e}),r=io({state:e}),o=wn({state:e})?.actions??{},{sectionId:i}=oe({state:e}).pointer,{sceneId:s}=hn(e.projectData,i),l=An({state:e}),c=t?.activePersistentAnimations??[],a=t?.restoredPersistentAnimations??[],u=ro({state:e}),{saveSlots:f}=xn({state:e}),d=_a(e);return Or({presentationState:n,previousPresentationState:r,currentLineActions:o,resources:e.projectData.resources,currentSceneId:s,screen:e.projectData.screen,dialogueUIHidden:l.dialogueUIHidden,autoMode:l.autoMode,skipMode:l.skipMode,isChoiceVisible:ie({state:e}),canRollback:yo({state:e}),skipOnlyViewedLines:!l.skipUnseenText,isLineCompleted:l.isLineCompleted,skipTransitionsAndAnimations:!!l.skipTransitionsAndAnimations||d,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,dialogueHistory:eo({state:e}),saveSlots:f,variables:u,runtime:l,activePersistentAnimations:c,restoredPersistentAnimations:a})},La=({state:e},t)=>(e.global.confirmDialog=Ks(t),e.global.pendingEffects.push({name:"render"}),e),$a=({state:e})=>(e.global.confirmDialog&&(ke(e),e.global.pendingEffects.push({name:"render"})),e),Oa=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),ce(e,"pushOverlay",t),e),ka=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),ce(e,"popOverlay",void 0),e),Pa=({state:e},t)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=t),e.global.pendingEffects.push({name:"render"}),ce(e,"replaceLastOverlay",t),e),Ta=({state:e})=>(e.global.overlayStack=[],ke(e),e.global.pendingEffects.push({name:"render"}),ce(e,"clearOverlays",void 0),e),Na=e=>{e.global.autoMode&&(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"})),e.global.skipMode&&(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"})),e.global.nextLineConfig?.auto?.enabled&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},yt=(e,t)=>{e.global.isLineCompleted=!1;let n=!!to({state:e,pointer:t});return n&&Na(e),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:n}},so=({state:e})=>(ie({state:e})||(e.global.skipMode&&(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"})),e.global.autoMode=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.isLineCompleted&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:ae(e,"autoForwardDelay")}}),e.global.pendingEffects.push({name:"render"})),e),Ye=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Da=({state:e})=>{let t=e.global.autoMode;return ie({state:e})&&!t||(t?Ye({state:e}):so({state:e})),e},ao=({state:e})=>(ie({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),Ee=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Va=({state:e})=>{let t=Qr({state:e});return ie({state:e})&&!t||(t?Ee({state:e}):ao({state:e})),e},bt=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),ce(e,"showDialogueUI",void 0),e),co=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),ce(e,"hideDialogueUI",void 0),e),ja=({state:e})=>(Zr({state:e})?bt({state:e}):co({state:e}),e),Se=(e,t,n)=>(Jr(e,t,n),ea(e),e.global.pendingEffects.push({name:"render"}),e),qe=(e,t,n,r)=>{let o=Jr(e,t,n);return e.global.pendingEffects.push({name:"render"}),ce(e,r,{value:o}),e},Ma=({state:e},t)=>Se(e,"dialogueTextSpeed",t?.value),Ua=({state:e},t)=>Se(e,"autoForwardDelay",t?.value),Ba=({state:e},t)=>Se(e,"skipUnseenText",t?.value),Fa=({state:e},t)=>Se(e,"skipTransitionsAndAnimations",t?.value),za=({state:e},t)=>Se(e,"soundVolume",t?.value),Wa=({state:e},t)=>Se(e,"musicVolume",t?.value),Ya=({state:e},t)=>Se(e,"muteAll",t?.value),qa=({state:e},t)=>qe(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),Ha=({state:e})=>{let t=ae(e,"saveLoadPagination")+1;return qe(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},Ja=({state:e})=>{let t=ae(e,"saveLoadPagination")-1;return qe(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},Ka=({state:e},t)=>qe(e,"menuPage",t?.value,"setMenuPage"),Ga=({state:e},t)=>qe(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),Xa=({state:e})=>(e.global.pendingEffects=[],e),Qa=({state:e},t)=>(e.global.pendingEffects.push(t),e),lo=(e,{sectionId:t,resetStoryState:n=!1})=>{let r=G({state:e},{sectionId:t});if(!r)return console.warn(`Section not found: ${t}`),e;let o=r.lines?.[0];if(!o)return console.warn(`Section ${t} has no lines`),e;if(n&&!ra(e))return e;e.global.autoMode&&Ye({state:e}),e.global.skipMode&&Ee({state:e});let i=e.contexts?.[e.contexts.length-1];if(i){let s=Pe(i);i.rollback||ve(i,{compatibilityAnchor:!0}),s.read={sectionId:t,lineId:o.id},n?i.rollback=ze({pointer:s.read}):bn(e,{sectionId:t,lineId:o.id})}return yt(e,i?.pointers?.read),e},Za=({state:e},t)=>lo(e,{sectionId:t?.sectionId,resetStoryState:!0}),uo=e=>(e.global.accountViewedRegistry=Ds(e.global.accountViewedRegistry),e.global.accountViewedRegistry),fo=(e,t)=>{!Array.isArray(t)||t.length===0||e.global.pendingEffects.push({name:"applyScopedDataUpdates",payload:{updates:t.map(n=>({scope:n.scope,path:n.path,op:n.op,value:F(n.value)}))}})},po=(e,t)=>{fo(e,[{scope:"account",path:"viewedRegistry",op:"markViewed",value:{sections:(Array.isArray(t?.sections)?t.sections:[]).map(n=>({sectionId:n.sectionId,...n.lastLineId===void 0?{}:{lineId:n.lastLineId}})),resources:Array.isArray(t?.resources)?t.resources:[]}}])},ec=(e,t,{sectionId:n,lineId:r})=>{if(!n||!r)return!1;let o=j(t)?t:{};Array.isArray(o.sections)||(o.sections=[]);let i=o.sections.find(s=>s.sectionId===n);if(i){if(i.lastLineId===void 0)return!1;let s=G({state:e},{sectionId:n});if(s?.lines){let l=s.lines.findIndex(a=>a.id===i.lastLineId),c=s.lines.findIndex(a=>a.id===r);if(l===-1||c>l)return i.lastLineId===r?!1:(i.lastLineId=r,!0)}else return i.lastLineId===r?!1:(i.lastLineId=r,!0);return!1}else return o.sections.push({sectionId:n,lastLineId:r}),!0},We=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;ec(e,uo(e),t)&&po(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},tc=({state:e},t)=>(We(e,t),e.global.pendingEffects.push({name:"render"}),e),nc=({state:e},t)=>{let{resourceId:n}=t;if(e.global.accountViewedRegistry!==void 0){let r=uo(e);r.resources.find(i=>i.resourceId===n)||(r.resources.push({resourceId:n}),po(e,{sections:[],resources:[{resourceId:n}]}))}return e.global.pendingEffects.push({name:"render"}),e},ho=({state:e},t)=>{let n=Us(t.manual),{auto:r,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,l=e.contexts?.[e.contexts.length-1]?.rollback?.isRestoring===!0;n&&r?(e.global.nextLineConfig={manual:n,auto:r},o!==void 0?e.global.nextLineConfig.applyMode=o:s!==void 0&&(e.global.nextLineConfig.applyMode=s)):(n&&(e.global.nextLineConfig.manual=n),r&&(e.global.nextLineConfig.auto=r),o!==void 0&&(e.global.nextLineConfig.applyMode=o));let c=e.global.nextLineConfig.auto?.enabled,a=ie({state:e});return!l&&!a&&c===!0&&!i?e.global.nextLineConfig.auto?.trigger==="fromStart"?e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):e.global.isLineCompleted&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):!l&&c===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),ce(e,"setNextLineConfig",t),e},rc=({state:e},t)=>{let n=t?.slotId;if(n==null||n==="")throw new Error("saveSlot requires slotId");let{thumbnailImage:r}=t,o=t?.savedAt,i=mt(n),s=F(e.contexts);s?.forEach(a=>{Pe(a),Gr(a.rollback),zs(a.rollback)});let l={contexts:s},c={formatVersion:jr,slotId:Br(n),savedAt:typeof o=="number"?o:Date.now(),image:r,state:l};return e.global.saveSlots[i]=c,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},oc=({state:e},t)=>{let n=t?.slotId;if(n==null||n==="")throw new Error("loadSlot requires slotId");let r=mt(n),o=e.global.saveSlots[r];if(o){let i=Js(o,e.projectData);e.contexts=i.state.contexts,e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=gt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,ke(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},ic=({state:e},t)=>{let{projectData:n}=t;return Ur(n),e.projectData=n,ke(e),e.global.pendingEffects.push({name:"render"}),e},sc=({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&&!G({state:e},{sectionId:n}))return console.warn(`Section not found: ${n}`),e;let s=G({state:e},{sectionId:i});if(!s?.lines||!Array.isArray(s.lines))return console.warn(`Section ${i} has no lines`),e;if(!s.lines.find(a=>a.id===r))return console.warn(`Line not found: ${r} in section ${i}`),e;let c=Pe(o);return c.read={sectionId:i,lineId:r},yt(e,c.read),e},ac=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return bt({state:e}),e;if(ie({state:e})&&t?._interactionSource!=="choice")return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0;let a=oe({state:e})?.pointer,u=a?.sectionId,f=a?.lineId;u&&f&&We(e,{sectionId:u,lineId:f}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:ae(e,"autoForwardDelay")}});let d=e.global.nextLineConfig;return d?.auto?.enabled&&d.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:d.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e}let n=oe({state:e})?.pointer,r=n?.sectionId,o=G({state:e},{sectionId:r}),i=e.contexts[e.contexts.length-1],s=o?.lines||[],c=s.findIndex(a=>a.id===n?.lineId)+1;if(c<s.length){let a=s[c],u=!ae(e,"skipUnseenText");if(e.global.skipMode&&u&&!In({state:e},{sectionId:r,lineId:a.id}))return Ee({state:e}),e;if(i&&!i.rollback&&ve(i,{compatibilityAnchor:!0}),i){let h=Pe(i),g=h.read?.lineId;g&&r&&We(e,{sectionId:r,lineId:g}),h.read={sectionId:r,lineId:a.id}}bn(e,{sectionId:r,lineId:a.id}),pn(e);let{isChoiceVisible:f}=yt(e,{sectionId:r,lineId:a.id}),d=e.global.nextLineConfig;d?.auto?.enabled&&!f&&d.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:d.auto.delay}})}else e.global.autoMode&&Ye({state:e}),e.global.skipMode&&Ee({state:e});return e},cc=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0;let t=ie({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:ae(e,"autoForwardDelay")}});let n=oe({state:e})?.pointer,r=n?.sectionId,o=n?.lineId;r&&o&&We(e,{sectionId:r,lineId:o});let i=e.global.nextLineConfig;return i?.auto?.enabled&&!t&&i.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:i.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e},lc=({state:e},t)=>lo(e,{sectionId:t?.sectionId}),uc=({state:e})=>{if(e.global.dialogueUIHidden)return bt({state:e}),e;if(ie({state:e}))return e;let t=oe({state:e})?.pointer,n=t?.sectionId,r=G({state:e},{sectionId:n}),o=e.contexts[e.contexts.length-1],i=r?.lines||[],l=i.findIndex(c=>c.id===t?.lineId)+1;if(l<i.length){let c=i[l],a=!ae(e,"skipUnseenText");if(e.global.skipMode&&a&&!In({state:e},{sectionId:n,lineId:c.id}))return Ee({state:e}),e;if(o&&!o.rollback&&ve(o,{compatibilityAnchor:!0}),o){let f=Pe(o),d=f.read?.lineId;d&&n&&We(e,{sectionId:n,lineId:d}),f.read={sectionId:n,lineId:c.id}}bn(e,{sectionId:n,lineId:c.id}),pn(e);let{isChoiceVisible:u}=yt(e,{sectionId:n,lineId:c.id});e.global.nextLineConfig.auto?.enabled&&!u&&e.global.nextLineConfig.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}})}else e.global.nextLineConfig.auto?.enabled&&(e.global.nextLineConfig.auto.enabled=!1,e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}));return e},fc=({state:e},t)=>{let{id:n,operations:r=[]}=t;if(!n)throw new Error("updateVariable requires an id field");if(typeof n!="string"||!/^[a-zA-Z0-9]+$/.test(n))throw new Error(`updateVariable id must be alphanumeric, got: "${n}"`);let o=e.contexts[e.contexts.length-1];if(o?.rollback?.isRestoring)return e;let i=!1,s=[],l=[];return r.forEach(({variableId:c,op:a,value:u})=>{let f=e.projectData.resources?.variables?.[c],d=f?.scope,h=f?.type;zt(d,c),Wt(h,a,c);let g=d==="context"?o.variables:e.global.variables;d==="context"&&(i=!0,l.push({variableId:c,op:a,value:u})),g[c]=Yt(g[c],a,u),(d==="device"||d==="account")&&s.push({scope:d,path:`variables.${c}`,op:"set",value:F(g[c])})}),i&&ce(e,"updateVariable",{id:n,operations:l}),fo(e,s),e.global.pendingEffects.push({name:"render"}),e},dc=e=>(t,n)=>e({state:t},n),pc=e=>({variables:{...e.global?.variables??{},...yn(e)?.variables??{}},runtime:dt(e)}),hc=e=>{if(!j(e))throw new Error("conditional action payload must be an object");if(!Array.isArray(e.branches))throw new Error("conditional action requires branches array");if(e.branches.length===0)throw new Error("conditional action requires at least one branch")},gc=(e,t,n)=>{if(!j(e))throw new Error(`conditional branch at index ${t} must be an object`);if(!j(e.actions))throw new Error(`conditional branch at index ${t} requires actions object`);if(!Object.prototype.hasOwnProperty.call(e,"when")&&t!==n-1)throw new Error("conditional else branch must be the last branch")},mc=(e,t)=>{hc(t);for(let n=0;n<t.branches.length;n+=1){let r=t.branches[n];if(gc(r,n,t.branches.length),!(Object.prototype.hasOwnProperty.call(r,"when")&&!je(r.when,pc(e)))){Object.entries(r.actions).forEach(([i,s])=>{go(e,i,s)});return}}},yc={conditional:{replayLine:mc},updateVariable:{recordSources:[gn],replayLine:Vr,replayRecorded:Vr,persistInSaveSlot:!0},setNextLineConfig:{replayLine:dc(ho)}},It=e=>yc[e]??null,bc=e=>It(e)?.persistInSaveSlot===!0,Ic=(e,t)=>{let n=It(e)?.recordSources;return Array.isArray(n)&&n.includes(t)},Ac=(e,t,n)=>{It(t)?.replayRecorded?.(e,n)},go=(e,t,n)=>{It(t)?.replayLine?.(e,n)},mo=({state:e},t)=>{let{offset:n}=t;if(n===void 0||typeof n!="number")return console.warn("selectLineIdByOffset requires a numeric offset"),null;let r=e.contexts[e.contexts.length-1];if(!r)return null;let o=r.rollback;if(!Array.isArray(o?.timeline)||typeof o?.currentIndex!="number")return null;let i=o.currentIndex+n;if(i<0||i>=o.timeline.length)return null;let s=o.timeline[i];return{sectionId:s.sectionId,lineId:s.lineId}},yo=({state:e})=>mo({state:e},{offset:-1})!==null,wc=({state:e},t)=>{let{offset:n=-1}=t;if(n>=0)throw new Error("rollbackByOffset requires a negative offset");let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let o=ve(r,{compatibilityAnchor:!r.rollback}),i=o.currentIndex+n;return i<0||i>=o.timeline.length?e:Xr(e,i)},xc=({state:e},t)=>{let{sectionId:n,lineId:r}=t,o=e.contexts[e.contexts.length-1];if(!o)throw new Error("No context available for rollbackToLine");let i=ve(o,{compatibilityAnchor:!o.rollback}),l=i.timeline.slice(0,i.currentIndex+1).findLastIndex(c=>c.sectionId===n&&c.lineId===r);if(l===-1)throw new Error(`Line ${r} not found in section ${n} rollback timeline`);return l===i.currentIndex?e:Xr(e,l)},bo=e=>{let t=ua(e);return rr(t,{selectPendingEffects:da,selectSkipMode:Qr,selectAutoMode:pa,selectIsChoiceVisible:ie,selectDialogueUIHidden:Zr,selectDialogueHistory:eo,selectConfirmDialog:ha,selectIsLineAccountViewed:In,selectIsResourceAccountViewed:ya,selectNextLineConfig:ba,selectSystemState:Ia,selectSaveSlotMap:no,selectSaveSlots:Sa,selectSaveSlot:Aa,selectRuntime:An,selectRuntimeValue:wa,selectAllVariables:ro,selectCurrentPointer:oe,selectSection:G,selectCurrentLine:wn,selectPresentationState:oo,selectPresentationChanges:xa,selectSectionLineChanges:va,selectSaveSlotPage:xn,selectCurrentPageSlots:Ca,selectRenderState:Ra,selectOverlayStack:fa,selectLineIdByOffset:mo,selectCanRollback:yo,startAutoMode:so,stopAutoMode:Ye,toggleAutoMode:Da,startSkipMode:ao,stopSkipMode:Ee,toggleSkipMode:Va,showDialogueUI:bt,hideDialogueUI:co,toggleDialogueUI:ja,setDialogueTextSpeed:Ma,setAutoForwardDelay:Ua,setSkipUnseenText:Ba,setSkipTransitionsAndAnimations:Fa,setSoundVolume:za,setMusicVolume:Wa,setMuteAll:Ya,setSaveLoadPagination:qa,incrementSaveLoadPagination:Ha,decrementSaveLoadPagination:Ja,setMenuPage:Ka,setMenuEntryPoint:Ga,showConfirmDialog:La,hideConfirmDialog:$a,resetStoryAtSection:Za,clearPendingEffects:Xa,appendPendingEffect:Qa,beginRollbackActionBatch:sa,endRollbackActionBatch:aa,addViewedLine:tc,addViewedResource:nc,setNextLineConfig:ho,saveSlot:rc,loadSlot:oc,updateProjectData:ic,sectionTransition:lc,jumpToLine:sc,nextLine:ac,markLineCompleted:cc,rollbackToLine:xc,rollbackByOffset:wc,pushOverlay:Oa,popOverlay:ka,replaceLastOverlay:Pa,clearOverlays:Ta,updateVariable:fc,nextLineFromSystem:uc},{transformActionFirstArgument:r=>({state:r}),transformSelectorFirstArgument:r=>({state:r})})};var Ec="route-engine",vc="projectPersistence";var Ao=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),H=e=>Object.prototype.toString.call(e)==="[object Object]",Io="variables.",Sc=(e={})=>{let t=H(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(n=>typeof n=="string"||typeof n=="number"?{sectionId:String(n)}:!H(n)||typeof n.sectionId!="string"||n.sectionId.length===0?null:{sectionId:n.sectionId,...typeof n.lineId=="string"?{lineId:n.lineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(n=>typeof n=="string"||typeof n=="number"?{resourceId:String(n)}:!H(n)||typeof n.resourceId!="string"||n.resourceId.length===0?null:{resourceId:n.resourceId}).filter(Boolean)}},Cc=(e={})=>{let t=H(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(n=>typeof n=="string"||typeof n=="number"?{sectionId:String(n)}:!H(n)||typeof n.sectionId!="string"||n.sectionId.length===0?null:{sectionId:n.sectionId,...typeof n.lastLineId=="string"?{lastLineId:n.lastLineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(n=>typeof n=="string"||typeof n=="number"?{resourceId:String(n)}:!H(n)||typeof n.resourceId!="string"||n.resourceId.length===0?null:{resourceId:n.resourceId}).filter(Boolean)}},_c=(e,t)=>{let n=Cc(e),r=Sc(t),o=n.sections.map(s=>({...s})),i=n.resources.map(s=>({...s}));return r.sections.forEach(s=>{let l=o.find(c=>c.sectionId===s.sectionId);if(!l){o.push({sectionId:s.sectionId,...s.lineId===void 0?{}:{lastLineId:s.lineId}});return}if(l.lastLineId!==void 0){if(s.lineId===void 0){delete l.lastLineId;return}l.lastLineId=s.lineId}}),r.resources.forEach(s=>{i.find(c=>c.resourceId===s.resourceId)||i.push({...s})}),{sections:o,resources:i}},wo=(e={})=>{let t=H(e)?e:{};return{saveSlots:H(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:H(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:H(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:H(t.globalRuntime)?t.globalRuntime:{},accountViewedRegistry:H(t.accountViewedRegistry)?t.accountViewedRegistry:{}}},Rc=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((t,n)=>{if(!H(t))throw new Error(`Malformed applyScopedDataUpdates.updates[${n}] entry.`);let r=t.path?.startsWith(Io)?t.path.slice(Io.length):null;if(r!==null){if(!["device","account"].includes(t.scope))throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${n}].`);if(r.length===0)throw new Error(`Malformed applyScopedDataUpdates path "${t.path}" at updates[${n}].`);if(t.op!=="set")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${n}].`);return{scope:t.scope,path:t.path,op:t.op,value:t.value,variableId:r}}if(t.path==="viewedRegistry"){if(t.scope!=="account")throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${n}].`);if(t.op!=="markViewed")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${n}].`);return t}throw typeof t.path!="string"?new Error(`Malformed applyScopedDataUpdates path at updates[${n}].`):new Error(`Unsupported applyScopedDataUpdates path "${t.path}" at updates[${n}].`)})},Lc=(e,t)=>{let n={};return Rc(t).forEach(r=>{if(r.path==="viewedRegistry"){n.accountViewedRegistry=_c(n.accountViewedRegistry??e.accountViewedRegistry,r.value);return}let o=r.scope==="device"?"globalDeviceVariables":"globalAccountVariables";n[o]={...e[o],...n[o],[r.variableId]:r.value}}),n},En=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},$c=e=>{let t=En(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},Oc=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},kc=({indexedDB:e,databaseName:t,objectStoreName:n})=>new Promise((r,o)=>{let i=e.open(t,1);i.onupgradeneeded=()=>{let s=i.result;s.objectStoreNames.contains(n)||s.createObjectStore(n,{keyPath:"namespace"})},i.onsuccess=()=>{r(i.result)},i.onerror=()=>{o(i.error??new Error(`Failed to open IndexedDB database "${t}".`))}}),Pc=async({databasePromise:e,objectStoreName:t,namespace:n})=>{let r=await e;return new Promise((o,i)=>{let c=r.transaction(t,"readonly").objectStore(t).get(n);c.onsuccess=()=>{o(c.result??null)},c.onerror=()=>{i(c.error??new Error(`Failed to read persisted namespace "${n}" from IndexedDB.`))}})},He=async({databasePromise:e,objectStoreName:t,namespace:n,patch:r})=>{let o=await e;return new Promise((i,s)=>{let l=o.transaction(t,"readwrite"),c=l.objectStore(t),a=c.get(n),u=!1,f=h=>{u||(u=!0,s(h))},d=()=>{u||(u=!0,i())};a.onerror=()=>{f(a.error??new Error(`Failed to read persisted namespace "${n}" before updating IndexedDB.`))},a.onsuccess=()=>{let h=wo(a.result),g=typeof r=="function"?r(h):r,y={namespace:n,version:1,...Ao(),...h,...g},I=c.put(y);I.onerror=()=>{f(I.error??new Error(`Failed to persist namespace "${n}" to IndexedDB.`))}},l.oncomplete=()=>{d()},l.onerror=()=>{f(l.error??new Error(`IndexedDB transaction failed while updating namespace "${n}".`))},l.onabort=()=>{f(l.error??new Error(`IndexedDB transaction aborted while updating namespace "${n}".`))}})},Tc=async({databasePromise:e,objectStoreName:t,namespace:n})=>{let r=await e;return new Promise((o,i)=>{let s=r.transaction(t,"readwrite"),c=s.objectStore(t).delete(n),a=!1,u=d=>{a||(a=!0,i(d))},f=()=>{a||(a=!0,o())};c.onerror=()=>{u(c.error??new Error(`Failed to clear persisted namespace "${n}" from IndexedDB.`))},s.oncomplete=()=>{f()},s.onerror=()=>{u(s.error??new Error(`IndexedDB transaction failed while clearing namespace "${n}".`))},s.onabort=()=>{u(s.error??new Error(`IndexedDB transaction aborted while clearing namespace "${n}".`))}})},vn=(e={})=>{let{indexedDB:t,databaseName:n=Ec,objectStoreName:r=vc,namespace:o}=e,i=Oc(t),s=$c(o),l=kc({indexedDB:i,databaseName:n,objectStoreName:r});return{namespace:s,load:async()=>{let c=await Pc({databasePromise:l,objectStoreName:r,namespace:s});return{...Ao(),...wo(c)}},clear:async()=>Tc({databasePromise:l,objectStoreName:r,namespace:s}),saveSlots:async c=>He({databasePromise:l,objectStoreName:r,namespace:s,patch:{saveSlots:H(c)?c:{}}}),saveGlobalDeviceVariables:async c=>He({databasePromise:l,objectStoreName:r,namespace:s,patch:{globalDeviceVariables:H(c)?c:{}}}),saveGlobalAccountVariables:async c=>He({databasePromise:l,objectStoreName:r,namespace:s,patch:{globalAccountVariables:H(c)?c:{}}}),saveGlobalRuntime:async c=>He({databasePromise:l,objectStoreName:r,namespace:s,patch:{globalRuntime:H(c)?c:{}}}),applyScopedDataUpdates:async c=>He({databasePromise:l,objectStoreName:r,namespace:s,patch:a=>Lc(a,c)})}},Nc=vn;var Dc=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),Vc=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),xo="conditional",Eo="choice",At=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function Sn(e){let t,n=0,r=null,o=new Map,i=new Map,s=new Map,{handlePendingEffects:l}=e,c=(A=new Map,v=Date.now())=>new Map(Array.from(A.entries()).filter(([,T])=>v<T.expiresAt).map(([T,V])=>[T,{animation:structuredClone(V.animation),startedAt:V.startedAt,expiresAt:V.expiresAt}])),a=(A=new Map)=>Array.from(A.values()).map(v=>structuredClone(v.animation)),u=(A=Date.now())=>{o=new Map(Array.from(o.entries()).filter(([,v])=>A<v.expiresAt))},f=()=>{for(;t.selectPendingEffects().length>0;){let A=[...t.selectPendingEffects()];t.clearPendingEffects();try{l(A)}catch(v){throw t.clearPendingEffects(),A.forEach(T=>{t.appendPendingEffect(T)}),v}}},d=({initialState:A,namespace:v})=>{t=bo(A),n=0,r=En(v),o=new Map,i=new Map,s=new Map,t.appendPendingEffect({name:"handleLineActions"}),f()},h=()=>r,g=()=>t.selectPresentationState(),y=()=>t.selectPresentationChanges(),I=A=>t.selectSectionLineChanges(A),b=(A={})=>{n+=1;let v=Date.now();u(v);let T=i.size>0,V=c(o,v),q=T?c(i,v):new Map,le={...t.selectRenderState({activePersistentAnimations:a(V),restoredPersistentAnimations:a(q)}),id:`render-${n}`};return s.set(le.id,{builtAt:v,persistentAnimationSessions:new Map([...q.entries(),...V.entries()]),usedRestoredPersistentAnimationSessions:T}),le},m=(A={})=>b(A),E=(A={})=>b(A),S=A=>{let v=typeof A?.id=="string"&&A.id.length>0?A.id:null,T=v?s.get(v):null;v&&s.delete(v);let V=new Map;wr(A?.animations).forEach(q=>{let te=lt(q);if(!te)return;let le=T?.persistentAnimationSessions?.get(te)??o.get(te),_o=Math.max(0,Er(q)),$n=le?.startedAt??T?.builtAt??Date.now();V.set(te,{animation:structuredClone(q),startedAt:$n,expiresAt:$n+_o})}),o=V,T?.usedRestoredPersistentAnimationSessions&&(i=new Map)},$=()=>t.selectSystemState(),O=()=>t.selectSaveSlotMap(),_=A=>t.selectSaveSlot(A),D=A=>t.selectSaveSlotPage(A),N=()=>t.selectSkipMode(),k=()=>t.selectAutoMode(),P=()=>t.selectRuntime(),x=()=>t.selectIsChoiceVisible(),C=(A,v,T={})=>T.interactionSource!==Eo||A!=="nextLine"||!At(v)?v:{...v,_interactionSource:Eo},M=(A,v)=>{t[A]&&(Dc.has(A)&&(Vc.has(A)?i=c(o):i=new Map,o=new Map),t[A](v),f())},z=(A,v,T,V={})=>{if(A===xo){let q=U(T),te=Jt({[A]:v},q);_n(te[A],T,V);return}M(A,v)},Y=(A,v)=>{z(A,v)},U=A=>{if(!A)return{variables:t.selectAllVariables?t.selectAllVariables():void 0,runtime:t.selectRuntime?t.selectRuntime():{}};if(Object.prototype.hasOwnProperty.call(A,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:v,...T}=A,V=t.selectAllVariables?t.selectAllVariables():void 0;return{...T,_event:v,variables:V,runtime:t.selectRuntime?t.selectRuntime():{}}},Je=A=>{if(!At(A))throw new Error("conditional action payload must be an object");if(!Array.isArray(A.branches))throw new Error("conditional action requires branches array");if(A.branches.length===0)throw new Error("conditional action requires at least one branch")},Ke=(A,v,T)=>{if(!At(A))throw new Error(`conditional branch at index ${v} must be an object`);if(!At(A.actions))throw new Error(`conditional branch at index ${v} requires actions object`);if(!Object.prototype.hasOwnProperty.call(A,"when")&&v!==T-1)throw new Error("conditional else branch must be the last branch")},_n=(A,v,T)=>{Je(A);for(let V=0;V<A.branches.length;V+=1){let q=A.branches[V];Ke(q,V,A.branches.length);let te=U(v);if(!(Object.prototype.hasOwnProperty.call(q,"when")&&!je(q.when,te))){Rn(q.actions,v,T);return}}},Co=(A,v,T,V)=>{let q=U(T),le=Jt({[A]:v},q)[A];if(A===xo){_n(le,T,V);return}M(A,C(A,le,V))},Rn=(A,v,T)=>{Object.entries(A).forEach(([V,q])=>{Co(V,q,v,T)})},Ln=(A,v,T={})=>{t.beginRollbackActionBatch({source:T.rollbackSource});try{Rn(A,v,T)}finally{t.endRollbackActionBatch({})}};return{init:d,handleAction:z,handleInternalAction:Y,handleActions:Ln,selectRenderState:m,prepareRenderState:E,commitRenderState:S,selectPresentationState:g,selectPresentationChanges:y,selectSectionLineChanges:I,selectSystemState:$,selectSaveSlotMap:O,selectSaveSlot:_,selectSaveSlotPage:D,selectSaveSlots:O,selectRuntime:P,selectIsChoiceVisible:x,handleLineActions:()=>{let A=t.selectCurrentLine();return A?.actions?(Ln(A.actions,void 0,{rollbackSource:"line"}),!0):!1},getNamespace:h}}var Cn=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:n=>{e=n},addElapsed:n=>{e+=n},getCallback:()=>t,setCallback:n=>{t=n}}},jc=80,So=({engine:e,routeGraphics:t,trackRenderDispatch:n},r)=>{let o=e.prepareRenderState?.(r)??e.selectRenderState(r);n?.(o),t.render(o),e.commitRenderState?.(o)},Mc=({engine:e,routeGraphics:t,trackRenderDispatch:n,getRenderDispatchCount:r},o)=>{let i=r?.()??0,s=e.handleLineActions();(r?.()??0)===i&&So({engine:e,routeGraphics:t,trackRenderDispatch:n},o)},Uc=({engine:e,ticker:t,autoTimer:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let l=r.delay??1e3;n.getElapsed()>=l&&(t.remove(i),n.setCallback(null),n.setElapsed(0),wt(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},Bc=({ticker:e,autoTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Fc=({engine:e,ticker:t,skipTimer:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let l=r?.delay??jc;n.getElapsed()>=l&&(n.setElapsed(0),wt(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},zc=({ticker:e,skipTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Wc=({engine:e,ticker:t,nextLineConfigTimerState:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let l=r.delay??1e3;n.getElapsed()>=l&&(n.setElapsed(0),wt(e,"nextLineFromSystem",{}),t.remove(i),n.setCallback(null))};n.setCallback(i),t.add(i)},Yc=({ticker:e,nextLineConfigTimerState:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},qc=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveSlots(t?.saveSlots))},Hc=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalDeviceVariables(t?.globalDeviceVariables))},Jc=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalAccountVariables(t?.globalAccountVariables))},Kc=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalRuntime(t?.globalRuntime))},Gc=({enqueuePersistenceWrite:e},t)=>{e(n=>{if(typeof n.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return n.applyScopedDataUpdates(t?.updates)})},vo={render:So,saveSlots:qc,saveGlobalDeviceVariables:Hc,saveGlobalAccountVariables:Jc,saveGlobalRuntime:Kc,applyScopedDataUpdates:Gc,handleLineActions:Mc,startAutoNextTimer:Uc,clearAutoNextTimer:Bc,startSkipNextTimer:Fc,clearSkipNextTimer:zc,nextLineConfigTimer:Wc,clearNextLineConfigTimer:Yc},Xc=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),wt=(e,t,n)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,n)},Qc=(e=[])=>{let t=new Set,n=[];for(let r=e.length-1;r>=0;r-=1){let o=e[r];if(typeof o?.name!="string"||o.name.length===0)throw new Error("Pending effect is missing a valid name.");if(!Xc.has(o.name)){n.unshift(o);continue}t.has(o.name)||(t.add(o.name),n.unshift(o))}return n},Zc=({getEngine:e,routeGraphics:t,ticker:n,handleUnhandledEffect:r,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:l})=>{let c=Cn(),a=Cn(),u=Cn(),f=s??null,d=Promise.resolve(),h=null,g=null,y=!1,I=0,b=x=>{if(o){o(x);return}console.error("RouteEngine persistence write failed.",x)},m=()=>{if(f)return f;let x=e();return f=vn({indexedDB:i,namespace:l??x?.getNamespace?.()}),f},E=x=>{d=d.catch(()=>{}).then(()=>{let C=m();return x(C)}).catch(C=>{b(C)})},S=x=>{let C=typeof x?.id=="string"&&x.id.length>0?x.id:null;I+=1,h=C,y=!1},$=()=>I,O=(x={})=>{if(x?.aborted===!0)return!1;let C=typeof x?.id=="string"&&x.id.length>0?x.id:null;return C?C!==h||C===g?!1:(g=C,!0):h!==null||y?!1:(y=!0,!0)},_=(x,C={})=>{if(x!=="renderComplete"||!O(C))return!1;let M=e();return wt(M,"markLineCompleted",{}),!0},D=(x={})=>{if(x?._interactionSource==="choice")return!0;let C=x?.actions;return!C||typeof C!="object"||Array.isArray(C)?!1:Object.values(C).some(M=>M?._interactionSource==="choice")},N=(x,C={})=>!C?.actions||typeof x?.selectIsChoiceVisible!="function"||!x.selectIsChoiceVisible()?!1:!D(C),k=({preprocessPayload:x,onEvent:C}={})=>async(M,z={})=>{let Y=e();if(N(Y,z))return C?.(M,z);let U=await x?.(M,z)??z;if(N(Y,U))return C?.(M,U);if(_(M,U),U?.actions){let Je=U?._event?{_event:U._event}:U?.event?{_event:U.event}:void 0,Ke=U?._interactionSource?{interactionSource:U._interactionSource}:void 0;Ke?Y.handleActions(U.actions,Je,Ke):Y.handleActions(U.actions,Je)}return C?.(M,U)},P=x=>{let C=e(),M=Qc(x);M.forEach(Y=>{if(!vo[Y.name]&&!r)throw new Error(`Unhandled pending effect "${Y.name}".`)});let z={engine:C,routeGraphics:t,ticker:n,autoTimer:c,skipTimer:a,nextLineConfigTimerState:u,trackRenderDispatch:S,getRenderDispatchCount:$,enqueuePersistenceWrite:E};for(let Y of M){let U=vo[Y.name];if(U){U(z,Y.payload);continue}r(Y,z)}};return P.handleRouteGraphicsEvent=_,P.createRouteGraphicsEventHandler=k,P},el=Zc;var tl=(e,t={})=>{let{resources:n={}}=t;return un(e,n)};var yu=Sn;export{el as createEffectsHandler,Nc as createIndexedDbPersistence,yu as default,tl as resolveLayoutReferences};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "route-engine-js",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.11.0",
|
|
4
4
|
"description": "A lightweight Visual Novel engine built in JavaScript for creating interactive narrative games with branching storylines",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -58,7 +58,7 @@
|
|
|
58
58
|
"ajv": "^8.18.0",
|
|
59
59
|
"husky": "^9.1.7",
|
|
60
60
|
"prettier": "^3.7.4",
|
|
61
|
-
"route-graphics": "1.
|
|
61
|
+
"route-graphics": "1.12.3",
|
|
62
62
|
"vitest": "^4.0.16"
|
|
63
63
|
}
|
|
64
64
|
}
|