route-engine-js 1.28.0 → 1.29.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- var ms=Object.defineProperty;var gs=(e,t)=>{for(var r in t)ms(e,r,{get:t[r],enumerable:!0})};var Nn=Symbol.for("immer-nothing"),$n=Symbol.for("immer-draftable"),fe=Symbol.for("immer-state");function Ie(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var Ze=Object.getPrototypeOf;function de(e){return!!e&&!!e[fe]}function Ue(e){return e?Vn(e)||Array.isArray(e)||!!e[$n]||!!e.constructor?.[$n]||kt(e)||Tt(e):!1}var ys=Object.prototype.constructor.toString();function Vn(e){if(!e||typeof e!="object")return!1;let t=Ze(e);if(t===null)return!0;let r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return r===Object?!0:typeof r=="function"&&Function.toString.call(r)===ys}function Rt(e,t){$t(e)===0?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,n)=>t(n,r,e))}function $t(e){let t=e[fe];return t?t.type_:Array.isArray(e)?1:kt(e)?2:Tt(e)?3:0}function gr(e,t){return $t(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function jn(e,t,r){let n=$t(e);n===2?e.set(t,r):n===3?e.add(r):e[t]=r}function bs(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function kt(e){return e instanceof Map}function Tt(e){return e instanceof Set}function Me(e){return e.copy_||e.base_}function yr(e,t){if(kt(e))return new Map(e);if(Tt(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=Vn(e);if(t===!0||t==="class_only"&&!r){let n=Object.getOwnPropertyDescriptors(e);delete n[fe];let o=Reflect.ownKeys(n);for(let i=0;i<o.length;i++){let s=o[i],c=n[s];c.writable===!1&&(c.writable=!0,c.configurable=!0),(c.get||c.set)&&(n[s]={configurable:!0,writable:!0,enumerable:c.enumerable,value:e[s]})}return Object.create(Ze(e),n)}else{let n=Ze(e);if(n!==null&&r)return{...e};let o=Object.create(n);return Object.assign(o,e)}}function Er(e,t=!1){return Dt(e)||de(e)||!Ue(e)||($t(e)>1&&(e.set=e.add=e.clear=e.delete=Is),Object.freeze(e),t&&Object.entries(e).forEach(([r,n])=>Er(n,!0))),e}function Is(){Ie(2)}function Dt(e){return Object.isFrozen(e)}var As={};function Be(e){let t=As[e];return t||Ie(0,e),t}var lt;function Fn(){return lt}function ws(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function kn(e,t){t&&(Be("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function br(e){Ir(e),e.drafts_.forEach(Es),e.drafts_=null}function Ir(e){e===lt&&(lt=e.parent_)}function Tn(e){return lt=ws(lt,e)}function Es(e){let t=e[fe];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function Dn(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[fe].modified_&&(br(t),Ie(4)),Ue(e)&&(e=Ot(t,e),t.parent_||Lt(t,e)),t.patches_&&Be("Patches").generateReplacementPatches_(r[fe].base_,e,t.patches_,t.inversePatches_)):e=Ot(t,r,[]),br(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Nn?e:void 0}function Ot(e,t,r){if(Dt(t))return t;let n=t[fe];if(!n)return Rt(t,(o,i)=>Pn(e,n,t,o,i,r)),t;if(n.scope_!==e)return t;if(!n.modified_)return Lt(e,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;let o=n.copy_,i=o,s=!1;n.type_===3&&(i=new Set(o),o.clear(),s=!0),Rt(i,(c,a)=>Pn(e,n,o,c,a,r,s)),Lt(e,o,!1),r&&e.patches_&&Be("Patches").generatePatches_(n,r,e.patches_,e.inversePatches_)}return n.copy_}function Pn(e,t,r,n,o,i,s){if(de(o)){let c=i&&t&&t.type_!==3&&!gr(t.assigned_,n)?i.concat(n):void 0,a=Ot(e,o,c);if(jn(r,n,a),de(a))e.canAutoFreeze_=!1;else return}else s&&r.add(o);if(Ue(o)&&!Dt(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Ot(e,o),(!t||!t.scope_.parent_)&&typeof n!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,n)&&Lt(e,o)}}function Lt(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&Er(t,r)}function xs(e,t){let r=Array.isArray(e),n={type_:r?1:0,scope_:t?t.scope_:Fn(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=n,i=xr;r&&(o=[n],i=ut);let{revoke:s,proxy:c}=Proxy.revocable(o,i);return n.draft_=c,n.revoke_=s,c}var xr={get(e,t){if(t===fe)return e;let r=Me(e);if(!gr(r,t))return vs(e,r,t);let n=r[t];return e.finalized_||!Ue(n)?n:n===hr(e.base_,t)?(mr(e),e.copy_[t]=wr(n,e)):n},has(e,t){return t in Me(e)},ownKeys(e){return Reflect.ownKeys(Me(e))},set(e,t,r){let n=Mn(Me(e),t);if(n?.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){let o=hr(Me(e),t),i=o?.[fe];if(i&&i.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(bs(r,o)&&(r!==void 0||gr(e.base_,t)))return!0;mr(e),Ar(e)}return e.copy_[t]===r&&(r!==void 0||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_[t]=!0),!0},deleteProperty(e,t){return hr(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,mr(e),Ar(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=Me(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:n.enumerable,value:r[t]}},defineProperty(){Ie(11)},getPrototypeOf(e){return Ze(e.base_)},setPrototypeOf(){Ie(12)}},ut={};Rt(xr,(e,t)=>{ut[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});ut.deleteProperty=function(e,t){return ut.set.call(this,e,t,void 0)};ut.set=function(e,t,r){return xr.set.call(this,e[0],t,r,e[0])};function hr(e,t){let r=e[fe];return(r?Me(r):e)[t]}function vs(e,t,r){let n=Mn(t,r);return n?"value"in n?n.value:n.get?.call(e.draft_):void 0}function Mn(e,t){if(!(t in e))return;let r=Ze(e);for(;r;){let n=Object.getOwnPropertyDescriptor(r,t);if(n)return n;r=Ze(r)}}function Ar(e){e.modified_||(e.modified_=!0,e.parent_&&Ar(e.parent_))}function mr(e){e.copy_||(e.copy_=yr(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Cs=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,r,n)=>{if(typeof t=="function"&&typeof r!="function"){let i=r;r=t;let s=this;return function(a=i,...l){return s.produce(a,f=>r.call(this,f,...l))}}typeof r!="function"&&Ie(6),n!==void 0&&typeof n!="function"&&Ie(7);let o;if(Ue(t)){let i=Tn(this),s=wr(t,void 0),c=!0;try{o=r(s),c=!1}finally{c?br(i):Ir(i)}return kn(i,n),Dn(o,i)}else if(!t||typeof t!="object"){if(o=r(t),o===void 0&&(o=t),o===Nn&&(o=void 0),this.autoFreeze_&&Er(o,!0),n){let i=[],s=[];Be("Patches").generateReplacementPatches_(t,o,i,s),n(i,s)}return o}else Ie(1,t)},this.produceWithPatches=(t,r)=>{if(typeof t=="function")return(s,...c)=>this.produceWithPatches(s,a=>t(a,...c));let n,o;return[this.produce(t,r,(s,c)=>{n=s,o=c}),n,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){Ue(e)||Ie(8),de(e)&&(e=ze(e));let t=Tn(this),r=wr(e,void 0);return r[fe].isManual_=!0,Ir(t),r}finishDraft(e,t){let r=e&&e[fe];(!r||!r.isManual_)&&Ie(9);let{scope_:n}=r;return kn(n,t),Dn(void 0,n)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){let o=t[r];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}r>-1&&(t=t.slice(r+1));let n=Be("Patches").applyPatches_;return de(e)?n(e,t):this.produce(e,o=>n(o,t))}};function wr(e,t){let r=kt(e)?Be("MapSet").proxyMap_(e,t):Tt(e)?Be("MapSet").proxySet_(e,t):xs(e,t);return(t?t.scope_:Fn()).drafts_.push(r),r}function ze(e){return de(e)||Ie(10,e),Un(e)}function Un(e){if(!Ue(e)||Dt(e))return e;let t=e[fe],r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=yr(e,t.scope_.immer_.useStrictShallowCopy_)}else r=yr(e,!0);return Rt(r,(n,o)=>{jn(r,n,Un(o))}),t&&(t.finalized_=!1),r}var pe=new Cs,vr=pe.produce,pd=pe.produceWithPatches.bind(pe),hd=pe.setAutoFreeze.bind(pe),md=pe.setUseStrictShallowCopy.bind(pe),gd=pe.applyPatches.bind(pe),yd=pe.createDraft.bind(pe),bd=pe.finishDraft.bind(pe);var m={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},O={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},et={NOT:0};var E=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},ue=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var Cr=e=>{if(!e||e.trim()==="")throw new E("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let r=e.includes("===")?"==":"!=";throw new E(`Invalid comparison operator '${e.includes("===")?"===":"!=="}' - did you mean '${r}'? (got: '${e}')`)}let t=["<",">","<=",">=","==","!="];for(let r of t)if(e.trim().endsWith(r))throw new E(`Incomplete comparison expression - missing right operand (got: '${e}')`)},Bn=e=>{if(e.trim().endsWith(" in"))throw new E(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new E(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,r]=e.split(" in ");if(!r||r.trim()==="")throw new E(`Missing iterable expression after 'in' (got: '$for ${e}')`);let n=t.includes(",")?t.split(",").map(o=>o.trim()):[t.trim()];for(let o of n){if(!o)throw new E(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new E(`Invalid loop syntax (got: '$for ${e}')`)}};var zn=(e,t,r=!1)=>{if(t===null)return new ue(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new ue(`Cannot iterate over undefined value at '$for ${e}'`);let n=typeof t;return r?new ue(`Cannot iterate over non-array value in loop '${e}' - got ${n} instead`):new ue(`Cannot iterate over non-array value (got: ${n}) at '$for ${e}'`)},qn=(e,t)=>{let r=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new ue(`Unknown function '${e}' (${r})`)};var Ss=(e,t,r={})=>{let n={},o={};r&&typeof r=="object"&&(r.functions!==void 0||r.partials!==void 0?(n=r.functions||{},o=r.partials||{}):typeof r=="object"&&(n=r));let s=L(e,{functions:n,partials:o},t,{});return s===void 0?{}:s},L=(e,t,r,n)=>{let o=t.functions||t;if(e.var&&!e.type)return H(e.var,r,n);if(e.type===m.LITERAL)return e.value;if(e.type===m.VARIABLE)return H(e.path,r,n);if(e.type===m.INTERPOLATION)return Rs(e.parts,t,r,n);switch(e.type){case m.FUNCTION:return Hn(e,t,r,n);case m.BINARY:return Yn(e,t,r,n);case m.UNARY:return Gn(e,t,r,n);case m.CONDITIONAL:return Ls(e,t,r,n);case m.LOOP:return Ps(e,t,r,n);case m.OBJECT:return Vs(e,t,r,n);case m.ARRAY:return js(e,t,r,n);case m.PARTIAL:return Fs(e,t,r,n);case m.PATH_REFERENCE:return Ms(e,t,r,n);default:throw new Error(`Unknown node type: ${e.type}`)}},Wn=new Map,_s=e=>{let t=[],r="",n=!1;for(let o=0;o<e.length;o++){let i=e[o];if(i==="[")r&&(t.push({type:"property",value:r}),r=""),n=!0;else if(i==="]"){if(n&&r){let s=r.trim();if(/^\d+$/.test(s))t.push({type:"index",value:parseInt(s,10)});else if(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'")){let c=s.slice(1,-1);t.push({type:"property",value:c})}else t.push({type:"property",value:s});r=""}n=!1}else r+=i}return r&&t.push({type:"property",value:r}),t},H=(e,t,r)=>{if(!e)return;if(e in r)return r[e];let n=Wn.get(e);if(!n){let i=[],s="",c=0;for(let a=0;a<e.length;a++){let l=e[a];l==="["?(c++,s+=l):l==="]"?(c--,s+=l):l==="."&&c===0?s&&(i.push(s),s=""):s+=l}s&&i.push(s),n=[];for(let a of i){let l=_s(a.trim());n.push(...l)}Wn.set(e,n)}let o=t;for(let i=0;i<n.length;i++){let s=n[i];if(s.type==="property"&&s.value in r){o=r[s.value];continue}if(o==null)return;(s.type==="property"||s.type==="index")&&(o=o[s.value])}return o},Rs=(e,t,r,n)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=L(i,t,r,n);o.push(s!=null?String(s):"")}return o.join("")},Hn=(e,t,r,n)=>{let o=t.functions||t,i=o[e.name];if(!i)throw qn(e.name,o);let s=e.args.map(c=>L(c,t,r,n));return i(...s)},$e=(e,t,r,n)=>{if(e.var&&!e.type)return H(e.var,r,n);switch(e.type){case m.VARIABLE:return H(e.path,r,n);case m.LITERAL:return e.value;case m.BINARY:return Yn(e,t,r,n);case m.UNARY:return Gn(e,t,r,n);case m.FUNCTION:return Hn(e,t,r,n);default:return L(e,t,r,n)}},Yn=(e,t,r,n)=>{if(e.op===O.AND||e.op===O.OR){let s=$e(e.left,t,r,n),c=$e(e.right,t,r,n);switch(e.op){case O.AND:return s&&c;case O.OR:return s||c}}let o=L(e.left,t,r,n),i=L(e.right,t,r,n);switch(e.op){case O.EQ:return o==i;case O.NEQ:return o!=i;case O.GT:return o>i;case O.LT:return o<i;case O.GTE:return o>=i;case O.LTE:return o<=i;case O.IN:return Array.isArray(i)?i.includes(o):!1;case O.ADD:if(typeof o!="number"||typeof i!="number")throw new ue(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case O.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new ue(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},Gn=(e,t,r,n)=>{let o=e.op===et.NOT?$e(e.operand,t,r,n):L(e.operand,t,r,n);if(e.op===et.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},Os=(e,t,r,n)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===m.VARIABLE)if(H(o.path,r,n)){let s=e.bodies[0];if(s.type===m.OBJECT&&s.properties.length<=5){let c={};for(let a of s.properties){let l=a.parsedKey?L(a.parsedKey,t,r,n):a.key,f=a.value;if(f.type===m.LITERAL)c[l]=f.value;else if(f.type===m.VARIABLE)c[l]=H(f.path,r,n);else if(f.type===m.INTERPOLATION){let u=[];for(let d of f.parts)if(typeof d=="string")u.push(d);else if(d.type===m.VARIABLE){let p=H(d.path,r,n);u.push(p!=null?String(p):"")}else{let p=L(d,t,r,n);u.push(p!=null?String(p):"")}c[l]=u.join("")}else c[l]=L(f,t,r,n)}return c}}else{let s=e.bodies[1];if(s.type===m.OBJECT&&s.properties.length<=5){let c={};for(let a of s.properties){let l=a.parsedKey?L(a.parsedKey,t,r,n):a.key,f=a.value;if(f.type===m.LITERAL)c[l]=f.value;else if(f.type===m.VARIABLE)c[l]=H(f.path,r,n);else if(f.type===m.INTERPOLATION){let u=[];for(let d of f.parts)if(typeof d=="string")u.push(d);else if(d.type===m.VARIABLE){let p=H(d.path,r,n);u.push(p!=null?String(p):"")}else{let p=L(d,t,r,n);u.push(p!=null?String(p):"")}c[l]=u.join("")}else c[l]=L(f,t,r,n)}return c}}}return null},Ls=(e,t,r,n)=>{let o=Os(e,t,r,n);if(o!==null)return o;for(let i=0;i<e.conditions.length;i++){let s=e.conditions[i];if(s===null||$e(s,t,r,n))return L(e.bodies[i],t,r,n)}return Kn},$s=(e,t)=>{let r=e.body,n=e.itemVar;if(r.type===m.CONDITIONAL&&r.conditions.length===1&&r.conditions[0].type===m.VARIABLE){let o=r.conditions[0].path,i=r.bodies[0];if(o.startsWith(n+".")){let s=o.substring(n.length+1);if(i.type===m.OBJECT&&i.properties.length<=5){for(let a of i.properties)if(a.parsedKey)return null;let c=[];for(let a=0;a<t.length;a++){let l=t[a];if(l[s]){let f={};for(let u of i.properties){let d=u.key,p=u.value;if(p.type===m.LITERAL)f[d]=p.value;else if(p.type===m.VARIABLE){let h=p.path;if(h===n)f[d]=l;else if(h.startsWith(n+".")){let g=h.substring(n.length+1);f[d]=l[g]}else return null}else if(p.type===m.INTERPOLATION){let h=[],g=!0;for(let y of p.parts)if(typeof y=="string")h.push(y);else if(y.type===m.VARIABLE){let b=y.path;if(b===n)h.push(l!=null?String(l):"");else if(b.startsWith(n+".")){let A=b.substring(n.length+1),x=l[A];h.push(x!=null?String(x):"")}else{g=!1;break}}else{g=!1;break}if(!g)return null;f[d]=h.join("")}else return null}c.push(f)}}return c}}}return null},ks=(e,t)=>{let r=e.body,n=e.itemVar,o=$s(e,t);if(o!==null)return o;if(r.type===m.OBJECT&&r.properties.length<=5&&!r.whenCondition){for(let c of r.properties)if(c.parsedKey)return null;let i=[],s=!0;for(let c of r.properties){let a=c.key,l=c.value;if(l.type===m.LITERAL)i.push({key:a,type:"literal",value:l.value});else if(l.type===m.VARIABLE){let f=l.path;if(f===n)i.push({key:a,type:"item"});else if(f.startsWith(n+".")){let u=f.substring(n.length+1);if(!u.includes(".")&&!u.includes("["))i.push({key:a,type:"prop",prop:u});else{s=!1;break}}else{s=!1;break}}else if(l.type===m.INTERPOLATION&&l.parts.length===1){let f=l.parts[0];if(f.type===m.VARIABLE){let u=f.path;if(u===n)i.push({key:a,type:"item_string"});else if(u.startsWith(n+".")){let d=u.substring(n.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:a,type:"prop_string",prop:d});else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}if(s){let c=new Array(t.length);if(i.length===3&&i[0].type==="prop"&&i[0].key==="id"&&i[1].type==="prop_string"&&i[1].key==="title"&&i[2].type==="prop"&&i[2].key==="completed")for(let a=0;a<t.length;a++){let l=t[a];c[a]={id:l.id,title:l.title!=null?String(l.title):"",completed:l.completed}}else for(let a=0;a<t.length;a++){let l=t[a],f={};for(let u of i)if(u.type==="literal")f[u.key]=u.value;else if(u.type==="item")f[u.key]=l;else if(u.type==="prop")f[u.key]=l[u.prop];else if(u.type==="item_string")f[u.key]=l!=null?String(l):"";else if(u.type==="prop_string"){let d=l[u.prop];f[u.key]=d!=null?String(d):""}c[a]=f}return c}}return null},Ts=(e,t,r,n,o)=>{let i=[],s=e.body;if(s.type===m.OBJECT&&s.fast!==!1){let c=e.itemVar,a=e.indexVar;for(let l=0;l<o.length;l++){let f=o[l],u={},d={...n,[c]:f,...a&&{[a]:l}};d.__paths__||(d.__paths__=n.__paths__||{});let p=e.iterable.path||"";if(n&&n.__paths__&&p){let h=p.split("."),g=h[0];g in n.__paths__&&(p=n.__paths__[g],h.length>1&&(p+="."+h.slice(1).join(".")))}d.__paths__={...d.__paths__,[c]:`${p}[${l}]`,...a&&{[a]:l}};for(let h of s.properties){let g=h.parsedKey?L(h.parsedKey,t,r,d):h.key,y=h.value;if(y.type===m.LITERAL)u[g]=y.value;else if(y.type===m.VARIABLE){let b=y.path;if(b===c)u[g]=f;else if(b===a)u[g]=l;else if(b.startsWith(c+".")){let A=b.substring(c.length+1);!A.includes(".")&&!A.includes("[")?u[g]=f[A]:u[g]=H(b,r,{...n,[c]:f,...a&&{[a]:l}})}else u[g]=H(b,r,{...n,[c]:f,...a&&{[a]:l}})}else if(y.type===m.INTERPOLATION){let b=[];for(let A of y.parts)if(typeof A=="string")b.push(A);else if(A.type===m.VARIABLE){let x=A.path,S;if(x===c)S=f;else if(x===a)S=l;else if(x.startsWith(c+".")){let P=x.substring(c.length+1);!P.includes(".")&&!P.includes("[")?S=f[P]:S=H(x,r,{...n,[c]:f,...a&&{[a]:l}})}else S=H(x,r,{...n,[c]:f,...a&&{[a]:l}});b.push(S!=null?String(S):"")}else{let x={...n,[c]:f,...a&&{[a]:l}},S=L(A,t,r,x);b.push(S!=null?String(S):"")}u[g]=b.join("")}else{let b={...n,[c]:f,...a&&{[a]:l}};u[g]=L(y,t,r,b)}}i.push(u)}return i}return null},Ds=(e,t,r)=>{let n=e.body;if(n.type===m.OBJECT&&n.properties.length===1&&n.properties[0].key==="$if item.visible"){let i=n.properties[0].value;if(i.type===m.CONDITIONAL&&i.conditions.length===1&&i.conditions[0].type===m.VARIABLE&&i.conditions[0].path==="item.visible"){let s=i.bodies[0];if(s.type===m.OBJECT&&s.properties.length===2){let c=s.properties[0],a=s.properties[1];if(c.key==="id"&&c.value.type===m.VARIABLE&&c.value.path==="item.id"&&a.key==="$if item.highlighted"&&a.value.type===m.CONDITIONAL){let l=[];for(let f=0;f<t.length;f++){let u=t[f];if(u.visible){let d={id:u.id};u.highlighted?(d.highlight=!0,d.message=`This item is highlighted: ${u.name}`):(d.highlight=!1,d.message=u.name),l.push(d)}}return l}}}}return null},Ps=(e,t,r,n)=>{let o=L(e.iterable,t,r,n);if(!Array.isArray(o)){let l,f=!1;if(e.iterable.type===m.FUNCTION){f=!0;let d=e.iterable.args.map(p=>p.type===m.LITERAL?typeof p.value=="string"?`'${p.value}'`:String(p.value):p.type===m.VARIABLE?p.path:p.type===m.FUNCTION?`${p.name}(...)`:"?").join(", ");l=`${e.iterable.name}(${d})`}else l=e.iterable.path||"undefined";let u=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${l}`;throw zn(u,o,f)}if(!e.indexVar){let l=Ds(e,o,e.itemVar);if(l!==null)return l}if(!e.indexVar){let l=ks(e,o);if(l!==null)return l}let i=Ts(e,t,r,n,o);if(i!==null)return i;let s=[],c=e.iterable.path||"";if(n&&n.__paths__&&c){let l=c.split("."),f=l[0];f in n.__paths__&&(c=n.__paths__[f],l.length>1&&(c+="."+l.slice(1).join(".")))}let a=!1;e.body.type===m.ARRAY&&(e.body.items.length<=1?a=!1:a=e.body._shouldPreserveArray??=e.body.items.some(l=>l.type===m.OBJECT&&l.properties.some(f=>f.key.startsWith("$if ")||f.key.startsWith("$when "))));for(let l=0;l<o.length;l++){let f=e.indexVar?{...n,[e.itemVar]:o[l],[e.indexVar]:l}:{...n,[e.itemVar]:o[l]};f.__paths__||(f.__paths__=n.__paths__||{}),f.__paths__={...f.__paths__,[e.itemVar]:`${c}[${l}]`},e.indexVar&&(f.__paths__[e.indexVar]=l);let u=L(e.body,t,r,f);if(Array.isArray(u)&&u.length===1&&!a){let d=u[0];s.push(d===void 0?{}:d)}else s.push(u===void 0?{}:u)}return s},Ns=(e,t,r,n)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?L(o.parsedKey,t,r,n):o.key,s=o.value;if(s.type===m.OBJECT&&s.properties.length<=10&&!s.whenCondition){let c={},a={},l=!0;for(let f of s.properties){let u=f.parsedKey?L(f.parsedKey,t,r,n):f.key,d=f.value;if(d.type===m.LITERAL)a[u]=d.value;else if(d.type===m.VARIABLE)a[u]=H(d.path,r,n);else if(d.type===m.INTERPOLATION){let p=[];for(let h of d.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let g=H(h.path,r,n);p.push(g!=null?String(g):"")}else{l=!1;break}if(!l)break;a[u]=p.join("")}else if(d.type===m.OBJECT&&d.properties.length<=5){let p={};for(let h of d.properties){let g=h.key,y=h.value;if(y.type===m.LITERAL)p[g]=y.value;else if(y.type===m.VARIABLE)p[g]=H(y.path,r,n);else if(y.type===m.INTERPOLATION){let b=[];for(let A of y.parts)if(typeof A=="string")b.push(A);else if(A.type===m.VARIABLE){let x=H(A.path,r,n);b.push(x!=null?String(x):"")}else{l=!1;break}if(!l)break;p[g]=b.join("")}else{l=!1;break}}if(!l)break;a[u]=p}else{l=!1;break}}if(l)return c[i]=a,c}}return null},Vs=(e,t,r,n)=>{let o=t.functions||t;if(e.whenCondition&&!$e(e.whenCondition,o,r,n))return;let i=Ns(e,t,r,n);if(i!==null)return i;if(e.fast){let l={};for(let f of e.properties){let u=f.parsedKey?L(f.parsedKey,t,r,n):f.key,d=f.value;if(d.type===m.LITERAL)l[u]=d.value;else if(d.type===m.VARIABLE)l[u]=H(d.path,r,n);else if(d.type===m.INTERPOLATION){let p=[];for(let h of d.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let g=H(h.path,r,n);p.push(g!=null?String(g):"")}else{let g=L(h,t,r,n);p.push(g!=null?String(g):"")}l[u]=p.join("")}else l[u]=L(d,t,r,n)}return l}let s={},c=null,a=!1;for(let l of e.properties)if(!l.key.startsWith("$if ")&&!l.key.match(/^\$if\s+\w+.*:?$/)&&!l.key.startsWith("$elif")&&!l.key.startsWith("$else")&&!l.key.startsWith("$for ")){a=!0;break}for(let l of e.properties)if(l.key.startsWith("$if ")||l.key.match(/^\$if\s+\w+.*:?$/)){let f=L(l.value,t,r,n);if(!a&&f!==null&&f!==void 0)return Array.isArray(f)&&f.length===1?f[0]:f;typeof f=="object"&&f!==null&&!Array.isArray(f)&&Object.assign(s,f)}else if(l.key.startsWith("$for ")){if(e.properties.length===1)return L(l.value,t,r,n)}else{let f=l.value;if(f&&f.type===m.OBJECT&&f.properties){let u=f.properties.find(d=>d.key.startsWith("$for "));if(u){let d=L(u.value,t,r,n);d!==void 0&&(s[l.key]=d)}else{let d=L(l.value,t,r,n);d!==void 0&&(s[l.key]=d)}}else{let u=l.parsedKey?L(l.parsedKey,t,r,n):l.key,d=L(l.value,t,r,n);d!==void 0&&(s[u]=d)}}return s},Kn={},js=(e,t,r,n)=>{let o=[];for(let i of e.items)if(i.type===m.LOOP){let s=L(i,t,r,n);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=L(i,t,r,n);s!==Kn&&s!==void 0&&o.push(s)}return o},Fs=(e,t,r,n)=>{let{name:o,data:i,whenCondition:s}=e,c=t.partials||{},a=t.functions||t;if(s&&!$e(s,a,r,n))return;if(!c[o])throw new ue(`Partial '${o}' is not defined`);let l=n._partialStack||[];if(l.includes(o))throw new ue(`Circular partial reference detected: ${o}`);let f=c[o],u=r,d={...n,_partialStack:[...l,o]};if(n){u={...r};for(let p of Object.keys(n))p.startsWith("_")||(u[p]=n[p])}if(i){let p=L(i,t,r,n);u={...u,...p}}return L(f,t,u,d)},Ms=(e,t,r,n)=>{let{path:o}=e,i=o.split("."),s=i[0],c=i.slice(1);if(!n||!(s in n))throw new ue(`Path reference '#{${o}}' refers to '${s}' which is not a loop variable in the current scope`);if(n.__paths__||(n.__paths__={}),!(s in n.__paths__))throw new ue(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let a=n.__paths__[s];if(typeof a=="number"){if(c.length>0)throw new ue(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(a)}return c.length>0&&(a+="."+c.join(".")),a};var Sr=Ss;var Us=/\$\{([^}]*)\}/g,Bs=/#\{([^}]*)\}/g,Xn=(e,t={})=>{let r=e.match(/^(\w+)\((.*)\)$/);if(!r)return{isFunction:!1};let[,n,o]=r,i=zs(o,t);return{isFunction:!0,type:m.FUNCTION,name:n,args:i}},zs=(e,t={})=>e.trim()?qs(e).map(n=>Ws(n.trim(),t)):[],qs=e=>{let t=[],r="",n=0,o=!1,i="";for(let s=0;s<e.length;s++){let c=e[s],a=s>0?e[s-1]:"";!o&&(c==='"'||c==="'")?(o=!0,i=c,r+=c):o&&c===i&&a!=="\\"?(o=!1,i="",r+=c):!o&&c==="("?(n++,r+=c):!o&&c===")"?(n--,r+=c):!o&&c===","&&n===0?(t.push(r),r=""):r+=c}return r&&t.push(r),t},Ws=(e,t={})=>{if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:m.LITERAL,value:e.slice(1,-1)};if(/^-?\d+(\.\d+)?$/.test(e))return{type:m.LITERAL,value:parseFloat(e)};if(e==="true")return{type:m.LITERAL,value:!0};if(e==="false")return{type:m.LITERAL,value:!1};if(e==="null")return{type:m.LITERAL,value:null};let r=Xn(e,t);if(r.isFunction)return{type:r.type,name:r.name,args:r.args};let n=e.trim(),o=[{op:" + ",type:"ADD"},{op:" - ",type:"SUBTRACT"}],i=-1,s=null;for(let{op:c,type:a}of o){let l=0;for(;l<n.length;){let f=qe(n.substring(l),c);if(f===-1)break;let u=l+f;u>i&&(i=u,s={op:c,type:a}),l=u+c.length}}if(i!==-1)try{return Q(n,t)}catch{return{type:m.VARIABLE,path:n}}return{type:m.VARIABLE,path:n}},Qn=/^\w+\(.*\)$/,Hs=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,Ys=e=>{if(!(!e||e.trim()===""||Qn.test(e))&&Hs.test(e))throw e.includes("?")&&e.includes(":")?new E(`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 E(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new E(`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(Qn.test(t))throw new E(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new E(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new E(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new E(`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 E(`Complex expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);return{type:m.PATH_REFERENCE,path:t}},ft=(e,t={})=>{let r=e.trim();Ys(r);let n=Xn(r,t);if(n.isFunction)return{type:n.type,name:n.name,args:n.args};if(r.includes("[")&&!/[\s+\-*/%|&?:]/.test(r)){let o=0;for(let i of r)i==="["?o++:i==="]"&&o--;if(o!==0)throw new Error("Invalid array index syntax")}return{type:m.VARIABLE,path:r}},_r=(e,t={})=>{let r=e,n=[];(e.includes("\\${")||e.includes("\\#{"))&&(r=e.replace(/\\\\(\$\{[^}]*\})/g,"\\DOUBLE_ESC_VAR$1"),r=r.replace(/\\\\(#\{[^}]*\})/g,"\\DOUBLE_ESC_PATH$1"),r=r.replace(/\\(\$\{[^}]*\})/g,(l,f)=>{let u=`__ESCAPED_${n.length}__`;return n.push(f),u}),r=r.replace(/\\(#\{[^}]*\})/g,(l,f)=>{let u=`__ESCAPED_${n.length}__`;return n.push(f),u}),r=r.replace(/\\DOUBLE_ESC_VAR/g,"\\"),r=r.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...r.matchAll(Us)],i=[...r.matchAll(Bs)],s=[...o.map(l=>({match:l,type:"variable"})),...i.map(l=>({match:l,type:"pathref"}))].sort((l,f)=>l.match.index-f.match.index);if(s.length===0){let l=r;for(let f=0;f<n.length;f++)l=l.replace(`__ESCAPED_${f}__`,n[f]);return{type:m.LITERAL,value:l}}if(s.length===1&&s[0].match[0]===r&&n.length===0){let{match:l,type:f}=s[0];try{return f==="variable"?ft(l[1],t):Jn(l[1])}catch(u){if(u.message==="Invalid array index syntax")return{type:m.LITERAL,value:r};throw u}}let c=[],a=0;for(let{match:l,type:f}of s){let[u,d]=l,p=l.index;if(p>a){let h=r.substring(a,p);for(let g=0;g<n.length;g++)h=h.replace(`__ESCAPED_${g}__`,n[g]);h&&c.push(h)}try{let h;f==="variable"?h=ft(d.trim(),t):h=Jn(d.trim()),c.push(h)}catch(h){if(h.message==="Invalid array index syntax")c.push(u);else throw h}a=p+u.length}if(a<r.length){let l=r.substring(a);for(let f=0;f<n.length;f++)l=l.replace(`__ESCAPED_${f}__`,n[f]);l&&c.push(l)}return{type:m.INTERPOLATION,parts:c}};var Lr=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),to=e=>Object.keys(e),ae=e=>e.join("."),ke=(e,t,r)=>{let n=to(e).filter(o=>!t.has(o));if(n.length>0)throw new E(`Unexpected key '${n[0]}' in condition JSON at '${ae(r)}'`)},Te=(e,t)=>typeof e=="string"?_r(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?Ks(e,t):Js(e,t):{type:m.LITERAL,value:e},Gs=e=>{let{$each:t,...r}=e;if(typeof t!="string")throw new E("$each value must be a non-empty string");let n=t.trim();if(n==="")throw new E("$each value must be a non-empty string");if(Object.keys(r).length===0)throw new E("Empty $each body not allowed");if(r.$partial!==void 0)throw new E("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${n}`]:r}},Ks=(e,t)=>{let r=[],n=!1;for(let o=0;o<e.length;o++){let i=e[o];if(typeof i=="object"&&i!==null&&!Array.isArray(i)){if(i.$each!==void 0)try{let a=Gs(i),l=Object.keys(a);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let f=eo(l[0],a[l[0]],t,!0);r.push(f),n=!0;continue}}catch(a){throw a instanceof E?a:new E(a.message)}let c=Object.keys(i);if(c.length===1&&/^\$for(?::\w+)?\s/.test(c[0])){let a=eo(c[0],i[c[0]],t);r.push(a),n=!0;continue}}let s=Te(i,t);r.push(s),(s.type===m.FUNCTION||s.type===m.CONDITIONAL||s.type===m.LOOP||s.type===m.PARTIAL||s.type===m.OBJECT&&!s.fast||s.type===m.ARRAY&&!s.fast)&&(n=!0)}return{type:m.ARRAY,items:r,fast:!n}},Js=(e,t)=>{let r=[],n=!1,o=null,i=Object.entries(e),s=0;if(e.$partial!==void 0){if(typeof e.$partial!="string")throw new E("$partial value must be a string");if(e.$partial.trim()==="")throw new E("$partial value cannot be an empty string");let a=["$if","$elif","$else","$for"],l=[];for(let[b]of i)for(let A of a)if(b===A||b.startsWith(A+" ")||b.startsWith(A+"#")){l.push(A);break}if(l.length>0)throw new E(`Cannot use $partial with ${l.join(", ")} at the same level. Wrap $partial in a parent object if you need conditionals.`);let{$partial:f,$when:u,...d}=e,p={},h=!1;for(let[b,A]of Object.entries(d)){let x=b;(b.startsWith("\\$")||b.startsWith("$$"))&&(x=b.slice(1)),p[x]=A,h=!0}let g=null;if(h&&(g=Te(p,t),g.type===m.OBJECT)){let b=!1;for(let A of g.properties)if(A.value.type===m.VARIABLE||A.value.type===m.INTERPOLATION||A.value.type===m.FUNCTION||A.value.type===m.CONDITIONAL||A.value.type===m.OBJECT&&!A.value.fast||A.value.type===m.ARRAY&&!A.value.fast){b=!0;break}b&&(g.fast=!1)}let y={type:m.PARTIAL,name:f,data:g};return u!==void 0&&(y.whenCondition=Zn(u,t)),y}for(let[a,l]of i)if(a==="$when"){if(o!==null)throw new E("Multiple '$when' directives on the same object are not allowed");if(l==null)throw new E("Missing condition expression after '$when'");o=Zn(l,t),n=!0}else if(a.startsWith("$when#")||a.startsWith("$when "))throw new E("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<i.length;){let[a,l]=i[s];if(a==="$when"){s++;continue}if(a==="$each")throw new E("$each can only be used inside arrays");if(a.startsWith("$if ")||a.match(/^\$if#\w+\s/)||a.match(/^\$if\s+\w+.*:$/)){let f=Xs(i,s,t);r.push({key:a,value:f.node}),n=!0,s=f.nextIndex}else if(/^\$for(?::\w+)?\s/.test(a)){let f=a.match(/^\$for(?::(\w+))?\s/)?.[1]||"",u=f?`:${f}`:"";throw new E(`$for loops must be inside arrays - use '- $for${u} item in items:' instead of '$for${u} item in items:'. For cleaner object generation syntax, consider using $each.`)}else{if(a.startsWith("$elif ")||a.startsWith("$else"))throw new E(`'${a.split(" ")[0]}' without matching '$if'`);if(a==="$if"||a==="$if:")throw new E("Missing condition expression after '$if'");{let f=Te(l,t);(f.type===m.FUNCTION||f.type===m.CONDITIONAL||f.type===m.PARTIAL||f.type===m.OBJECT&&!f.fast||f.type===m.ARRAY&&!f.fast)&&(n=!0);let u=_r(a,t),d={key:a,value:f};(u.type!==m.LITERAL||u.value!==a)&&(d.parsedKey=u),r.push(d),s++}}}let c={type:m.OBJECT,properties:r,fast:!n};return o&&(c.whenCondition=o),c},Xs=(e,t,r={})=>{let n=[],o=[],i=t,[s,c]=e[i],a=null,l;if(s.startsWith("$if#")){let u=s.match(/^\$if#(\w+)\s+(.+)$/);if(u)a=u[1],l=u[2];else throw new E(`Invalid conditional syntax: ${s}`)}else l=s.substring(4),l.endsWith(":")&&(l=l.slice(0,-1).trim());Cr(l);let f=Q(l,r);for(n.push(f),o.push(Te(c,r)),i++;i<e.length;){let[u,d]=e[i],p=!1,h;if(a?u.startsWith(`$elif#${a} `)?(h=u.substring(`$elif#${a} `.length),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(u===`$else#${a}`||u===`$else#${a}:`)&&(p=!0,h=null):u.startsWith("$elif ")?(h=u.substring(6),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(u==="$else"||u==="$else:")&&(p=!0,h=null),p){if(h===null)n.push(null);else{Cr(h);let g=Q(h,r);n.push(g)}if(o.push(Te(d,r)),i++,h===null)break}else break}return{node:{type:m.CONDITIONAL,conditions:n,bodies:o,id:a},nextIndex:i}},Rr={eq:O.EQ,neq:O.NEQ,gt:O.GT,gte:O.GTE,lt:O.LT,lte:O.LTE,in:O.IN,add:O.ADD,sub:O.SUBTRACT},Or={all:O.AND,any:O.OR},Qs=new Set(["var","literal","call","not",...Object.keys(Rr),...Object.keys(Or)]),Zs=(e,t,r)=>{if(!Array.isArray(e))throw new E(`Condition JSON operator '${t}' at '${ae(r)}' requires an array`);if(e.length!==2)throw new E(`Condition JSON operator '${t}' at '${ae(r)}' requires exactly 2 operands`);return e},ea=(e,t,r,n,o)=>{if(!Array.isArray(e))throw new E(`Condition JSON operator '${t}' at '${ae(o)}' requires an array`);if(e.length===0)throw new E(`Condition JSON operator '${t}' at '${ae(o)}' requires at least 1 condition`);return e.map((s,c)=>Ce(s,n,[...o,c])).reduce((s,c)=>({type:m.BINARY,op:r,left:s,right:c}))},ta=(e,t,r)=>{let n,o;if(typeof e.call=="string")n=e.call,o=e.args??[],ke(e,new Set(["call","args"]),r);else if(Lr(e.call))n=e.call.name,o=e.call.args??[],ke(e,new Set(["call"]),r),ke(e.call,new Set(["name","args"]),[...r,"call"]);else throw new E(`Condition JSON call at '${ae(r)}' requires a function name`);if(typeof n!="string"||n.trim()==="")throw new E(`Condition JSON call at '${ae(r)}' requires a non-empty function name`);if(!/^\w+$/.test(n))throw new E(`Invalid condition JSON function name '${n}' at '${ae(r)}'`);if(!Array.isArray(o))throw new E(`Condition JSON call '${n}' at '${ae(r)}' requires args to be an array`);return{type:m.FUNCTION,name:n,args:o.map((i,s)=>Ce(i,t,[...r,"args",s]))}},Ce=(e,t={},r=["$when"])=>{if(typeof e=="string"||typeof e=="number"||typeof e=="boolean"||e===null)return{type:m.LITERAL,value:e};if(Array.isArray(e))throw new E(`Condition JSON array at '${ae(r)}' must be wrapped in an operator or { literal: [...] }`);if(!Lr(e))throw new E(`Invalid condition JSON value at '${ae(r)}'`);let n=to(e);if(n.length===0)throw new E(`Condition JSON object at '${ae(r)}' must contain an operator`);let o=n.filter(s=>Qs.has(s));if(o.length===0)throw new E(`Unknown condition JSON operator '${n[0]}' at '${ae(r)}'`);if(o.length>1)throw new E(`Condition JSON at '${ae(r)}' must contain exactly one operator`);let i=o.includes("call")?"call":o[0];if(i==="var"){if(ke(e,new Set(["var"]),r),typeof e.var!="string"||e.var.trim()==="")throw new E(`Condition JSON var at '${ae(r)}' requires a non-empty path`);return{type:m.VARIABLE,path:e.var}}if(i==="literal")return ke(e,new Set(["literal"]),r),{type:m.LITERAL,value:e.literal};if(i==="call")return ta(e,t,r);if(i==="not")return ke(e,new Set(["not"]),r),{type:m.UNARY,op:et.NOT,operand:Ce(e.not,t,[...r,"not"])};if(i in Or)return ke(e,new Set([i]),r),ea(e[i],i,Or[i],t,[...r,i]);if(i in Rr){ke(e,new Set([i]),r);let s=Zs(e[i],i,[...r,i]);return{type:m.BINARY,op:Rr[i],left:Ce(s[0],t,[...r,i,0]),right:Ce(s[1],t,[...r,i,1])}}throw new E(`Unknown condition JSON operator '${i}' at '${ae(r)}'`)},Zn=(e,t={})=>{if(e==null)throw new E("Missing condition expression after '$when'");if(typeof e=="string"){if(e.trim()==="")throw new E("Empty condition expression after '$when'");return Q(e,t)}return Lr(e)||Array.isArray(e)?Ce(e,t):{type:m.LITERAL,value:e}},Q=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let l=e.slice(1,-1),f=0,u=!0;for(let d=0;d<l.length;d++)if(l[d]==="("?f++:l[d]===")"&&f--,f<0){u=!1;break}if(u&&f===0)return Q(l,t)}let r=qe(e,"||");if(r!==-1)return{type:m.BINARY,op:O.OR,left:Q(e.substring(0,r).trim(),t),right:Q(e.substring(r+2).trim(),t)};let n=qe(e,"&&");if(n!==-1)return{type:m.BINARY,op:O.AND,left:Q(e.substring(0,n).trim(),t),right:Q(e.substring(n+2).trim(),t)};let o=[{op:">=",type:O.GTE},{op:"<=",type:O.LTE},{op:"==",type:O.EQ},{op:"!=",type:O.NEQ},{op:">",type:O.GT},{op:"<",type:O.LT},{op:" in ",type:O.IN}];for(let{op:l,type:f}of o){let u=qe(e,l);if(u!==-1)return{type:m.BINARY,op:f,left:Q(e.substring(0,u).trim(),t),right:Q(e.substring(u+l.length).trim(),t)}}let i=-1,s=null,c=[{op:" + ",type:O.ADD},{op:" - ",type:O.SUBTRACT}];for(let{op:l,type:f}of c){let u=0;for(;u<e.length;){let d=qe(e.substring(u),l);if(d===-1)break;let p=u+d;p>i&&(i=p,s={op:l,type:f}),u=p+l.length}}if(i!==-1&&s)return{type:m.BINARY,op:s.type,left:Q(e.substring(0,i).trim(),t),right:Q(e.substring(i+s.op.length).trim(),t)};let a=[" * "," / "," % "];for(let l of a)if(qe(e,l)!==-1)throw new E(`Arithmetic operations are not allowed in conditionals: "${l}"`);return e.startsWith("!")?{type:m.UNARY,op:et.NOT,operand:Q(e.substring(1).trim(),t)}:ro(e,t)},qe=(e,t)=>{let r=0,n=0;for(;n<=e.length-t.length;){if(e[n]==="(")r++;else if(e[n]===")")r--;else if(r===0&&e.substring(n,n+t.length)===t)return n;n++}return-1},ra=e=>{if(e=e.trim(),e==="true")return{type:m.LITERAL,value:!0};if(e==="false")return{type:m.LITERAL,value:!1};if(e==="null")return{type:m.LITERAL,value:null};if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:m.LITERAL,value:e.slice(1,-1)};if(e==='""'||e==="''")return{type:m.LITERAL,value:""};if(e==="{}")return{type:m.LITERAL,value:{}};if(e==="[]")return{type:m.LITERAL,value:[]};let t=Number(e);return!isNaN(t)&&isFinite(t)?{type:m.LITERAL,value:t}:{type:m.VARIABLE,path:e}},ro=(e,t)=>{let r=e.trim();if(r.match(/^(\w+)\((.*)\)$/))return ft(r,t);let o=ra(r);if(o.type===m.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(r))return{type:m.VARIABLE,path:r};try{return ft(r,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},na=(e,t=!1)=>{let r=t?"$each":"$for";try{Bn(e)}catch(n){if(n instanceof E&&t){let o=n.message.replace(/\$for/g,"$each");throw new E(o.replace("Parse Error: ",""))}throw n}},eo=(e,t,r,n=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let y=n?"$each":"$for";throw new E(`Invalid loop syntax (got: '${e.replace("$for",y)}')`)}let s=i[1],c=i[2].trim();na(c,n);let a=c.match(/^(.+?)\s+in\s+(.+)$/);if(!a){let y=n?"$each":"$for";throw new E(`Invalid loop syntax - missing 'in' keyword (got: '${y} ${c}')`)}let l=a[1].trim(),f=a[2].trim(),u,d=null;if(l.includes(",")){let y=l.split(",").map(b=>b.trim());if(y.length!==2)throw new E(`Invalid loop variables: ${l}. Expected format: "item" or "item, index"`);u=y[0],d=y[1]}else u=l;let p=["this","undefined","null","true","false"];if(p.includes(u))throw new E(`Reserved variable name: ${u}`);if(d&&p.includes(d))throw new E(`Reserved variable name: ${d}`);let h=ro(f,r),g=Te(t,r);return{type:m.LOOP,itemVar:u,indexVar:d,iterable:h,body:g,flatten:s!=="nested"}};var oa=(e,t={})=>{let{functions:r={}}=t;return Te(e,r)},Pt=oa;var dt={};gs(dt,{now:()=>ia});var ia=()=>Date.now();var sa=(e,t,r={})=>{let{functions:n={},partials:o={}}=r,i={...dt,...n},s=Pt(e,{functions:i}),c={};for(let[a,l]of Object.entries(o))c[a]=Pt(l,{functions:i});return Sr(s,t,{functions:i,partials:c})},ce=sa;var aa=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",ca=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,la=(e,t)=>{if(aa(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new E("Empty condition expression");return Q(e,t)}return Ce(e,t)},ua=(e,t={},r={})=>{let n=ca(r),o={...dt,...n},i=la(e,o);return!!$e(i,{functions:o,partials:{}},t,{})},$r=ua;var ht=(e,t={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return $r(e,t)},co=(e,t,r={})=>{let n=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=a=>a,transformActionFirstArgument:c=a=>a}=r;for(let[a,l]of Object.entries(t))a!=="createInitialState"&&(a.startsWith("select")?o[a]=(...f)=>l(s(n),...f):i[a]=(...f)=>{let u;return n=vr(n,p=>{let h=l(c(p),...f);u=h!==void 0&&!de(h)?h:void 0}),u});return{...o,...i}},jt=(e,t)=>r=>{let n=e(),o=Array.isArray(r)?r:[r];return vr(n,i=>{o.forEach(s=>{t.forEach(c=>{c(i,s)})})})};var fa=(e,t)=>{if(e.default!==void 0)return e.default;let r=["number","boolean","string","object"];if(!r.includes(e.type))throw new Error(`Invalid variable type: ${e.type} for variable ${t}. Expected one of: ${r.join(", ")}`);switch(e.type){case"number":return 0;case"boolean":return!1;case"string":return"";case"object":return{}}},ge=(e,t)=>Object.prototype.hasOwnProperty.call(e??{},t),pt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),lo=e=>{let t=de(e)?ze(e):e;return structuredClone(t)},da=({characterId:e,resourceCharacter:t,variables:r={}}={})=>{if(!ge(t,"nameVariableId"))return;let n=t.nameVariableId,o=r?.[n];if(typeof o!="string")throw new Error(`Character "${e}" nameVariableId "${n}" must resolve to a string variable`);return o},Ft=({characterId:e,character:t,characterName:r,characters:n={},variables:o={}}={})=>{let i=e?n?.[e]:void 0;if(t?.name!==void 0)return t.name;if(r!==void 0)return r;let s=da({characterId:e,resourceCharacter:i,variables:o});return s!==void 0?s:i?.name||""},De=e=>ge(e,"computed"),tt=(e={},t={})=>Object.fromEntries(Object.entries(e??{}).filter(([r])=>!De(t[r]))),pa=e=>String(e).replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean),kr=(e,t)=>{let r=e;for(let n of t){if(r==null)return;r=r[n]}return r},ha=(e,t={})=>{if(typeof e!="string"||e.trim()==="")throw new Error("Computed expression var requires a non-empty string path");let r=pa(e),[n,o,...i]=r;if(n==="variables"){if(!o)return t.variables;let s=typeof t.resolveVariable=="function"?t.resolveVariable(o):t.variables?.[o];return kr(s,i)}return n==="runtime"?kr(t.runtime,r.slice(1)):kr(t,r)},ma=(e,t,r)=>{if(!Array.isArray(t))throw new Error(`Computed expression operator "${e}" requires an array`);if(r!==void 0&&t.length!==r)throw new Error(`Computed expression operator "${e}" requires ${r} operand(s)`)},no=(e,t)=>{if(!Array.isArray(t))throw new Error(`Computed expression operator "${e}" requires an array`);if(t.length===0)throw new Error(`Computed expression operator "${e}" requires at least one operand`)},ga=(e,t)=>{if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Computed expression operator "${e}" requires finite numeric operands`)},Ae=(e,t,r,n)=>(ma(e,t,n),t.map(o=>Vt(o,r))),me=(e,t,r,n)=>{let o=Ae(e,t,r,n);return o.forEach(i=>ga(e,i)),o},ya=(e,t,r)=>{switch(e){case"var":return ha(t,r);case"add":{let[n,o]=me(e,t,r,2);return n+o}case"sub":{let[n,o]=me(e,t,r,2);return n-o}case"mul":{let[n,o]=me(e,t,r,2);return n*o}case"div":{let[n,o]=me(e,t,r,2);return n/o}case"mod":{let[n,o]=me(e,t,r,2);return n%o}case"neg":{let[n]=me(e,t,r,1);return-n}case"round":{let[n]=me(e,t,r,1);return Math.round(n)}case"floor":{let[n]=me(e,t,r,1);return Math.floor(n)}case"ceil":{let[n]=me(e,t,r,1);return Math.ceil(n)}case"min":{let[n,o]=me(e,t,r,2);return Math.min(n,o)}case"max":{let[n,o]=me(e,t,r,2);return Math.max(n,o)}case"clamp":{let[n,o,i]=me(e,t,r,3);return Math.min(i,Math.max(o,n))}case"eq":{let[n,o]=Ae(e,t,r,2);return n==o}case"neq":{let[n,o]=Ae(e,t,r,2);return n!=o}case"gt":{let[n,o]=Ae(e,t,r,2);return n>o}case"gte":{let[n,o]=Ae(e,t,r,2);return n>=o}case"lt":{let[n,o]=Ae(e,t,r,2);return n<o}case"lte":{let[n,o]=Ae(e,t,r,2);return n<=o}case"in":{let[n,o]=Ae(e,t,r,2);return Array.isArray(o)?o.includes(n):!1}case"and":case"all":return no(e,t),t.every(n=>!!Vt(n,r));case"or":case"any":return no(e,t),t.some(n=>!!Vt(n,r));case"not":{let[n]=Ae(e,t,r,1);return!n}case"length":{let[n]=Ae(e,t,r,1);return typeof n=="string"||Array.isArray(n)?n.length:pt(n)?Object.keys(n).length:0}case"includes":{let[n,o]=Ae(e,t,r,2);return typeof n=="string"||Array.isArray(n)?n.includes(o):!1}case"literal":return lo(t);default:throw new Error(`Unknown computed expression operator: ${e}`)}},Vt=(e,t={})=>{if(e===null||typeof e!="object")return e;if(Array.isArray(e))throw new Error("Computed expression arrays are not valid; use value for literal arrays");let r=Object.entries(e);if(r.length!==1)throw new Error("Computed expression objects must contain exactly one operator");let[[n,o]]=r;return ya(n,o,t)},ba=(e,t={})=>ht(e,{variables:t.variables,runtime:t.runtime}),Ia=(e,t)=>{if(!pt(e))throw new Error(`${t} must be an object`);let r=ge(e,"expr"),n=ge(e,"value");if(r===n)throw new Error(`${t} must contain exactly one of expr or value`)},Tr=(e,t,r)=>(Ia(e,t),ge(e,"value")?lo(e.value):Vt(e.expr,r)),Aa=(e,t={},r="unknown")=>{if(!pt(e))throw new Error(`Computed variable "${r}" computed must be an object`);let n=ge(e,"expr"),o=ge(e,"value");if(ge(e,"branches")){if(n||o)throw new Error(`Computed variable "${r}" cannot combine branches with expr or value`);if(!Array.isArray(e.branches))throw new Error(`Computed variable "${r}" branches must be an array`);if(e.branches.length===0)throw new Error(`Computed variable "${r}" branches must not be empty`);if(!pt(e.default))throw new Error(`Computed variable "${r}" requires default`);for(let s=0;s<e.branches.length;s+=1){let c=e.branches[s];if(!pt(c))throw new Error(`Computed variable "${r}" branch ${s} must be an object`);if(!ge(c,"when"))throw new Error(`Computed variable "${r}" branch ${s} requires when`);if(ba(c.when,t))return Tr(c,`Computed variable "${r}" branch ${s}`,t)}return Tr(e.default,`Computed variable "${r}" default`,t)}if(n===o)throw new Error(`Computed variable "${r}" must contain exactly one of expr, value, or branches`);return Tr(e,`Computed variable "${r}"`,t)},wa=(e,t,r)=>{switch(t){case"number":if(typeof r!="number"||!Number.isFinite(r))throw new Error(`Computed variable "${e}" expected type number, got ${Array.isArray(r)?"array":typeof r}`);return;case"boolean":if(typeof r!="boolean")throw new Error(`Computed variable "${e}" expected type boolean, got ${Array.isArray(r)?"array":typeof r}`);return;case"string":if(typeof r!="string")throw new Error(`Computed variable "${e}" expected type string, got ${Array.isArray(r)?"array":typeof r}`);return;case"object":if(r===null||typeof r!="object")throw new Error(`Computed variable "${e}" expected type object, got ${typeof r}`);return;default:throw new Error(`Invalid variable type: ${t} for computed variable ${e}`)}},mt=({variables:e={},runtime:t={},variableConfigs:r={},eager:n=!0}={})=>{let o=tt(e,r),i=Object.entries(r).filter(([,u])=>De(u)).map(([u])=>u),s={},c=[],a=u=>{if(ge(s,u))return s[u];let d=r[u];if(!De(d))return o[u];let p=c.indexOf(u);if(p>=0){let h=[...c.slice(p),u].join(" -> ");throw new Error(`Computed variable cycle detected: ${h}`)}c.push(u);try{let h=Aa(d.computed,f,u);return wa(u,d.type,h),s[u]=h,h}finally{c.pop()}},l=new Proxy({},{get:(u,d)=>{if(typeof d=="string")return a(d)},has:(u,d)=>typeof d=="string"&&(ge(o,d)||i.includes(d)),ownKeys:()=>[...new Set([...Object.keys(o),...i])],getOwnPropertyDescriptor:(u,d)=>{if(!(typeof d!="string"||!ge(o,d)&&!i.includes(d)))return{enumerable:!0,configurable:!0}}}),f={variables:l,runtime:t,resolveVariable:a};return n?(i.forEach(u=>{a(u)}),{...o,...s}):l},Ea=({variables:e={},runtime:t={},variableConfigs:r,projectData:n}={})=>mt({variables:e,runtime:t,variableConfigs:r??n?.resources?.variables??{},eager:!0}),Mt=e=>{let t={},r={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([n,o])=>{if(De(o))return;let i=fa(o,n);o.scope==="context"?t[n]=i:r[n]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}},Ut=(e,t)=>{let r=["context","device","account"];if(!e)throw new Error(`Variable scope is required for variable: ${t}`);if(!r.includes(e))throw new Error(`Invalid variable scope: ${e} for variable ${t}. Expected one of: ${r.join(", ")}`)},Bt=(e,t,r)=>{let n={number:["set","increment","decrement","multiply","divide"],boolean:["set","toggle"],string:["set"],object:["set"]},o=n[e];if(!o)throw new Error(`Unknown variable type: ${e} for variable ${r}`);if(!Object.values(n).flat().includes(t))throw new Error(`Unknown operation: ${t}`);if(!o.includes(t))throw new Error(`Operation "${t}" is not valid for variable "${r}" of type "${e}". Valid operations: ${o.join(", ")}`)},xa=2,oo=12,uo=(e=xa)=>{if(!Number.isInteger(e)||e<0||e>oo)throw new Error(`Operation "divide" requires roundTo to be an integer between 0 and ${oo}.`);return e},va=(e,t)=>{let r=10**t;return Math.round((e+Number.EPSILON)*r)/r},Nt=e=>typeof e=="number"&&Number.isFinite(e),Nr=(e,t,r,n,o={})=>{if(e==="number"){if(t==="set"&&!Nt(r))throw new Error(`Operation "set" requires value to be a number for variable "${n}".`);if(t==="multiply"&&!Nt(r))throw new Error(`Operation "multiply" requires value to be a number for variable "${n}".`);if(t==="divide"&&!Nt(r))throw new Error(`Operation "divide" requires value to be a number for variable "${n}".`);if(t==="divide"){if(r===0)throw new Error(`Operation "divide" requires value to be a non-zero number for variable "${n}".`);uo(o.roundTo)}}},zt=(e,t,r,n={})=>{let o=(s,c,a)=>{let l=s??c;if(!Nt(l))throw new Error(`Operation "${t}" requires ${a} to be a number.`);return l},i=s=>{let c=o(s,void 0,"value");if(c===0)throw new Error(`Operation "${t}" requires value to be a non-zero number.`);return c};switch(t){case"set":return r;case"multiply":return o(e,1,"current value")*o(r,void 0,"value");case"divide":return va(o(e,0,"current value")/i(r),uo(n.roundTo));case"increment":return o(e,0,"current value")+o(r,1,"value");case"decrement":return o(e,0,"current value")-o(r,1,"value");case"toggle":return!e;default:throw new Error(`Unknown operation: ${t}`)}};var fo=(e,t="DD/MM/YYYY - HH:mm")=>{if(!e)return"";let r=new Date(e),n=o=>String(o).padStart(2,"0");return t.replace("DD",n(r.getDate())).replace("MM",n(r.getMonth()+1)).replace("YYYY",r.getFullYear()).replace("YY",String(r.getFullYear()).slice(-2)).replace("HH",n(r.getHours())).replace("mm",n(r.getMinutes())).replace("ss",n(r.getSeconds()))},Ca=(e,t)=>{let r=i=>{if(!i)return;let s={};i.ui&&(s.ui=i.ui);let c=i.character?.sprite;return c&&Object.keys(c).length>0&&(s.sprite=c),Object.keys(s).length>0?s:void 0},n=r(e),o=r(t);return JSON.stringify(n)===JSON.stringify(o)?null:n&&!o?{changeType:"delete",data:e}:o&&!n?{changeType:"add",data:t}:o&&n?{changeType:"update",data:t}:null},io=e=>{if(e?.resourceId===void 0)return;let t={resourceId:e.resourceId};e.transformId!==void 0&&(t.transformId=e.transformId);for(let r of["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"])e[r]!==void 0&&(t[r]=e[r]);for(let r of["animationName","animationSpeed","loop"])e[r]!==void 0&&(t[r]=e[r]);return t},so=e=>{if(e?.colorId!==void 0)return{colorId:e.colorId}},ao=(e,t)=>t&&!e?{changeType:"add",data:t}:e&&!t?{changeType:"delete",data:e}:e&&t&&JSON.stringify(e)!==JSON.stringify(t)?{changeType:"update",data:t}:null,Sa=(e,t)=>{let r={},n=ao(io(e),io(t)),o=ao(so(e),so(t));return n&&(r.resource=n),o&&(r.color=o),Object.keys(r).length>0?r:null},Vr=(e={},t={})=>{let r={},n=["sfx","voice"],o=c=>{let a=e[c],l=t[c];l&&!a?r[c]={changeType:"add",data:l}:a&&!l?n.includes(c)||(r[c]={changeType:"delete",data:a}):a&&l&&JSON.stringify(a)!==JSON.stringify(l)&&(r[c]={changeType:"update",data:l})},i=Sa(e.background,t.background);i&&(r.background=i),o("screen"),o("bgm"),o("voice");let s=Ca(e.dialogue,t.dialogue);return s&&(r.dialogue=s),o("choice"),o("form"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),r},jr=(e={})=>{let t=structuredClone(e);t.background&&(t.background.animations?.playback?.continuity!=="persistent"&&delete t.background.animations,!t.background.resourceId&&!t.background.colorId&&delete t.background);let r=o=>{t[o]&&(delete t[o].animations,Object.keys(t[o]).length===0&&delete t[o])};r("layout"),r("choice"),r("form"),r("screen"),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 n=(o,i)=>{let s=t[o]?.items;Array.isArray(s)&&(t[o].items=s.map(c=>{let a={...c};return delete a.animations,i(a)?a:null}).filter(Boolean),t[o].items.length===0&&delete t[o])};return n("character",o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId),n("visual",o=>o.resourceId||o.transformId),t},_a=(e,t)=>{if(!e||!t)return;let r=e;for(let n of t.split(".")){if(r==null||!(n in Object(r)))return;r=r[n]}return r},Ra=(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 r=e.slice(7),n=_a(t,r);if(n===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return n},Oa={conditional:new Set(["branches"]),updateProjectData:new Set(["projectData"]),showConfirmDialog:new Set(["confirmActions","cancelActions"]),form:new Set(["submitActions","cancelActions"]),submitForm:new Set(["actions"]),cancelForm:new Set(["actions"])},po=(e,t)=>{let r=e[e.length-1];return r?Oa[r]?.has(t)===!0:!1},Dr=(e,t,r=[])=>Array.isArray(e)?e.map(n=>Dr(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,po(r,n)?o:Dr(o,t,[...r,n])])):Ra(e,t),Pr=(e,t,r=[])=>Array.isArray(e)?e.map(n=>Pr(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,po(r,n)?o:Pr(o,t,[...r,n])])):typeof e=="string"?ce(e,t):e,Fr=(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 r=Dr(e,t._event);return Pr(r,t)};var Z=e=>structuredClone(de(e)?ze(e):e),U=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),ho=e=>e?.animations?.playback?.continuity==="persistent",$=(e,t)=>U(e??{},t)&&e[t]!==void 0,gt=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:Z(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},La=e=>$(e,"opacity")||$(e,"blur"),bo=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],Io=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],Mr=["animationName","animationSpeed","loop"],$a=e=>bo.some(t=>$(e,t)),Ao=e=>e?.text&&$(e.text,"content")&&$(e.text,"textStyleId"),wo=e=>$(e,"text"),ka=(e,t)=>e.resourceId?!0:Ao(e)?!t?.text:!1,Ta=(e,t)=>{let r={...Z(e),...t};return t.text&&e.text&&(r.text={...Z(e.text),...Z(t.text)}),r},Da=(e,t)=>{if(wo(e)){if(e.resourceId)throw new Error(`Visual item "${e.id}" cannot define both resourceId and text`);if(!Ao(e)&&!t?.text)throw new Error(`Visual item "${e.id}" text requires content and textStyleId`)}},mo=e=>Io.some(t=>$(e,t)),go=e=>Mr.some(t=>$(e,t)),Pa=(e,t,{hasAuthoredTransformId:r=!1}={})=>{if(!t)return e;for(let n of Io)!r&&!$(e,n)&&$(t,n)&&(e[n]=t[n]),U(e,n)&&e[n]===void 0&&delete e[n];return e},Eo=(e,t,r)=>{let n=e[r];return n?.id===t?.id?n:e.find(o=>o.id===t?.id)},Na=(e,t)=>{if(!t)return e;for(let r of bo)!$(e,r)&&$(t,r)&&(e[r]=t[r]),U(e,r)&&e[r]===void 0&&delete e[r];return e},Va=(e,t)=>(t&&(!$(e,"opacity")&&$(t,"opacity")&&(e.opacity=t.opacity),!$(e,"blur")&&$(t,"blur")&&(e.blur=Z(t.blur)),U(e,"opacity")&&e.opacity===void 0&&delete e.opacity,U(e,"blur")&&e.blur===void 0&&delete e.blur),e),xo=(e,t,r=[],{hasPatchFn:n=()=>!1,mergeItemFn:o}={})=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let i=e.map((s,c)=>{let a=Eo(r,s,c),l=t(s,a),f=La(s),u=$a(s),d=n(s),p=U(s,"animations"),h=Z(s);return!l&&(f||u||d)&&a&&(h=o?o(a,h):{...Z(a),...h},p||delete h.animations),Va(Na(h,a),a)}).filter(s=>t(s)||s.animations);return{hasValidItems:i.length>0,processedItems:i}},ja=e=>{if(e){if(e.character&&U(e.character,"name"))return e.character.name;if(U(e,"characterName"))return e.characterName}},vo=e=>!!e?.character&&U(e.character,"sprite"),Fa=e=>{let t={},r=!1,n=ja(e);return n!==void 0&&(t.name=n,r=!0),vo(e)&&(t.sprite=Z(e.character.sprite),r=!0),r?t:void 0},yo=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},Ma=({dialogueState:e,content:t,append:r=!1})=>{if(!r||!Array.isArray(t)){e.content=t,delete e.initialRevealedContent;return}let n=Array.isArray(e.content)?e.content:[];n.length>0?e.initialRevealedContent=n.map(o=>Z(o)):delete e.initialRevealedContent,e.content=[...n,...t]},Ua=()=>({}),Ba=(e,t)=>{if(!t.screen)return;let r=$(t.screen,"opacity"),n=$(t.screen,"blur"),o=U(t.screen,"animations");if(!r&&!n){o||delete e.screen;return}let i=e.screen,s={};if(r?s.opacity=t.screen.opacity:$(i,"opacity")&&(s.opacity=i.opacity),n?s.blur=Z(t.screen.blur):$(i,"blur")&&(s.blur=Z(i.blur)),U(s,"opacity")&&s.opacity===void 0&&delete s.opacity,U(s,"blur")&&s.blur===void 0&&delete s.blur,Object.keys(s).length===0){delete e.screen;return}e.screen=s},za=(e,t)=>{if(t.background){let r=$(t.background,"resourceId"),n=$(t.background,"colorId"),o=$(t.background,"opacity"),i=$(t.background,"blur"),s=$(t.background,"transformId"),c=mo(t.background),a=go(t.background),{animationsOnly:l,state:f}=gt(t.background,p=>$(p,"resourceId")||$(p,"colorId")||$(p,"opacity")||$(p,"blur")||$(p,"transformId")||mo(p)||go(p));if(l){e.background=e.background?{...Z(e.background),...f}:f;return}if(!r&&!n&&!o&&!i&&!s&&!c&&!a){delete e.background;return}let u=e.background,d=Z(t.background);if(!r&&u?.resourceId){d.resourceId=u.resourceId,!U(d,"transformId")&&u.transformId&&(d.transformId=u.transformId);for(let p of Mr)!$(d,p)&&$(u,p)&&(d[p]=u[p])}Pa(d,u,{hasAuthoredTransformId:s}),!n&&u?.colorId&&(d.colorId=u.colorId),!o&&$(u,"opacity")&&(d.opacity=u.opacity),!i&&$(u,"blur")&&(d.blur=Z(u.blur)),U(d,"resourceId")&&d.resourceId===void 0&&delete d.resourceId,U(d,"colorId")&&d.colorId===void 0&&delete d.colorId,U(d,"animations")&&d.animations===void 0&&delete d.animations,U(d,"transformId")&&d.transformId===void 0&&delete d.transformId,U(d,"opacity")&&d.opacity===void 0&&delete d.opacity,U(d,"blur")&&d.blur===void 0&&delete d.blur;for(let p of Mr)U(d,p)&&d[p]===void 0&&delete d[p];if(!d.resourceId&&!d.colorId){delete e.background;return}u?.resourceId===d.resourceId&&u?.transformId===d.transformId&&!U(d,"animations")&&ho(u)&&(d.animations=Z(u.animations)),e.background=d}else e.background?.animations&&!ho(e.background)&&(e.background.animations={})},qa=(e,t)=>{if(!t.dialogue){e.dialogue&&(yo(e.dialogue),e.dialogue.mode==="adv"&&(e.dialogue.content=void 0,delete e.dialogue.initialRevealedContent,delete e.dialogue.textSpeed,e.dialogue.persistCharacter!==!0&&(delete e.dialogue.characterId,delete e.dialogue.character)));return}e.dialogue||(e.dialogue={});let r=e.dialogue.mode;if(t.dialogue.ui){let{animationsOnly:l,state:f}=gt(t.dialogue.ui,u=>!!u.resourceId);l?e.dialogue.ui={...e.dialogue.ui,...f}: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 n=t.dialogue.append===!0&&r!=="nvl"&&e.dialogue?.mode!=="nvl"&&Array.isArray(t.dialogue.content);t.dialogue.content!==void 0&&Ma({dialogueState:e.dialogue,content:t.dialogue.content,append:n}),U(t.dialogue,"textSpeed")?e.dialogue.textSpeed=t.dialogue.textSpeed:delete e.dialogue.textSpeed;let o=U(t.dialogue,"persistCharacter")?t.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;o?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let i=U(t.dialogue,"characterId"),s=Fa(t.dialogue),c=s!==void 0,a=vo(t.dialogue);if(i?t.dialogue.characterId?e.dialogue.characterId=t.dialogue.characterId:delete e.dialogue.characterId:!o&&!n&&delete e.dialogue.characterId,c?e.dialogue.character=!i&&o&&e.dialogue.character?{...Z(e.dialogue.character),...s}:s:(i||!o&&!n)&&delete e.dialogue.character,a||yo(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 l={content:t.dialogue.content,characterId:e.dialogue.characterId??null};e.dialogue.textSpeed!==void 0&&(l.textSpeed=e.dialogue.textSpeed),e.dialogue.character&&(l.character=Z(e.dialogue.character)),e.dialogue.lines.push(l)}},Wa=(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},Ha=(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}}},Ya=(e,t)=>{if(t.visual){let r=e.visual?.items||[];t.visual.items?.forEach((i,s)=>{Da(i,Eo(r,i,s))});let{hasValidItems:n,processedItems:o}=xo(t.visual.items,ka,r,{hasPatchFn:wo,mergeItemFn:Ta});n?e.visual={items:o}:delete e.visual}else e.visual?.items&&(e.visual.items=e.visual.items.map(r=>r.animations?{...r,animations:{}}:r))},Ga=(e,t)=>{if(!t.character){e.character?.items&&(e.character.items=e.character.items.map(o=>o.animations?{...o,animations:{}}:o));return}let{hasValidItems:r,processedItems:n}=xo(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId,e.character?.items||[]);r?e.character={items:n}:delete e.character},Ka=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},Ja=(e,t)=>{if(t.layout){let{animationsOnly:r,state:n}=gt(t.layout,o=>!!o.resourceId);if(r){e.layout=n;return}if(!t.layout.resourceId){delete e.layout;return}e.layout=t.layout}else e.layout&&delete e.layout},Xa=(e,t)=>{if(t.choice){let{animationsOnly:r,state:n}=gt(t.choice,o=>!!o.resourceId);if(r){e.choice={...e.choice,...n};return}if(!t.choice.resourceId){delete e.choice;return}e.choice=t.choice}else e.choice&&delete e.choice},Qa=(e,t)=>{if(t.form){let{animationsOnly:r,state:n}=gt(t.form,o=>!!o.resourceId);if(r){e.form={...e.form,...n};return}if(!t.form.resourceId){delete e.form;return}e.form=Z(t.form)}else e.form&&delete e.form},Za=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},ec=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},tc=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(r=>{delete e[r]})},We=e=>jt(Ua,[tc,Ba,za,Wa,Ha,Ya,qa,Ga,Ka,Ja,Xa,Qa,Za,ec])(e);var rt=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let r=ce(e,t);return r&&typeof r=="object"?e:r};var rc=Object.freeze({dialogueTextSpeed:{source:"global.dialogueTextSpeed"},autoForwardDelay:{source:"global.autoForwardDelay"},autoForwardSpeed:{source:"global.autoForwardSpeed"},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"}}),Pe=Object.freeze({dialogueTextSpeed:50,autoForwardDelay:1e3,autoForwardSpeed:1,skipUnseenText:!1,skipTransitionsAndAnimations:!1,soundVolume:50,musicVolume:50,muteAll:!1,autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isLineCompleted:!1}),yt=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),Co=Object.freeze({dialogueTextSpeed:"number",autoForwardDelay:"number",autoForwardSpeed:"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"}),Ur=Object.freeze(["dialogueTextSpeed","autoForwardDelay","autoForwardSpeed","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),Br=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),nc=(e,t)=>{if(t.startsWith("global.")){let r=t.slice(7);return e?.global?.[r]}if(t.startsWith("context.runtime.")){let r=t.slice(16),n=Array.isArray(e?.contexts)?e.contexts:[];return n[n.length-1]?.runtime?.[r]}},He=e=>Object.fromEntries(Object.entries(rc).map(([t,r])=>{let n=nc(e,r.source),o=n!==void 0?n:Pe[t]??yt[t];return[t,o]})),Ne=(e,t)=>He(e)[t],So=(e={})=>Object.fromEntries(Ur.map(t=>[t,e[t]??Pe[t]]));var nt=Object.freeze({VISUAL_BEHIND_BACKGROUND:10,BACKGROUND:20,VISUAL_BEHIND_CHARACTER:30,CHARACTER:40,VISUAL_BEHIND_DIALOGUE:50,DIALOGUE:60,VISUAL_BEHIND_CHOICE:70,CHOICE:80,VISUAL_FOREGROUND:90}),_e=Object.freeze({BEHIND_BACKGROUND:nt.VISUAL_BEHIND_BACKGROUND,BEHIND_CHARACTER:nt.VISUAL_BEHIND_CHARACTER,BEHIND_DIALOGUE:nt.VISUAL_BEHIND_DIALOGUE,BEHIND_CHOICE:nt.VISUAL_BEHIND_CHOICE,FOREGROUND:nt.VISUAL_FOREGROUND}),zr=_e.BEHIND_DIALOGUE,qr=Object.freeze(Object.values(_e).sort((e,t)=>e-t));var Re={objectValues:e=>Object.entries(e).map(([t,r])=>({id:t,...r})),formatDate:fo},oc=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,ic=(e,t)=>{let r=String(t||"").trim();if(!r)return;let n=r.match(/[A-Za-z_][A-Za-z0-9_]*|\[\d+\]/g)||[],o=e;for(let i of n){if(i.startsWith("[")){let s=Number(i.slice(1,-1));o=Array.isArray(o)?o[s]:void 0;continue}o=o?.[i]}return o},Ht=(e,t,r)=>{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),c=oc.exec(s);if(c){let[,a,l,f]=c,u=ic(t,f);if(!Array.isArray(u))continue;let d=Array.isArray(i[s])?i[s]:[];u.forEach((p,h)=>{let g={...t,[a]:p};l&&(g[l]=h),d.forEach(y=>{let b=Ht(y,g,r),A=ce(b,g,r);Array.isArray(A)?o.push(...A):o.push(A)})});continue}}o.push(Ht(i,t,r))}return o}if(!e||typeof e!="object")return e;let n={};return Object.entries(e).forEach(([o,i])=>{n[o]=Ht(i,t,r)}),n},sn=({animationType:e,animationId:t,animationPath:r})=>{if(e!==void 0&&!(e==="update"||e==="transition"))throw new Error(`[${r}] Animation "${t}" has unsupported type "${e}". Use "update" or "transition".`)},sc=({id:e,targetId:t,animation:r,playback:n,animationPath:o="animation"})=>{let i=structuredClone(r);if(sn({animationType:i.type,animationId:e,animationPath:o}),delete i.name,delete i.playback,i.id=e,i.targetId=t,n!==void 0){let s=uc(n,`${o}.playback`);s!==void 0&&(i.playback=s)}return i},ac=(e,{animationId:t="animation",animationPath:r="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return sn({animationType:e.type,animationId:t,animationPath:r}),e.type},cc=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},lc=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},uc=(e,t="animation.playback")=>{if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`[${t}] playback must be an object.`);if(e.continuity!==void 0&&e.continuity!=="render"&&e.continuity!=="persistent")throw new Error(`[${t}] playback.continuity must be "render" or "persistent".`);if(e.speed!==void 0&&(typeof e.speed!="number"||!Number.isFinite(e.speed)||e.speed<=0))throw new Error(`[${t}] playback.speed must be a finite number greater than 0.`);let r={};return e.continuity!==void 0&&(r.continuity=e.continuity),e.speed!==void 0&&e.speed!==1&&(r.speed=e.speed),Object.keys(r).length>0?r:void 0},fc=e=>{let t=e?.playback?.speed;return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1},Ye=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Mo=e=>e?.playback?.continuity==="persistent",Jr=e=>Array.isArray(e)?e.map(Jr):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((t,r)=>(t[r]=Jr(e[r]),t),{}),Gt=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let t=structuredClone(e);return t.playback&&(delete t.playback.continuity,t.playback.speed===1&&delete t.playback.speed,Object.keys(t.playback).length===0&&delete t.playback),JSON.stringify(Jr(t))},Uo=(e=[])=>e.filter(t=>Mo(t)).map(t=>structuredClone(t)),Bo=e=>Array.isArray(e?.keyframes)?e.keyframes.reduce((t,r)=>{let n=typeof r?.duration=="number"&&Number.isFinite(r.duration)?r.duration:0;return t+n},0):0,Wr=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((t,r)=>Math.max(t,Bo(r)),0),zo=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max(Wr(e.tween),Wr(e.prev?.tween),Wr(e.next?.tween),Bo(e.mask?.progress))/fc(e),_o=({animationInstances:e,activePersistentAnimations:t})=>{if(!Array.isArray(e)||e.length===0||!Array.isArray(t)||t.length===0)return!1;let r=new Set(t.map(Gt).filter(Boolean));return e.some(n=>{if(!Mo(n))return!1;let o=Gt(n);return o?r.has(o):!1})},we=({animationInstances:e,isLineCompleted:t,skipTransitionsAndAnimations:r,activePersistentAnimations:n,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||r?!1:i&&!t||_o({animationInstances:e,activePersistentAnimations:n})?!0:i?!1:_o({animationInstances:e,activePersistentAnimations:o}),dc=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),pc=(e,t)=>{if(dc(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},hc=({resources:e,animationId:t,playback:r,instanceId:n,targetId:o,animationPath:i="animation"})=>{if(!t||!o)return!1;let s=e?.animations?.[t];return s?sc({id:n,targetId:o,animation:s,playback:r,animationPath:i}):null},mc=(e,{defaultTargetId:t,defaultId:r,animationPath:n="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return sn({animationType:o.type,animationId:o.id??r,animationPath:n}),o.id??=r,o.targetId??=t,o},an=({animations:e,transitions:t,defaultTargetId:r,idPrefix:n,animationPathPrefix:o=n})=>{t.forEach((i,s)=>{e.push(mc(i,{defaultTargetId:r,defaultId:`${n}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},Xr=(e,t)=>{if(e===void 0)return[];if(!Array.isArray(e)||e.some(r=>r===null||typeof r!="object"||Array.isArray(r)))throw new Error(`${t} must be an array of objects`);return e},gc=({content:e,path:t,variables:r})=>Xr(e,t).reduce((n,o)=>{let i=rt(o.text,{variables:r});return n+`${i??""}`.length},0),Ro=(e=[])=>{let t=new Map;for(let r of e)r?.id&&t.set(r.id,(t.get(r.id)??0)+1);return new Set(Array.from(t.entries()).filter(([,r])=>r>1).map(([r])=>r))},qt=(e,t=0,r=new Set)=>{if(!r.has(e?.id))return`character-container-${e.id}`;let n=e?.sprites?.map(({resourceId:o})=>o)||[];return n.length===0?`character-container-${e.id}`:`character-container-${e.id}-${t}-${n.join("-")}`},Wt=(e,t)=>{if(!t.transformId)throw new Error(`Visual item "${t.id}" requires transformId`);let r=e.transforms?.[t.transformId];if(!r)throw new Error(`Transform "${t.transformId}" not found for visual item "${t.id}"`);return r},yc=(e,t={})=>{if(!t?.transformId)return;let r=e.transforms?.[t.transformId];if(!r)throw new Error(`Transform "${t.transformId}" not found for background`);return r},bc=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],Ic=(e={})=>bc.some(t=>Ye(e,t)),qo=(e={},t)=>{if(t){if(e.images?.[t])return"sprite";if(e.videos?.[t])return"video";if(e.spritesheets?.[t])return"spritesheet-animation";if(e.layouts?.[t])return"container"}},Yt=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},Ac=(e={})=>e.textStyles||{},wc=(e={})=>e.images||{},Ec=.5,xc=(e={},t,r)=>{if(t){if(!e.animations?.[t])throw new Error(`Animation '${t}' not found in spritesheet resource '${r}'`);return t}return Object.keys(e.animations??{})[0]},Wo=({id:e,resourceId:t,spritesheet:r,animationName:n,animationSpeed:o,loop:i,transform:s={}}={})=>{let c=xc(r,n,t),a=c?r.animations?.[c]:void 0;if(!a){console.warn(`Spritesheet animation not found: ${t}`);return}return{id:e,type:"spritesheet-animation",...s,width:r.width,height:r.height,src:r.fileId,atlas:r.jsonData,playback:{frames:a.frames,animationSpeed:o??a.animationSpeed??Ec,loop:i??a.loop??!0}}},Ho=({id:e,item:t,resources:r={}}={})=>{let n=r.images?.[t.resourceId];if(n)return{type:"sprite",id:e,src:n.fileId,width:n.width,height:n.height,x:0,y:0};let o=r.spritesheets?.[t.resourceId];if(o)return Wo({id:e,resourceId:t.resourceId,spritesheet:o,animationName:t.animationName,animationSpeed:t.animationSpeed,loop:t.loop,transform:{x:0,y:0}});console.warn(`Character sprite resource not found: ${t.resourceId}`)},vc=(e={})=>e.colors||{},Cc=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,It=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,it=(e,t,r)=>{if(typeof e!="string"||e.length===0)throw new Error(`${r} at "${t}" must resolve to a non-empty string`)},Oo=(e,t,r)=>{if(e===void 0)return 1;if(typeof e!="number"||!Number.isFinite(e))throw new Error(`${t} for text style "${r}" must be a number between 0 and 1`);if(e<0||e>1)throw new Error(`${t} for text style "${r}" must be a number between 0 and 1`);return e},cn=(e,t)=>{if(typeof e!="string"||!Cc.test(e))throw new Error(`${t} must resolve to a hex color`);return e.length===4?`#${e.slice(1).split("").map(r=>r.repeat(2)).join("")}`:e},Lo=(e,t,r)=>{let n=cn(e,r);if(t===1)return n;let o=Number.parseInt(n.slice(1,3),16),i=Number.parseInt(n.slice(3,5),16),s=Number.parseInt(n.slice(5,7),16);return`rgba(${o}, ${i}, ${s}, ${t})`},Sc=(e={},t)=>{let r=Ac(e)?.[t];if(!r)throw new Error(`Text style "${t}" not found`);let n=e.fonts?.[r.fontId];if(!n)throw new Error(`Font "${r.fontId}" not found for text style "${t}"`);let o=e.colors?.[r.colorId];if(!o)throw new Error(`Color "${r.colorId}" not found for text style "${t}"`);let i=Oo(r.colorAlpha,"colorAlpha",t),s={fontFamily:n.fileId,fontSize:r.fontSize??16,fontWeight:r.fontWeight??"400",fontStyle:r.fontStyle??"normal",lineHeight:r.lineHeight??1.2,fill:Lo(o.hex,i,`Color "${r.colorId}" for text style "${t}"`)};if(r.align!==void 0&&(s.align=r.align),r.wordWrap!==void 0&&(s.wordWrap=r.wordWrap),r.breakWords!==void 0&&(s.breakWords=r.breakWords),r.wordWrapWidth!==void 0&&(s.wordWrapWidth=r.wordWrapWidth),r.strokeColorId){let c=e.colors?.[r.strokeColorId];if(!c)throw new Error(`Stroke color "${r.strokeColorId}" not found for text style "${t}"`);let a=Oo(r.strokeAlpha,"strokeAlpha",t);s.strokeColor=Lo(c.hex,a,`Stroke color "${r.strokeColorId}" for text style "${t}"`)}else if(r.strokeAlpha!==void 0)throw new Error(`strokeAlpha for text style "${t}" requires strokeColorId`);return r.strokeWidth!==void 0&&(s.strokeWidth=r.strokeWidth),s},Qr=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>Qr(o,t,`${r}[${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 "${r}". Use textStyleId instead`);let n={};for(let[o,i]of Object.entries(e))o!=="textStyleId"&&(n[o]=Qr(i,t,It(r,o)));return e.textStyleId!==void 0&&(it(e.textStyleId,r,"textStyleId"),n.textStyle=Sc(t,e.textStyleId)),n},ln=(e={},t)=>{let r=vc(e)?.[t];if(!r)throw new Error(`Color "${t}" not found`);return cn(r.hex,`Color "${t}"`)},Yo=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",Hr=(e,t,r)=>{let n=e?.[t];if(!(!n||typeof n!="object"||Array.isArray(n))&&Object.prototype.hasOwnProperty.call(n,"fill"))throw new Error(`Inline ${t}.fill is not allowed in rect layout elements at "${r}". Use ${Yo(`${t}.fill`)} instead`)},_c=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>At(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;let n={};for(let[o,i]of Object.entries(e))o!=="colorId"&&(n[o]=At(i,t,It(r,o)));return e.colorId!==void 0&&(it(e.colorId,r,"colorId"),n.fill=ln(t,e.colorId)),n},At=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>At(o,t,`${r}[${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 "${r}". Use ${Yo("fill")} instead`);Hr(e,"hover",r),Hr(e,"click",r),Hr(e,"rightClick",r)}let n={};for(let[o,i]of Object.entries(e))if(!(e.type==="rect"&&o==="colorId")){if(e.type==="rect"&&(o==="hover"||o==="click"||o==="rightClick")){n[o]=_c(i,t,It(r,o));continue}n[o]=At(i,t,It(r,o))}return e.type==="rect"&&e.colorId!==void 0&&(it(e.colorId,r,"colorId"),n.fill=ln(t,e.colorId)),n},Yr=(e={},t)=>{let r=wc(e)?.[t];return r||null},Go=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",$o=(e,t,r,n)=>{let o=e?.[t];if(!(!o||typeof o!="object"||Array.isArray(o))&&Object.prototype.hasOwnProperty.call(o,n))throw new Error(`Inline ${t}.${n} is not allowed in sprite layout elements at "${r}". Use ${Go(`${t}.${n}`)} instead`)},ko=(e,t,r)=>{let n=e[t];e[t]={...n&&typeof n=="object"&&!Array.isArray(n)?n:{},src:r}},Zr=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>Zr(o,t,`${r}[${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 "${r}". Use ${Go(o)} instead`);$o(e,"hover",r,"src"),$o(e,"click",r,"src")}let n={};for(let[o,i]of Object.entries(e))e.type==="sprite"&&(o==="imageId"||o==="hoverImageId"||o==="clickImageId")||(n[o]=Zr(i,t,It(r,o)));if(e.type==="sprite"&&e.imageId!==void 0){it(e.imageId,r,"imageId");let o=Yr(t,e.imageId),i=o?.fileId??e.imageId;n.src=i,n.width===void 0&&o?.width!==void 0&&(n.width=o.width),n.height===void 0&&o?.height!==void 0&&(n.height=o.height)}return e.type==="sprite"&&e.hoverImageId!==void 0&&(it(e.hoverImageId,r,"hoverImageId"),ko(n,"hover",Yr(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(it(e.clickImageId,r,"clickImageId"),ko(n,"click",Yr(t,e.clickImageId)?.fileId??e.clickImageId)),n},un=(e,t={},r="root")=>Zr(At(Qr(e,t,r),t,r),t,r),Oe=un,Ge=(e=[])=>e.find(t=>t.id==="story"),Rc="#000000",en="bg-cg-background-color",Oc=({resources:e={},background:t={},screen:r})=>t?.colorId===void 0?cn(r?.backgroundColor??Rc,"screen.backgroundColor"):ln(e,t.colorId),Ko=(e={})=>{if(Ye(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},Lc=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},To=(e={},{includeDefaultAlpha:t=!1}={})=>{let r=Ko(e),n=Lc(e),o={};return(t||r!==void 0)&&(o.alpha=r??1),n&&(o.blur=n),o},$c=(e={})=>{if(Ye(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},kc=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},Jo=(e={})=>{let t=$c(e),r=kc(e),n={};return t!==void 0&&(n.alpha=t),r&&(n.blur=r),n},bt=(e={})=>Jo(e),Ve=(e={},t={})=>{let r={x:t.x??e.x,y:t.y??e.y,anchorX:t.anchorX??e.anchorX,anchorY:t.anchorY??e.anchorY,rotation:t.rotation??e.rotation,scaleX:t.scaleX??e.scaleX,scaleY:t.scaleY??e.scaleY},n=t.originX??e.originX,o=t.originY??e.originY;return n!==void 0&&(r.originX=n),o!==void 0&&(r.originY=o),r},Tc=["id","type","resourceId","transformId","x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY","layer","opacity","blur","animations"],fn=(e={})=>e.text&&Ye(e.text,"content")&&Ye(e.text,"textStyleId"),Do=(e={})=>{if(e.resourceId)return e.resourceId;if(fn(e))return"text"},Dc=e=>{if(e.text){if(e.resourceId)throw new Error(`Visual item "${e.id}" cannot define both resourceId and text`);if(!fn(e))throw new Error(`Visual item "${e.id}" text requires content and textStyleId`);for(let t of Tc)if(Ye(e.text,t))throw new Error(`Visual item "${e.id}" text.${t} is reserved for the visual item`)}},Pc=({resources:e,background:t,screen:r={width:1920,height:1080},includeOpacity:n=!1})=>{let o={id:en,type:"rect",x:0,y:0,width:r?.width??1920,height:r?.height??1080,fill:Oc({resources:e,background:t,screen:r})};if(n){let i=Ko(t);i!==void 0&&(o.alpha=i)}return o},Nc=(e={},t)=>t?!!(e.images?.[t]||e.videos?.[t]||e.spritesheets?.[t]||e.layouts?.[t]):!1,Po=({resources:e={},resourceId:t,colorId:r})=>{let n=qo(e,t);return t&&(n||r===void 0)?{resourceId:t,targetId:Yt({resourceId:t,kind:n})}:r!==void 0?{resourceId:en,targetId:en}:{resourceId:void 0,targetId:void 0}},Xo=100,Jt=Xo,Qo=(e,t)=>e*t/Xo,Vc=(e={},t=Jt)=>e?.muteAll?0:Qo(t,e?.soundVolume??Pe.soundVolume),jc=(e={},t=Jt)=>e?.muteAll?0:Qo(t,e?.musicVolume??Pe.musicVolume),Fc=({item:e,index:t}={})=>`sfx:${t}:${e?.resourceId}`,Ee=({variables:e,runtime:t,saveSlots:r=[],dialogueState:n,includeInactiveAdvDialogue:o=!1,isLineCompleted:i,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:f,confirmDialog:u,form:d,historyDialogue:p=[],characters:h={},dialogueUIHidden:g,skipOnlyViewedLines:y,skipTransitionsAndAnimations:b}={})=>{let A={dialogueTextSpeed:t?.dialogueTextSpeed??50,autoForwardDelay:t?.autoForwardDelay??1e3,autoForwardSpeed:t?.autoForwardSpeed??1,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??c??!1,dialogueUIHidden:t?.dialogueUIHidden??g??!1,isLineCompleted:t?.isLineCompleted??i??!1},x=qc({dialogueState:n,includeInactiveAdvDialogue:o,characters:h,variables:e,runtime:A}),S={variables:e,runtime:A,saveSlots:r,isChoiceVisible:a,isFormVisible:l,canRollback:f,confirmDialog:u,form:d,historyDialogue:p,characters:h};return x&&(S.dialogue=x,S.dialogueLines=x.lines),S},No=100,Kt=(e,t)=>{if(Array.isArray(e))return e.map(n=>Kt(n,t));if(!e||typeof e!="object")return e;let r={...e};return Object.keys(r).forEach(n=>{r[n]=Kt(r[n],t)}),r.type==="text-revealing"?t(r):r},Mc=e=>Kt(e,t=>({...t,revealEffect:"none"})),Uc=e=>Kt(e,t=>{let r=Number(t.speed??t.displaySpeed),n=Number.isFinite(r)?Math.max(r,No):No;return{...t,speed:n,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:n}:{}}}),je=(e,{isLineCompleted:t=!1,skipMode:r=!1,skipTransitionsAndAnimations:n=!1}={})=>t||n?Mc(e):r?Uc(e):e,Zo=({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:{}}}}),tn=e=>{if(Array.isArray(e))return e.map(tn);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=tn(s);let r=t.click?.payload;if(!r||typeof r!="object"||Array.isArray(r))return t;let n=r.actions,o=n&&typeof n=="object"&&!Array.isArray(n)&&Object.prototype.hasOwnProperty.call(n,"nextLine")?{...n.nextLine,bypassChoice:!0}:void 0;return{...t,click:{...t.click,payload:{...r,bypassChoice:!0,...o?{actions:{...n,nextLine:o}}:{}}}}},Bc=new Set(["click","change","submit","focusEvent","blurEvent","selectionChange","compositionStart","compositionUpdate","compositionEnd"]),Vo="submit",Gr=(e,t,r={})=>{let n=e?.payload&&typeof e.payload=="object"&&!Array.isArray(e.payload)?e.payload:{},o=n.actions&&typeof n.actions=="object"?n.actions:{},i=r.replaceActions===!0?t:{...o,...t};return{...e||{},payload:{...n,actions:i}}},rn=(e,t,r={})=>{if(Array.isArray(e))return e.map(l=>rn(l,t,r));if(!e||typeof e!="object")return e;let n=typeof e.type=="string",o=n&&e.formRole===Vo,i=n&&r.submitRoleAncestor,s=o||i?{submitRoleAncestor:!0}:{},c={};for(let[l,f]of Object.entries(e))c[l]=rn(f,t,l==="children"?s:{});let a=c;if(a.type==="input"&&typeof a.field=="string"){let l=t?.fields?.[a.field];if(l){let f={updateFormField:{formKey:t.key,field:l.id,value:"_event.value"}};a={...a,value:l.value,placeholder:a.placeholder===void 0?l.placeholder:a.placeholder,multiline:a.multiline===void 0?l.multiline:a.multiline,...a.maxLength===void 0&&l.maxLength!==void 0?{maxLength:l.maxLength}:{},change:Gr(a.change,f),submit:Gr(a.submit,t.submitActions)}}}return a.formRole===Vo||i?{...a,click:Gr(a.click,t.submitActions,{replaceActions:!0})}:a},nn=(e,t)=>{if(Array.isArray(e))return e.map(n=>nn(n,t));if(!e||typeof e!="object")return e;let r={};for(let[n,o]of Object.entries(e))r[n]=nn(o,t);for(let n of Bc){let o=r[n]?.payload;!o||typeof o!="object"||Array.isArray(o)||(r[n]={...r[n],payload:{...o,_interactionSource:"form"}})}return r},on=({characterId:e,character:t,characterName:r,characters:n={},variables:o={}}={})=>{let i=e?n?.[e]:void 0,s=Ft({characterId:e,character:t,characterName:r,characters:n,variables:o});return{...i||{},...t||{},name:s}},ei=(e=[],t={},r={})=>e.map(n=>{let o=on({characterId:n.characterId,character:n.character,characterName:n.characterName,characters:t,variables:r}),i=typeof n.text=="string"?n.text:Array.isArray(n.content)?n.content.map(s=>s?.text??"").join(""):"";return{...n,text:i,character:o,characterName:o.name}}),zc=e=>!(!e||e.mode==="adv"&&e.content===void 0),qc=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:r={},variables:n,runtime:o}={})=>{if(!t&&!zc(e))return;let i=e.content===void 0?[{text:""}]:Xr(e.content,"dialogue.content"),s=e.content===void 0?0:gc({content:e.initialRevealedContent,path:"dialogue.initialRevealedContent",variables:n}),c=o?.dialogueTextSpeed??Pe.dialogueTextSpeed,a=e.textSpeed??c,l=(e.lines||[]).map((u,d)=>{let p=Xr(u.content,`dialogue.lines[${d}].content`),h=on({characterId:u.characterId,character:u.character,characterName:u.characterName,characters:r,variables:n});return{...u,textSpeed:u.textSpeed??c,content:p.map(g=>({...g,text:rt(g.text,{variables:n})})),character:h,characterName:h.name}}),f=on({characterId:e.characterId,character:e.character,characters:r,variables:n});return{characterId:e.characterId,persistCharacter:e.persistCharacter,character:f,textSpeed:a,content:i.map(u=>({...u,text:rt(u.text,{variables:n})})),initialRevealedCharacters:s,lines:l}},ti=({container:e,resources:t,templateData:r,isLineCompleted:n=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=ce(e,r,{functions:Re});return Oe(je(s,{isLineCompleted:n,skipMode:o,skipTransitionsAndAnimations:i}),t)},Kr=(e,t={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(t),jo=({renderStateKeyboard:e,keyboard:t,phase:r})=>{!t||typeof t!="object"||Array.isArray(t)||Object.entries(t).forEach(([n,o])=>{let i=e[n]??{},s=r==="keydown"?o?.keydown:o?.keyup;if(r==="keydown"&&s&&typeof s=="object"){e[n]={...i,keydown:{payload:Kr(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[n].keyup={payload:Kr(o.keyup)});return}e[n]={...i,[r]:{payload:Kr(o)}}})},Wc=(e={},t={})=>{let r={};return jo({renderStateKeyboard:r,keyboard:e,phase:"keydown"}),jo({renderStateKeyboard:r,keyboard:t,phase:"keyup"}),Object.keys(r).length>0?r:void 0},Le=({animationsDef:e,resources:t,previousResourceId:r,currentResourceId:n,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:c})=>{if(!e)return[];let a=[],l=({instanceId:b,targetId:A})=>{let x=hc({resources:t,animationId:p,playback:h,instanceId:b,targetId:A,animationPath:s});x&&a.push(x)},f=r!=null&&r!==!1,u=n!=null&&n!==!1,d=o&&i&&o===i;pc(e,s);let p=cc(e),h=lc(e),g=t?.animations?.[p],y=ac(g,{animationId:p,animationPath:s});if(y==="update")return u&&i?l({instanceId:`${c}-animation-update`,targetId:i}):f&&o&&l({instanceId:`${c}-animation-update`,targetId:o}),a;if(y==="transition"){let b=`${c}-animation-transition`,A=h?.continuity==="persistent"?b:`${c}-animation-in`;if(f&&u&&d)return l({instanceId:b,targetId:i}),a;f&&l({instanceId:`${c}-animation-out`,targetId:o}),u&&l({instanceId:A,targetId:i})}return a},Hc=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),Yc=(e,{presentationState:t,previousPresentationState:r,currentLineActions:n,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:c,variables:a,runtime:l,activePersistentAnimations:f,restoredPersistentAnimations:u,autoMode:d,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:b,saveSlots:A=[]})=>{let{elements:x,animations:S}=e;if(t.background){let P=n===void 0?!0:Ye(n?.background??{},"animations"),k=x.find(oe=>oe.id==="story");if(!k)return e;let w=yc(o,t.background),j=w||Ic(t.background),M=r?.background?.resourceId,ee=r?.background?.colorId,N=t.background.resourceId??(t.background.animations?M:void 0),q=t.background.colorId??(t.background.animations?ee:void 0),W=Nc(o,N),te={...t.background,colorId:q};if((q!==void 0||W)&&k.children.push(Pc({resources:o,background:te,screen:i,includeOpacity:!W})),N){let{images:oe={},videos:re={},spritesheets:K={}}=o,ie=qo(o,N),se;if(ie==="sprite"?se=oe[N]:ie==="video"?se=re[N]:ie==="spritesheet-animation"&&(se=K[N]),se){let v=ie==="video",_=ie==="spritesheet-animation",V={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...w},J={...To(t.background,{includeDefaultAlpha:!0}),...Ve(V,t.background)},z;_?z=Wo({id:Yt({resourceId:N,kind:ie}),resourceId:N,spritesheet:se,animationName:t.background.animationName,animationSpeed:t.background.animationSpeed,loop:t.background.loop,transform:J}):z={id:Yt({resourceId:N,kind:ie}),type:v?"video":"sprite",src:se.fileId,width:se.width,height:se.height,...J},v&&(z.loop=t.background.loop??!1,z.volume=se.volume??50),z&&k.children.push(z)}}if(N){let{layouts:oe={}}=o,re=oe[N];if(re){let K={id:Yt({resourceId:N,kind:"container"}),type:"container",children:re.elements,...To(t.background)};j&&Object.assign(K,Ve({x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...w},t.background));let ie=ce(K,Ee({variables:a,runtime:l,saveSlots:A,dialogueState:t.dialogue,isLineCompleted:s,autoMode:d,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:b,characters:o.characters||{},skipTransitionsAndAnimations:c}),{functions:Re});k.children.push(Oe(je(ie,{isLineCompleted:s,skipMode:p,skipTransitionsAndAnimations:c}),o))}}let xe=Po({resources:o,resourceId:M,colorId:ee}),Y=Po({resources:o,resourceId:N,colorId:q}),G=Le({animationsDef:t.background.animations,resources:o,previousResourceId:xe.resourceId,currentResourceId:Y.resourceId,previousTargetId:xe.targetId,currentTargetId:Y.targetId,animationPath:"background.animations",idPrefix:"bg-cg"});we({animationInstances:G,isLineCompleted:s,skipTransitionsAndAnimations:c,activePersistentAnimations:f,restoredPersistentAnimations:u,isAuthoredOnCurrentLine:P})&&S.push(...G)}return e},Gc=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:c,animations:a}=e;if(t.character&&n){let l=c.find(h=>h.id==="story");if(!l)return e;let f=t.character.items||[],u=r?.character?.items||[],d=Ro(f),p=Ro(u);for(let h=0;h<f.length;h++){let g=f[h],{transformId:y,sprites:b}=g,A=u.find(N=>N.id===g.id),x=u.findIndex(N=>N.id===g.id),S=A?.sprites&&A.sprites.length>0,P=b&&b.length>0,k=x>=0?qt(A,x,p):void 0,w=Le({animationsDef:g.animations,resources:n,previousResourceId:k,currentResourceId:P?qt(g,h,d):void 0,previousTargetId:k,currentTargetId:P?qt(g,h,d):void 0,animationPath:`character.items[${h}].animations`,idPrefix:"character"});if(g.animations&&!b&&!y&&S&&we({animationInstances:w,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){a.push(...w);continue}if(g.animations&&!b&&!y)continue;if(!b||b.length===0||!y){console.warn("Character item missing sprites or transformId:",g);continue}let j=qt(g,h,d),M=n.transforms[y];if(!M){console.warn("Transform not found:",y);continue}let ee={type:"container",id:j,...Ve(M,g),...bt(g),children:[]};for(let N of b){let q=Ho({id:`${j}-${N.id}`,item:N,resources:n});q&&ee.children.push(q)}l.children.push(ee),we({animationInstances:w,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...w)}}return e},ri=(e,t)=>{if(!qr.includes(e))throw new Error(`${t} must be one of: ${qr.join(", ")}.`)},Kc=(e,t)=>{let r=!!e.resourceId||fn(e),n=e.layer??(r?void 0:t?.layer)??zr;return ri(n,`Visual item "${e.id}" layer`),n},Jc=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,runtime:c,activePersistentAnimations:a,autoMode:l,skipMode:f,isChoiceVisible:u,isFormVisible:d,canRollback:p,form:h,saveSlots:g=[],visualLayer:y})=>{let{elements:b,animations:A}=e;if(t.visual&&n){let x=b.find(w=>w.id==="story");if(!x)return e;let S=t.visual.items,P=r?.visual?.items||[],k=Ee({variables:s,runtime:c,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:o,autoMode:l,skipMode:f,isChoiceVisible:u,isFormVisible:d,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:i});y!==void 0&&ri(y,"visualLayer");for(let w of S){let j=P.find(W=>W.id===w.id),M=Kc(w,j);if(y!==void 0&&M!==y)continue;if(Dc(w),w.text){let W=Wt(n,w),te={...structuredClone(w.text),id:`visual-${w.id}`,type:"text",...Ve(W,w)};Object.assign(te,bt(w)),x.children.push(Oe(ce(te,k,{functions:Re}),n))}if(w.resourceId){let{images:W={},videos:te={},spritesheets:xe={}}=n,Y=xe[w.resourceId];if(Y){let G=Wt(n,w),oe=w.animationName;if(oe){let re=Y.animations?.[oe];if(!re)throw new Error(`Animation '${oe}' not found in spritesheet resource '${w.resourceId}'`);let K=bt(w),ie={id:`visual-${w.id}`,type:"spritesheet-animation",...Ve(G,w),width:w.width??Y.width,height:w.height??Y.height,alpha:K.alpha??w.alpha??1,src:Y.fileId,atlas:Y.jsonData,playback:{frames:re.frames,animationSpeed:w.animationSpeed??re.animationSpeed??.5,loop:w.loop??re.loop??!0}};K.blur&&(ie.blur=K.blur),x.children.push(structuredClone(ie))}}else{let G=W[w.resourceId]||te[w.resourceId];if(G){let oe=te[w.resourceId]!==void 0,re=Wt(n,w),K={id:`visual-${w.id}`,type:oe?"video":"sprite",src:G.fileId,width:G.width,height:G.height,...Ve(re,w)};Object.assign(K,bt(w)),oe&&(K.loop=G.loop??!1,K.volume=G.volume??50),x.children.push(K)}}}if(w.resourceId){let{layouts:W={}}=n,te=W[w.resourceId];if(te){let xe=Wt(n,w),Y={id:`visual-${w.id}`,type:"container",children:structuredClone(te.elements),...Ve(xe,w)};Object.assign(Y,bt(w));let G=ce(Y,k,{functions:Re});x.children.push(Oe(je(G,{isLineCompleted:o,skipMode:f,skipTransitionsAndAnimations:i}),n))}}let ee=Do(j),N=Do(w),q=Le({animationsDef:w.animations,resources:n,previousResourceId:ee,currentResourceId:N,previousTargetId:ee?`visual-${w.id}`:void 0,currentTargetId:N?`visual-${w.id}`:void 0,animationPath:`visual.items[${w.id}].animations`,idPrefix:w.id});we({animationInstances:q,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:a})&&A.push(...q)}}return e},ot="dialogue-character-sprite",Fo=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,Xc=(e,{presentationState:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:c}=e,a=Ge(e.elements);if(!a)return e;let l=t.dialogue?.character?.sprite,f=r?.dialogue?.character?.sprite,u=Fo(l),d=Fo(f),p=Le({animationsDef:l?.animations,resources:n,previousResourceId:d?ot:void 0,currentResourceId:u?ot:void 0,previousTargetId:d?ot:void 0,currentTargetId:u?ot:void 0,animationPath:"dialogue.character.sprite.animations",idPrefix:"dialogue-character-sprite"});if(!u)return l?.animations&&d&&we({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...p),e;let h=n.transforms?.[l.transformId];if(!h)return console.warn("Transform not found:",l.transformId),e;let g={type:"container",id:ot,...Ve(h),children:[]};for(let y of l.items){let b=Ho({id:`${ot}-${y.id}`,item:y,resources:n});b&&g.children.push(b)}return a.children.push(g),we({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...p),e},Qc=(e,{presentationState:t,previousPresentationState:r,resources:n={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:c,isFormVisible:a,canRollback:l,form:f,skipOnlyViewedLines:u,isLineCompleted:d,skipTransitionsAndAnimations:p,variables:h,runtime:g,activePersistentAnimations:y,saveSlots:b=[]})=>{let{elements:A,animations:x}=e;if(!t.dialogue||o)return e;let S=A.find(k=>k.id==="story");if(!S)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:k={}}=n,w=k[t.dialogue.ui.resourceId];if(w){let j={elements:w.elements},M=Ee({variables:h,runtime:g,saveSlots:b,dialogueState:t.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:d,autoMode:i,skipMode:s,isChoiceVisible:c,isFormVisible:a,canRollback:l,form:f,characters:n.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:u,skipTransitionsAndAnimations:p}),ee={functions:Re},N=Ht(j,M,ee),q=ce(N,M,ee),W=Oe(je(q?.elements,{isLineCompleted:d,skipMode:s,skipTransitionsAndAnimations:p}),n);if(Array.isArray(W))for(let te of W)S.children.push(te);else W&&S.children.push(W)}}Xc(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:d,skipTransitionsAndAnimations:p,activePersistentAnimations:y});let P=Le({animationsDef:t.dialogue.ui?.animations,resources:n,previousResourceId:r?.dialogue?.ui?.resourceId,currentResourceId:t.dialogue.ui?.resourceId,previousTargetId:r?.dialogue?.ui?.resourceId?"dialogue-container":void 0,currentTargetId:t.dialogue.ui?.resourceId?"dialogue-container":void 0,animationPath:"dialogue.ui.animations",idPrefix:"dialogue-ui"});return we({animationInstances:P,isLineCompleted:d,skipTransitionsAndAnimations:p,activePersistentAnimations:y})&&x.push(...P),e},Zc=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:c,runtime:a,autoMode:l,skipMode:f,isChoiceVisible:u,isFormVisible:d,canRollback:p,form:h,activePersistentAnimations:g,saveSlots:y=[]})=>{let{elements:b,animations:A}=e;if(t.choice&&n){let x=Ge(b);if(!x)return e;let S=n?.layouts[t.choice.resourceId];if(S&&S.elements){let k={elements:S.elements},w=ce(k,{...Ee({variables:c,runtime:a,saveSlots:y,dialogueState:t.dialogue,isLineCompleted:i,autoMode:l,skipMode:f,isChoiceVisible:u??!!t.choice,isFormVisible:d,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}},{functions:Re}),j=tn(Oe(je(w?.elements,{isLineCompleted:i,skipMode:f,skipTransitionsAndAnimations:s}),n));if(Array.isArray(j))for(let M of j)x.children.push(M);else j&&x.children.push(j)}let P=Le({animationsDef:t.choice.animations,resources:n,previousResourceId:r?.choice?.resourceId,currentResourceId:t.choice.resourceId,previousTargetId:r?.choice?.resourceId?"choice-container":void 0,currentTargetId:t.choice.resourceId?"choice-container":void 0,animationPath:"choice.animations",idPrefix:"choice"});we({animationInstances:P,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:g})&&A.push(...P)}return e},el=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:c,runtime:a,autoMode:l,skipMode:f,isChoiceVisible:u,isFormVisible:d,canRollback:p,activePersistentAnimations:h,saveSlots:g=[],form:y})=>{let{elements:b,animations:A}=e;if(!y?.resourceId||!n)return e;let x=Ge(b);if(!x)return e;let S=n?.layouts?.[y.resourceId];if(!S)return console.warn(`Form layout not found: ${y.resourceId}`),e;let P={id:"form-container",type:"container",x:0,y:0,children:S.elements||[]},k={...Ee({variables:c,runtime:a,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:i,autoMode:l,skipMode:f,isChoiceVisible:u,isFormVisible:d,canRollback:p,characters:n.characters||{},skipTransitionsAndAnimations:s,form:y}),form:y},w=ce(P,k,{functions:Re}),j=nn(Oe(je(rn(w,y),{isLineCompleted:i,skipMode:f,skipTransitionsAndAnimations:s}),n),y);j&&x.children.push(j);let M=Le({animationsDef:y.animations,resources:n,previousResourceId:r?.form?.resourceId,currentResourceId:y.resourceId,previousTargetId:r?.form?.resourceId?"form-container":void 0,currentTargetId:y.resourceId?"form-container":void 0,animationPath:"form.animations",idPrefix:"form"});return we({animationInstances:M,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:h})&&A.push(...M),e},tl=(e,{presentationState:t,resources:r={},variables:n,runtime:o,isLineCompleted:i,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:f,form:u,saveSlots:d=[],skipTransitionsAndAnimations:p})=>{if(!t.control?.resourceId)return e;let h=r.controls?.[t.control.resourceId];if(!h)return e;let g=Wc(h.keyboard,h.keyup);if(g&&Object.keys(g).length>0&&(e.global.keyboard=g),!Array.isArray(h.elements)||h.elements.length===0)return e;let y=Ge(e.elements);if(!y)return e;let b={id:`control-${t.control.resourceId}`,type:"container",x:0,y:0,children:h.elements};return y.children.push(ti({container:b,resources:r,templateData:Ee({variables:n,runtime:o,saveSlots:d,dialogueState:t.dialogue,isLineCompleted:i,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:f,form:u,characters:r.characters||{},skipTransitionsAndAnimations:p}),isLineCompleted:i,skipMode:c,skipTransitionsAndAnimations:p})),e},rl=(e,{presentationState:t,resources:r,runtime:n,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&r){if(!Ge(i))return e;let a=r.sounds[t.bgm.resourceId];if(!a)return e;let l=Ee({variables:o,runtime:n}).runtime;s.push({id:"bgm",type:"sound",src:a.fileId,loop:t.bgm.loop??!0,volume:jc(l,t.bgm.volume??a.volume??Jt),startDelayMs:t.bgm.startDelayMs??null})}return e},nl=(e,{presentationState:t,resources:r,runtime:n})=>{let{audio:o}=e;if(t.sfx&&r){let i=t.sfx.items;for(let[s,c]of i.entries()){let a=r.sounds?.[c.resourceId];a&&o.push({id:Fc({item:c,index:s}),type:"sound",src:a.fileId,loop:c.loop??a.loop??!1,volume:Vc(n,c.volume??a.volume??Jt),startDelayMs:c.startDelayMs??a.startDelayMs??null})}}return e},ol=(e,t,r)=>{if(!(!t||!r))return e?.voices?.[t]?.[r]},il=(e={},t={})=>t.muteAll?0:e.volume??t.soundVolume??50,sl=(e,{presentationState:t,resources:r,currentSceneId:n,runtime:o,variables:i})=>{let{audio:s}=e;if(!t?.voice)return e;let c=t.voice,{resourceId:a,loop:l,startDelayMs:f}=c,u=ol(r,n,a);if(!u)return e;let d=Ee({variables:i,runtime:o}).runtime;return s.push({id:`voice-${n}-${a}`,type:"sound",src:u.fileId,volume:il(c,d),loop:l??!1,startDelayMs:f??null}),e},al=(e,{presentationState:t,previousPresentationState:r,resources:n={},variables:o,runtime:i,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:f,form:u,saveSlots:d=[],isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})=>{let{elements:y,animations:b}=e;if(t.layout){let P=Ge(y);if(!P)return e;let k=n.layouts[t.layout.resourceId];if(!k)return e;Array.isArray(k.transitions)&&!p&&!h&&an({animations:b,transitions:k.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let w={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:k.elements||[]};P.children.push(ti({container:w,resources:n,templateData:Ee({variables:o,runtime:i,saveSlots:d,dialogueState:t.dialogue,isLineCompleted:p,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:f,form:u,characters:n.characters||{},skipTransitionsAndAnimations:h}),isLineCompleted:p,skipMode:c,skipTransitionsAndAnimations:h}))}let A=r?.layout?.resourceId,x=t.layout?.resourceId,S=Le({animationsDef:t.layout?.animations,resources:n,previousResourceId:A,currentResourceId:x,previousTargetId:A?`layout-${A}`:void 0,currentTargetId:x?`layout-${x}`:void 0,animationPath:"layout.animations",idPrefix:"layout"});return we({animationInstances:S,isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})&&b.push(...S),e},cl=(e,{currentLineActions:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:c}=e,a=t?.screen?.animations;if(!a)return e;let l=r!=null,f=Le({animationsDef:a,resources:n,previousResourceId:l?"story":void 0,currentResourceId:"story",previousTargetId:l?"story":void 0,currentTargetId:"story",animationPath:"screen.animations",idPrefix:"screen"});return we({animationInstances:f,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...f),e},ll=(e,{presentationState:t})=>{let r=Ge(e.elements);return!r||!t?.screen||Object.assign(r,Jo(t.screen)),e},ul=(e,{presentationState:t,resources:r={},variables:n,runtime:o,autoMode:i,skipMode:s,isChoiceVisible:c,isFormVisible:a,canRollback:l,form:f,overlayStack:u=[],dialogueHistory:d=[],saveSlots:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:b,animations:A}=e;return u&&u.length>0&&u.forEach((x,S)=>{let P=r.layouts[x.resourceId];if(!P){console.warn(`Overlay layout not found: ${x.resourceId}`);return}Array.isArray(P.transitions)&&(y||an({animations:A,transitions:P.transitions,defaultTargetId:`overlayStack-${S}`,idPrefix:`overlayStack-${S}`,animationPathPrefix:`overlayStack[${S}]`}));let k={id:`overlayStack-${S}`,type:"container",x:0,y:0,children:[Zo({id:`overlayStack-${S}-blocker`,screen:h}),...P.elements||[]]},w=ei(d,r.characters,n),j=Ee({variables:n,runtime:o,saveSlots:p,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:i,skipMode:s,isChoiceVisible:c,isFormVisible:a,canRollback:l,form:f,historyDialogue:w,characters:r.characters||{},skipTransitionsAndAnimations:y}),M=ce(k,j,{functions:Re}),[ee,...N]=M.children||[],q=Oe(je({...M,children:N},{isLineCompleted:g,skipMode:s,skipTransitionsAndAnimations:y}),r);b.push({...q,children:ee?[ee,...q.children||[]]:q.children})}),e},fl=(e,{presentationState:t,resources:r={},variables:n,runtime:o,saveSlots:i=[],autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:f,form:u,confirmDialog:d,dialogueHistory:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:b,animations:A}=e;if(!d?.resourceId)return e;let x=r.layouts?.[d.resourceId];if(!x)return console.warn(`ConfirmDialog layout not found: ${d.resourceId}`),e;Array.isArray(x.transitions)&&!y&&an({animations:A,transitions:x.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let S={id:"confirmDialog",type:"container",x:0,y:0,children:[Zo({id:"confirmDialog-blocker",screen:h}),...x.elements||[]]},P=ei(p,r.characters,n),k=ce(S,Ee({variables:n,runtime:o,saveSlots:i,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:f,form:u,confirmDialog:d,historyDialogue:P,characters:r.characters||{},skipTransitionsAndAnimations:y}),{functions:Re}),[w,...j]=k.children||[],M=Oe(je({...k,children:j},{isLineCompleted:g,skipMode:c,skipTransitionsAndAnimations:y}),r);return b.push({...M,children:w?[w,...M.children||[]]:M.children}),e},wt=e=>(t,r)=>Jc(t,{...r,visualLayer:e}),dl=wt(_e.BEHIND_BACKGROUND),pl=wt(_e.BEHIND_CHARACTER),hl=wt(_e.BEHIND_DIALOGUE),ml=wt(_e.BEHIND_CHOICE),gl=wt(_e.FOREGROUND),ni=e=>jt(Hc,[tl,dl,Yc,pl,Gc,hl,Qc,ml,Zc,el,al,gl,ll,cl,rl,nl,sl,ul,fl])(e);function oi(e,t=""){let r=[],n=e.length,o=0,i=0,s=-1,c=()=>{let a=0,l=0,f;do f=parseInt(e[o++],36),a+=(f&15)<<l,l+=4;while(f&16);return a};for(;o<n;){let a=s+1+c();s=a+c(),r.push([a,s,t?parseInt(t[i++],36):0])}return r}function ii(e,t,r){let n=0,o=t.length-1;for(;n<=o;){let i=n+o>>>1,s=r[i];if(e<t[i])o=i-1;else if(e>s>>>5)n=i+1;else return s&31}return 0}var si="090001000h1v5g2903000hl2v6jh16ng1s210111110o35aa10u2k1g10l6600152113h2010u1q1r5aq3890o13181214r22k3158q2n1000v100h1k20000001207030001160721k171001h1j11610332010010321210090411021c1c02100o301201412230u1130b100h1j116111420120411001100k11l10051001h1j11611142011000321210072411021d0g10r3000000132120090o200200g1j11f2012031213711271t1001o301001000001121371b1f0c101h1l2011001031212000080a1t1001m40400102101600i11t301006c7i601008b6p41r10101041h3d0004115a1j290p3q223000511010100g1501010302003172030c0010016000e0i6v50n40n5tl12ir33s12t11u11cj30100060700010a90t220000l71i20m7203010241000502rd101004k300000006101027050920g3t22bk1300616g209030207u18c1000t10003010501b2o20000102000004g37070101o921c000640602001mcv3rg20000001o16d0c0m1fg6g2h30m10q55f1vm11c0ma0p1a42nc0ne1a090q3314902021204020112030318250105bb1201110i1021i15101131502141b15120511011k1155132040202510201010603060a1f02040104210b1g3290e0e0kn11vs12j11j3040pp12t80g6v1vmo7319g21g51gh103040n11010040j51i3f01q1h1d0m27p1a0000cs13200523j200010301010100v140018a4q2501010101c08000i1f12601011g3012215110u1a0001015000pcq181000100011000iji5fvc0u91g5bhg20ie0l94lo6002115303121s12240la1tj23h44tj11t45m4ah33q700000l3ep2021a200t220301012040a0i320j2040007f00100r20c100g3208000011531000s520201036020t900207l1101n311000000321210090a12634b910201l22001051020120011020000e1i520701020000n10h5001050000010000010001re0010323010001r11i520701000001q6000000107l600000230004gg12080001lc62027111n1000411230000000000t820321030030r10090n205001380800501020n2050c0001mc00002000000nc006150000i5l1100600010001q753011160000i441111000000rl11019100000c1h201043102n10ltk1f006eoss2b0202gs94r36si2033ku101m373h50b1rqs4113sli1t22m1uh2435070726u13k92rr7m34h380e0m141egl561g1261114k60ga6nn10t33sv13uf1jf0207150qt16t66pr60n23k6bf1f0e1l29g71c1e029j1n30p11ea0k1028139m16rb2v621122i52213040tf1u3b51n17127c0232041d120819052c28220104060306l5g3l4572g130152cqdl2c3o37a5o27u11c32d9m2cu2191obo57eh9gg1tv3",ai="262122424333333393233393339333333333393393bf3b3b3b3b3f3f3bffff33b3bb33ff3f33b3b3333333bffff3b33bb33f33bffff33b3bb33ff3f33b3bbb333b3ff33b333f33b3b3b3b3333b3bf33b3bb39333b33b33b3b3b333b333333b3b33333f3b33b3ffb3f3fff3f3b33f35dc33333f3b3b3b33323333b3bb3b33b3fb3b3333b33333bff3b3f33bfb3b3ff3b3b3b3b3b333b333b3323e22442344444444444444444444444444444444444444444444444444444444444444444444444444444443333333333b3b3bb33333b353bff3b3b3b3f3ff3b3b333bfff3f33333fb3bb3fb3b3bb33232333f333fff333333333b3b3333bb3b39393f3b3fbf33bb3b393b3b3b3333b33b33b3bbb33b33ffff3b3333bb3933b3b3b333b3b3b3b3b33b3b3b33b3b3b33b3b33b33b3b3b3fffff3bb39b9b3b33b3bf3f3b33f3b3f93b33b3b3bb33b33b3b3b3333393b3b3b33b39bffb3b332333b333dd3b3333233332333333333333333333333333333444444444444a4444444444444344444444444444444444444444444444444444444444",ci="0001000000010010000000100000000000000000000000000001000000010014000100000001001000010101100101100000000000000000000100000001111000010000000110101001110111111111000100000021001000010000000100100001000000011010000100000001111000013000000100140001000000010010";var li=65535,dn=40960,Xt=126976,di=new Uint8Array(12288),pi=new Uint8Array(3072),hi=new Uint8Array(2816),mi,gi;{let e=(o,i,s,c,a)=>{let l=i+o.length-1;for(let f=s<i?i:s,u=c>l?l:c;f<=u;f++)o[f-i]=a},t=new Uint32Array(320),r=new Uint32Array(320),n=0;for(let[o,i,s]of oi(si,ai))e(di,0,o,i,s),e(pi,dn,o,i,s),e(hi,Xt,o,i,s),i>=65040&&!(o>=Xt&&i<=129791)&&(t[n]=o,r[n++]=i<<5|s);mi=t.slice(0,n),gi=r.slice(0,n)}function ui(e){return e<12288?di[e]:e<dn?e<12336?e>=12330?3:0:e<12443?e===12336||e===12349?4:e>=12441?3:0:e===12951||e===12953?4:0:e<44032?pi[e-dn]:e<55204?(e-44032)%28?8:7:e<57344?e<=55238?e>=55216?13:0:e>=55243&&e<=55291?12:0:e<65024?e===64286?3:0:e<65040?3:e>=Xt&&e<129792?hi[e-Xt]:e>=917504?e>921599?0:e>=917536&&e<917632||e>=917760&&e<918e3?3:2:ii(e,mi,gi)}var yi=Uint8Array.from(ci,Number);function yl(e){return e===2381||e===2509||e===2637||e===2765||e===2893||e===3149||e===3405||e===4153||e===6098||e===6752||e===6980||e===7083||e===43456||e===43766||e===68159||e===69939||e===70608||e===71998||e===72263||e===72345||e===73538}function fi(e,t,r){switch(t){case 3:return e&24?r===8204?e&6:(e&24)===16||yl(r)?e&6|16:e&6|8:e&6;case 4:return 2;case 10:return e&1^1;case 14:return(e&2)<<1|e&24;default:return 8}}function*bi(e){let t=e.length;if(t===0)return;let r=e.codePointAt(0),n=r>li?2:1,o=ui(r),i=50200>>o&1?fi(0,o,r):0,s=0,c=r,a=o;for(;n<t;){r=e.codePointAt(n);let l=r>li?2:1,f=ui(r),u=yi[o<<4|f],d;u===0?d=!0:u===1?d=!1:u===2?d=!(i&1):u===3?d=!(i&4):d=(i&24)!==16,i=50200>>f&1&&(i!==0||f!==3)?fi(i,f,r):0,d&&(yield{segment:e.slice(s,n),index:s,input:e,_hd:c,_catBegin:a===15?0:a,_catEnd:o===15?0:o},s=n,c=r,a=f),n+=l,o=f}yield{segment:e.slice(s),index:s,input:e,_hd:c,_catBegin:a===15?0:a,_catEnd:o===15?0:o}}function*Ii(e){for(let t of bi(e))yield t.segment}{let e=bi("_");yi._keep=[e,e.next()]}var Ai=1e3,bl=1,Il=60,Al=3,wl=.5,El=2e4,xl=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,vl=/^\s+$/u,wi,Cl=e=>{let t=`${e??""}`.normalize("NFC"),r=globalThis.Intl?.Segmenter;return typeof r!="function"?Array.from(Ii(t)):(wi??=new r(void 0,{granularity:"grapheme"}),Array.from(wi.segment(t),({segment:n})=>n))},Sl=e=>Cl(e).reduce((t,r)=>vl.test(r)?t+wl:xl.test(r)?t+Al:t+1,0),Ei=({text:e="",baseDelay:t=Ai,speed:r=bl}={})=>{let n=Number.isFinite(t)?Math.max(0,t):Ai,o=Number.isFinite(r)&&r>0?r:1,i=Sl(e)*Il/o,s=Math.max(n,El);return Math.min(n+i,s)};var Qt={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},_i=1,rr="choice",Zt="form",nr=()=>({manual:{...Qt.manual},auto:{...Qt.auto},applyMode:Qt.applyMode}),pn=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let r=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...nr()},r&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},D=e=>{let t=de(e)?ze(e):e;return structuredClone(t)},T=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),or=e=>String(e),Ri=()=>({sections:[],resources:[]}),_l=e=>T(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):Ri(),Rl=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",Ol=({sectionId:e,lineId:t,content:r,dialogueState:n,characterName:o})=>({sectionId:e,lineId:t,content:r,text:Rl(r),characterId:n.characterId,character:{...n.character||{},name:o},characterName:o}),Ll=()=>({resourceId:void 0}),$l=e=>{if(!T(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 r=e?.story?.scenes??{};for(let[n,o]of Object.entries(r))if(o?.sections?.[t])return{sceneId:n,section:o.sections[t]};return{sceneId:void 0,section:void 0}},Oi=e=>{let t=e?.story?.scenes??{},r=new Map;for(let[n,o]of Object.entries(t)){let i=o?.sections??{};for(let s of Object.keys(i)){let c=r.get(s);if(c!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${c}" and "${n}". Section IDs must be globally unique.`);r.set(s,n)}}},Li=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},$i=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==_i)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},kl=(e,t={})=>{let r;try{r=$i(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let n={...t,formatVersion:r,slotId:Li(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete n.slotKey,delete n.date,n},Tl=(e={})=>Object.fromEntries(Object.entries(e).map(([t,r])=>[t,kl(t,r)])),ki=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:r})=>_f(r));return t.length>0?t:void 0},Dl=e=>{!T(e)||!Array.isArray(e.timeline)||e.timeline.forEach(t=>{if(!T(t))return;let r=ki(t.executedActions);if(r){t.executedActions=r;return}delete t.executedActions})},xi=(e,t,r,n="viewedRegistry")=>{let o=t==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[o]:String(e)};if(!T(e))throw new Error(`Malformed ${n}.${t}[${r}] entry.`);if(typeof e[o]!="string"||e[o].length===0)throw new Error(`Malformed ${n}.${t}[${r}] 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 ${n}.sections[${r}] entry: invalid lastLineId.`);return typeof e.lastLineId=="string"&&e.lastLineId.length>0&&(i.lastLineId=e.lastLineId),i}return{resourceId:e.resourceId}},Pl=(e,t="viewedRegistry")=>{if(e===void 0)return Ri();if(!T(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 r=e.sections??[],n=e.resources??[];return{sections:Object.values(Object.fromEntries(r.map((o,i)=>{let s=xi(o,"sections",i,t);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(n.map((o,i)=>{let s=xi(o,"resources",i,t);return[s.resourceId,s]})))}},Ti=(e,t,r)=>{if(!T(e))throw new Error(`Malformed save slot ${r}.`);let{sectionId:n,lineId:o}=e;if(typeof n!="string"||n.length===0)throw new Error(`Malformed save slot ${r}: missing sectionId.`);if(typeof o!="string"||o.length===0)throw new Error(`Malformed save slot ${r}: missing lineId.`);let{sceneId:i,section:s}=hn(t,n);if(!s)throw new Error(`Malformed save slot ${r}: section "${n}" does not exist in projectData.`);if(!s.lines?.some(a=>a.id===o))throw new Error(`Malformed save slot ${r}: line "${o}" does not exist in section "${n}".`);return{sceneId:i,sectionId:n,lineId:o}},Nl=(e,t,r)=>{if(!T(e)||!Array.isArray(e.timeline))return Et({pointer:t,replayStartIndex:1});let n=e.timeline.flatMap((c,a)=>{if(!T(c))return[];try{let l=Ti(c,r,`rollback.timeline[${a}]`),f=tr({sectionId:l.sectionId,lineId:l.lineId,rollbackPolicy:c.rollbackPolicy}),u=ki(D(c.executedActions));return u&&(f.executedActions=u),[f]}catch{return[]}});if(n.length===0)return Et({pointer:t,replayStartIndex:1});let o=typeof e.currentIndex=="number"?Math.trunc(e.currentIndex):n.length-1;(o<0||o>=n.length)&&(o=n.length-1);let i=n[o];if(i?.sectionId!==t.sectionId||i?.lineId!==t.lineId){let c=n.findLastIndex(a=>a.sectionId===t.sectionId&&a.lineId===t.lineId);c>=0?o=c:(n.push(tr({sectionId:t.sectionId,lineId:t.lineId})),o=n.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:n}},Vl=(e,t,r)=>{if(!T(e))throw new Error(`Malformed save slot contexts[${r}] entry.`);let n=yn(t),o=Ti(e.pointers?.read,t,`contexts[${r}].pointers.read`);if(e.variables!==void 0&&!T(e.variables))throw new Error(`Malformed save slot contexts[${r}].variables entry.`);if(e.runtime!==void 0&&!T(e.runtime))throw new Error(`Malformed save slot contexts[${r}].runtime entry.`);let i=e.variables?tt(D(e.variables),t.resources?.variables??{}):{},s=Jl({loadedContextRuntime:T(e.runtime)?D(e.runtime):{}}),c={currentPointerMode:"read",pointers:{read:o},configuration:T(e.configuration)?D(e.configuration):{},views:Array.isArray(e.views)?D(e.views):[],bgm:T(e.bgm)?D(e.bgm):{resourceId:void 0},variables:{...n,...i},rollback:Nl(e.rollback,o,t)};return s&&(c.runtime=s),c},jl=(e,t)=>{if(!T(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((r,n)=>Vl(r,t,n))}},Fl=(e,t)=>{if(!T(e))throw new Error("Malformed save slot.");let r=$i(e.formatVersion);return{...e,formatVersion:r,state:jl(e.state,t)}},vi=(e,t,{required:r=!1}={})=>{if(e===void 0){if(r)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 n=D(e);return Object.prototype.hasOwnProperty.call(n,"hideConfirmDialog")||(n.hideConfirmDialog={}),n},Ml=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:vi(e.confirmActions,"confirmActions",{required:!0}),cancelActions:vi(e.cancelActions,"cancelActions")}},st=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},Ul=e=>(T(e.global.formDrafts)||(e.global.formDrafts={}),e.global.formDrafts),at=e=>{Object.prototype.hasOwnProperty.call(e.global,"formDrafts")&&(e.global.formDrafts={})},Di=e=>{if(!(!T(e)||!e.animations))return{animations:D(e.animations)}},Bl=(e,t)=>{let r=Di(t);if(r){e.global.pendingScreenTransition=r;return}delete e.global.pendingScreenTransition},zl=e=>{let t=e?.id??e?.resourceId;return typeof t=="string"&&t.length>0?t:void 0},ql=(e,t)=>{let r=e?.sectionId,n=e?.lineId;if(!(!r||!n||!t))return`${r}:${n}:${t}`},er=e=>String(e??""),Pi=(e,t)=>{let r=er(t);return e?.trim===!0?r.trim():r},Wl=e=>T(e?.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,t])=>T(t)).map(([t,r])=>[t,{id:t,...D(r)}])):{},Hl=(e,t)=>{if(!t||!T(e.global.formDrafts))return;let r=e.global.formDrafts[t];return T(r)?r:void 0},Ni=(e,t)=>{let r=Ul(e);T(r[t])||(r[t]={values:{},touched:{},errors:{},submitted:!1});let n=r[t];return T(n.values)||(n.values={}),T(n.touched)||(n.touched={}),T(n.errors)||(n.errors={}),typeof n.submitted!="boolean"&&(n.submitted=!1),n},mn=(e,t)=>{let r=Pi(e,t);return e?.required===!0&&r.length===0?"required":null},Yl=({state:e,pointer:t})=>{if(!t?.sectionId||!t?.lineId)return{};let n=le({state:e},{sectionId:t.sectionId})?.lines||[],o=n.findIndex(i=>i.id===t.lineId);return o<0?{}:We(n.slice(0,o+1).map(i=>i.actions||{}))},Gl=({state:e,form:t,pointer:r})=>{if(!t?.resourceId)return null;let n=zl(t),o=ql(r,n);if(!n||!o)return null;let i=Hl(e,o),s=Wl(t),c=sr({state:e}),a={},l=[],f={},u=!0;return Object.entries(s).forEach(([d,p])=>{let h=er(c?.[p.variableId]),g=Object.prototype.hasOwnProperty.call(i?.values??{},d)?er(i.values[d]):h,y=i?.touched?.[d]===!0,b=mn(p,g),A=i?.submitted||y?b:null,x=typeof p.maxLength=="number"?Math.max(0,Math.round(p.maxLength)):void 0,S={id:d,variableId:p.variableId,value:g,initialValue:h,valid:!b,error:A,touched:y,required:p.required===!0,trim:p.trim===!0,placeholder:p.placeholder===void 0?"":String(p.placeholder),multiline:p.multiline===!0,...x!==void 0?{maxLength:x}:{}};b&&(u=!1),a[d]=S,l.push(S),f[d]=g}),{id:n,key:o,resourceId:t.resourceId,animations:t.animations,valid:u,submitted:i?.submitted===!0,fields:a,fieldList:l,values:f,submitActions:{submitForm:{formKey:o,actions:D(t.submitActions??{})}},cancelActions:{cancelForm:{formKey:o,actions:D(t.cancelActions??{})}}}},Ke=[],Ci="line",gn="interaction",tr=({sectionId:e,lineId:t,rollbackPolicy:r})=>({sectionId:e,lineId:t,rollbackPolicy:r??"free"}),yn=e=>{let{contextVariableDefaultValues:t}=Mt(e??{});return D(t)},Vi=()=>({...D(yt)}),ji=({loadedRuntime:e,runtimeIds:t,defaults:r={},path:n})=>{if(e===void 0)return{runtimeState:D(r),hasLoadedValues:!1};if(!T(e))throw new Error(`Malformed ${n}.`);let o=D(r),i=!1;return t.forEach(s=>{e[s]!==void 0&&(o[s]=Fi(s,D(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},Kl=({loadedGlobalRuntime:e={}})=>ji({loadedRuntime:e,runtimeIds:Ur,defaults:Pe,path:"global.runtime"}).runtimeState,Jl=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:r}=ji({loadedRuntime:e,runtimeIds:Br,defaults:Vi(),path:"context.runtime"});return r?t:void 0},ir=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},Xl=e=>e.runtime?(Br.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=D(yt[t]))}),e.runtime):(e.runtime=Vi(),e.runtime),Ql=e=>So(e.global),Zl=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:Ql(e)}})},eu=e=>Co[e],tu=(e,t)=>{let r=eu(e);if(r==="number"){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} requires a finite numeric value`);return}if(r==="boolean"){if(typeof t!="boolean")throw new Error(`${e} requires a boolean value`);return}if(r==="string"){if(typeof t!="string")throw new Error(`${e} requires a string value`);return}throw new Error(`Unsupported runtime field "${e}"`)},Fi=(e,t)=>{if(tu(e,t),e==="autoForwardSpeed"&&t<=0)throw new Error("autoForwardSpeed requires a value greater than 0");return e==="saveLoadPagination"?Math.max(1,Math.trunc(t)):t},Mi=(e,t,r)=>{let n=Fi(t,r);if(t in yt){let o=ir(e);if(!o)return n;let i=Xl(o);return i[t]=n,n}return e.global[t]=n,n},Ui=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:D(e)},configuration:{},views:[],bgm:Ll(),variables:yn(t),rollback:Et({pointer:e})}),ct=e=>e?(e.currentPointerMode="read",T(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,ru=(e,{queueRender:t=!0}={})=>{let r=e.contexts?.[e.contexts.length-1],n=r?.pointers?.read;if(!r||!n?.sectionId||!n?.lineId)return null;let o=Ui({pointer:n,projectData:e.projectData});return e.contexts[e.contexts.length-1]=o,nu(e,{queueRender:t}),o},nu=(e,{queueRender:t=!0}={})=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,st(e),at(e),e.global.nextLineConfig=nr(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"}),t&&e.global.pendingEffects.push({name:"render"})},Bi=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},Et=({pointer:e,replayStartIndex:t=0})=>{let r=e?.sectionId&&e?.lineId;return{currentIndex:r?0:-1,isRestoring:!1,replayStartIndex:t,timeline:r?[tr({sectionId:e.sectionId,lineId:e.lineId})]:[]}},Qe=(e,t={})=>{if(e?.rollback)return Bi(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 r=e?.pointers?.read;return e.rollback=Et({pointer:r,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},bn=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return;let n=Qe(r);if(n.isRestoring)return;n.currentIndex<n.timeline.length-1&&(n.timeline=n.timeline.slice(0,n.currentIndex+1));let o=n.timeline[n.timeline.length-1];if(o?.sectionId===t.sectionId&&o?.lineId===t.lineId&&(o?.rollbackPolicy??"free")===(t.rollbackPolicy??"free")){n.currentIndex=n.timeline.length-1;return}n.timeline.push(tr(t)),n.currentIndex=n.timeline.length-1},ou=e=>{let r=e.contexts?.[e.contexts.length-1]?.rollback;if(!r||r.isRestoring||!Array.isArray(r.timeline)||typeof r.currentIndex!="number")return null;let n=Ke[Ke.length-1],o=typeof n?.checkpointIndex=="number"?n.checkpointIndex:r.currentIndex;return o<0||o>=r.timeline.length?null:(typeof n?.checkpointIndex!="number"&&o<r.timeline.length-1&&(r.timeline=r.timeline.slice(0,o+1)),r.timeline[o]??null)},iu=({state:e},t={})=>{let r=t?.source===Ci?Ci: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?(Ke.push({checkpointIndex:null,source:r}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),Ke.push({checkpointIndex:o.currentIndex,source:r}),e)},su=({state:e})=>(Ke.pop(),e),Se=(e,t,r)=>{let o=Ke[Ke.length-1]?.source??gn;if(!Rf(t,o))return;let i=ou(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:D(r)}))},Si=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return;let n=t?.operations??[];for(let{variableId:o,op:i,value:s,roundTo:c}of n){let a=e.projectData.resources?.variables?.[o],l=a?.scope,f=a?.type;if(De(a))throw new Error(`Cannot update computed variable: ${o}`);if(a?.readonly===!0)throw new Error(`Cannot update readonly variable: ${o}`);Ut(l,o),Bt(f,i,o),Nr(f,i,s,o,{roundTo:c}),l==="context"&&(r.variables[o]=zt(r.variables[o],i,s,{roundTo:c}))}},au=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:r,payload:n})=>{Of(e,r,n)})},cu=(e,t)=>{let{sectionId:r,lineId:n}=t,s=le({state:e},{sectionId:r})?.lines?.find(c=>c.id===n)?.actions;s&&Object.entries(s).forEach(([c,a])=>{is(e,c,a)})},zi=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let n=Qe(r),o=n.timeline[t];if(!o)return e;e.global.autoMode&&ur({state:e}),e.global.skipMode&&Je({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),n.isRestoring=!0,n.currentIndex=t;try{r.variables=yn(e.projectData),delete r.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=D(Qt),e.global.overlayStack=[],st(e),at(e),e.global.isLineCompleted=!0;let i=n.replayStartIndex??0;for(let c=i;c<=t;c++)c>i&&pn(e),cu(e,n.timeline[c]),au(e,n.timeline[c]);let s=ct(r);s.read={sectionId:o.sectionId,lineId:o.lineId},e.global.pendingEffects=e.global.pendingEffects.filter(c=>c?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{n.isRestoring=!1}return e},lu=e=>{let{projectData:t}=e,r=e.global??{},{saveSlots:n={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=r;Oi(t);let c=t.story.initialSceneId,a=t.story.scenes[c],l=a.initialSectionId,f=a.sections[l],u={sceneId:c,sectionId:l,lineId:f.initialLineId??f.lines[0].id},{globalVariablesDefaultValues:d}=Mt(t),p={...d,...tt(o,t.resources?.variables??{})};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,formDrafts:{},accountViewedRegistry:Pl(s,"accountViewedRegistry"),nextLineConfig:nr(),saveSlots:Tl(n),overlayStack:[],variables:p,...Kl({loadedGlobalRuntime:i})},contexts:[Ui({pointer:u,projectData:t})]}},uu=({state:e})=>e.global.overlayStack||[],fu=({state:e})=>e.global.pendingEffects,qi=({state:e})=>e.global.skipMode,du=({state:e})=>e.global.autoMode,Wi=({state:e})=>e.global.dialogueUIHidden,Hi=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],r=t[t.length-1];if(!r)return[];let{sectionId:n,lineId:o}=r.pointers.read,i=le({state:e},{sectionId:n});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(u=>u.id===o),c=i.lines.slice(0,s+1),a=[],l={},f=mt({variables:{...e.global?.variables??{},...ir(e)?.variables??{}},runtime:He(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1});for(let u of c){let d=u.actions||{};if(l=We([l,d]),!d.dialogue)continue;let p=l.dialogue||{},h=Ft({characterId:p.characterId,character:p.character,characters:e.projectData.resources?.characters??{},variables:f}),g=Ol({sectionId:n,lineId:u.id,content:d.dialogue.append===!0?p.content:d.dialogue.content,dialogueState:p,characterName:h});if(d.dialogue.append===!0&&a.length>0){a[a.length-1]={...a[a.length-1],content:g.content,text:g.text,characterId:g.characterId,character:g.character,characterName:g.characterName};continue}a.push(g)}return a},pu=({state:e})=>e.global.confirmDialog??null,xt=({state:e},{pointer:t}={})=>{let r=t??ye({state:e})?.pointer,n=Yl({state:e,pointer:r});return Gl({state:e,form:n.form,pointer:r})},hu=({state:e},{pointer:t}={})=>!!xt({state:e},{pointer:t}),be=({state:e},{pointer:t}={})=>{let r=xt({state:e},{pointer:t});if(r)return{source:Zt,formId:r.id,formKey:r.key};let n=Yi({state:e,pointer:t});return n?{source:rr,resourceId:n}:null},mu=({state:e,registry:t},r)=>{let{sectionId:n,lineId:o}=r,s=(Array.isArray(t?.sections)?t.sections:[]).find(f=>f.sectionId===n);if(!s)return!1;if(s.lastLineId===void 0||o===void 0)return!0;let c=le({state:e},{sectionId:n});if(!c||!c.lines||!Array.isArray(c.lines))return s.lastLineId===o;let a=c.lines.findIndex(f=>f.id===s.lastLineId),l=c.lines.findIndex(f=>f.id===o);return a===-1||l===-1?s.lastLineId===o:l<=a},gu=({registry:e},t)=>{let{resourceId:r}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===r)},In=({state:e},t)=>mu({state:e,registry:e.global.accountViewedRegistry},t),yu=({state:e},t)=>gu({registry:e.global.accountViewedRegistry},t),bu=({state:e})=>e.global.nextLineConfig,Yi=({state:e,pointer:t}={})=>{let r=t??ye({state:e})?.pointer;if(!r)return;let n=r?.sectionId,o=r?.lineId,s=le({state:e},{sectionId:n})?.lines||[],c=s.findIndex(l=>l.id===o);if(c<0)return;let a;for(let l of s.slice(0,c+1)){let f=l?.actions;if(f?.cleanAll&&(a=void 0),!f||!Object.prototype.hasOwnProperty.call(f,"choice")){a=void 0;continue}let u=f.choice;if(u?.resourceId){a=u.resourceId;continue}u?.animations||(a=void 0)}return a},Gi=({state:e})=>!!Yi({state:e}),Iu=({state:e})=>structuredClone(e),Ki=({state:e})=>e.global.saveSlots,Au=({state:e},t)=>{let r=t?.slotId,n=or(r);return e.global.saveSlots[n]},An=({state:e})=>He(e),wu=({state:e},t)=>Ne(e,t?.runtimeId),sr=({state:e})=>{let t={...e.global?.variables??{},...ir(e)?.variables??{}};return mt({variables:t,runtime:He(e),variableConfigs:e.projectData.resources?.variables??{}})},ye=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],r=t[t.length-1];if(r)return{currentPointerMode:"read",pointer:r.pointers?.read}},le=({state:e},t)=>{let{sectionId:r}=t;return hn(e.projectData,r).section},ar=({state:e})=>{let t=ye({state:e});if(!t?.pointer)return;let{sectionId:r,lineId:n}=t.pointer,o=le({state:e},{sectionId:r});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===n)},Ji=({state:e})=>{let{sectionId:t,lineId:r}=ye({state:e}).pointer,o=le({state:e},{sectionId:t})?.lines||[],i=o.findIndex(l=>l.id===r),c=o.slice(0,i+1).map(l=>{let f=l.actions||{},u={};return Object.keys(f).forEach(d=>{u[d]=f[d]}),u});return We(c)},Eu=e=>{let t=ar({state:e})?.actions?.dialogue;if(t?.clear===!0||!Array.isArray(t?.content))return"";let r=sr({state:e});return t.content.map(n=>`${rt(n?.text,{variables:r})??""}`).join("")},cr=({state:e})=>Ei({text:Eu(e),baseDelay:Ne(e,"autoForwardDelay"),speed:Ne(e,"autoForwardSpeed")}),xu=({state:e})=>{let t=Xi({state:e}),n=ar({state:e})?.actions??{},o=We([t??{},n]);return Vr(t??{},o??{})},vu=({state:e},{sectionId:t})=>{let r=le({state:e},{sectionId:t});if(!r?.lines)return[];let n=[],o={};for(let i of r.lines){let s=i.actions||{},c=We([o,s]),a=Vr(o,c);n.push({id:i.id,changes:a,presentationState:c}),o=jr(c)}return n},Cu=({state:e},{sectionId:t,includePresentationState:r=!1})=>{let n=vu({state:e},{sectionId:t});return r?{lines:n}:{lines:n.map(({presentationState:o,...i})=>i)}},Xi=({state:e})=>{let{sectionId:t,lineId:r}=ye({state:e}).pointer,o=le({state:e},{sectionId:t})?.lines||[],i=o.findIndex(a=>a.id===r);if(i<=0)return null;let c=o.slice(0,i).map(a=>{let l=a.actions||{},f={};return Object.keys(l).forEach(u=>{f[u]=l[u]}),f});return jr(We(c))},wn=({state:e},{slotsPerPage:t=6}={})=>{let o=((An({state:e}).saveLoadPagination??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let c=o+s,a=e.global.saveSlots&&e.global.saveSlots[or(c)]||{};i.push({...a,slotId:c})}return{saveSlots:i}},Su=Ki,_u=wn,Ru=e=>{let r=e.contexts?.[e.contexts.length-1]?.rollback;return!r||!Array.isArray(r.timeline)||typeof r.currentIndex!="number"?!1:r.currentIndex>=0&&r.currentIndex<r.timeline.length-1},Ou=({state:e},t={})=>{let r=Ji({state:e}),n=Xi({state:e}),o=ar({state:e})?.actions??{},i=e.global.pendingScreenTransition,s=i?.animations?{...o,screen:D(i)}:o,c=i?.animations&&n===null?{}:n,{sectionId:a}=ye({state:e}).pointer,{sceneId:l}=hn(e.projectData,a),f=An({state:e}),u=t?.activePersistentAnimations??[],d=t?.restoredPersistentAnimations??[],p=xt({state:e}),h=Gi({state:e}),g=sr({state:e}),{saveSlots:y}=wn({state:e}),b=Ru(e);return ni({presentationState:r,previousPresentationState:c,currentLineActions:s,resources:e.projectData.resources,currentSceneId:l,screen:e.projectData.screen,dialogueUIHidden:f.dialogueUIHidden,autoMode:f.autoMode,skipMode:f.skipMode,isChoiceVisible:h,isFormVisible:!!p,canRollback:as({state:e}),skipOnlyViewedLines:!f.skipUnseenText,isLineCompleted:f.isLineCompleted,skipTransitionsAndAnimations:!!f.skipTransitionsAndAnimations||b,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,form:p,dialogueHistory:Hi({state:e}),saveSlots:y,variables:g,runtime:f,activePersistentAnimations:u,restoredPersistentAnimations:d})},Lu=({state:e},t)=>(e.global.confirmDialog=Ml(t),e.global.pendingEffects.push({name:"render"}),e),$u=({state:e})=>(e.global.confirmDialog&&(st(e),e.global.pendingEffects.push({name:"render"})),e),ku=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),Se(e,"pushOverlay",t),e),Tu=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),Se(e,"popOverlay",void 0),e),Du=({state:e},t)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=t),e.global.pendingEffects.push({name:"render"}),Se(e,"replaceLastOverlay",t),e),Pu=({state:e})=>(e.global.overlayStack=[],st(e),at(e),e.global.pendingEffects.push({name:"render"}),Se(e,"clearOverlays",void 0),e),Nu=e=>{e.global.autoMode&&e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.skipMode&&e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.nextLineConfig?.auto?.enabled&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},lr=(e,t,{screenTransition:r}={})=>{e.global.isLineCompleted=!1,Bl(e,r),at(e);let n=be({state:e},{pointer:t}),o=n?.source===rr,i=n?.source===Zt;return n&&Nu(e),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:o,isFormVisible:i,activeInteraction:n}},En=(e,t,r)=>{t?.source!==rr||r||!e.global.skipMode||e.global.pendingEffects.push({name:"startSkipNextTimer"})},Qi=({state:e})=>(be({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:cr({state:e})}}),e.global.pendingEffects.push({name:"render"})),e),ur=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Vu=({state:e})=>{let t=e.global.autoMode;return be({state:e})&&!t||(t?ur({state:e}):Qi({state:e})),e},Zi=({state:e})=>(be({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),Je=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),ju=({state:e})=>{let t=qi({state:e});return be({state:e})&&!t||(t?Je({state:e}):Zi({state:e})),e},fr=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),Se(e,"showDialogueUI",void 0),e),es=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),Se(e,"hideDialogueUI",void 0),e),Fu=({state:e})=>(Wi({state:e})?fr({state:e}):es({state:e}),e),Fe=(e,t,r)=>(Mi(e,t,r),Zl(e),e.global.pendingEffects.push({name:"render"}),e),vt=(e,t,r,n)=>{let o=Mi(e,t,r);return e.global.pendingEffects.push({name:"render"}),Se(e,n,{value:o}),e},Mu=({state:e},t)=>Fe(e,"dialogueTextSpeed",t?.value),Uu=({state:e},t)=>Fe(e,"autoForwardDelay",t?.value),Bu=({state:e},t)=>Fe(e,"autoForwardSpeed",t?.value),zu=({state:e},t)=>Fe(e,"skipUnseenText",t?.value),qu=({state:e},t)=>Fe(e,"skipTransitionsAndAnimations",t?.value),Wu=({state:e},t)=>Fe(e,"soundVolume",t?.value),Hu=({state:e},t)=>Fe(e,"musicVolume",t?.value),Yu=({state:e},t)=>Fe(e,"muteAll",t?.value),Gu=({state:e},t)=>vt(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),Ku=({state:e})=>{let t=Ne(e,"saveLoadPagination")+1;return vt(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},Ju=({state:e})=>{let t=Ne(e,"saveLoadPagination")-1;return vt(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},Xu=({state:e},t)=>vt(e,"menuPage",t?.value,"setMenuPage"),Qu=({state:e},t)=>vt(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),Zu=({state:e})=>(e.global.pendingEffects=[],e),ef=({state:e},t)=>(e.global.pendingEffects.push(t),e),ts=(e,{sectionId:t,resetStoryState:r=!1,screen:n})=>{let o=!!Di(n),i=le({state:e},{sectionId:t});if(!i)return console.warn(`Section not found: ${t}`),e;let s=i.lines?.[0];if(!s)return console.warn(`Section ${t} has no lines`),e;if(r&&!ru(e,{queueRender:!o}))return e;let c=be({state:e});r&&e.global.skipMode&&Je({state:e});let a=e.contexts?.[e.contexts.length-1];if(a){let f=ct(a),u=f.read;r||Xe(e,{sectionId:u?.sectionId,lineId:u?.lineId}),a.rollback||Qe(a,{compatibilityAnchor:!0}),f.read={sectionId:t,lineId:s.id},r?a.rollback=Et({pointer:f.read}):bn(e,{sectionId:t,lineId:s.id})}let{activeInteraction:l}=lr(e,a?.pointers?.read,{screenTransition:n});return En(e,c,l),!r&&e.global.autoMode&&!c&&!l&&e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e},tf=({state:e},t)=>ts(e,{sectionId:t?.sectionId,resetStoryState:!0,screen:t?.screen}),rs=e=>(e.global.accountViewedRegistry=_l(e.global.accountViewedRegistry),e.global.accountViewedRegistry),xn=(e,t)=>{!Array.isArray(t)||t.length===0||e.global.pendingEffects.push({name:"applyScopedDataUpdates",payload:{updates:t.map(r=>({scope:r.scope,path:r.path,op:r.op,value:D(r.value)}))}})},ns=(e,t)=>{xn(e,[{scope:"account",path:"viewedRegistry",op:"markViewed",value:{sections:(Array.isArray(t?.sections)?t.sections:[]).map(r=>({sectionId:r.sectionId,...r.lastLineId===void 0?{}:{lineId:r.lastLineId}})),resources:Array.isArray(t?.resources)?t.resources:[]}}])},rf=(e,t,{sectionId:r,lineId:n})=>{if(!r||!n)return!1;let o=T(t)?t:{};Array.isArray(o.sections)||(o.sections=[]);let i=o.sections.find(s=>s.sectionId===r);if(i){if(i.lastLineId===void 0)return!1;let s=le({state:e},{sectionId:r});if(s?.lines){let c=s.lines.findIndex(l=>l.id===i.lastLineId),a=s.lines.findIndex(l=>l.id===n);if(c===-1||a>c)return i.lastLineId===n?!1:(i.lastLineId=n,!0)}else return i.lastLineId===n?!1:(i.lastLineId=n,!0);return!1}else return o.sections.push({sectionId:r,lastLineId:n}),!0},Xe=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;rf(e,rs(e),t)&&ns(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},nf=({state:e},t)=>(Xe(e,t),e.global.pendingEffects.push({name:"render"}),e),of=({state:e},t)=>{let{resourceId:r}=t;if(e.global.accountViewedRegistry!==void 0){let n=rs(e);n.resources.find(i=>i.resourceId===r)||(n.resources.push({resourceId:r}),ns(e,{sections:[],resources:[{resourceId:r}]}))}return e.global.pendingEffects.push({name:"render"}),e},os=({state:e},t)=>{let r=$l(t.manual),{auto:n,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,c=e.contexts?.[e.contexts.length-1]?.rollback?.isRestoring===!0;r&&n?(e.global.nextLineConfig={manual:r,auto:n},o!==void 0?e.global.nextLineConfig.applyMode=o:s!==void 0&&(e.global.nextLineConfig.applyMode=s)):(r&&(e.global.nextLineConfig.manual=r),n&&(e.global.nextLineConfig.auto=n),o!==void 0&&(e.global.nextLineConfig.applyMode=o));let a=e.global.nextLineConfig.auto?.enabled,l=be({state:e});return!c&&!l&&a===!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}}):!c&&a===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),Se(e,"setNextLineConfig",t),e},sf=({state:e},t)=>{let r=t?.slotId;if(r==null||r==="")throw new Error("saveSlot requires slotId");let{thumbnailImage:n}=t,o=t?.savedAt,i=or(r),s=D(e.contexts);s?.forEach(l=>{ct(l),Bi(l.rollback),Dl(l.rollback)});let c={contexts:s},a={formatVersion:_i,slotId:Li(r),savedAt:typeof o=="number"?o:Date.now(),image:n,state:c};return e.global.saveSlots[i]=a,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},af=({state:e},t)=>{let r=t?.slotId;if(r==null||r==="")throw new Error("loadSlot requires slotId");let n=or(r),o=e.global.saveSlots[n];if(o){let i=Fl(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=nr(),e.global.overlayStack=[],e.global.isLineCompleted=!0,st(e),at(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},cf=({state:e},t)=>{let{projectData:r}=t;Oi(r),e.projectData=r;let n=r?.resources?.variables??{},{contextVariableDefaultValues:o,globalVariablesDefaultValues:i}=Mt(r??{});return Object.prototype.hasOwnProperty.call(e.global??{},"variables")&&(e.global.variables={...i,...tt(e.global.variables,n)}),e.contexts?.forEach(s=>{Object.prototype.hasOwnProperty.call(s??{},"variables")&&(s.variables={...o,...tt(s.variables,n)})}),st(e),at(e),e.global.pendingEffects.push({name:"render"}),e},lf=({state:e},t)=>{let{sectionId:r,lineId:n}=t;if(!n)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=r||o.pointers.read?.sectionId;if(r&&!le({state:e},{sectionId:r}))return console.warn(`Section not found: ${r}`),e;let s=le({state:e},{sectionId:i});if(!s?.lines||!Array.isArray(s.lines))return console.warn(`Section ${i} has no lines`),e;if(!s.lines.find(u=>u.id===n))return console.warn(`Line not found: ${n} in section ${i}`),e;let a=be({state:e}),l=ct(o);l.read={sectionId:i,lineId:n};let{activeInteraction:f}=lr(e,l.read);return En(e,a,f),e},uf=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return fr({state:e}),e;let r=be({state:e});if(r?.source===rr&&t?.bypassChoice!==!0||r?.source===Zt&&t?._interactionSource!==Zt)return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let f=ye({state:e})?.pointer,u=f?.sectionId,d=f?.lineId;u&&d&&Xe(e,{sectionId:u,lineId:d}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&!r&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:cr({state:e})}});let p=e.global.nextLineConfig;return p?.auto?.enabled&&!r&&p.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:p.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e}let n=ye({state:e})?.pointer,o=n?.sectionId,i=le({state:e},{sectionId:o}),s=e.contexts[e.contexts.length-1],c=i?.lines||[],l=c.findIndex(f=>f.id===n?.lineId)+1;if(l<c.length){let f=c[l],u=!Ne(e,"skipUnseenText");if(e.global.skipMode&&u&&!In({state:e},{sectionId:o,lineId:f.id}))return Je({state:e}),e;if(s&&!s.rollback&&Qe(s,{compatibilityAnchor:!0}),s){let h=ct(s),g=h.read?.lineId;g&&o&&Xe(e,{sectionId:o,lineId:g}),h.read={sectionId:o,lineId:f.id}}bn(e,{sectionId:o,lineId:f.id}),pn(e);let{activeInteraction:d}=lr(e,{sectionId:o,lineId:f.id});En(e,r,d);let p=e.global.nextLineConfig;p?.auto?.enabled&&!d&&p.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:p.auto.delay}})}else e.global.autoMode&&ur({state:e}),e.global.skipMode&&Je({state:e});return e},ff=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=be({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:cr({state:e})}});let r=ye({state:e})?.pointer,n=r?.sectionId,o=r?.lineId;n&&o&&Xe(e,{sectionId:n,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},df=({state:e},t)=>ts(e,{sectionId:t?.sectionId,screen:t?.screen}),pf=({state:e})=>{if(e.global.dialogueUIHidden)return fr({state:e}),e;if(be({state:e}))return e;let t=ye({state:e})?.pointer,r=t?.sectionId,n=le({state:e},{sectionId:r}),o=e.contexts[e.contexts.length-1],i=n?.lines||[],c=i.findIndex(a=>a.id===t?.lineId)+1;if(c<i.length){let a=i[c],l=!Ne(e,"skipUnseenText");if(e.global.skipMode&&l&&!In({state:e},{sectionId:r,lineId:a.id}))return Je({state:e}),e;if(o&&!o.rollback&&Qe(o,{compatibilityAnchor:!0}),o){let u=ct(o),d=u.read?.lineId;d&&r&&Xe(e,{sectionId:r,lineId:d}),u.read={sectionId:r,lineId:a.id}}bn(e,{sectionId:r,lineId:a.id}),pn(e);let{activeInteraction:f}=lr(e,{sectionId:r,lineId:a.id});e.global.nextLineConfig.auto?.enabled&&!f&&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},vn=(e,t={})=>{let r=xt({state:e});return!r||t.formKey&&t.formKey!==r.key||t.formId&&t.formId!==r.id?null:r},hf=(e,t)=>{if(!t.variableId)throw new Error(`form field "${t.id}" requires variableId`);let r=e.projectData.resources?.variables?.[t.variableId],n=r?.scope,o=r?.type;if(De(r))throw new Error(`Cannot update computed variable: ${t.variableId}`);if(r?.readonly===!0)throw new Error(`Cannot update readonly variable: ${t.variableId}`);return Ut(n,t.variableId),Bt(o,"set",t.variableId),{variableConfig:r,scope:n}},mf=(e,t)=>({id:e.id,key:e.key,valid:!0,values:D(t),fields:D(e.fields),fieldList:D(e.fieldList)}),gf=e=>{if(e.global.isLineCompleted)return;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=ye({state:e})?.pointer,r=t?.sectionId,n=t?.lineId;r&&n&&Xe(e,{sectionId:r,lineId:n})},yf=({state:e},t={})=>{let r=vn(e,t),n=t.field;if(!r?.fields?.[n])return e;let o=Ni(e,r.key),i=er(t.value),s=r.fields[n],c=mn(s,i);return o.values[n]=i,o.touched[n]=!0,c?o.errors[n]=c:delete o.errors[n],e.global.pendingEffects.push({name:"render"}),e},bf=({state:e},t={})=>{let r=vn(e,t);if(!r)return{submitted:!1,valid:!1,reason:"inactive"};let n=Ni(e,r.key);n.submitted=!0;let o={},i={};if(Object.entries(r.fields).forEach(([u,d])=>{let p=Object.prototype.hasOwnProperty.call(n.values,u)?n.values[u]:d.value,h=mn(d,p);n.touched[u]=!0,h&&(i[u]=h),o[u]=Pi(d,p)}),n.errors=i,Object.keys(i).length>0)return e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!1,errors:D(i),form:{id:r.id,key:r.key,values:D(o)}};let s=e.contexts[e.contexts.length-1];if(s?.rollback?.isRestoring)return{submitted:!1,valid:!1,reason:"restoring"};let c=!1,a=[],l=[];Object.entries(r.fields).forEach(([u,d])=>{let{scope:p}=hf(e,d),h=p==="context"?s.variables:e.global.variables,g=o[u];h[d.variableId]=zt(h[d.variableId],"set",g),p==="context"&&(c=!0,l.push({variableId:d.variableId,op:"set",value:g})),(p==="device"||p==="account")&&a.push({scope:p,path:`variables.${d.variableId}`,op:"set",value:D(h[d.variableId])})}),c&&Se(e,"updateVariable",{id:"submitForm",operations:l}),xn(e,a);let f=mf(r,o);return gf(e),delete e.global.formDrafts[r.key],e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!0,form:f}},If=({state:e},t={})=>{let r=vn(e,t);return r?(delete e.global.formDrafts?.[r.key],e.global.pendingEffects.push({name:"render"}),{cancelled:!0,form:{id:r.id,key:r.key,values:D(r.values),fields:D(r.fields),fieldList:D(r.fieldList)}}):{cancelled:!1,reason:"inactive"}},Af=({state:e},t)=>{let{id:r,operations:n=[]}=t;if(!r)throw new Error("updateVariable requires an id field");if(typeof r!="string"||!/^[a-zA-Z0-9]+$/.test(r))throw new Error(`updateVariable id must be alphanumeric, got: "${r}"`);let o=e.contexts[e.contexts.length-1];if(o?.rollback?.isRestoring)return e;let i=!1,s=[],c=[];return n.forEach(({variableId:a,op:l,value:f,roundTo:u})=>{let d=e.projectData.resources?.variables?.[a],p=d?.scope,h=d?.type;if(De(d))throw new Error(`Cannot update computed variable: ${a}`);if(d?.readonly===!0)throw new Error(`Cannot update readonly variable: ${a}`);Ut(p,a),Bt(h,l,a),Nr(h,l,f,a,{roundTo:u});let g=p==="context"?o.variables:e.global.variables;if(p==="context"){i=!0;let y={variableId:a,op:l,value:f};u!==void 0&&(y.roundTo=u),c.push(y)}g[a]=zt(g[a],l,f,{roundTo:u}),(p==="device"||p==="account")&&s.push({scope:p,path:`variables.${a}`,op:"set",value:D(g[a])})}),i&&Se(e,"updateVariable",{id:r,operations:c}),xn(e,s),e.global.pendingEffects.push({name:"render"}),e},wf=e=>(t,r)=>e({state:t},r),Ef=e=>({variables:mt({variables:{...e.global?.variables??{},...ir(e)?.variables??{}},runtime:He(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1}),runtime:He(e)}),xf=e=>{if(!T(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")},vf=(e,t,r)=>{if(!T(e))throw new Error(`conditional branch at index ${t} must be an object`);if(!T(e.actions))throw new Error(`conditional branch at index ${t} requires actions object`);if(!Object.prototype.hasOwnProperty.call(e,"when")&&t!==r-1)throw new Error("conditional else branch must be the last branch")},Cf=(e,t)=>{xf(t);for(let r=0;r<t.branches.length;r+=1){let n=t.branches[r];if(vf(n,r,t.branches.length),!(Object.prototype.hasOwnProperty.call(n,"when")&&!ht(n.when,Ef(e)))){Object.entries(n.actions).forEach(([i,s])=>{is(e,i,s)});return}}},Sf={conditional:{replayLine:Cf},updateVariable:{recordSources:[gn],replayLine:Si,replayRecorded:Si,persistInSaveSlot:!0},setNextLineConfig:{replayLine:wf(os)}},dr=e=>Sf[e]??null,_f=e=>dr(e)?.persistInSaveSlot===!0,Rf=(e,t)=>{let r=dr(e)?.recordSources;return Array.isArray(r)&&r.includes(t)},Of=(e,t,r)=>{dr(t)?.replayRecorded?.(e,r)},is=(e,t,r)=>{dr(t)?.replayLine?.(e,r)},ss=({state:e},t)=>{let{offset:r}=t;if(r===void 0||typeof r!="number")return console.warn("selectLineIdByOffset requires a numeric offset"),null;let n=e.contexts[e.contexts.length-1];if(!n)return null;let o=n.rollback;if(!Array.isArray(o?.timeline)||typeof o?.currentIndex!="number")return null;let i=o.currentIndex+r;if(i<0||i>=o.timeline.length)return null;let s=o.timeline[i];return{sectionId:s.sectionId,lineId:s.lineId}},as=({state:e})=>ss({state:e},{offset:-1})!==null,Lf=({state:e},t)=>{let{offset:r=-1}=t;if(r>=0)throw new Error("rollbackByOffset requires a negative offset");let n=e.contexts?.[e.contexts.length-1];if(!n)return e;let o=Qe(n,{compatibilityAnchor:!n.rollback}),i=o.currentIndex+r;return i<0||i>=o.timeline.length?e:zi(e,i)},$f=({state:e},t)=>{let{sectionId:r,lineId:n}=t,o=e.contexts[e.contexts.length-1];if(!o)throw new Error("No context available for rollbackToLine");let i=Qe(o,{compatibilityAnchor:!o.rollback}),c=i.timeline.slice(0,i.currentIndex+1).findLastIndex(a=>a.sectionId===r&&a.lineId===n);if(c===-1)throw new Error(`Line ${n} not found in section ${r} rollback timeline`);return c===i.currentIndex?e:zi(e,c)},cs=e=>{let t=lu(e);return co(t,{selectPendingEffects:fu,selectSkipMode:qi,selectAutoMode:du,selectIsChoiceVisible:Gi,selectIsFormVisible:hu,selectActiveInteraction:be,selectActiveForm:xt,selectDialogueUIHidden:Wi,selectDialogueHistory:Hi,selectConfirmDialog:pu,selectIsLineAccountViewed:In,selectIsResourceAccountViewed:yu,selectNextLineConfig:bu,selectSystemState:Iu,selectSaveSlotMap:Ki,selectSaveSlots:Su,selectSaveSlot:Au,selectRuntime:An,selectRuntimeValue:wu,selectAllVariables:sr,selectCurrentPointer:ye,selectSection:le,selectCurrentLine:ar,selectPresentationState:Ji,selectAutoForwardTimerDelay:cr,selectPresentationChanges:xu,selectSectionLineChanges:Cu,selectSaveSlotPage:wn,selectCurrentPageSlots:_u,selectRenderState:Ou,selectOverlayStack:uu,selectLineIdByOffset:ss,selectCanRollback:as,startAutoMode:Qi,stopAutoMode:ur,toggleAutoMode:Vu,startSkipMode:Zi,stopSkipMode:Je,toggleSkipMode:ju,showDialogueUI:fr,hideDialogueUI:es,toggleDialogueUI:Fu,setDialogueTextSpeed:Mu,setAutoForwardDelay:Uu,setAutoForwardSpeed:Bu,setSkipUnseenText:zu,setSkipTransitionsAndAnimations:qu,setSoundVolume:Wu,setMusicVolume:Hu,setMuteAll:Yu,setSaveLoadPagination:Gu,incrementSaveLoadPagination:Ku,decrementSaveLoadPagination:Ju,setMenuPage:Xu,setMenuEntryPoint:Qu,showConfirmDialog:Lu,hideConfirmDialog:$u,resetStoryAtSection:tf,clearPendingEffects:Zu,appendPendingEffect:ef,beginRollbackActionBatch:iu,endRollbackActionBatch:su,addViewedLine:nf,addViewedResource:of,setNextLineConfig:os,saveSlot:sf,loadSlot:af,updateProjectData:cf,sectionTransition:df,jumpToLine:lf,nextLine:uf,markLineCompleted:ff,rollbackToLine:$f,rollbackByOffset:Lf,pushOverlay:ku,popOverlay:Tu,replaceLastOverlay:Du,clearOverlays:Pu,updateFormField:yf,submitForm:bf,cancelForm:If,updateVariable:Af,nextLineFromSystem:pf},{transformActionFirstArgument:n=>({state:n}),transformSelectorFirstArgument:n=>({state:n})})};var kf="route-engine",Tf="projectPersistence";var us=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),ne=e=>Object.prototype.toString.call(e)==="[object Object]",ls="variables.",Df=(e={})=>{let t=ne(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!ne(r)||typeof r.sectionId!="string"||r.sectionId.length===0?null:{sectionId:r.sectionId,...typeof r.lineId=="string"?{lineId:r.lineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(r=>typeof r=="string"||typeof r=="number"?{resourceId:String(r)}:!ne(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},Pf=(e={})=>{let t=ne(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!ne(r)||typeof r.sectionId!="string"||r.sectionId.length===0?null:{sectionId:r.sectionId,...typeof r.lastLineId=="string"?{lastLineId:r.lastLineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(r=>typeof r=="string"||typeof r=="number"?{resourceId:String(r)}:!ne(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},Nf=(e,t)=>{let r=Pf(e),n=Df(t),o=r.sections.map(s=>({...s})),i=r.resources.map(s=>({...s}));return n.sections.forEach(s=>{let c=o.find(a=>a.sectionId===s.sectionId);if(!c){o.push({sectionId:s.sectionId,...s.lineId===void 0?{}:{lastLineId:s.lineId}});return}if(c.lastLineId!==void 0){if(s.lineId===void 0){delete c.lastLineId;return}c.lastLineId=s.lineId}}),n.resources.forEach(s=>{i.find(a=>a.resourceId===s.resourceId)||i.push({...s})}),{sections:o,resources:i}},fs=(e={})=>{let t=ne(e)?e:{};return{saveSlots:ne(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:ne(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:ne(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:ne(t.globalRuntime)?t.globalRuntime:{},accountViewedRegistry:ne(t.accountViewedRegistry)?t.accountViewedRegistry:{}}},Vf=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((t,r)=>{if(!ne(t))throw new Error(`Malformed applyScopedDataUpdates.updates[${r}] entry.`);let n=t.path?.startsWith(ls)?t.path.slice(ls.length):null;if(n!==null){if(!["device","account"].includes(t.scope))throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${r}].`);if(n.length===0)throw new Error(`Malformed applyScopedDataUpdates path "${t.path}" at updates[${r}].`);if(t.op!=="set")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${r}].`);return{scope:t.scope,path:t.path,op:t.op,value:t.value,variableId:n}}if(t.path==="viewedRegistry"){if(t.scope!=="account")throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${r}].`);if(t.op!=="markViewed")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${r}].`);return t}throw typeof t.path!="string"?new Error(`Malformed applyScopedDataUpdates path at updates[${r}].`):new Error(`Unsupported applyScopedDataUpdates path "${t.path}" at updates[${r}].`)})},jf=(e,t)=>{let r={};return Vf(t).forEach(n=>{if(n.path==="viewedRegistry"){r.accountViewedRegistry=Nf(r.accountViewedRegistry??e.accountViewedRegistry,n.value);return}let o=n.scope==="device"?"globalDeviceVariables":"globalAccountVariables";r[o]={...e[o],...r[o],[n.variableId]:n.value}}),r},Cn=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},Ff=e=>{let t=Cn(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},Mf=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},Uf=({indexedDB:e,databaseName:t,objectStoreName:r})=>new Promise((n,o)=>{let i=e.open(t,1);i.onupgradeneeded=()=>{let s=i.result;s.objectStoreNames.contains(r)||s.createObjectStore(r,{keyPath:"namespace"})},i.onsuccess=()=>{n(i.result)},i.onerror=()=>{o(i.error??new Error(`Failed to open IndexedDB database "${t}".`))}}),Bf=async({databasePromise:e,objectStoreName:t,namespace:r})=>{let n=await e;return new Promise((o,i)=>{let a=n.transaction(t,"readonly").objectStore(t).get(r);a.onsuccess=()=>{o(a.result??null)},a.onerror=()=>{i(a.error??new Error(`Failed to read persisted namespace "${r}" from IndexedDB.`))}})},Ct=async({databasePromise:e,objectStoreName:t,namespace:r,patch:n})=>{let o=await e;return new Promise((i,s)=>{let c=o.transaction(t,"readwrite"),a=c.objectStore(t),l=a.get(r),f=!1,u=p=>{f||(f=!0,s(p))},d=()=>{f||(f=!0,i())};l.onerror=()=>{u(l.error??new Error(`Failed to read persisted namespace "${r}" before updating IndexedDB.`))},l.onsuccess=()=>{let p=fs(l.result),h=typeof n=="function"?n(p):n,g={namespace:r,version:1,...us(),...p,...h},y=a.put(g);y.onerror=()=>{u(y.error??new Error(`Failed to persist namespace "${r}" to IndexedDB.`))}},c.oncomplete=()=>{d()},c.onerror=()=>{u(c.error??new Error(`IndexedDB transaction failed while updating namespace "${r}".`))},c.onabort=()=>{u(c.error??new Error(`IndexedDB transaction aborted while updating namespace "${r}".`))}})},zf=async({databasePromise:e,objectStoreName:t,namespace:r})=>{let n=await e;return new Promise((o,i)=>{let s=n.transaction(t,"readwrite"),a=s.objectStore(t).delete(r),l=!1,f=d=>{l||(l=!0,i(d))},u=()=>{l||(l=!0,o())};a.onerror=()=>{f(a.error??new Error(`Failed to clear persisted namespace "${r}" from IndexedDB.`))},s.oncomplete=()=>{u()},s.onerror=()=>{f(s.error??new Error(`IndexedDB transaction failed while clearing namespace "${r}".`))},s.onabort=()=>{f(s.error??new Error(`IndexedDB transaction aborted while clearing namespace "${r}".`))}})},Sn=(e={})=>{let{indexedDB:t,databaseName:r=kf,objectStoreName:n=Tf,namespace:o}=e,i=Mf(t),s=Ff(o),c=Uf({indexedDB:i,databaseName:r,objectStoreName:n});return{namespace:s,load:async()=>{let a=await Bf({databasePromise:c,objectStoreName:n,namespace:s});return{...us(),...fs(a)}},clear:async()=>zf({databasePromise:c,objectStoreName:n,namespace:s}),saveSlots:async a=>Ct({databasePromise:c,objectStoreName:n,namespace:s,patch:{saveSlots:ne(a)?a:{}}}),saveGlobalDeviceVariables:async a=>Ct({databasePromise:c,objectStoreName:n,namespace:s,patch:{globalDeviceVariables:ne(a)?a:{}}}),saveGlobalAccountVariables:async a=>Ct({databasePromise:c,objectStoreName:n,namespace:s,patch:{globalAccountVariables:ne(a)?a:{}}}),saveGlobalRuntime:async a=>Ct({databasePromise:c,objectStoreName:n,namespace:s,patch:{globalRuntime:ne(a)?a:{}}}),applyScopedDataUpdates:async a=>Ct({databasePromise:c,objectStoreName:n,namespace:s,patch:l=>jf(l,a)})}},qf=Sn;var Wf=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),Hf=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),ds="conditional",_n="form",Yf=new Set(["submitForm","cancelForm"]),St=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function Rn(e){let t,r=0,n=null,o=new Map,i=new Map,s=new Map,{handlePendingEffects:c}=e,a=(I=new Map,C=Date.now())=>new Map(Array.from(I.entries()).filter(([,R])=>C<R.expiresAt).map(([R,F])=>[R,{animation:structuredClone(F.animation),startedAt:F.startedAt,expiresAt:F.expiresAt}])),l=(I=new Map)=>Array.from(I.values()).map(C=>structuredClone(C.animation)),f=(I=Date.now())=>{o=new Map(Array.from(o.entries()).filter(([,C])=>I<C.expiresAt))},u=()=>{for(;t.selectPendingEffects().length>0;){let I=[...t.selectPendingEffects()];t.clearPendingEffects();try{c(I)}catch(C){throw t.clearPendingEffects(),I.forEach(R=>{t.appendPendingEffect(R)}),C}}},d=({initialState:I,namespace:C})=>{t=cs(I),r=0,n=Cn(C),o=new Map,i=new Map,s=new Map,t.appendPendingEffect({name:"handleLineActions"}),u()},p=()=>n,h=()=>t.selectPresentationState(),g=()=>t.selectPresentationChanges(),y=I=>t.selectSectionLineChanges(I),b=(I={})=>{r+=1;let C=Date.now();f(C);let R=i.size>0,F=a(o,C),B=R?a(i,C):new Map,ve={...t.selectRenderState({activePersistentAnimations:l(F),restoredPersistentAnimations:l(B)}),id:`render-${r}`};return s.set(ve.id,{builtAt:C,persistentAnimationSessions:new Map([...B.entries(),...F.entries()]),usedRestoredPersistentAnimationSessions:R}),ve},A=(I={})=>b(I),x=(I={})=>b(I),S=I=>{let C=typeof I?.id=="string"&&I.id.length>0?I.id:null,R=C?s.get(C):null;C&&s.delete(C);let F=new Map;Uo(I?.animations).forEach(B=>{let he=Gt(B);if(!he)return;let ve=R?.persistentAnimationSessions?.get(he)??o.get(he),_t=Math.max(0,zo(B)),Ln=ve?.startedAt??R?.builtAt??Date.now();F.set(he,{animation:structuredClone(B),startedAt:Ln,expiresAt:Ln+_t})}),o=F,R?.usedRestoredPersistentAnimationSessions&&(i=new Map)},P=()=>t.selectSystemState(),k=()=>t.selectSaveSlotMap(),w=I=>t.selectSaveSlot(I),j=I=>t.selectSaveSlotPage(I),M=()=>t.selectSkipMode(),ee=()=>t.selectAutoMode(),N=()=>t.selectRuntime(),q=()=>t.selectIsChoiceVisible(),W=()=>t.selectIsFormVisible(),te=()=>t.selectActiveInteraction(),xe=(I,C,R={})=>!St(C)||I!=="nextLine"?C:R.bypassChoice===!0?{...C,bypassChoice:!0}:R.interactionSource===_n?{...C,_interactionSource:_n}:C,Y=(I,C)=>{if(!t[I])return;Wf.has(I)&&(Hf.has(I)?i=a(o):i=new Map,o=new Map);let R=t[I](C);return u(),R},G=(I,C,R,F={})=>{if(I===ds){let B=re(R),he=Fr({[I]:C},B);se(he[I],R,F);return}Y(I,C)},oe=(I,C)=>{G(I,C)},re=I=>{if(!I)return{variables:t.selectAllVariables?t.selectAllVariables():void 0,runtime:t.selectRuntime?t.selectRuntime():{}};if(Object.prototype.hasOwnProperty.call(I,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:C,...R}=I,F=t.selectAllVariables?t.selectAllVariables():void 0;return{...R,_event:C,variables:F,runtime:t.selectRuntime?t.selectRuntime():{}}},K=I=>{if(!St(I))throw new Error("conditional action payload must be an object");if(!Array.isArray(I.branches))throw new Error("conditional action requires branches array");if(I.branches.length===0)throw new Error("conditional action requires at least one branch")},ie=(I,C,R)=>{if(!St(I))throw new Error(`conditional branch at index ${C} must be an object`);if(!St(I.actions))throw new Error(`conditional branch at index ${C} requires actions object`);if(!Object.prototype.hasOwnProperty.call(I,"when")&&C!==R-1)throw new Error("conditional else branch must be the last branch")},se=(I,C,R)=>{K(I);for(let F=0;F<I.branches.length;F+=1){let B=I.branches[F];ie(B,F,I.branches.length);let he=re(C);if(!(Object.prototype.hasOwnProperty.call(B,"when")&&!ht(B.when,he))){J(B.actions,C,R);return}}},v=(I,C)=>({...I??{},_form:C}),_=(I,C,R,F)=>{let B=Y(I,C),he=B?.submitted===!0&&B.valid===!0,ve=B?.cancelled===!0;!he&&!ve||St(C.actions)&&J(C.actions,v(R,B.form),{...F,interactionSource:_n})},V=(I,C,R,F)=>{let B=re(R),ve=Fr({[I]:C},B)[I];if(I===ds){se(ve,R,F);return}let _t=xe(I,ve,F);if(Yf.has(I)){_(I,_t,R,F);return}Y(I,_t)},J=(I,C,R)=>{Object.entries(I).forEach(([F,B])=>{V(F,B,C,R)})},z=(I,C,R={})=>{t.beginRollbackActionBatch({source:R.rollbackSource});try{J(I,C,R)}finally{t.endRollbackActionBatch({})}};return{init:d,handleAction:G,handleInternalAction:oe,handleActions:z,selectRenderState:A,prepareRenderState:x,commitRenderState:S,selectPresentationState:h,selectPresentationChanges:g,selectSectionLineChanges:y,selectSystemState:P,selectSaveSlotMap:k,selectSaveSlot:w,selectSaveSlotPage:j,selectSaveSlots:k,selectRuntime:N,selectIsChoiceVisible:q,selectIsFormVisible:W,selectActiveInteraction:te,handleLineActions:()=>{let I=t.selectCurrentLine();return I?.actions?(z(I.actions,void 0,{rollbackSource:"line"}),!0):!1},getNamespace:p}}var On=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:r=>{e=r},addElapsed:r=>{e+=r},getCallback:()=>t,setCallback:r=>{t=r}}},Gf=80,hs=({engine:e,routeGraphics:t,trackRenderDispatch:r},n)=>{let o=e.prepareRenderState?.(n)??e.selectRenderState(n);r?.(o),t.render(o),e.commitRenderState?.(o)},Kf=({engine:e,routeGraphics:t,trackRenderDispatch:r,getRenderDispatchCount:n},o)=>{let i=n?.()??0,s=e.handleLineActions();(n?.()??0)===i&&hs({engine:e,routeGraphics:t,trackRenderDispatch:r},o)},Jf=({engine:e,ticker:t,autoTimer:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let c=n.delay??1e3;r.getElapsed()>=c&&(t.remove(i),r.setCallback(null),r.setElapsed(0),pr(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},Xf=({ticker:e,autoTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},Qf=({engine:e,ticker:t,skipTimer:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let c=n?.delay??Gf;r.getElapsed()>=c&&(r.setElapsed(0),pr(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},Zf=({ticker:e,skipTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},ed=({engine:e,ticker:t,nextLineConfigTimerState:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let c=n.delay??1e3;r.getElapsed()>=c&&(r.setElapsed(0),pr(e,"nextLineFromSystem",{}),t.remove(i),r.setCallback(null))};r.setCallback(i),t.add(i)},td=({ticker:e,nextLineConfigTimerState:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},rd=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveSlots(t?.saveSlots))},nd=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalDeviceVariables(t?.globalDeviceVariables))},od=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalAccountVariables(t?.globalAccountVariables))},id=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalRuntime(t?.globalRuntime))},sd=({enqueuePersistenceWrite:e},t)=>{e(r=>{if(typeof r.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return r.applyScopedDataUpdates(t?.updates)})},ps={render:hs,saveSlots:rd,saveGlobalDeviceVariables:nd,saveGlobalAccountVariables:od,saveGlobalRuntime:id,applyScopedDataUpdates:sd,handleLineActions:Kf,startAutoNextTimer:Jf,clearAutoNextTimer:Xf,startSkipNextTimer:Qf,clearSkipNextTimer:Zf,nextLineConfigTimer:ed,clearNextLineConfigTimer:td},ad=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),pr=(e,t,r)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,r)},cd=(e=[])=>{let t=new Set,r=[];for(let n=e.length-1;n>=0;n-=1){let o=e[n];if(typeof o?.name!="string"||o.name.length===0)throw new Error("Pending effect is missing a valid name.");if(!ad.has(o.name)){r.unshift(o);continue}t.has(o.name)||(t.add(o.name),r.unshift(o))}return r},ld=({getEngine:e,routeGraphics:t,ticker:r,handleUnhandledEffect:n,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:c})=>{let a=On(),l=On(),f=On(),u=s??null,d=Promise.resolve(),p=null,h=null,g=!1,y=0,b=v=>{if(o){o(v);return}console.error("RouteEngine persistence write failed.",v)},A=()=>{if(u)return u;let v=e();return u=Sn({indexedDB:i,namespace:c??v?.getNamespace?.()}),u},x=v=>{d=d.catch(()=>{}).then(()=>{let _=A();return v(_)}).catch(_=>{b(_)})},S=v=>{let _=typeof v?.id=="string"&&v.id.length>0?v.id:null;y+=1,p=_,g=!1},P=()=>y,k=(v={})=>{if(v?.aborted===!0)return!1;let _=typeof v?.id=="string"&&v.id.length>0?v.id:null;return _?_!==p||_===h?!1:(h=_,!0):p!==null||g?!1:(g=!0,!0)},w=(v,_={})=>{if(v!=="renderComplete"||!k(_))return!1;let V=e();return pr(V,"markLineCompleted",{}),!0},j=new Set(["updateFormField","submitForm","cancelForm"]),M=new Set(["updateVariable"]),ee=v=>typeof v?.selectActiveInteraction=="function"?v.selectActiveInteraction():typeof v?.selectIsChoiceVisible=="function"&&v.selectIsChoiceVisible()?{source:"choice"}:null,N=v=>v?._formKey??v?.formKey,q=(v,_)=>N(v)===_?.formKey,W=(v,_)=>!v||typeof v!="object"||Array.isArray(v)?!1:v._interactionSource===_?.source,te=(v,_)=>W(v,_)?_.source==="form"?q(v,_):!0:!1,xe=(v,_)=>!v||typeof v!="object"||Array.isArray(v)||_?.source!=="form"?!1:q(v,_),Y=(v={})=>Object.keys(v).some(_=>j.has(_)),G=(v={},_)=>Object.entries(v).some(([V,J])=>j.has(V)&&xe(J,_)),oe=(v={})=>Object.keys(v).length>0&&Object.keys(v).every(_=>M.has(_)),re=(v={},_)=>{let V=v?.actions;return _?.source==="form"?!V||typeof V!="object"||Array.isArray(V)?!1:G(V,_)?!0:Y(V)?!1:oe(V):te(v,_)?!0:!V||typeof V!="object"||Array.isArray(V)?!1:Object.values(V).some(J=>te(J,_))},K=(v,_={})=>{if(!_?.actions)return!1;let V=ee(v);return!V||V.source==="choice"?!1:!re(_,V)},ie=({preprocessPayload:v,onEvent:_}={})=>async(V,J={})=>{let z=e();if(K(z,J))return _?.(V,J);let X=await v?.(V,J)??J;if(K(z,X))return _?.(V,X);if(w(V,X),X?.actions){let I=X?._event?{_event:X._event}:X?.event?{_event:X.event}:void 0,C;X?.bypassChoice===!0?C={bypassChoice:!0}:X?._interactionSource&&(C={interactionSource:X._interactionSource}),C?z.handleActions(X.actions,I,C):z.handleActions(X.actions,I)}return _?.(V,X)},se=v=>{let _=e(),V=cd(v);V.forEach(z=>{if(!ps[z.name]&&!n)throw new Error(`Unhandled pending effect "${z.name}".`)});let J={engine:_,routeGraphics:t,ticker:r,autoTimer:a,skipTimer:l,nextLineConfigTimerState:f,trackRenderDispatch:S,getRenderDispatchCount:P,enqueuePersistenceWrite:x};for(let z of V){let X=ps[z.name];if(X){X(J,z.payload);continue}n(z,J)}};return se.handleRouteGraphicsEvent=w,se.createRouteGraphicsEventHandler=ie,se},ud=ld;var fd=(e,t={})=>{let{resources:r={}}=t;return un(e,r)};var Bp=Rn;export{zr as DEFAULT_VISUAL_LAYER,nt as RENDER_LAYER,_e as VISUAL_LAYER,ud as createEffectsHandler,qf as createIndexedDbPersistence,Bp as default,Ea as resolveComputedVariables,fd as resolveLayoutReferences};
1
+ var Ss=Object.defineProperty;var _s=(e,t)=>{for(var r in t)Ss(e,r,{get:t[r],enumerable:!0})};var Gn=Symbol.for("immer-nothing"),zn=Symbol.for("immer-draftable"),fe=Symbol.for("immer-state");function be(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var rt=Object.getPrototypeOf;function de(e){return!!e&&!!e[fe]}function Ue(e){return e?Kn(e)||Array.isArray(e)||!!e[zn]||!!e.constructor?.[zn]||Nt(e)||Vt(e):!1}var Rs=Object.prototype.constructor.toString();function Kn(e){if(!e||typeof e!="object")return!1;let t=rt(e);if(t===null)return!0;let r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return r===Object?!0:typeof r=="function"&&Function.toString.call(r)===Rs}function kt(e,t){Pt(e)===0?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,n)=>t(n,r,e))}function Pt(e){let t=e[fe];return t?t.type_:Array.isArray(e)?1:Nt(e)?2:Vt(e)?3:0}function xr(e,t){return Pt(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Jn(e,t,r){let n=Pt(e);n===2?e.set(t,r):n===3?e.add(r):e[t]=r}function Os(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Nt(e){return e instanceof Map}function Vt(e){return e instanceof Set}function Me(e){return e.copy_||e.base_}function vr(e,t){if(Nt(e))return new Map(e);if(Vt(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=Kn(e);if(t===!0||t==="class_only"&&!r){let n=Object.getOwnPropertyDescriptors(e);delete n[fe];let o=Reflect.ownKeys(n);for(let i=0;i<o.length;i++){let s=o[i],c=n[s];c.writable===!1&&(c.writable=!0,c.configurable=!0),(c.get||c.set)&&(n[s]={configurable:!0,writable:!0,enumerable:c.enumerable,value:e[s]})}return Object.create(rt(e),n)}else{let n=rt(e);if(n!==null&&r)return{...e};let o=Object.create(n);return Object.assign(o,e)}}function Or(e,t=!1){return jt(e)||de(e)||!Ue(e)||(Pt(e)>1&&(e.set=e.add=e.clear=e.delete=Ls),Object.freeze(e),t&&Object.entries(e).forEach(([r,n])=>Or(n,!0))),e}function Ls(){be(2)}function jt(e){return Object.isFrozen(e)}var $s={};function Be(e){let t=$s[e];return t||be(0,e),t}var dt;function Xn(){return dt}function ks(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function Wn(e,t){t&&(Be("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Cr(e){Sr(e),e.drafts_.forEach(Ds),e.drafts_=null}function Sr(e){e===dt&&(dt=e.parent_)}function qn(e){return dt=ks(dt,e)}function Ds(e){let t=e[fe];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function Hn(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[fe].modified_&&(Cr(t),be(4)),Ue(e)&&(e=Dt(t,e),t.parent_||Tt(t,e)),t.patches_&&Be("Patches").generateReplacementPatches_(r[fe].base_,e,t.patches_,t.inversePatches_)):e=Dt(t,r,[]),Cr(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Gn?e:void 0}function Dt(e,t,r){if(jt(t))return t;let n=t[fe];if(!n)return kt(t,(o,i)=>Yn(e,n,t,o,i,r)),t;if(n.scope_!==e)return t;if(!n.modified_)return Tt(e,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;let o=n.copy_,i=o,s=!1;n.type_===3&&(i=new Set(o),o.clear(),s=!0),kt(i,(c,a)=>Yn(e,n,o,c,a,r,s)),Tt(e,o,!1),r&&e.patches_&&Be("Patches").generatePatches_(n,r,e.patches_,e.inversePatches_)}return n.copy_}function Yn(e,t,r,n,o,i,s){if(de(o)){let c=i&&t&&t.type_!==3&&!xr(t.assigned_,n)?i.concat(n):void 0,a=Dt(e,o,c);if(Jn(r,n,a),de(a))e.canAutoFreeze_=!1;else return}else s&&r.add(o);if(Ue(o)&&!jt(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Dt(e,o),(!t||!t.scope_.parent_)&&typeof n!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,n)&&Tt(e,o)}}function Tt(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&Or(t,r)}function Ts(e,t){let r=Array.isArray(e),n={type_:r?1:0,scope_:t?t.scope_:Xn(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=n,i=Lr;r&&(o=[n],i=pt);let{revoke:s,proxy:c}=Proxy.revocable(o,i);return n.draft_=c,n.revoke_=s,c}var Lr={get(e,t){if(t===fe)return e;let r=Me(e);if(!xr(r,t))return Ps(e,r,t);let n=r[t];return e.finalized_||!Ue(n)?n:n===wr(e.base_,t)?(Er(e),e.copy_[t]=Rr(n,e)):n},has(e,t){return t in Me(e)},ownKeys(e){return Reflect.ownKeys(Me(e))},set(e,t,r){let n=Qn(Me(e),t);if(n?.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){let o=wr(Me(e),t),i=o?.[fe];if(i&&i.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(Os(r,o)&&(r!==void 0||xr(e.base_,t)))return!0;Er(e),_r(e)}return e.copy_[t]===r&&(r!==void 0||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_[t]=!0),!0},deleteProperty(e,t){return wr(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,Er(e),_r(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=Me(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:n.enumerable,value:r[t]}},defineProperty(){be(11)},getPrototypeOf(e){return rt(e.base_)},setPrototypeOf(){be(12)}},pt={};kt(Lr,(e,t)=>{pt[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});pt.deleteProperty=function(e,t){return pt.set.call(this,e,t,void 0)};pt.set=function(e,t,r){return Lr.set.call(this,e[0],t,r,e[0])};function wr(e,t){let r=e[fe];return(r?Me(r):e)[t]}function Ps(e,t,r){let n=Qn(t,r);return n?"value"in n?n.value:n.get?.call(e.draft_):void 0}function Qn(e,t){if(!(t in e))return;let r=rt(e);for(;r;){let n=Object.getOwnPropertyDescriptor(r,t);if(n)return n;r=rt(r)}}function _r(e){e.modified_||(e.modified_=!0,e.parent_&&_r(e.parent_))}function Er(e){e.copy_||(e.copy_=vr(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Ns=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,r,n)=>{if(typeof t=="function"&&typeof r!="function"){let i=r;r=t;let s=this;return function(a=i,...l){return s.produce(a,f=>r.call(this,f,...l))}}typeof r!="function"&&be(6),n!==void 0&&typeof n!="function"&&be(7);let o;if(Ue(t)){let i=qn(this),s=Rr(t,void 0),c=!0;try{o=r(s),c=!1}finally{c?Cr(i):Sr(i)}return Wn(i,n),Hn(o,i)}else if(!t||typeof t!="object"){if(o=r(t),o===void 0&&(o=t),o===Gn&&(o=void 0),this.autoFreeze_&&Or(o,!0),n){let i=[],s=[];Be("Patches").generateReplacementPatches_(t,o,i,s),n(i,s)}return o}else be(1,t)},this.produceWithPatches=(t,r)=>{if(typeof t=="function")return(s,...c)=>this.produceWithPatches(s,a=>t(a,...c));let n,o;return[this.produce(t,r,(s,c)=>{n=s,o=c}),n,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){Ue(e)||be(8),de(e)&&(e=ze(e));let t=qn(this),r=Rr(e,void 0);return r[fe].isManual_=!0,Sr(t),r}finishDraft(e,t){let r=e&&e[fe];(!r||!r.isManual_)&&be(9);let{scope_:n}=r;return Wn(n,t),Hn(void 0,n)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){let o=t[r];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}r>-1&&(t=t.slice(r+1));let n=Be("Patches").applyPatches_;return de(e)?n(e,t):this.produce(e,o=>n(o,t))}};function Rr(e,t){let r=Nt(e)?Be("MapSet").proxyMap_(e,t):Vt(e)?Be("MapSet").proxySet_(e,t):Ts(e,t);return(t?t.scope_:Xn()).drafts_.push(r),r}function ze(e){return de(e)||be(10,e),Zn(e)}function Zn(e){if(!Ue(e)||jt(e))return e;let t=e[fe],r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=vr(e,t.scope_.immer_.useStrictShallowCopy_)}else r=vr(e,!0);return kt(r,(n,o)=>{Jn(r,n,Zn(o))}),t&&(t.finalized_=!1),r}var pe=new Ns,$r=pe.produce,_d=pe.produceWithPatches.bind(pe),Rd=pe.setAutoFreeze.bind(pe),Od=pe.setUseStrictShallowCopy.bind(pe),Ld=pe.applyPatches.bind(pe),$d=pe.createDraft.bind(pe),kd=pe.finishDraft.bind(pe);var m={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},O={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},nt={NOT:0};var E=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},ue=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var kr=e=>{if(!e||e.trim()==="")throw new E("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let r=e.includes("===")?"==":"!=";throw new E(`Invalid comparison operator '${e.includes("===")?"===":"!=="}' - did you mean '${r}'? (got: '${e}')`)}let t=["<",">","<=",">=","==","!="];for(let r of t)if(e.trim().endsWith(r))throw new E(`Incomplete comparison expression - missing right operand (got: '${e}')`)},eo=e=>{if(e.trim().endsWith(" in"))throw new E(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new E(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,r]=e.split(" in ");if(!r||r.trim()==="")throw new E(`Missing iterable expression after 'in' (got: '$for ${e}')`);let n=t.includes(",")?t.split(",").map(o=>o.trim()):[t.trim()];for(let o of n){if(!o)throw new E(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new E(`Invalid loop syntax (got: '$for ${e}')`)}};var to=(e,t,r=!1)=>{if(t===null)return new ue(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new ue(`Cannot iterate over undefined value at '$for ${e}'`);let n=typeof t;return r?new ue(`Cannot iterate over non-array value in loop '${e}' - got ${n} instead`):new ue(`Cannot iterate over non-array value (got: ${n}) at '$for ${e}'`)},ro=(e,t)=>{let r=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new ue(`Unknown function '${e}' (${r})`)};var Vs=(e,t,r={})=>{let n={},o={};r&&typeof r=="object"&&(r.functions!==void 0||r.partials!==void 0?(n=r.functions||{},o=r.partials||{}):typeof r=="object"&&(n=r));let s=$(e,{functions:n,partials:o},t,{});return s===void 0?{}:s},$=(e,t,r,n)=>{let o=t.functions||t;if(e.var&&!e.type)return Y(e.var,r,n);if(e.type===m.LITERAL)return e.value;if(e.type===m.VARIABLE)return Y(e.path,r,n);if(e.type===m.INTERPOLATION)return Fs(e.parts,t,r,n);switch(e.type){case m.FUNCTION:return oo(e,t,r,n);case m.BINARY:return io(e,t,r,n);case m.UNARY:return so(e,t,r,n);case m.CONDITIONAL:return Us(e,t,r,n);case m.LOOP:return Hs(e,t,r,n);case m.OBJECT:return Gs(e,t,r,n);case m.ARRAY:return Ks(e,t,r,n);case m.PARTIAL:return Js(e,t,r,n);case m.PATH_REFERENCE:return Xs(e,t,r,n);default:throw new Error(`Unknown node type: ${e.type}`)}},no=new Map,js=e=>{let t=[],r="",n=!1;for(let o=0;o<e.length;o++){let i=e[o];if(i==="[")r&&(t.push({type:"property",value:r}),r=""),n=!0;else if(i==="]"){if(n&&r){let s=r.trim();if(/^\d+$/.test(s))t.push({type:"index",value:parseInt(s,10)});else if(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'")){let c=s.slice(1,-1);t.push({type:"property",value:c})}else t.push({type:"property",value:s});r=""}n=!1}else r+=i}return r&&t.push({type:"property",value:r}),t},Y=(e,t,r)=>{if(!e)return;if(e in r)return r[e];let n=no.get(e);if(!n){let i=[],s="",c=0;for(let a=0;a<e.length;a++){let l=e[a];l==="["?(c++,s+=l):l==="]"?(c--,s+=l):l==="."&&c===0?s&&(i.push(s),s=""):s+=l}s&&i.push(s),n=[];for(let a of i){let l=js(a.trim());n.push(...l)}no.set(e,n)}let o=t;for(let i=0;i<n.length;i++){let s=n[i];if(s.type==="property"&&s.value in r){o=r[s.value];continue}if(o==null)return;(s.type==="property"||s.type==="index")&&(o=o[s.value])}return o},Fs=(e,t,r,n)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=$(i,t,r,n);o.push(s!=null?String(s):"")}return o.join("")},oo=(e,t,r,n)=>{let o=t.functions||t,i=o[e.name];if(!i)throw ro(e.name,o);let s=e.args.map(c=>$(c,t,r,n));return i(...s)},$e=(e,t,r,n)=>{if(e.var&&!e.type)return Y(e.var,r,n);switch(e.type){case m.VARIABLE:return Y(e.path,r,n);case m.LITERAL:return e.value;case m.BINARY:return io(e,t,r,n);case m.UNARY:return so(e,t,r,n);case m.FUNCTION:return oo(e,t,r,n);default:return $(e,t,r,n)}},io=(e,t,r,n)=>{if(e.op===O.AND||e.op===O.OR){let s=$e(e.left,t,r,n),c=$e(e.right,t,r,n);switch(e.op){case O.AND:return s&&c;case O.OR:return s||c}}let o=$(e.left,t,r,n),i=$(e.right,t,r,n);switch(e.op){case O.EQ:return o==i;case O.NEQ:return o!=i;case O.GT:return o>i;case O.LT:return o<i;case O.GTE:return o>=i;case O.LTE:return o<=i;case O.IN:return Array.isArray(i)?i.includes(o):!1;case O.ADD:if(typeof o!="number"||typeof i!="number")throw new ue(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case O.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new ue(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},so=(e,t,r,n)=>{let o=e.op===nt.NOT?$e(e.operand,t,r,n):$(e.operand,t,r,n);if(e.op===nt.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},Ms=(e,t,r,n)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===m.VARIABLE)if(Y(o.path,r,n)){let s=e.bodies[0];if(s.type===m.OBJECT&&s.properties.length<=5){let c={};for(let a of s.properties){let l=a.parsedKey?$(a.parsedKey,t,r,n):a.key,f=a.value;if(f.type===m.LITERAL)c[l]=f.value;else if(f.type===m.VARIABLE)c[l]=Y(f.path,r,n);else if(f.type===m.INTERPOLATION){let u=[];for(let d of f.parts)if(typeof d=="string")u.push(d);else if(d.type===m.VARIABLE){let p=Y(d.path,r,n);u.push(p!=null?String(p):"")}else{let p=$(d,t,r,n);u.push(p!=null?String(p):"")}c[l]=u.join("")}else c[l]=$(f,t,r,n)}return c}}else{let s=e.bodies[1];if(s.type===m.OBJECT&&s.properties.length<=5){let c={};for(let a of s.properties){let l=a.parsedKey?$(a.parsedKey,t,r,n):a.key,f=a.value;if(f.type===m.LITERAL)c[l]=f.value;else if(f.type===m.VARIABLE)c[l]=Y(f.path,r,n);else if(f.type===m.INTERPOLATION){let u=[];for(let d of f.parts)if(typeof d=="string")u.push(d);else if(d.type===m.VARIABLE){let p=Y(d.path,r,n);u.push(p!=null?String(p):"")}else{let p=$(d,t,r,n);u.push(p!=null?String(p):"")}c[l]=u.join("")}else c[l]=$(f,t,r,n)}return c}}}return null},Us=(e,t,r,n)=>{let o=Ms(e,t,r,n);if(o!==null)return o;for(let i=0;i<e.conditions.length;i++){let s=e.conditions[i];if(s===null||$e(s,t,r,n))return $(e.bodies[i],t,r,n)}return ao},Bs=(e,t)=>{let r=e.body,n=e.itemVar;if(r.type===m.CONDITIONAL&&r.conditions.length===1&&r.conditions[0].type===m.VARIABLE){let o=r.conditions[0].path,i=r.bodies[0];if(o.startsWith(n+".")){let s=o.substring(n.length+1);if(i.type===m.OBJECT&&i.properties.length<=5){for(let a of i.properties)if(a.parsedKey)return null;let c=[];for(let a=0;a<t.length;a++){let l=t[a];if(l[s]){let f={};for(let u of i.properties){let d=u.key,p=u.value;if(p.type===m.LITERAL)f[d]=p.value;else if(p.type===m.VARIABLE){let h=p.path;if(h===n)f[d]=l;else if(h.startsWith(n+".")){let g=h.substring(n.length+1);f[d]=l[g]}else return null}else if(p.type===m.INTERPOLATION){let h=[],g=!0;for(let y of p.parts)if(typeof y=="string")h.push(y);else if(y.type===m.VARIABLE){let b=y.path;if(b===n)h.push(l!=null?String(l):"");else if(b.startsWith(n+".")){let A=b.substring(n.length+1),x=l[A];h.push(x!=null?String(x):"")}else{g=!1;break}}else{g=!1;break}if(!g)return null;f[d]=h.join("")}else return null}c.push(f)}}return c}}}return null},zs=(e,t)=>{let r=e.body,n=e.itemVar,o=Bs(e,t);if(o!==null)return o;if(r.type===m.OBJECT&&r.properties.length<=5&&!r.whenCondition){for(let c of r.properties)if(c.parsedKey)return null;let i=[],s=!0;for(let c of r.properties){let a=c.key,l=c.value;if(l.type===m.LITERAL)i.push({key:a,type:"literal",value:l.value});else if(l.type===m.VARIABLE){let f=l.path;if(f===n)i.push({key:a,type:"item"});else if(f.startsWith(n+".")){let u=f.substring(n.length+1);if(!u.includes(".")&&!u.includes("["))i.push({key:a,type:"prop",prop:u});else{s=!1;break}}else{s=!1;break}}else if(l.type===m.INTERPOLATION&&l.parts.length===1){let f=l.parts[0];if(f.type===m.VARIABLE){let u=f.path;if(u===n)i.push({key:a,type:"item_string"});else if(u.startsWith(n+".")){let d=u.substring(n.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:a,type:"prop_string",prop:d});else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}if(s){let c=new Array(t.length);if(i.length===3&&i[0].type==="prop"&&i[0].key==="id"&&i[1].type==="prop_string"&&i[1].key==="title"&&i[2].type==="prop"&&i[2].key==="completed")for(let a=0;a<t.length;a++){let l=t[a];c[a]={id:l.id,title:l.title!=null?String(l.title):"",completed:l.completed}}else for(let a=0;a<t.length;a++){let l=t[a],f={};for(let u of i)if(u.type==="literal")f[u.key]=u.value;else if(u.type==="item")f[u.key]=l;else if(u.type==="prop")f[u.key]=l[u.prop];else if(u.type==="item_string")f[u.key]=l!=null?String(l):"";else if(u.type==="prop_string"){let d=l[u.prop];f[u.key]=d!=null?String(d):""}c[a]=f}return c}}return null},Ws=(e,t,r,n,o)=>{let i=[],s=e.body;if(s.type===m.OBJECT&&s.fast!==!1){let c=e.itemVar,a=e.indexVar;for(let l=0;l<o.length;l++){let f=o[l],u={},d={...n,[c]:f,...a&&{[a]:l}};d.__paths__||(d.__paths__=n.__paths__||{});let p=e.iterable.path||"";if(n&&n.__paths__&&p){let h=p.split("."),g=h[0];g in n.__paths__&&(p=n.__paths__[g],h.length>1&&(p+="."+h.slice(1).join(".")))}d.__paths__={...d.__paths__,[c]:`${p}[${l}]`,...a&&{[a]:l}};for(let h of s.properties){let g=h.parsedKey?$(h.parsedKey,t,r,d):h.key,y=h.value;if(y.type===m.LITERAL)u[g]=y.value;else if(y.type===m.VARIABLE){let b=y.path;if(b===c)u[g]=f;else if(b===a)u[g]=l;else if(b.startsWith(c+".")){let A=b.substring(c.length+1);!A.includes(".")&&!A.includes("[")?u[g]=f[A]:u[g]=Y(b,r,{...n,[c]:f,...a&&{[a]:l}})}else u[g]=Y(b,r,{...n,[c]:f,...a&&{[a]:l}})}else if(y.type===m.INTERPOLATION){let b=[];for(let A of y.parts)if(typeof A=="string")b.push(A);else if(A.type===m.VARIABLE){let x=A.path,S;if(x===c)S=f;else if(x===a)S=l;else if(x.startsWith(c+".")){let P=x.substring(c.length+1);!P.includes(".")&&!P.includes("[")?S=f[P]:S=Y(x,r,{...n,[c]:f,...a&&{[a]:l}})}else S=Y(x,r,{...n,[c]:f,...a&&{[a]:l}});b.push(S!=null?String(S):"")}else{let x={...n,[c]:f,...a&&{[a]:l}},S=$(A,t,r,x);b.push(S!=null?String(S):"")}u[g]=b.join("")}else{let b={...n,[c]:f,...a&&{[a]:l}};u[g]=$(y,t,r,b)}}i.push(u)}return i}return null},qs=(e,t,r)=>{let n=e.body;if(n.type===m.OBJECT&&n.properties.length===1&&n.properties[0].key==="$if item.visible"){let i=n.properties[0].value;if(i.type===m.CONDITIONAL&&i.conditions.length===1&&i.conditions[0].type===m.VARIABLE&&i.conditions[0].path==="item.visible"){let s=i.bodies[0];if(s.type===m.OBJECT&&s.properties.length===2){let c=s.properties[0],a=s.properties[1];if(c.key==="id"&&c.value.type===m.VARIABLE&&c.value.path==="item.id"&&a.key==="$if item.highlighted"&&a.value.type===m.CONDITIONAL){let l=[];for(let f=0;f<t.length;f++){let u=t[f];if(u.visible){let d={id:u.id};u.highlighted?(d.highlight=!0,d.message=`This item is highlighted: ${u.name}`):(d.highlight=!1,d.message=u.name),l.push(d)}}return l}}}}return null},Hs=(e,t,r,n)=>{let o=$(e.iterable,t,r,n);if(!Array.isArray(o)){let l,f=!1;if(e.iterable.type===m.FUNCTION){f=!0;let d=e.iterable.args.map(p=>p.type===m.LITERAL?typeof p.value=="string"?`'${p.value}'`:String(p.value):p.type===m.VARIABLE?p.path:p.type===m.FUNCTION?`${p.name}(...)`:"?").join(", ");l=`${e.iterable.name}(${d})`}else l=e.iterable.path||"undefined";let u=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${l}`;throw to(u,o,f)}if(!e.indexVar){let l=qs(e,o,e.itemVar);if(l!==null)return l}if(!e.indexVar){let l=zs(e,o);if(l!==null)return l}let i=Ws(e,t,r,n,o);if(i!==null)return i;let s=[],c=e.iterable.path||"";if(n&&n.__paths__&&c){let l=c.split("."),f=l[0];f in n.__paths__&&(c=n.__paths__[f],l.length>1&&(c+="."+l.slice(1).join(".")))}let a=!1;e.body.type===m.ARRAY&&(e.body.items.length<=1?a=!1:a=e.body._shouldPreserveArray??=e.body.items.some(l=>l.type===m.OBJECT&&l.properties.some(f=>f.key.startsWith("$if ")||f.key.startsWith("$when "))));for(let l=0;l<o.length;l++){let f=e.indexVar?{...n,[e.itemVar]:o[l],[e.indexVar]:l}:{...n,[e.itemVar]:o[l]};f.__paths__||(f.__paths__=n.__paths__||{}),f.__paths__={...f.__paths__,[e.itemVar]:`${c}[${l}]`},e.indexVar&&(f.__paths__[e.indexVar]=l);let u=$(e.body,t,r,f);if(Array.isArray(u)&&u.length===1&&!a){let d=u[0];s.push(d===void 0?{}:d)}else s.push(u===void 0?{}:u)}return s},Ys=(e,t,r,n)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?$(o.parsedKey,t,r,n):o.key,s=o.value;if(s.type===m.OBJECT&&s.properties.length<=10&&!s.whenCondition){let c={},a={},l=!0;for(let f of s.properties){let u=f.parsedKey?$(f.parsedKey,t,r,n):f.key,d=f.value;if(d.type===m.LITERAL)a[u]=d.value;else if(d.type===m.VARIABLE)a[u]=Y(d.path,r,n);else if(d.type===m.INTERPOLATION){let p=[];for(let h of d.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let g=Y(h.path,r,n);p.push(g!=null?String(g):"")}else{l=!1;break}if(!l)break;a[u]=p.join("")}else if(d.type===m.OBJECT&&d.properties.length<=5){let p={};for(let h of d.properties){let g=h.key,y=h.value;if(y.type===m.LITERAL)p[g]=y.value;else if(y.type===m.VARIABLE)p[g]=Y(y.path,r,n);else if(y.type===m.INTERPOLATION){let b=[];for(let A of y.parts)if(typeof A=="string")b.push(A);else if(A.type===m.VARIABLE){let x=Y(A.path,r,n);b.push(x!=null?String(x):"")}else{l=!1;break}if(!l)break;p[g]=b.join("")}else{l=!1;break}}if(!l)break;a[u]=p}else{l=!1;break}}if(l)return c[i]=a,c}}return null},Gs=(e,t,r,n)=>{let o=t.functions||t;if(e.whenCondition&&!$e(e.whenCondition,o,r,n))return;let i=Ys(e,t,r,n);if(i!==null)return i;if(e.fast){let l={};for(let f of e.properties){let u=f.parsedKey?$(f.parsedKey,t,r,n):f.key,d=f.value;if(d.type===m.LITERAL)l[u]=d.value;else if(d.type===m.VARIABLE)l[u]=Y(d.path,r,n);else if(d.type===m.INTERPOLATION){let p=[];for(let h of d.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let g=Y(h.path,r,n);p.push(g!=null?String(g):"")}else{let g=$(h,t,r,n);p.push(g!=null?String(g):"")}l[u]=p.join("")}else l[u]=$(d,t,r,n)}return l}let s={},c=null,a=!1;for(let l of e.properties)if(!l.key.startsWith("$if ")&&!l.key.match(/^\$if\s+\w+.*:?$/)&&!l.key.startsWith("$elif")&&!l.key.startsWith("$else")&&!l.key.startsWith("$for ")){a=!0;break}for(let l of e.properties)if(l.key.startsWith("$if ")||l.key.match(/^\$if\s+\w+.*:?$/)){let f=$(l.value,t,r,n);if(!a&&f!==null&&f!==void 0)return Array.isArray(f)&&f.length===1?f[0]:f;typeof f=="object"&&f!==null&&!Array.isArray(f)&&Object.assign(s,f)}else if(l.key.startsWith("$for ")){if(e.properties.length===1)return $(l.value,t,r,n)}else{let f=l.value;if(f&&f.type===m.OBJECT&&f.properties){let u=f.properties.find(d=>d.key.startsWith("$for "));if(u){let d=$(u.value,t,r,n);d!==void 0&&(s[l.key]=d)}else{let d=$(l.value,t,r,n);d!==void 0&&(s[l.key]=d)}}else{let u=l.parsedKey?$(l.parsedKey,t,r,n):l.key,d=$(l.value,t,r,n);d!==void 0&&(s[u]=d)}}return s},ao={},Ks=(e,t,r,n)=>{let o=[];for(let i of e.items)if(i.type===m.LOOP){let s=$(i,t,r,n);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=$(i,t,r,n);s!==ao&&s!==void 0&&o.push(s)}return o},Js=(e,t,r,n)=>{let{name:o,data:i,whenCondition:s}=e,c=t.partials||{},a=t.functions||t;if(s&&!$e(s,a,r,n))return;if(!c[o])throw new ue(`Partial '${o}' is not defined`);let l=n._partialStack||[];if(l.includes(o))throw new ue(`Circular partial reference detected: ${o}`);let f=c[o],u=r,d={...n,_partialStack:[...l,o]};if(n){u={...r};for(let p of Object.keys(n))p.startsWith("_")||(u[p]=n[p])}if(i){let p=$(i,t,r,n);u={...u,...p}}return $(f,t,u,d)},Xs=(e,t,r,n)=>{let{path:o}=e,i=o.split("."),s=i[0],c=i.slice(1);if(!n||!(s in n))throw new ue(`Path reference '#{${o}}' refers to '${s}' which is not a loop variable in the current scope`);if(n.__paths__||(n.__paths__={}),!(s in n.__paths__))throw new ue(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let a=n.__paths__[s];if(typeof a=="number"){if(c.length>0)throw new ue(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(a)}return c.length>0&&(a+="."+c.join(".")),a};var Dr=Vs;var Qs=/\$\{([^}]*)\}/g,Zs=/#\{([^}]*)\}/g,lo=(e,t={})=>{let r=e.match(/^(\w+)\((.*)\)$/);if(!r)return{isFunction:!1};let[,n,o]=r,i=ea(o,t);return{isFunction:!0,type:m.FUNCTION,name:n,args:i}},ea=(e,t={})=>e.trim()?ta(e).map(n=>ra(n.trim(),t)):[],ta=e=>{let t=[],r="",n=0,o=!1,i="";for(let s=0;s<e.length;s++){let c=e[s],a=s>0?e[s-1]:"";!o&&(c==='"'||c==="'")?(o=!0,i=c,r+=c):o&&c===i&&a!=="\\"?(o=!1,i="",r+=c):!o&&c==="("?(n++,r+=c):!o&&c===")"?(n--,r+=c):!o&&c===","&&n===0?(t.push(r),r=""):r+=c}return r&&t.push(r),t},ra=(e,t={})=>{if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:m.LITERAL,value:e.slice(1,-1)};if(/^-?\d+(\.\d+)?$/.test(e))return{type:m.LITERAL,value:parseFloat(e)};if(e==="true")return{type:m.LITERAL,value:!0};if(e==="false")return{type:m.LITERAL,value:!1};if(e==="null")return{type:m.LITERAL,value:null};let r=lo(e,t);if(r.isFunction)return{type:r.type,name:r.name,args:r.args};let n=e.trim(),o=[{op:" + ",type:"ADD"},{op:" - ",type:"SUBTRACT"}],i=-1,s=null;for(let{op:c,type:a}of o){let l=0;for(;l<n.length;){let f=We(n.substring(l),c);if(f===-1)break;let u=l+f;u>i&&(i=u,s={op:c,type:a}),l=u+c.length}}if(i!==-1)try{return J(n,t)}catch{return{type:m.VARIABLE,path:n}}return{type:m.VARIABLE,path:n}},uo=/^\w+\(.*\)$/,na=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,oa=e=>{if(!(!e||e.trim()===""||uo.test(e))&&na.test(e))throw e.includes("?")&&e.includes(":")?new E(`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 E(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new E(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},co=e=>{let t=e.trim();if(uo.test(t))throw new E(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new E(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new E(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new E(`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 E(`Complex expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);return{type:m.PATH_REFERENCE,path:t}},ht=(e,t={})=>{let r=e.trim();oa(r);let n=lo(r,t);if(n.isFunction)return{type:n.type,name:n.name,args:n.args};if(r.includes("[")&&!/[\s+\-*/%|&?:]/.test(r)){let o=0;for(let i of r)i==="["?o++:i==="]"&&o--;if(o!==0)throw new Error("Invalid array index syntax")}return{type:m.VARIABLE,path:r}},Tr=(e,t={})=>{let r=e,n=[];(e.includes("\\${")||e.includes("\\#{"))&&(r=e.replace(/\\\\(\$\{[^}]*\})/g,"\\DOUBLE_ESC_VAR$1"),r=r.replace(/\\\\(#\{[^}]*\})/g,"\\DOUBLE_ESC_PATH$1"),r=r.replace(/\\(\$\{[^}]*\})/g,(l,f)=>{let u=`__ESCAPED_${n.length}__`;return n.push(f),u}),r=r.replace(/\\(#\{[^}]*\})/g,(l,f)=>{let u=`__ESCAPED_${n.length}__`;return n.push(f),u}),r=r.replace(/\\DOUBLE_ESC_VAR/g,"\\"),r=r.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...r.matchAll(Qs)],i=[...r.matchAll(Zs)],s=[...o.map(l=>({match:l,type:"variable"})),...i.map(l=>({match:l,type:"pathref"}))].sort((l,f)=>l.match.index-f.match.index);if(s.length===0){let l=r;for(let f=0;f<n.length;f++)l=l.replace(`__ESCAPED_${f}__`,n[f]);return{type:m.LITERAL,value:l}}if(s.length===1&&s[0].match[0]===r&&n.length===0){let{match:l,type:f}=s[0];try{return f==="variable"?ht(l[1],t):co(l[1])}catch(u){if(u.message==="Invalid array index syntax")return{type:m.LITERAL,value:r};throw u}}let c=[],a=0;for(let{match:l,type:f}of s){let[u,d]=l,p=l.index;if(p>a){let h=r.substring(a,p);for(let g=0;g<n.length;g++)h=h.replace(`__ESCAPED_${g}__`,n[g]);h&&c.push(h)}try{let h;f==="variable"?h=ht(d.trim(),t):h=co(d.trim()),c.push(h)}catch(h){if(h.message==="Invalid array index syntax")c.push(u);else throw h}a=p+u.length}if(a<r.length){let l=r.substring(a);for(let f=0;f<n.length;f++)l=l.replace(`__ESCAPED_${f}__`,n[f]);l&&c.push(l)}return{type:m.INTERPOLATION,parts:c}};var Vr=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),ho=e=>Object.keys(e),ie=e=>e.join("."),ke=(e,t,r)=>{let n=ho(e).filter(o=>!t.has(o));if(n.length>0)throw new E(`Unexpected key '${n[0]}' in condition JSON at '${ie(r)}'`)},De=(e,t)=>typeof e=="string"?Tr(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?sa(e,t):aa(e,t):{type:m.LITERAL,value:e},ia=e=>{let{$each:t,...r}=e;if(typeof t!="string")throw new E("$each value must be a non-empty string");let n=t.trim();if(n==="")throw new E("$each value must be a non-empty string");if(Object.keys(r).length===0)throw new E("Empty $each body not allowed");if(r.$partial!==void 0)throw new E("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${n}`]:r}},sa=(e,t)=>{let r=[],n=!1;for(let o=0;o<e.length;o++){let i=e[o];if(typeof i=="object"&&i!==null&&!Array.isArray(i)){if(i.$each!==void 0)try{let a=ia(i),l=Object.keys(a);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let f=po(l[0],a[l[0]],t,!0);r.push(f),n=!0;continue}}catch(a){throw a instanceof E?a:new E(a.message)}let c=Object.keys(i);if(c.length===1&&/^\$for(?::\w+)?\s/.test(c[0])){let a=po(c[0],i[c[0]],t);r.push(a),n=!0;continue}}let s=De(i,t);r.push(s),(s.type===m.FUNCTION||s.type===m.CONDITIONAL||s.type===m.LOOP||s.type===m.PARTIAL||s.type===m.OBJECT&&!s.fast||s.type===m.ARRAY&&!s.fast)&&(n=!0)}return{type:m.ARRAY,items:r,fast:!n}},aa=(e,t)=>{let r=[],n=!1,o=null,i=Object.entries(e),s=0;if(e.$partial!==void 0){if(typeof e.$partial!="string")throw new E("$partial value must be a string");if(e.$partial.trim()==="")throw new E("$partial value cannot be an empty string");let a=["$if","$elif","$else","$for"],l=[];for(let[b]of i)for(let A of a)if(b===A||b.startsWith(A+" ")||b.startsWith(A+"#")){l.push(A);break}if(l.length>0)throw new E(`Cannot use $partial with ${l.join(", ")} at the same level. Wrap $partial in a parent object if you need conditionals.`);let{$partial:f,$when:u,...d}=e,p={},h=!1;for(let[b,A]of Object.entries(d)){let x=b;(b.startsWith("\\$")||b.startsWith("$$"))&&(x=b.slice(1)),p[x]=A,h=!0}let g=null;if(h&&(g=De(p,t),g.type===m.OBJECT)){let b=!1;for(let A of g.properties)if(A.value.type===m.VARIABLE||A.value.type===m.INTERPOLATION||A.value.type===m.FUNCTION||A.value.type===m.CONDITIONAL||A.value.type===m.OBJECT&&!A.value.fast||A.value.type===m.ARRAY&&!A.value.fast){b=!0;break}b&&(g.fast=!1)}let y={type:m.PARTIAL,name:f,data:g};return u!==void 0&&(y.whenCondition=fo(u,t)),y}for(let[a,l]of i)if(a==="$when"){if(o!==null)throw new E("Multiple '$when' directives on the same object are not allowed");if(l==null)throw new E("Missing condition expression after '$when'");o=fo(l,t),n=!0}else if(a.startsWith("$when#")||a.startsWith("$when "))throw new E("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<i.length;){let[a,l]=i[s];if(a==="$when"){s++;continue}if(a==="$each")throw new E("$each can only be used inside arrays");if(a.startsWith("$if ")||a.match(/^\$if#\w+\s/)||a.match(/^\$if\s+\w+.*:$/)){let f=ca(i,s,t);r.push({key:a,value:f.node}),n=!0,s=f.nextIndex}else if(/^\$for(?::\w+)?\s/.test(a)){let f=a.match(/^\$for(?::(\w+))?\s/)?.[1]||"",u=f?`:${f}`:"";throw new E(`$for loops must be inside arrays - use '- $for${u} item in items:' instead of '$for${u} item in items:'. For cleaner object generation syntax, consider using $each.`)}else{if(a.startsWith("$elif ")||a.startsWith("$else"))throw new E(`'${a.split(" ")[0]}' without matching '$if'`);if(a==="$if"||a==="$if:")throw new E("Missing condition expression after '$if'");{let f=De(l,t);(f.type===m.FUNCTION||f.type===m.CONDITIONAL||f.type===m.PARTIAL||f.type===m.OBJECT&&!f.fast||f.type===m.ARRAY&&!f.fast)&&(n=!0);let u=Tr(a,t),d={key:a,value:f};(u.type!==m.LITERAL||u.value!==a)&&(d.parsedKey=u),r.push(d),s++}}}let c={type:m.OBJECT,properties:r,fast:!n};return o&&(c.whenCondition=o),c},ca=(e,t,r={})=>{let n=[],o=[],i=t,[s,c]=e[i],a=null,l;if(s.startsWith("$if#")){let u=s.match(/^\$if#(\w+)\s+(.+)$/);if(u)a=u[1],l=u[2];else throw new E(`Invalid conditional syntax: ${s}`)}else l=s.substring(4),l.endsWith(":")&&(l=l.slice(0,-1).trim());kr(l);let f=J(l,r);for(n.push(f),o.push(De(c,r)),i++;i<e.length;){let[u,d]=e[i],p=!1,h;if(a?u.startsWith(`$elif#${a} `)?(h=u.substring(`$elif#${a} `.length),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(u===`$else#${a}`||u===`$else#${a}:`)&&(p=!0,h=null):u.startsWith("$elif ")?(h=u.substring(6),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(u==="$else"||u==="$else:")&&(p=!0,h=null),p){if(h===null)n.push(null);else{kr(h);let g=J(h,r);n.push(g)}if(o.push(De(d,r)),i++,h===null)break}else break}return{node:{type:m.CONDITIONAL,conditions:n,bodies:o,id:a},nextIndex:i}},Pr={eq:O.EQ,neq:O.NEQ,gt:O.GT,gte:O.GTE,lt:O.LT,lte:O.LTE,in:O.IN,add:O.ADD,sub:O.SUBTRACT},Nr={all:O.AND,any:O.OR},la=new Set(["var","literal","call","not",...Object.keys(Pr),...Object.keys(Nr)]),ua=(e,t,r)=>{if(!Array.isArray(e))throw new E(`Condition JSON operator '${t}' at '${ie(r)}' requires an array`);if(e.length!==2)throw new E(`Condition JSON operator '${t}' at '${ie(r)}' requires exactly 2 operands`);return e},fa=(e,t,r,n,o)=>{if(!Array.isArray(e))throw new E(`Condition JSON operator '${t}' at '${ie(o)}' requires an array`);if(e.length===0)throw new E(`Condition JSON operator '${t}' at '${ie(o)}' requires at least 1 condition`);return e.map((s,c)=>Ce(s,n,[...o,c])).reduce((s,c)=>({type:m.BINARY,op:r,left:s,right:c}))},da=(e,t,r)=>{let n,o;if(typeof e.call=="string")n=e.call,o=e.args??[],ke(e,new Set(["call","args"]),r);else if(Vr(e.call))n=e.call.name,o=e.call.args??[],ke(e,new Set(["call"]),r),ke(e.call,new Set(["name","args"]),[...r,"call"]);else throw new E(`Condition JSON call at '${ie(r)}' requires a function name`);if(typeof n!="string"||n.trim()==="")throw new E(`Condition JSON call at '${ie(r)}' requires a non-empty function name`);if(!/^\w+$/.test(n))throw new E(`Invalid condition JSON function name '${n}' at '${ie(r)}'`);if(!Array.isArray(o))throw new E(`Condition JSON call '${n}' at '${ie(r)}' requires args to be an array`);return{type:m.FUNCTION,name:n,args:o.map((i,s)=>Ce(i,t,[...r,"args",s]))}},Ce=(e,t={},r=["$when"])=>{if(typeof e=="string"||typeof e=="number"||typeof e=="boolean"||e===null)return{type:m.LITERAL,value:e};if(Array.isArray(e))throw new E(`Condition JSON array at '${ie(r)}' must be wrapped in an operator or { literal: [...] }`);if(!Vr(e))throw new E(`Invalid condition JSON value at '${ie(r)}'`);let n=ho(e);if(n.length===0)throw new E(`Condition JSON object at '${ie(r)}' must contain an operator`);let o=n.filter(s=>la.has(s));if(o.length===0)throw new E(`Unknown condition JSON operator '${n[0]}' at '${ie(r)}'`);if(o.length>1)throw new E(`Condition JSON at '${ie(r)}' must contain exactly one operator`);let i=o.includes("call")?"call":o[0];if(i==="var"){if(ke(e,new Set(["var"]),r),typeof e.var!="string"||e.var.trim()==="")throw new E(`Condition JSON var at '${ie(r)}' requires a non-empty path`);return{type:m.VARIABLE,path:e.var}}if(i==="literal")return ke(e,new Set(["literal"]),r),{type:m.LITERAL,value:e.literal};if(i==="call")return da(e,t,r);if(i==="not")return ke(e,new Set(["not"]),r),{type:m.UNARY,op:nt.NOT,operand:Ce(e.not,t,[...r,"not"])};if(i in Nr)return ke(e,new Set([i]),r),fa(e[i],i,Nr[i],t,[...r,i]);if(i in Pr){ke(e,new Set([i]),r);let s=ua(e[i],i,[...r,i]);return{type:m.BINARY,op:Pr[i],left:Ce(s[0],t,[...r,i,0]),right:Ce(s[1],t,[...r,i,1])}}throw new E(`Unknown condition JSON operator '${i}' at '${ie(r)}'`)},fo=(e,t={})=>{if(e==null)throw new E("Missing condition expression after '$when'");if(typeof e=="string"){if(e.trim()==="")throw new E("Empty condition expression after '$when'");return J(e,t)}return Vr(e)||Array.isArray(e)?Ce(e,t):{type:m.LITERAL,value:e}},J=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let l=e.slice(1,-1),f=0,u=!0;for(let d=0;d<l.length;d++)if(l[d]==="("?f++:l[d]===")"&&f--,f<0){u=!1;break}if(u&&f===0)return J(l,t)}let r=We(e,"||");if(r!==-1)return{type:m.BINARY,op:O.OR,left:J(e.substring(0,r).trim(),t),right:J(e.substring(r+2).trim(),t)};let n=We(e,"&&");if(n!==-1)return{type:m.BINARY,op:O.AND,left:J(e.substring(0,n).trim(),t),right:J(e.substring(n+2).trim(),t)};let o=[{op:">=",type:O.GTE},{op:"<=",type:O.LTE},{op:"==",type:O.EQ},{op:"!=",type:O.NEQ},{op:">",type:O.GT},{op:"<",type:O.LT},{op:" in ",type:O.IN}];for(let{op:l,type:f}of o){let u=We(e,l);if(u!==-1)return{type:m.BINARY,op:f,left:J(e.substring(0,u).trim(),t),right:J(e.substring(u+l.length).trim(),t)}}let i=-1,s=null,c=[{op:" + ",type:O.ADD},{op:" - ",type:O.SUBTRACT}];for(let{op:l,type:f}of c){let u=0;for(;u<e.length;){let d=We(e.substring(u),l);if(d===-1)break;let p=u+d;p>i&&(i=p,s={op:l,type:f}),u=p+l.length}}if(i!==-1&&s)return{type:m.BINARY,op:s.type,left:J(e.substring(0,i).trim(),t),right:J(e.substring(i+s.op.length).trim(),t)};let a=[" * "," / "," % "];for(let l of a)if(We(e,l)!==-1)throw new E(`Arithmetic operations are not allowed in conditionals: "${l}"`);return e.startsWith("!")?{type:m.UNARY,op:nt.NOT,operand:J(e.substring(1).trim(),t)}:mo(e,t)},We=(e,t)=>{let r=0,n=0;for(;n<=e.length-t.length;){if(e[n]==="(")r++;else if(e[n]===")")r--;else if(r===0&&e.substring(n,n+t.length)===t)return n;n++}return-1},pa=e=>{if(e=e.trim(),e==="true")return{type:m.LITERAL,value:!0};if(e==="false")return{type:m.LITERAL,value:!1};if(e==="null")return{type:m.LITERAL,value:null};if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:m.LITERAL,value:e.slice(1,-1)};if(e==='""'||e==="''")return{type:m.LITERAL,value:""};if(e==="{}")return{type:m.LITERAL,value:{}};if(e==="[]")return{type:m.LITERAL,value:[]};let t=Number(e);return!isNaN(t)&&isFinite(t)?{type:m.LITERAL,value:t}:{type:m.VARIABLE,path:e}},mo=(e,t)=>{let r=e.trim();if(r.match(/^(\w+)\((.*)\)$/))return ht(r,t);let o=pa(r);if(o.type===m.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(r))return{type:m.VARIABLE,path:r};try{return ht(r,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},ha=(e,t=!1)=>{let r=t?"$each":"$for";try{eo(e)}catch(n){if(n instanceof E&&t){let o=n.message.replace(/\$for/g,"$each");throw new E(o.replace("Parse Error: ",""))}throw n}},po=(e,t,r,n=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let y=n?"$each":"$for";throw new E(`Invalid loop syntax (got: '${e.replace("$for",y)}')`)}let s=i[1],c=i[2].trim();ha(c,n);let a=c.match(/^(.+?)\s+in\s+(.+)$/);if(!a){let y=n?"$each":"$for";throw new E(`Invalid loop syntax - missing 'in' keyword (got: '${y} ${c}')`)}let l=a[1].trim(),f=a[2].trim(),u,d=null;if(l.includes(",")){let y=l.split(",").map(b=>b.trim());if(y.length!==2)throw new E(`Invalid loop variables: ${l}. Expected format: "item" or "item, index"`);u=y[0],d=y[1]}else u=l;let p=["this","undefined","null","true","false"];if(p.includes(u))throw new E(`Reserved variable name: ${u}`);if(d&&p.includes(d))throw new E(`Reserved variable name: ${d}`);let h=mo(f,r),g=De(t,r);return{type:m.LOOP,itemVar:u,indexVar:d,iterable:h,body:g,flatten:s!=="nested"}};var ma=(e,t={})=>{let{functions:r={}}=t;return De(e,r)},Ft=ma;var mt={};_s(mt,{now:()=>ga});var ga=()=>Date.now();var ya=(e,t,r={})=>{let{functions:n={},partials:o={}}=r,i={...mt,...n},s=Ft(e,{functions:i}),c={};for(let[a,l]of Object.entries(o))c[a]=Ft(l,{functions:i});return Dr(s,t,{functions:i,partials:c})},se=ya;var ba=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",Ia=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,Aa=(e,t)=>{if(ba(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new E("Empty condition expression");return J(e,t)}return Ce(e,t)},wa=(e,t={},r={})=>{let n=Ia(r),o={...mt,...n},i=Aa(e,o);return!!$e(i,{functions:o,partials:{}},t,{})},jr=wa;var yt=(e,t={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return jr(e,t)},wo=(e,t,r={})=>{let n=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=a=>a,transformActionFirstArgument:c=a=>a}=r;for(let[a,l]of Object.entries(t))a!=="createInitialState"&&(a.startsWith("select")?o[a]=(...f)=>l(s(n),...f):i[a]=(...f)=>{let u;return n=$r(n,p=>{let h=l(c(p),...f);u=h!==void 0&&!de(h)?h:void 0}),u});return{...o,...i}},Bt=(e,t)=>r=>{let n=e(),o=Array.isArray(r)?r:[r];return $r(n,i=>{o.forEach(s=>{t.forEach(c=>{c(i,s)})})})};var Ea=(e,t)=>{if(e.default!==void 0)return e.default;let r=["number","boolean","string","object"];if(!r.includes(e.type))throw new Error(`Invalid variable type: ${e.type} for variable ${t}. Expected one of: ${r.join(", ")}`);switch(e.type){case"number":return 0;case"boolean":return!1;case"string":return"";case"object":return{}}},ge=(e,t)=>Object.prototype.hasOwnProperty.call(e??{},t),gt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Eo=e=>{let t=de(e)?ze(e):e;return structuredClone(t)},xa=({characterId:e,resourceCharacter:t,variables:r={}}={})=>{if(!ge(t,"nameVariableId"))return;let n=t.nameVariableId,o=r?.[n];if(typeof o!="string")throw new Error(`Character "${e}" nameVariableId "${n}" must resolve to a string variable`);return o},zt=({characterId:e,character:t,characterName:r,characters:n={},variables:o={}}={})=>{let i=e?n?.[e]:void 0;if(t?.name!==void 0)return t.name;if(r!==void 0)return r;let s=xa({characterId:e,resourceCharacter:i,variables:o});return s!==void 0?s:i?.name||""},Te=e=>ge(e,"computed"),ot=(e={},t={})=>Object.fromEntries(Object.entries(e??{}).filter(([r])=>!Te(t[r]))),va=e=>String(e).replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean),Fr=(e,t)=>{let r=e;for(let n of t){if(r==null)return;r=r[n]}return r},Ca=(e,t={})=>{if(typeof e!="string"||e.trim()==="")throw new Error("Computed expression var requires a non-empty string path");let r=va(e),[n,o,...i]=r;if(n==="variables"){if(!o)return t.variables;let s=typeof t.resolveVariable=="function"?t.resolveVariable(o):t.variables?.[o];return Fr(s,i)}return n==="runtime"?Fr(t.runtime,r.slice(1)):Fr(t,r)},Sa=(e,t,r)=>{if(!Array.isArray(t))throw new Error(`Computed expression operator "${e}" requires an array`);if(r!==void 0&&t.length!==r)throw new Error(`Computed expression operator "${e}" requires ${r} operand(s)`)},go=(e,t)=>{if(!Array.isArray(t))throw new Error(`Computed expression operator "${e}" requires an array`);if(t.length===0)throw new Error(`Computed expression operator "${e}" requires at least one operand`)},_a=(e,t)=>{if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Computed expression operator "${e}" requires finite numeric operands`)},Ie=(e,t,r,n)=>(Sa(e,t,n),t.map(o=>Ut(o,r))),me=(e,t,r,n)=>{let o=Ie(e,t,r,n);return o.forEach(i=>_a(e,i)),o},Ra=(e,t,r)=>{switch(e){case"var":return Ca(t,r);case"add":{let[n,o]=me(e,t,r,2);return n+o}case"sub":{let[n,o]=me(e,t,r,2);return n-o}case"mul":{let[n,o]=me(e,t,r,2);return n*o}case"div":{let[n,o]=me(e,t,r,2);return n/o}case"mod":{let[n,o]=me(e,t,r,2);return n%o}case"neg":{let[n]=me(e,t,r,1);return-n}case"round":{let[n]=me(e,t,r,1);return Math.round(n)}case"floor":{let[n]=me(e,t,r,1);return Math.floor(n)}case"ceil":{let[n]=me(e,t,r,1);return Math.ceil(n)}case"min":{let[n,o]=me(e,t,r,2);return Math.min(n,o)}case"max":{let[n,o]=me(e,t,r,2);return Math.max(n,o)}case"clamp":{let[n,o,i]=me(e,t,r,3);return Math.min(i,Math.max(o,n))}case"eq":{let[n,o]=Ie(e,t,r,2);return n==o}case"neq":{let[n,o]=Ie(e,t,r,2);return n!=o}case"gt":{let[n,o]=Ie(e,t,r,2);return n>o}case"gte":{let[n,o]=Ie(e,t,r,2);return n>=o}case"lt":{let[n,o]=Ie(e,t,r,2);return n<o}case"lte":{let[n,o]=Ie(e,t,r,2);return n<=o}case"in":{let[n,o]=Ie(e,t,r,2);return Array.isArray(o)?o.includes(n):!1}case"and":case"all":return go(e,t),t.every(n=>!!Ut(n,r));case"or":case"any":return go(e,t),t.some(n=>!!Ut(n,r));case"not":{let[n]=Ie(e,t,r,1);return!n}case"length":{let[n]=Ie(e,t,r,1);return typeof n=="string"||Array.isArray(n)?n.length:gt(n)?Object.keys(n).length:0}case"includes":{let[n,o]=Ie(e,t,r,2);return typeof n=="string"||Array.isArray(n)?n.includes(o):!1}case"literal":return Eo(t);default:throw new Error(`Unknown computed expression operator: ${e}`)}},Ut=(e,t={})=>{if(e===null||typeof e!="object")return e;if(Array.isArray(e))throw new Error("Computed expression arrays are not valid; use value for literal arrays");let r=Object.entries(e);if(r.length!==1)throw new Error("Computed expression objects must contain exactly one operator");let[[n,o]]=r;return Ra(n,o,t)},Oa=(e,t={})=>yt(e,{variables:t.variables,runtime:t.runtime}),La=(e,t)=>{if(!gt(e))throw new Error(`${t} must be an object`);let r=ge(e,"expr"),n=ge(e,"value");if(r===n)throw new Error(`${t} must contain exactly one of expr or value`)},Mr=(e,t,r)=>(La(e,t),ge(e,"value")?Eo(e.value):Ut(e.expr,r)),$a=(e,t={},r="unknown")=>{if(!gt(e))throw new Error(`Computed variable "${r}" computed must be an object`);let n=ge(e,"expr"),o=ge(e,"value");if(ge(e,"branches")){if(n||o)throw new Error(`Computed variable "${r}" cannot combine branches with expr or value`);if(!Array.isArray(e.branches))throw new Error(`Computed variable "${r}" branches must be an array`);if(e.branches.length===0)throw new Error(`Computed variable "${r}" branches must not be empty`);if(!gt(e.default))throw new Error(`Computed variable "${r}" requires default`);for(let s=0;s<e.branches.length;s+=1){let c=e.branches[s];if(!gt(c))throw new Error(`Computed variable "${r}" branch ${s} must be an object`);if(!ge(c,"when"))throw new Error(`Computed variable "${r}" branch ${s} requires when`);if(Oa(c.when,t))return Mr(c,`Computed variable "${r}" branch ${s}`,t)}return Mr(e.default,`Computed variable "${r}" default`,t)}if(n===o)throw new Error(`Computed variable "${r}" must contain exactly one of expr, value, or branches`);return Mr(e,`Computed variable "${r}"`,t)},ka=(e,t,r)=>{switch(t){case"number":if(typeof r!="number"||!Number.isFinite(r))throw new Error(`Computed variable "${e}" expected type number, got ${Array.isArray(r)?"array":typeof r}`);return;case"boolean":if(typeof r!="boolean")throw new Error(`Computed variable "${e}" expected type boolean, got ${Array.isArray(r)?"array":typeof r}`);return;case"string":if(typeof r!="string")throw new Error(`Computed variable "${e}" expected type string, got ${Array.isArray(r)?"array":typeof r}`);return;case"object":if(r===null||typeof r!="object")throw new Error(`Computed variable "${e}" expected type object, got ${typeof r}`);return;default:throw new Error(`Invalid variable type: ${t} for computed variable ${e}`)}},bt=({variables:e={},runtime:t={},variableConfigs:r={},eager:n=!0}={})=>{let o=ot(e,r),i=Object.entries(r).filter(([,u])=>Te(u)).map(([u])=>u),s={},c=[],a=u=>{if(ge(s,u))return s[u];let d=r[u];if(!Te(d))return o[u];let p=c.indexOf(u);if(p>=0){let h=[...c.slice(p),u].join(" -> ");throw new Error(`Computed variable cycle detected: ${h}`)}c.push(u);try{let h=$a(d.computed,f,u);return ka(u,d.type,h),s[u]=h,h}finally{c.pop()}},l=new Proxy({},{get:(u,d)=>{if(typeof d=="string")return a(d)},has:(u,d)=>typeof d=="string"&&(ge(o,d)||i.includes(d)),ownKeys:()=>[...new Set([...Object.keys(o),...i])],getOwnPropertyDescriptor:(u,d)=>{if(!(typeof d!="string"||!ge(o,d)&&!i.includes(d)))return{enumerable:!0,configurable:!0}}}),f={variables:l,runtime:t,resolveVariable:a};return n?(i.forEach(u=>{a(u)}),{...o,...s}):l},Da=({variables:e={},runtime:t={},variableConfigs:r,projectData:n}={})=>bt({variables:e,runtime:t,variableConfigs:r??n?.resources?.variables??{},eager:!0}),Wt=e=>{let t={},r={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([n,o])=>{if(Te(o))return;let i=Ea(o,n);o.scope==="context"?t[n]=i:r[n]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}},qt=(e,t)=>{let r=["context","device","account"];if(!e)throw new Error(`Variable scope is required for variable: ${t}`);if(!r.includes(e))throw new Error(`Invalid variable scope: ${e} for variable ${t}. Expected one of: ${r.join(", ")}`)},Ht=(e,t,r)=>{let n={number:["set","increment","decrement","multiply","divide"],boolean:["set","toggle"],string:["set"],object:["set"]},o=n[e];if(!o)throw new Error(`Unknown variable type: ${e} for variable ${r}`);if(!Object.values(n).flat().includes(t))throw new Error(`Unknown operation: ${t}`);if(!o.includes(t))throw new Error(`Operation "${t}" is not valid for variable "${r}" of type "${e}". Valid operations: ${o.join(", ")}`)},Ta=2,yo=12,xo=(e=Ta)=>{if(!Number.isInteger(e)||e<0||e>yo)throw new Error(`Operation "divide" requires roundTo to be an integer between 0 and ${yo}.`);return e},Pa=(e,t)=>{let r=10**t;return Math.round((e+Number.EPSILON)*r)/r},Mt=e=>typeof e=="number"&&Number.isFinite(e),zr=(e,t,r,n,o={})=>{if(e==="number"){if(t==="set"&&!Mt(r))throw new Error(`Operation "set" requires value to be a number for variable "${n}".`);if(t==="multiply"&&!Mt(r))throw new Error(`Operation "multiply" requires value to be a number for variable "${n}".`);if(t==="divide"&&!Mt(r))throw new Error(`Operation "divide" requires value to be a number for variable "${n}".`);if(t==="divide"){if(r===0)throw new Error(`Operation "divide" requires value to be a non-zero number for variable "${n}".`);xo(o.roundTo)}}},Yt=(e,t,r,n={})=>{let o=(s,c,a)=>{let l=s??c;if(!Mt(l))throw new Error(`Operation "${t}" requires ${a} to be a number.`);return l},i=s=>{let c=o(s,void 0,"value");if(c===0)throw new Error(`Operation "${t}" requires value to be a non-zero number.`);return c};switch(t){case"set":return r;case"multiply":return o(e,1,"current value")*o(r,void 0,"value");case"divide":return Pa(o(e,0,"current value")/i(r),xo(n.roundTo));case"increment":return o(e,0,"current value")+o(r,1,"value");case"decrement":return o(e,0,"current value")-o(r,1,"value");case"toggle":return!e;default:throw new Error(`Unknown operation: ${t}`)}};var vo=(e,t="DD/MM/YYYY - HH:mm")=>{if(!e)return"";let r=new Date(e),n=o=>String(o).padStart(2,"0");return t.replace("DD",n(r.getDate())).replace("MM",n(r.getMonth()+1)).replace("YYYY",r.getFullYear()).replace("YY",String(r.getFullYear()).slice(-2)).replace("HH",n(r.getHours())).replace("mm",n(r.getMinutes())).replace("ss",n(r.getSeconds()))},Na=(e,t)=>{let r=i=>{if(!i)return;let s={};i.ui&&(s.ui=i.ui);let c=i.character?.sprite;return c&&Object.keys(c).length>0&&(s.sprite=c),Object.keys(s).length>0?s:void 0},n=r(e),o=r(t);return JSON.stringify(n)===JSON.stringify(o)?null:n&&!o?{changeType:"delete",data:e}:o&&!n?{changeType:"add",data:t}:o&&n?{changeType:"update",data:t}:null},bo=e=>{if(e?.resourceId===void 0)return;let t={resourceId:e.resourceId};e.transformId!==void 0&&(t.transformId=e.transformId);for(let r of["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"])e[r]!==void 0&&(t[r]=e[r]);for(let r of["animationName","animationSpeed","loop"])e[r]!==void 0&&(t[r]=e[r]);return t},Io=e=>{if(e?.colorId!==void 0)return{colorId:e.colorId}},Ao=(e,t)=>t&&!e?{changeType:"add",data:t}:e&&!t?{changeType:"delete",data:e}:e&&t&&JSON.stringify(e)!==JSON.stringify(t)?{changeType:"update",data:t}:null,Va=(e,t)=>{let r={},n=Ao(bo(e),bo(t)),o=Ao(Io(e),Io(t));return n&&(r.resource=n),o&&(r.color=o),Object.keys(r).length>0?r:null},Wr=(e={},t={})=>{let r={},n=["sfx","voice"],o=c=>{let a=e[c],l=t[c];l&&!a?r[c]={changeType:"add",data:l}:a&&!l?n.includes(c)||(r[c]={changeType:"delete",data:a}):a&&l&&JSON.stringify(a)!==JSON.stringify(l)&&(r[c]={changeType:"update",data:l})},i=Va(e.background,t.background);i&&(r.background=i),o("screen"),o("bgm"),o("voice");let s=Na(e.dialogue,t.dialogue);return s&&(r.dialogue=s),o("choice"),o("form"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),r},qr=(e={})=>{let t=structuredClone(e);t.background&&(t.background.animations?.playback?.continuity!=="persistent"&&delete t.background.animations,!t.background.resourceId&&!t.background.colorId&&delete t.background);let r=o=>{t[o]&&(delete t[o].animations,Object.keys(t[o]).length===0&&delete t[o])};r("layout"),r("choice"),r("form"),r("screen"),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 n=(o,i)=>{let s=t[o]?.items;Array.isArray(s)&&(t[o].items=s.map(c=>{let a={...c};return delete a.animations,i(a)?a:null}).filter(Boolean),t[o].items.length===0&&delete t[o])};return n("character",o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId),n("visual",o=>o.resourceId||o.transformId),t},ja=(e,t)=>{if(!e||!t)return;let r=e;for(let n of t.split(".")){if(r==null||!(n in Object(r)))return;r=r[n]}return r},Fa=(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 r=e.slice(7),n=ja(t,r);if(n===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return n},Ma={conditional:new Set(["branches"]),updateProjectData:new Set(["projectData"]),showConfirmDialog:new Set(["confirmActions","cancelActions"]),form:new Set(["submitActions","cancelActions"]),submitForm:new Set(["actions"]),cancelForm:new Set(["actions"])},Co=(e,t)=>{let r=e[e.length-1];return r?Ma[r]?.has(t)===!0:!1},Ur=(e,t,r=[])=>Array.isArray(e)?e.map(n=>Ur(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,Co(r,n)?o:Ur(o,t,[...r,n])])):Fa(e,t),Br=(e,t,r=[])=>Array.isArray(e)?e.map(n=>Br(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,Co(r,n)?o:Br(o,t,[...r,n])])):typeof e=="string"?se(e,t):e,Hr=(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 r=Ur(e,t._event);return Br(r,t)};var W=e=>structuredClone(de(e)?ze(e):e),B=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),So=e=>e?.animations?.playback?.continuity==="persistent",k=(e,t)=>B(e??{},t)&&e[t]!==void 0,It=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:W(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},Ua=e=>k(e,"opacity")||k(e,"blur"),Lo=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],$o=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],Yr=["animationName","animationSpeed","loop"],Ba=e=>Lo.some(t=>k(e,t)),ko=e=>e?.text&&k(e.text,"content")&&k(e.text,"textStyleId"),Do=e=>k(e,"text"),za=(e,t)=>e.resourceId?!0:ko(e)?!t?.text:!1,Wa=(e,t)=>{let r={...W(e),...t};return t.text&&e.text&&(r.text={...W(e.text),...W(t.text)}),r},qa=(e,t)=>{if(Do(e)){if(e.resourceId)throw new Error(`Visual item "${e.id}" cannot define both resourceId and text`);if(!ko(e)&&!t?.text)throw new Error(`Visual item "${e.id}" text requires content and textStyleId`)}},_o=e=>$o.some(t=>k(e,t)),Ro=e=>Yr.some(t=>k(e,t)),Ha=(e,t,{hasAuthoredTransformId:r=!1}={})=>{if(!t)return e;for(let n of $o)!r&&!k(e,n)&&k(t,n)&&(e[n]=t[n]),B(e,n)&&e[n]===void 0&&delete e[n];return e},To=(e,t,r)=>{let n=e[r];return n?.id===t?.id?n:e.find(o=>o.id===t?.id)},Ya=(e,t)=>{if(!t)return e;for(let r of Lo)!k(e,r)&&k(t,r)&&(e[r]=t[r]),B(e,r)&&e[r]===void 0&&delete e[r];return e},Ga=(e,t)=>(t&&(!k(e,"opacity")&&k(t,"opacity")&&(e.opacity=t.opacity),!k(e,"blur")&&k(t,"blur")&&(e.blur=W(t.blur)),B(e,"opacity")&&e.opacity===void 0&&delete e.opacity,B(e,"blur")&&e.blur===void 0&&delete e.blur),e),Po=(e,t,r=[],{hasPatchFn:n=()=>!1,mergeItemFn:o}={})=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let i=e.map((s,c)=>{let a=To(r,s,c),l=t(s,a),f=Ua(s),u=Ba(s),d=n(s),p=B(s,"animations"),h=W(s);return!l&&(f||u||d)&&a&&(h=o?o(a,h):{...W(a),...h},p||delete h.animations),Ga(Ya(h,a),a)}).filter(s=>t(s)||s.animations);return{hasValidItems:i.length>0,processedItems:i}},Ka=e=>{if(e){if(e.character&&B(e.character,"name"))return e.character.name;if(B(e,"characterName"))return e.characterName}},No=e=>!!e?.character&&B(e.character,"sprite"),Ja=e=>{let t={},r=!1,n=Ka(e);return n!==void 0&&(t.name=n,r=!0),No(e)&&(t.sprite=W(e.character.sprite),r=!0),r?t:void 0},Oo=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},Xa=({dialogueState:e,content:t,append:r=!1})=>{if(!r||!Array.isArray(t)){e.content=t,delete e.initialRevealedContent;return}let n=Array.isArray(e.content)?e.content:[];n.length>0?e.initialRevealedContent=n.map(o=>W(o)):delete e.initialRevealedContent,e.content=[...n,...t]},Qa=()=>({}),Za=(e,t)=>{if(!t.screen)return;let r=k(t.screen,"opacity"),n=k(t.screen,"blur"),o=B(t.screen,"animations");if(!r&&!n){o||delete e.screen;return}let i=e.screen,s={};if(r?s.opacity=t.screen.opacity:k(i,"opacity")&&(s.opacity=i.opacity),n?s.blur=W(t.screen.blur):k(i,"blur")&&(s.blur=W(i.blur)),B(s,"opacity")&&s.opacity===void 0&&delete s.opacity,B(s,"blur")&&s.blur===void 0&&delete s.blur,Object.keys(s).length===0){delete e.screen;return}e.screen=s},ec=(e,t)=>{if(t.background){let r=k(t.background,"resourceId"),n=k(t.background,"colorId"),o=k(t.background,"opacity"),i=k(t.background,"blur"),s=k(t.background,"transformId"),c=_o(t.background),a=Ro(t.background),{animationsOnly:l,state:f}=It(t.background,p=>k(p,"resourceId")||k(p,"colorId")||k(p,"opacity")||k(p,"blur")||k(p,"transformId")||_o(p)||Ro(p));if(l){e.background=e.background?{...W(e.background),...f}:f;return}if(!r&&!n&&!o&&!i&&!s&&!c&&!a){delete e.background;return}let u=e.background,d=W(t.background);if(!r&&u?.resourceId){d.resourceId=u.resourceId,!B(d,"transformId")&&u.transformId&&(d.transformId=u.transformId);for(let p of Yr)!k(d,p)&&k(u,p)&&(d[p]=u[p])}Ha(d,u,{hasAuthoredTransformId:s}),!n&&u?.colorId&&(d.colorId=u.colorId),!o&&k(u,"opacity")&&(d.opacity=u.opacity),!i&&k(u,"blur")&&(d.blur=W(u.blur)),B(d,"resourceId")&&d.resourceId===void 0&&delete d.resourceId,B(d,"colorId")&&d.colorId===void 0&&delete d.colorId,B(d,"animations")&&d.animations===void 0&&delete d.animations,B(d,"transformId")&&d.transformId===void 0&&delete d.transformId,B(d,"opacity")&&d.opacity===void 0&&delete d.opacity,B(d,"blur")&&d.blur===void 0&&delete d.blur;for(let p of Yr)B(d,p)&&d[p]===void 0&&delete d[p];if(!d.resourceId&&!d.colorId){delete e.background;return}u?.resourceId===d.resourceId&&u?.transformId===d.transformId&&!B(d,"animations")&&So(u)&&(d.animations=W(u.animations)),e.background=d}else e.background?.animations&&!So(e.background)&&(e.background.animations={})},tc=(e,t)=>{if(!t.dialogue){e.dialogue&&(Oo(e.dialogue),e.dialogue.mode==="adv"&&(e.dialogue.content=void 0,delete e.dialogue.initialRevealedContent,delete e.dialogue.textSpeed,e.dialogue.persistCharacter!==!0&&(delete e.dialogue.characterId,delete e.dialogue.character)));return}e.dialogue||(e.dialogue={});let r=e.dialogue.mode;if(t.dialogue.ui){let{animationsOnly:l,state:f}=It(t.dialogue.ui,u=>!!u.resourceId);l?e.dialogue.ui={...e.dialogue.ui,...f}: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 n=t.dialogue.append===!0&&r!=="nvl"&&e.dialogue?.mode!=="nvl"&&Array.isArray(t.dialogue.content);t.dialogue.content!==void 0&&Xa({dialogueState:e.dialogue,content:t.dialogue.content,append:n}),B(t.dialogue,"textSpeed")?e.dialogue.textSpeed=t.dialogue.textSpeed:delete e.dialogue.textSpeed;let o=B(t.dialogue,"persistCharacter")?t.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;o?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let i=B(t.dialogue,"characterId"),s=Ja(t.dialogue),c=s!==void 0,a=No(t.dialogue);if(i?t.dialogue.characterId?e.dialogue.characterId=t.dialogue.characterId:delete e.dialogue.characterId:!o&&!n&&delete e.dialogue.characterId,c?e.dialogue.character=!i&&o&&e.dialogue.character?{...W(e.dialogue.character),...s}:s:(i||!o&&!n)&&delete e.dialogue.character,a||Oo(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 l={content:t.dialogue.content,characterId:e.dialogue.characterId??null};e.dialogue.textSpeed!==void 0&&(l.textSpeed=e.dialogue.textSpeed),e.dialogue.character&&(l.character=W(e.dialogue.character)),e.dialogue.lines.push(l)}},rc=(e,t)=>{if(t.sfx){let r=Array.isArray(t.sfx.items)&&t.sfx.items.length>0,n=Array.isArray(t.sfx.channels)&&t.sfx.channels.length>0;if(!r&&!n){delete e.sfx;return}e.sfx=W(t.sfx)}else e.sfx&&delete e.sfx},nc=(e,t)=>{if(t.bgm){let r=Array.isArray(t.bgm.sounds);if(!t.bgm.resourceId&&!r||r&&t.bgm.sounds.length===0){e.bgm=void 0;return}e.bgm=W(t.bgm),t.bgm.resourceId&&(e.bgm.loop=t.bgm.loop??!0)}},oc=(e,t)=>{if(t.visual){let r=e.visual?.items||[];t.visual.items?.forEach((i,s)=>{qa(i,To(r,i,s))});let{hasValidItems:n,processedItems:o}=Po(t.visual.items,za,r,{hasPatchFn:Do,mergeItemFn:Wa});n?e.visual={items:o}:delete e.visual}else e.visual?.items&&(e.visual.items=e.visual.items.map(r=>r.animations?{...r,animations:{}}:r))},ic=(e,t)=>{if(!t.character){e.character?.items&&(e.character.items=e.character.items.map(o=>o.animations?{...o,animations:{}}:o));return}let{hasValidItems:r,processedItems:n}=Po(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId,e.character?.items||[]);r?e.character={items:n}:delete e.character},sc=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},ac=(e,t)=>{if(t.layout){let{animationsOnly:r,state:n}=It(t.layout,o=>!!o.resourceId);if(r){e.layout=n;return}if(!t.layout.resourceId){delete e.layout;return}e.layout=t.layout}else e.layout&&delete e.layout},cc=(e,t)=>{if(t.choice){let{animationsOnly:r,state:n}=It(t.choice,o=>!!o.resourceId);if(r){e.choice={...e.choice,...n};return}if(!t.choice.resourceId){delete e.choice;return}e.choice=t.choice}else e.choice&&delete e.choice},lc=(e,t)=>{if(t.form){let{animationsOnly:r,state:n}=It(t.form,o=>!!o.resourceId);if(r){e.form={...e.form,...n};return}if(!t.form.resourceId){delete e.form;return}e.form=W(t.form)}else e.form&&delete e.form},uc=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},fc=(e,t)=>{if(t.voice){let r=Array.isArray(t.voice.sounds);if(!t.voice.resourceId&&!r||r&&t.voice.sounds.length===0){delete e.voice;return}e.voice=W(t.voice)}else e.voice&&delete e.voice},dc=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(r=>{delete e[r]})},qe=e=>Bt(Qa,[dc,Za,ec,rc,nc,oc,tc,ic,sc,ac,cc,lc,uc,fc])(e);var it=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let r=se(e,t);return r&&typeof r=="object"?e:r};var pc=Object.freeze({dialogueTextSpeed:{source:"global.dialogueTextSpeed"},autoForwardDelay:{source:"global.autoForwardDelay"},autoForwardSpeed:{source:"global.autoForwardSpeed"},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"}}),He=Object.freeze({dialogueTextSpeed:50,autoForwardDelay:1e3,autoForwardSpeed:1,skipUnseenText:!1,skipTransitionsAndAnimations:!1,soundVolume:50,musicVolume:50,muteAll:!1,autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isLineCompleted:!1}),At=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),Vo=Object.freeze({dialogueTextSpeed:"number",autoForwardDelay:"number",autoForwardSpeed:"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"}),Gr=Object.freeze(["dialogueTextSpeed","autoForwardDelay","autoForwardSpeed","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),Kr=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),hc=(e,t)=>{if(t.startsWith("global.")){let r=t.slice(7);return e?.global?.[r]}if(t.startsWith("context.runtime.")){let r=t.slice(16),n=Array.isArray(e?.contexts)?e.contexts:[];return n[n.length-1]?.runtime?.[r]}},Ye=e=>Object.fromEntries(Object.entries(pc).map(([t,r])=>{let n=hc(e,r.source),o=n!==void 0?n:He[t]??At[t];return[t,o]})),Pe=(e,t)=>Ye(e)[t],jo=(e={})=>Object.fromEntries(Gr.map(t=>[t,e[t]??He[t]]));var st=Object.freeze({VISUAL_BEHIND_BACKGROUND:10,BACKGROUND:20,VISUAL_BEHIND_CHARACTER:30,CHARACTER:40,VISUAL_BEHIND_DIALOGUE:50,DIALOGUE:60,VISUAL_BEHIND_CHOICE:70,CHOICE:80,VISUAL_FOREGROUND:90}),_e=Object.freeze({BEHIND_BACKGROUND:st.VISUAL_BEHIND_BACKGROUND,BEHIND_CHARACTER:st.VISUAL_BEHIND_CHARACTER,BEHIND_DIALOGUE:st.VISUAL_BEHIND_DIALOGUE,BEHIND_CHOICE:st.VISUAL_BEHIND_CHOICE,FOREGROUND:st.VISUAL_FOREGROUND}),Jr=_e.BEHIND_DIALOGUE,Xr=Object.freeze(Object.values(_e).sort((e,t)=>e-t));var Re={objectValues:e=>Object.entries(e).map(([t,r])=>({id:t,...r})),formatDate:vo},mc=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,gc=(e,t)=>{let r=String(t||"").trim();if(!r)return;let n=r.match(/[A-Za-z_][A-Za-z0-9_]*|\[\d+\]/g)||[],o=e;for(let i of n){if(i.startsWith("[")){let s=Number(i.slice(1,-1));o=Array.isArray(o)?o[s]:void 0;continue}o=o?.[i]}return o},Xt=(e,t,r)=>{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),c=mc.exec(s);if(c){let[,a,l,f]=c,u=gc(t,f);if(!Array.isArray(u))continue;let d=Array.isArray(i[s])?i[s]:[];u.forEach((p,h)=>{let g={...t,[a]:p};l&&(g[l]=h),d.forEach(y=>{let b=Xt(y,g,r),A=se(b,g,r);Array.isArray(A)?o.push(...A):o.push(A)})});continue}}o.push(Xt(i,t,r))}return o}if(!e||typeof e!="object")return e;let n={};return Object.entries(e).forEach(([o,i])=>{n[o]=Xt(i,t,r)}),n},mn=({animationType:e,animationId:t,animationPath:r})=>{if(e!==void 0&&!(e==="update"||e==="transition"))throw new Error(`[${r}] Animation "${t}" has unsupported type "${e}". Use "update" or "transition".`)},yc=({id:e,targetId:t,animation:r,playback:n,animationPath:o="animation"})=>{let i=structuredClone(r);if(mn({animationType:i.type,animationId:e,animationPath:o}),delete i.name,delete i.playback,i.id=e,i.targetId=t,n!==void 0){let s=wc(n,`${o}.playback`);s!==void 0&&(i.playback=s)}return i},bc=(e,{animationId:t="animation",animationPath:r="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return mn({animationType:e.type,animationId:t,animationPath:r}),e.type},Ic=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},Ac=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},wc=(e,t="animation.playback")=>{if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`[${t}] playback must be an object.`);if(e.continuity!==void 0&&e.continuity!=="render"&&e.continuity!=="persistent")throw new Error(`[${t}] playback.continuity must be "render" or "persistent".`);if(e.speed!==void 0&&(typeof e.speed!="number"||!Number.isFinite(e.speed)||e.speed<=0))throw new Error(`[${t}] playback.speed must be a finite number greater than 0.`);let r={};return e.continuity!==void 0&&(r.continuity=e.continuity),e.speed!==void 0&&e.speed!==1&&(r.speed=e.speed),Object.keys(r).length>0?r:void 0},Ec=e=>{let t=e?.playback?.speed;return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1},Ge=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Xo=e=>e?.playback?.continuity==="persistent",sn=e=>Array.isArray(e)?e.map(sn):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((t,r)=>(t[r]=sn(e[r]),t),{}),Zt=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let t=structuredClone(e);return t.playback&&(delete t.playback.continuity,t.playback.speed===1&&delete t.playback.speed,Object.keys(t.playback).length===0&&delete t.playback),JSON.stringify(sn(t))},Qo=(e=[])=>e.filter(t=>Xo(t)).map(t=>structuredClone(t)),Zo=e=>Array.isArray(e?.keyframes)?e.keyframes.reduce((t,r)=>{let n=typeof r?.duration=="number"&&Number.isFinite(r.duration)?r.duration:0;return t+n},0):0,Qr=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((t,r)=>Math.max(t,Zo(r)),0),ei=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max(Qr(e.tween),Qr(e.prev?.tween),Qr(e.next?.tween),Zo(e.mask?.progress))/Ec(e),Fo=({animationInstances:e,activePersistentAnimations:t})=>{if(!Array.isArray(e)||e.length===0||!Array.isArray(t)||t.length===0)return!1;let r=new Set(t.map(Zt).filter(Boolean));return e.some(n=>{if(!Xo(n))return!1;let o=Zt(n);return o?r.has(o):!1})},Ae=({animationInstances:e,isLineCompleted:t,skipTransitionsAndAnimations:r,activePersistentAnimations:n,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||r?!1:i&&!t||Fo({animationInstances:e,activePersistentAnimations:n})?!0:i?!1:Fo({animationInstances:e,activePersistentAnimations:o}),xc=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),vc=(e,t)=>{if(xc(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},Cc=({resources:e,animationId:t,playback:r,instanceId:n,targetId:o,animationPath:i="animation"})=>{if(!t||!o)return!1;let s=e?.animations?.[t];return s?yc({id:n,targetId:o,animation:s,playback:r,animationPath:i}):null},Sc=(e,{defaultTargetId:t,defaultId:r,animationPath:n="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return mn({animationType:o.type,animationId:o.id??r,animationPath:n}),o.id??=r,o.targetId??=t,o},gn=({animations:e,transitions:t,defaultTargetId:r,idPrefix:n,animationPathPrefix:o=n})=>{t.forEach((i,s)=>{e.push(Sc(i,{defaultTargetId:r,defaultId:`${n}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},an=(e,t)=>{if(e===void 0)return[];if(!Array.isArray(e)||e.some(r=>r===null||typeof r!="object"||Array.isArray(r)))throw new Error(`${t} must be an array of objects`);return e},_c=({content:e,path:t,variables:r})=>an(e,t).reduce((n,o)=>{let i=it(o.text,{variables:r});return n+`${i??""}`.length},0),Mo=(e=[])=>{let t=new Map;for(let r of e)r?.id&&t.set(r.id,(t.get(r.id)??0)+1);return new Set(Array.from(t.entries()).filter(([,r])=>r>1).map(([r])=>r))},Gt=(e,t=0,r=new Set)=>{if(!r.has(e?.id))return`character-container-${e.id}`;let n=e?.sprites?.map(({resourceId:o})=>o)||[];return n.length===0?`character-container-${e.id}`:`character-container-${e.id}-${t}-${n.join("-")}`},Kt=(e,t)=>{if(!t.transformId)throw new Error(`Visual item "${t.id}" requires transformId`);let r=e.transforms?.[t.transformId];if(!r)throw new Error(`Transform "${t.transformId}" not found for visual item "${t.id}"`);return r},Rc=(e,t={})=>{if(!t?.transformId)return;let r=e.transforms?.[t.transformId];if(!r)throw new Error(`Transform "${t.transformId}" not found for background`);return r},Oc=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],Lc=(e={})=>Oc.some(t=>Ge(e,t)),ti=(e={},t)=>{if(t){if(e.images?.[t])return"sprite";if(e.videos?.[t])return"video";if(e.spritesheets?.[t])return"spritesheet-animation";if(e.layouts?.[t])return"container"}},Qt=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},$c=(e={})=>e.textStyles||{},kc=(e={})=>e.images||{},Dc=.5,Tc=(e={},t,r)=>{if(t){if(!e.animations?.[t])throw new Error(`Animation '${t}' not found in spritesheet resource '${r}'`);return t}return Object.keys(e.animations??{})[0]},ri=({id:e,resourceId:t,spritesheet:r,animationName:n,animationSpeed:o,loop:i,transform:s={}}={})=>{let c=Tc(r,n,t),a=c?r.animations?.[c]:void 0;if(!a){console.warn(`Spritesheet animation not found: ${t}`);return}return{id:e,type:"spritesheet-animation",...s,width:r.width,height:r.height,src:r.fileId,atlas:r.jsonData,playback:{frames:a.frames,animationSpeed:o??a.animationSpeed??Dc,loop:i??a.loop??!0}}},ni=({id:e,item:t,resources:r={}}={})=>{let n=r.images?.[t.resourceId];if(n)return{type:"sprite",id:e,src:n.fileId,width:n.width,height:n.height,x:0,y:0};let o=r.spritesheets?.[t.resourceId];if(o)return ri({id:e,resourceId:t.resourceId,spritesheet:o,animationName:t.animationName,animationSpeed:t.animationSpeed,loop:t.loop,transform:{x:0,y:0}});console.warn(`Character sprite resource not found: ${t.resourceId}`)},Pc=(e={})=>e.colors||{},Nc=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,xt=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,ct=(e,t,r)=>{if(typeof e!="string"||e.length===0)throw new Error(`${r} at "${t}" must resolve to a non-empty string`)},Zr=(e,t,r)=>{if(e===void 0)return 1;if(typeof e!="number"||!Number.isFinite(e))throw new Error(`${t} for text style "${r}" must be a number between 0 and 1`);if(e<0||e>1)throw new Error(`${t} for text style "${r}" must be a number between 0 and 1`);return e},en=(e,t,r,n,{minimum:o}={})=>{if(e===void 0)return n;if(typeof e!="number"||!Number.isFinite(e)||o!==void 0&&e<o){let i=o===void 0?"a finite number":`a finite number >= ${o}`;throw new Error(`shadow.${t} for text style "${r}" must be ${i}`)}return e},rr=(e,t)=>{if(typeof e!="string"||!Nc.test(e))throw new Error(`${t} must resolve to a hex color`);return e.length===4?`#${e.slice(1).split("").map(r=>r.repeat(2)).join("")}`:e},Uo=(e,t,r)=>{let n=rr(e,r);if(t===1)return n;let o=Number.parseInt(n.slice(1,3),16),i=Number.parseInt(n.slice(3,5),16),s=Number.parseInt(n.slice(5,7),16);return`rgba(${o}, ${i}, ${s}, ${t})`},Vc=(e={},t)=>{let r=$c(e)?.[t];if(!r)throw new Error(`Text style "${t}" not found`);let n=e.fonts?.[r.fontId];if(!n)throw new Error(`Font "${r.fontId}" not found for text style "${t}"`);let o=e.colors?.[r.colorId];if(!o)throw new Error(`Color "${r.colorId}" not found for text style "${t}"`);let i=Zr(r.colorAlpha,"colorAlpha",t),s={fontFamily:n.fileId,fontSize:r.fontSize??16,fontWeight:r.fontWeight??"400",fontStyle:r.fontStyle??"normal",lineHeight:r.lineHeight??1.2,fill:Uo(o.hex,i,`Color "${r.colorId}" for text style "${t}"`)};if(r.align!==void 0&&(s.align=r.align),r.wordWrap!==void 0&&(s.wordWrap=r.wordWrap),r.breakWords!==void 0&&(s.breakWords=r.breakWords),r.wordWrapWidth!==void 0&&(s.wordWrapWidth=r.wordWrapWidth),r.strokeColorId){let c=e.colors?.[r.strokeColorId];if(!c)throw new Error(`Stroke color "${r.strokeColorId}" not found for text style "${t}"`);let a=Zr(r.strokeAlpha,"strokeAlpha",t);s.strokeColor=Uo(c.hex,a,`Stroke color "${r.strokeColorId}" for text style "${t}"`)}else if(r.strokeAlpha!==void 0)throw new Error(`strokeAlpha for text style "${t}" requires strokeColorId`);if(r.strokeWidth!==void 0&&(s.strokeWidth=r.strokeWidth),r.shadow!==void 0){let c=e.colors?.[r.shadow.colorId];if(!c)throw new Error(`Shadow color "${r.shadow.colorId}" not found for text style "${t}"`);s.shadow={color:rr(c.hex,`Shadow color "${r.shadow.colorId}" for text style "${t}"`),alpha:Zr(r.shadow.alpha,"shadow.alpha",t),blur:en(r.shadow.blur,"blur",t,0,{minimum:0}),offsetX:en(r.shadow.offsetX,"offsetX",t,2),offsetY:en(r.shadow.offsetY,"offsetY",t,2)}}return s},cn=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>cn(o,t,`${r}[${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 "${r}". Use textStyleId instead`);let n={};for(let[o,i]of Object.entries(e))o!=="textStyleId"&&(n[o]=cn(i,t,xt(r,o)));return e.textStyleId!==void 0&&(ct(e.textStyleId,r,"textStyleId"),n.textStyle=Vc(t,e.textStyleId)),n},yn=(e={},t)=>{let r=Pc(e)?.[t];if(!r)throw new Error(`Color "${t}" not found`);return rr(r.hex,`Color "${t}"`)},oi=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",tn=(e,t,r)=>{let n=e?.[t];if(!(!n||typeof n!="object"||Array.isArray(n))&&Object.prototype.hasOwnProperty.call(n,"fill"))throw new Error(`Inline ${t}.fill is not allowed in rect layout elements at "${r}". Use ${oi(`${t}.fill`)} instead`)},jc=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>vt(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;let n={};for(let[o,i]of Object.entries(e))o!=="colorId"&&(n[o]=vt(i,t,xt(r,o)));return e.colorId!==void 0&&(ct(e.colorId,r,"colorId"),n.fill=yn(t,e.colorId)),n},vt=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>vt(o,t,`${r}[${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 "${r}". Use ${oi("fill")} instead`);tn(e,"hover",r),tn(e,"click",r),tn(e,"rightClick",r)}let n={};for(let[o,i]of Object.entries(e))if(!(e.type==="rect"&&o==="colorId")){if(e.type==="rect"&&(o==="hover"||o==="click"||o==="rightClick")){n[o]=jc(i,t,xt(r,o));continue}n[o]=vt(i,t,xt(r,o))}return e.type==="rect"&&e.colorId!==void 0&&(ct(e.colorId,r,"colorId"),n.fill=yn(t,e.colorId)),n},rn=(e={},t)=>{let r=kc(e)?.[t];return r||null},ii=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",Bo=(e,t,r,n)=>{let o=e?.[t];if(!(!o||typeof o!="object"||Array.isArray(o))&&Object.prototype.hasOwnProperty.call(o,n))throw new Error(`Inline ${t}.${n} is not allowed in sprite layout elements at "${r}". Use ${ii(`${t}.${n}`)} instead`)},zo=(e,t,r)=>{let n=e[t];e[t]={...n&&typeof n=="object"&&!Array.isArray(n)?n:{},src:r}},ln=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>ln(o,t,`${r}[${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 "${r}". Use ${ii(o)} instead`);Bo(e,"hover",r,"src"),Bo(e,"click",r,"src")}let n={};for(let[o,i]of Object.entries(e))e.type==="sprite"&&(o==="imageId"||o==="hoverImageId"||o==="clickImageId")||(n[o]=ln(i,t,xt(r,o)));if(e.type==="sprite"&&e.imageId!==void 0){ct(e.imageId,r,"imageId");let o=rn(t,e.imageId),i=o?.fileId??e.imageId;n.src=i,n.width===void 0&&o?.width!==void 0&&(n.width=o.width),n.height===void 0&&o?.height!==void 0&&(n.height=o.height)}return e.type==="sprite"&&e.hoverImageId!==void 0&&(ct(e.hoverImageId,r,"hoverImageId"),zo(n,"hover",rn(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(ct(e.clickImageId,r,"clickImageId"),zo(n,"click",rn(t,e.clickImageId)?.fileId??e.clickImageId)),n},bn=(e,t={},r="root")=>ln(vt(cn(e,t,r),t,r),t,r),Oe=bn,Je=(e=[])=>e.find(t=>t.id==="story"),Fc="#000000",un="bg-cg-background-color",Mc=({resources:e={},background:t={},screen:r})=>t?.colorId===void 0?rr(r?.backgroundColor??Fc,"screen.backgroundColor"):yn(e,t.colorId),si=(e={})=>{if(Ge(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},Uc=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},Wo=(e={},{includeDefaultAlpha:t=!1}={})=>{let r=si(e),n=Uc(e),o={};return(t||r!==void 0)&&(o.alpha=r??1),n&&(o.blur=n),o},Bc=(e={})=>{if(Ge(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},zc=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},ai=(e={})=>{let t=Bc(e),r=zc(e),n={};return t!==void 0&&(n.alpha=t),r&&(n.blur=r),n},wt=(e={})=>ai(e),Ne=(e={},t={})=>{let r={x:t.x??e.x,y:t.y??e.y,anchorX:t.anchorX??e.anchorX,anchorY:t.anchorY??e.anchorY,rotation:t.rotation??e.rotation,scaleX:t.scaleX??e.scaleX,scaleY:t.scaleY??e.scaleY},n=t.originX??e.originX,o=t.originY??e.originY;return n!==void 0&&(r.originX=n),o!==void 0&&(r.originY=o),r},Wc=["id","type","resourceId","transformId","x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY","layer","opacity","blur","animations"],In=(e={})=>e.text&&Ge(e.text,"content")&&Ge(e.text,"textStyleId"),qo=(e={})=>{if(e.resourceId)return e.resourceId;if(In(e))return"text"},qc=e=>{if(e.text){if(e.resourceId)throw new Error(`Visual item "${e.id}" cannot define both resourceId and text`);if(!In(e))throw new Error(`Visual item "${e.id}" text requires content and textStyleId`);for(let t of Wc)if(Ge(e.text,t))throw new Error(`Visual item "${e.id}" text.${t} is reserved for the visual item`)}},Hc=({resources:e,background:t,screen:r={width:1920,height:1080},includeOpacity:n=!1})=>{let o={id:un,type:"rect",x:0,y:0,width:r?.width??1920,height:r?.height??1080,fill:Mc({resources:e,background:t,screen:r})};if(n){let i=si(t);i!==void 0&&(o.alpha=i)}return o},Yc=(e={},t)=>t?!!(e.images?.[t]||e.videos?.[t]||e.spritesheets?.[t]||e.layouts?.[t]):!1,Ho=({resources:e={},resourceId:t,colorId:r})=>{let n=ti(e,t);return t&&(n||r===void 0)?{resourceId:t,targetId:Qt({resourceId:t,kind:n})}:r!==void 0?{resourceId:un,targetId:un}:{resourceId:void 0,targetId:void 0}},ci=100,Ke=ci,Gc="channel:bgm",Kc="channel:voice",Jc="default",Xc=e=>String(e).replaceAll("%","%25").replaceAll(":","%3A"),Et=(...e)=>e.map(Xc).join(":"),er=(e,t,r)=>{let n=new Set;e.forEach(({id:o})=>{if(n.has(o)){let i=r?` in ${r}`:"";throw new Error(`Duplicate ${t} id "${o}"${i}.`)}n.add(o)})},Qc=(e,t)=>e*t/ci,li=(e={},t)=>e?.[t]??He[t],An=(e={},t,r=Ke)=>Qc(r,li(e,t)),wn=({id:e,volume:t,muted:r,pan:n,children:o,runtime:i})=>({id:e,type:"audio-channel",volume:t,muted:!!i?.muteAll||(r??!1),pan:n??0,children:o}),Jt=(e,t,r,n)=>e[r]!==void 0?e[r]:t[r]!==void 0?t[r]:n,Zc=["muted","pan","playbackRate","startAt","endAt"],En=({id:e,sound:t,resource:r,defaultLoop:n=!1})=>{let o={id:e,type:"sound",src:r.fileId,loop:Jt(t,r,"loop",n),volume:Jt(t,r,"volume",Ke),startDelayMs:Jt(t,r,"startDelayMs",0)};Zc.forEach(s=>{let c=Jt(t,r,s,void 0);c!==void 0&&(o[s]=c)});let i=o.startAt??0;if(o.endAt!==void 0&&o.endAt!==null&&o.endAt<i)throw new Error(`Sound "${e}" endAt (${o.endAt}) must be greater than or equal to startAt (${i}).`);return o},we=({variables:e,runtime:t,saveSlots:r=[],dialogueState:n,includeInactiveAdvDialogue:o=!1,isLineCompleted:i,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:f,confirmDialog:u,form:d,historyDialogue:p=[],characters:h={},dialogueUIHidden:g,skipOnlyViewedLines:y,skipTransitionsAndAnimations:b}={})=>{let A={dialogueTextSpeed:t?.dialogueTextSpeed??50,autoForwardDelay:t?.autoForwardDelay??1e3,autoForwardSpeed:t?.autoForwardSpeed??1,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??c??!1,dialogueUIHidden:t?.dialogueUIHidden??g??!1,isLineCompleted:t?.isLineCompleted??i??!1},x=ol({dialogueState:n,includeInactiveAdvDialogue:o,characters:h,variables:e,runtime:A}),S={variables:e,runtime:A,saveSlots:r,isChoiceVisible:a,isFormVisible:l,canRollback:f,confirmDialog:u,form:d,historyDialogue:p,characters:h};return x&&(S.dialogue=x,S.dialogueLines=x.lines),S},Yo=100,tr=(e,t)=>{if(Array.isArray(e))return e.map(n=>tr(n,t));if(!e||typeof e!="object")return e;let r={...e};return Object.keys(r).forEach(n=>{r[n]=tr(r[n],t)}),r.type==="text-revealing"?t(r):r},el=e=>tr(e,t=>({...t,revealEffect:"none"})),tl=e=>tr(e,t=>{let r=Number(t.speed??t.displaySpeed),n=Number.isFinite(r)?Math.max(r,Yo):Yo;return{...t,speed:n,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:n}:{}}}),Ve=(e,{isLineCompleted:t=!1,skipMode:r=!1,skipTransitionsAndAnimations:n=!1}={})=>t||n?el(e):r?tl(e):e,ui=({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:{}}}}),fn=e=>{if(Array.isArray(e))return e.map(fn);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=fn(s);let r=t.click?.payload;if(!r||typeof r!="object"||Array.isArray(r))return t;let n=r.actions,o=n&&typeof n=="object"&&!Array.isArray(n)&&Object.prototype.hasOwnProperty.call(n,"nextLine")?{...n.nextLine,bypassChoice:!0}:void 0;return{...t,click:{...t.click,payload:{...r,bypassChoice:!0,...o?{actions:{...n,nextLine:o}}:{}}}}},rl=new Set(["click","change","submit","focusEvent","blurEvent","selectionChange","compositionStart","compositionUpdate","compositionEnd"]),Go="submit",nn=(e,t,r={})=>{let n=e?.payload&&typeof e.payload=="object"&&!Array.isArray(e.payload)?e.payload:{},o=n.actions&&typeof n.actions=="object"?n.actions:{},i=r.replaceActions===!0?t:{...o,...t};return{...e||{},payload:{...n,actions:i}}},dn=(e,t,r={})=>{if(Array.isArray(e))return e.map(l=>dn(l,t,r));if(!e||typeof e!="object")return e;let n=typeof e.type=="string",o=n&&e.formRole===Go,i=n&&r.submitRoleAncestor,s=o||i?{submitRoleAncestor:!0}:{},c={};for(let[l,f]of Object.entries(e))c[l]=dn(f,t,l==="children"?s:{});let a=c;if(a.type==="input"&&typeof a.field=="string"){let l=t?.fields?.[a.field];if(l){let f={updateFormField:{formKey:t.key,field:l.id,value:"_event.value"}};a={...a,value:l.value,placeholder:a.placeholder===void 0?l.placeholder:a.placeholder,multiline:a.multiline===void 0?l.multiline:a.multiline,...a.maxLength===void 0&&l.maxLength!==void 0?{maxLength:l.maxLength}:{},change:nn(a.change,f),submit:nn(a.submit,t.submitActions)}}}return a.formRole===Go||i?{...a,click:nn(a.click,t.submitActions,{replaceActions:!0})}:a},pn=(e,t)=>{if(Array.isArray(e))return e.map(n=>pn(n,t));if(!e||typeof e!="object")return e;let r={};for(let[n,o]of Object.entries(e))r[n]=pn(o,t);for(let n of rl){let o=r[n]?.payload;!o||typeof o!="object"||Array.isArray(o)||(r[n]={...r[n],payload:{...o,_interactionSource:"form"}})}return r},hn=({characterId:e,character:t,characterName:r,characters:n={},variables:o={}}={})=>{let i=e?n?.[e]:void 0,s=zt({characterId:e,character:t,characterName:r,characters:n,variables:o});return{...i||{},...t||{},name:s}},fi=(e=[],t={},r={})=>e.map(n=>{let o=hn({characterId:n.characterId,character:n.character,characterName:n.characterName,characters:t,variables:r}),i=typeof n.text=="string"?n.text:Array.isArray(n.content)?n.content.map(s=>s?.text??"").join(""):"";return{...n,text:i,character:o,characterName:o.name}}),nl=e=>!(!e||e.mode==="adv"&&e.content===void 0),ol=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:r={},variables:n,runtime:o}={})=>{if(!t&&!nl(e))return;let i=e.content===void 0?[{text:""}]:an(e.content,"dialogue.content"),s=e.content===void 0?0:_c({content:e.initialRevealedContent,path:"dialogue.initialRevealedContent",variables:n}),c=o?.dialogueTextSpeed??He.dialogueTextSpeed,a=e.textSpeed??c,l=(e.lines||[]).map((u,d)=>{let p=an(u.content,`dialogue.lines[${d}].content`),h=hn({characterId:u.characterId,character:u.character,characterName:u.characterName,characters:r,variables:n});return{...u,textSpeed:u.textSpeed??c,content:p.map(g=>({...g,text:it(g.text,{variables:n})})),character:h,characterName:h.name}}),f=hn({characterId:e.characterId,character:e.character,characters:r,variables:n});return{characterId:e.characterId,persistCharacter:e.persistCharacter,character:f,textSpeed:a,content:i.map(u=>({...u,text:it(u.text,{variables:n})})),initialRevealedCharacters:s,lines:l}},di=({container:e,resources:t,templateData:r,isLineCompleted:n=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=se(e,r,{functions:Re});return Oe(Ve(s,{isLineCompleted:n,skipMode:o,skipTransitionsAndAnimations:i}),t)},on=(e,t={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(t),Ko=({renderStateKeyboard:e,keyboard:t,phase:r})=>{!t||typeof t!="object"||Array.isArray(t)||Object.entries(t).forEach(([n,o])=>{let i=e[n]??{},s=r==="keydown"?o?.keydown:o?.keyup;if(r==="keydown"&&s&&typeof s=="object"){e[n]={...i,keydown:{payload:on(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[n].keyup={payload:on(o.keyup)});return}e[n]={...i,[r]:{payload:on(o)}}})},il=(e={},t={})=>{let r={};return Ko({renderStateKeyboard:r,keyboard:e,phase:"keydown"}),Ko({renderStateKeyboard:r,keyboard:t,phase:"keyup"}),Object.keys(r).length>0?r:void 0},Le=({animationsDef:e,resources:t,previousResourceId:r,currentResourceId:n,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:c})=>{if(!e)return[];let a=[],l=({instanceId:b,targetId:A})=>{let x=Cc({resources:t,animationId:p,playback:h,instanceId:b,targetId:A,animationPath:s});x&&a.push(x)},f=r!=null&&r!==!1,u=n!=null&&n!==!1,d=o&&i&&o===i;vc(e,s);let p=Ic(e),h=Ac(e),g=t?.animations?.[p],y=bc(g,{animationId:p,animationPath:s});if(y==="update")return u&&i?l({instanceId:`${c}-animation-update`,targetId:i}):f&&o&&l({instanceId:`${c}-animation-update`,targetId:o}),a;if(y==="transition"){let b=`${c}-animation-transition`,A=h?.continuity==="persistent"?b:`${c}-animation-in`;if(f&&u&&d)return l({instanceId:b,targetId:i}),a;f&&l({instanceId:`${c}-animation-out`,targetId:o}),u&&l({instanceId:A,targetId:i})}return a},sl=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),al=(e,{presentationState:t,previousPresentationState:r,currentLineActions:n,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:c,variables:a,runtime:l,activePersistentAnimations:f,restoredPersistentAnimations:u,autoMode:d,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:b,saveSlots:A=[]})=>{let{elements:x,animations:S}=e;if(t.background){let P=n===void 0?!0:Ge(n?.background??{},"animations"),N=x.find(ne=>ne.id==="story");if(!N)return e;let w=Rc(o,t.background),M=w||Lc(t.background),F=r?.background?.resourceId,G=r?.background?.colorId,j=t.background.resourceId??(t.background.animations?F:void 0),H=t.background.colorId??(t.background.animations?G:void 0),K=Yc(o,j),X={...t.background,colorId:H};if((H!==void 0||K)&&N.children.push(Hc({resources:o,background:X,screen:i,includeOpacity:!K})),j){let{images:ne={},videos:ce={},spritesheets:q={}}=o,Z=ti(o,j),oe;if(Z==="sprite"?oe=ne[j]:Z==="video"?oe=ce[j]:Z==="spritesheet-animation"&&(oe=q[j]),oe){let v=Z==="video",_=Z==="spritesheet-animation",V={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...w},le={...Wo(t.background,{includeDefaultAlpha:!0}),...Ne(V,t.background)},ee;_?ee=ri({id:Qt({resourceId:j,kind:Z}),resourceId:j,spritesheet:oe,animationName:t.background.animationName,animationSpeed:t.background.animationSpeed,loop:t.background.loop,transform:le}):ee={id:Qt({resourceId:j,kind:Z}),type:v?"video":"sprite",src:oe.fileId,width:oe.width,height:oe.height,...le},v&&(ee.loop=t.background.loop??!1,ee.volume=oe.volume??50),ee&&N.children.push(ee)}}if(j){let{layouts:ne={}}=o,ce=ne[j];if(ce){let q={id:Qt({resourceId:j,kind:"container"}),type:"container",children:ce.elements,...Wo(t.background)};M&&Object.assign(q,Ne({x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...w},t.background));let Z=se(q,we({variables:a,runtime:l,saveSlots:A,dialogueState:t.dialogue,isLineCompleted:s,autoMode:d,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:b,characters:o.characters||{},skipTransitionsAndAnimations:c}),{functions:Re});N.children.push(Oe(Ve(Z,{isLineCompleted:s,skipMode:p,skipTransitionsAndAnimations:c}),o))}}let xe=Ho({resources:o,resourceId:F,colorId:G}),re=Ho({resources:o,resourceId:j,colorId:H}),Q=Le({animationsDef:t.background.animations,resources:o,previousResourceId:xe.resourceId,currentResourceId:re.resourceId,previousTargetId:xe.targetId,currentTargetId:re.targetId,animationPath:"background.animations",idPrefix:"bg-cg"});Ae({animationInstances:Q,isLineCompleted:s,skipTransitionsAndAnimations:c,activePersistentAnimations:f,restoredPersistentAnimations:u,isAuthoredOnCurrentLine:P})&&S.push(...Q)}return e},cl=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:c,animations:a}=e;if(t.character&&n){let l=c.find(h=>h.id==="story");if(!l)return e;let f=t.character.items||[],u=r?.character?.items||[],d=Mo(f),p=Mo(u);for(let h=0;h<f.length;h++){let g=f[h],{transformId:y,sprites:b}=g,A=u.find(j=>j.id===g.id),x=u.findIndex(j=>j.id===g.id),S=A?.sprites&&A.sprites.length>0,P=b&&b.length>0,N=x>=0?Gt(A,x,p):void 0,w=Le({animationsDef:g.animations,resources:n,previousResourceId:N,currentResourceId:P?Gt(g,h,d):void 0,previousTargetId:N,currentTargetId:P?Gt(g,h,d):void 0,animationPath:`character.items[${h}].animations`,idPrefix:"character"});if(g.animations&&!b&&!y&&S&&Ae({animationInstances:w,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){a.push(...w);continue}if(g.animations&&!b&&!y)continue;if(!b||b.length===0||!y){console.warn("Character item missing sprites or transformId:",g);continue}let M=Gt(g,h,d),F=n.transforms[y];if(!F){console.warn("Transform not found:",y);continue}let G={type:"container",id:M,...Ne(F,g),...wt(g),children:[]};for(let j of b){let H=ni({id:`${M}-${j.id}`,item:j,resources:n});H&&G.children.push(H)}l.children.push(G),Ae({animationInstances:w,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...w)}}return e},pi=(e,t)=>{if(!Xr.includes(e))throw new Error(`${t} must be one of: ${Xr.join(", ")}.`)},ll=(e,t)=>{let r=!!e.resourceId||In(e),n=e.layer??(r?void 0:t?.layer)??Jr;return pi(n,`Visual item "${e.id}" layer`),n},ul=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,runtime:c,activePersistentAnimations:a,autoMode:l,skipMode:f,isChoiceVisible:u,isFormVisible:d,canRollback:p,form:h,saveSlots:g=[],visualLayer:y})=>{let{elements:b,animations:A}=e;if(t.visual&&n){let x=b.find(w=>w.id==="story");if(!x)return e;let S=t.visual.items,P=r?.visual?.items||[],N=we({variables:s,runtime:c,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:o,autoMode:l,skipMode:f,isChoiceVisible:u,isFormVisible:d,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:i});y!==void 0&&pi(y,"visualLayer");for(let w of S){let M=P.find(K=>K.id===w.id),F=ll(w,M);if(y!==void 0&&F!==y)continue;if(qc(w),w.text){let K=Kt(n,w),X={...structuredClone(w.text),id:`visual-${w.id}`,type:"text",...Ne(K,w)};Object.assign(X,wt(w)),x.children.push(Oe(se(X,N,{functions:Re}),n))}if(w.resourceId){let{images:K={},videos:X={},spritesheets:xe={}}=n,re=xe[w.resourceId];if(re){let Q=Kt(n,w),ne=w.animationName;if(ne){let ce=re.animations?.[ne];if(!ce)throw new Error(`Animation '${ne}' not found in spritesheet resource '${w.resourceId}'`);let q=wt(w),Z={id:`visual-${w.id}`,type:"spritesheet-animation",...Ne(Q,w),width:w.width??re.width,height:w.height??re.height,alpha:q.alpha??w.alpha??1,src:re.fileId,atlas:re.jsonData,playback:{frames:ce.frames,animationSpeed:w.animationSpeed??ce.animationSpeed??.5,loop:w.loop??ce.loop??!0}};q.blur&&(Z.blur=q.blur),x.children.push(structuredClone(Z))}}else{let Q=K[w.resourceId]||X[w.resourceId];if(Q){let ne=X[w.resourceId]!==void 0,ce=Kt(n,w),q={id:`visual-${w.id}`,type:ne?"video":"sprite",src:Q.fileId,width:Q.width,height:Q.height,...Ne(ce,w)};Object.assign(q,wt(w)),ne&&(q.loop=Q.loop??!1,q.volume=Q.volume??50),x.children.push(q)}}}if(w.resourceId){let{layouts:K={}}=n,X=K[w.resourceId];if(X){let xe=Kt(n,w),re={id:`visual-${w.id}`,type:"container",children:structuredClone(X.elements),...Ne(xe,w)};Object.assign(re,wt(w));let Q=se(re,N,{functions:Re});x.children.push(Oe(Ve(Q,{isLineCompleted:o,skipMode:f,skipTransitionsAndAnimations:i}),n))}}let G=qo(M),j=qo(w),H=Le({animationsDef:w.animations,resources:n,previousResourceId:G,currentResourceId:j,previousTargetId:G?`visual-${w.id}`:void 0,currentTargetId:j?`visual-${w.id}`:void 0,animationPath:`visual.items[${w.id}].animations`,idPrefix:w.id});Ae({animationInstances:H,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:a})&&A.push(...H)}}return e},at="dialogue-character-sprite",Jo=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,fl=(e,{presentationState:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:c}=e,a=Je(e.elements);if(!a)return e;let l=t.dialogue?.character?.sprite,f=r?.dialogue?.character?.sprite,u=Jo(l),d=Jo(f),p=Le({animationsDef:l?.animations,resources:n,previousResourceId:d?at:void 0,currentResourceId:u?at:void 0,previousTargetId:d?at:void 0,currentTargetId:u?at:void 0,animationPath:"dialogue.character.sprite.animations",idPrefix:"dialogue-character-sprite"});if(!u)return l?.animations&&d&&Ae({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...p),e;let h=n.transforms?.[l.transformId];if(!h)return console.warn("Transform not found:",l.transformId),e;let g={type:"container",id:at,...Ne(h),children:[]};for(let y of l.items){let b=ni({id:`${at}-${y.id}`,item:y,resources:n});b&&g.children.push(b)}return a.children.push(g),Ae({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...p),e},dl=(e,{presentationState:t,previousPresentationState:r,resources:n={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:c,isFormVisible:a,canRollback:l,form:f,skipOnlyViewedLines:u,isLineCompleted:d,skipTransitionsAndAnimations:p,variables:h,runtime:g,activePersistentAnimations:y,saveSlots:b=[]})=>{let{elements:A,animations:x}=e;if(!t.dialogue||o)return e;let S=A.find(N=>N.id==="story");if(!S)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:N={}}=n,w=N[t.dialogue.ui.resourceId];if(w){let M={elements:w.elements},F=we({variables:h,runtime:g,saveSlots:b,dialogueState:t.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:d,autoMode:i,skipMode:s,isChoiceVisible:c,isFormVisible:a,canRollback:l,form:f,characters:n.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:u,skipTransitionsAndAnimations:p}),G={functions:Re},j=Xt(M,F,G),H=se(j,F,G),K=Oe(Ve(H?.elements,{isLineCompleted:d,skipMode:s,skipTransitionsAndAnimations:p}),n);if(Array.isArray(K))for(let X of K)S.children.push(X);else K&&S.children.push(K)}}fl(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:d,skipTransitionsAndAnimations:p,activePersistentAnimations:y});let P=Le({animationsDef:t.dialogue.ui?.animations,resources:n,previousResourceId:r?.dialogue?.ui?.resourceId,currentResourceId:t.dialogue.ui?.resourceId,previousTargetId:r?.dialogue?.ui?.resourceId?"dialogue-container":void 0,currentTargetId:t.dialogue.ui?.resourceId?"dialogue-container":void 0,animationPath:"dialogue.ui.animations",idPrefix:"dialogue-ui"});return Ae({animationInstances:P,isLineCompleted:d,skipTransitionsAndAnimations:p,activePersistentAnimations:y})&&x.push(...P),e},pl=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:c,runtime:a,autoMode:l,skipMode:f,isChoiceVisible:u,isFormVisible:d,canRollback:p,form:h,activePersistentAnimations:g,saveSlots:y=[]})=>{let{elements:b,animations:A}=e;if(t.choice&&n){let x=Je(b);if(!x)return e;let S=n?.layouts[t.choice.resourceId];if(S&&S.elements){let N={elements:S.elements},w=se(N,{...we({variables:c,runtime:a,saveSlots:y,dialogueState:t.dialogue,isLineCompleted:i,autoMode:l,skipMode:f,isChoiceVisible:u??!!t.choice,isFormVisible:d,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}},{functions:Re}),M=fn(Oe(Ve(w?.elements,{isLineCompleted:i,skipMode:f,skipTransitionsAndAnimations:s}),n));if(Array.isArray(M))for(let F of M)x.children.push(F);else M&&x.children.push(M)}let P=Le({animationsDef:t.choice.animations,resources:n,previousResourceId:r?.choice?.resourceId,currentResourceId:t.choice.resourceId,previousTargetId:r?.choice?.resourceId?"choice-container":void 0,currentTargetId:t.choice.resourceId?"choice-container":void 0,animationPath:"choice.animations",idPrefix:"choice"});Ae({animationInstances:P,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:g})&&A.push(...P)}return e},hl=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:c,runtime:a,autoMode:l,skipMode:f,isChoiceVisible:u,isFormVisible:d,canRollback:p,activePersistentAnimations:h,saveSlots:g=[],form:y})=>{let{elements:b,animations:A}=e;if(!y?.resourceId||!n)return e;let x=Je(b);if(!x)return e;let S=n?.layouts?.[y.resourceId];if(!S)return console.warn(`Form layout not found: ${y.resourceId}`),e;let P={id:"form-container",type:"container",x:0,y:0,children:S.elements||[]},N={...we({variables:c,runtime:a,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:i,autoMode:l,skipMode:f,isChoiceVisible:u,isFormVisible:d,canRollback:p,characters:n.characters||{},skipTransitionsAndAnimations:s,form:y}),form:y},w=se(P,N,{functions:Re}),M=pn(Oe(Ve(dn(w,y),{isLineCompleted:i,skipMode:f,skipTransitionsAndAnimations:s}),n),y);M&&x.children.push(M);let F=Le({animationsDef:y.animations,resources:n,previousResourceId:r?.form?.resourceId,currentResourceId:y.resourceId,previousTargetId:r?.form?.resourceId?"form-container":void 0,currentTargetId:y.resourceId?"form-container":void 0,animationPath:"form.animations",idPrefix:"form"});return Ae({animationInstances:F,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:h})&&A.push(...F),e},ml=(e,{presentationState:t,resources:r={},variables:n,runtime:o,isLineCompleted:i,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:f,form:u,saveSlots:d=[],skipTransitionsAndAnimations:p})=>{if(!t.control?.resourceId)return e;let h=r.controls?.[t.control.resourceId];if(!h)return e;let g=il(h.keyboard,h.keyup);if(g&&Object.keys(g).length>0&&(e.global.keyboard=g),!Array.isArray(h.elements)||h.elements.length===0)return e;let y=Je(e.elements);if(!y)return e;let b={id:`control-${t.control.resourceId}`,type:"container",x:0,y:0,children:h.elements};return y.children.push(di({container:b,resources:r,templateData:we({variables:n,runtime:o,saveSlots:d,dialogueState:t.dialogue,isLineCompleted:i,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:f,form:u,characters:r.characters||{},skipTransitionsAndAnimations:p}),isLineCompleted:i,skipMode:c,skipTransitionsAndAnimations:p})),e},gl=(e,{presentationState:t,resources:r,runtime:n,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&r){if(!Je(i))return e;let a=t.bgm,l=!Array.isArray(a.sounds),f=l?a.resourceId?[{id:"default",resourceId:a.resourceId,loop:a.loop??!0,volume:a.volume,startDelayMs:a.startDelayMs??0}]:[]:a.sounds,u=[];if(l||er(f,"BGM sound"),f.forEach(p=>{let h=r.sounds?.[p.resourceId];h&&u.push(En({id:Et("bgm",l?"default":p.id),sound:p,resource:h,defaultLoop:!0}))}),u.length===0)return e;let d=we({variables:o,runtime:n}).runtime;s.push(wn({id:Gc,volume:An(d,"musicVolume",l?Ke:a.volume??Ke),muted:a.muted,pan:a.pan,children:u,runtime:d}))}return e},yl=(e,{presentationState:t,resources:r,runtime:n})=>{let{audio:o}=e;if(t.sfx&&r){let i=t.sfx,s=!Array.isArray(i.channels),c=s?[{id:Jc,sounds:i.items??[]}]:i.channels;s||er(c,"SFX channel"),c.forEach(a=>{let l=[];s||er(a.sounds,"SFX sound",`SFX channel "${a.id}"`),a.sounds.forEach((f,u)=>{let d=r.sounds?.[f.resourceId];d&&l.push(En({id:s?Et("sfx","default",u,f.id):Et("sfx",a.id,f.id),sound:f,resource:d}))}),l.length!==0&&o.push(wn({id:Et("channel","sfx",a.id),volume:An(n,"soundVolume",a.volume??Ke),muted:a.muted,pan:a.pan,children:l,runtime:n}))})}return e},bl=(e,t,r)=>{if(!(!t||!r))return e?.voices?.[t]?.[r]},Il=(e,{presentationState:t,resources:r,currentSceneId:n,runtime:o,variables:i})=>{let{audio:s}=e;if(!t?.voice)return e;let c=t.voice,a=!Array.isArray(c.sounds),l=a?c.resourceId?[{id:"default",resourceId:c.resourceId,loop:c.loop??!1,volume:Ke,startDelayMs:c.startDelayMs??0}]:[]:c.sounds,f=[];if(a||er(l,"Voice sound"),l.forEach(d=>{let p=bl(r,n,d.resourceId);p&&f.push(En({id:Et("voice",n,a?"default":d.id),sound:d,resource:p}))}),f.length===0)return e;let u=we({variables:i,runtime:o}).runtime;return s.push(wn({id:Kc,volume:a?c.volume??li(u,"soundVolume"):An(u,"soundVolume",c.volume??Ke),muted:c.muted,pan:c.pan,children:f,runtime:u})),e},Al=(e,{presentationState:t,previousPresentationState:r,resources:n={},variables:o,runtime:i,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:f,form:u,saveSlots:d=[],isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})=>{let{elements:y,animations:b}=e;if(t.layout){let P=Je(y);if(!P)return e;let N=n.layouts[t.layout.resourceId];if(!N)return e;Array.isArray(N.transitions)&&!p&&!h&&gn({animations:b,transitions:N.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let w={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:N.elements||[]};P.children.push(di({container:w,resources:n,templateData:we({variables:o,runtime:i,saveSlots:d,dialogueState:t.dialogue,isLineCompleted:p,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:f,form:u,characters:n.characters||{},skipTransitionsAndAnimations:h}),isLineCompleted:p,skipMode:c,skipTransitionsAndAnimations:h}))}let A=r?.layout?.resourceId,x=t.layout?.resourceId,S=Le({animationsDef:t.layout?.animations,resources:n,previousResourceId:A,currentResourceId:x,previousTargetId:A?`layout-${A}`:void 0,currentTargetId:x?`layout-${x}`:void 0,animationPath:"layout.animations",idPrefix:"layout"});return Ae({animationInstances:S,isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})&&b.push(...S),e},wl=(e,{currentLineActions:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:c}=e,a=t?.screen?.animations;if(!a)return e;let l=r!=null,f=Le({animationsDef:a,resources:n,previousResourceId:l?"story":void 0,currentResourceId:"story",previousTargetId:l?"story":void 0,currentTargetId:"story",animationPath:"screen.animations",idPrefix:"screen"});return Ae({animationInstances:f,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...f),e},El=(e,{presentationState:t})=>{let r=Je(e.elements);return!r||!t?.screen||Object.assign(r,ai(t.screen)),e},xl=(e,{presentationState:t,resources:r={},variables:n,runtime:o,autoMode:i,skipMode:s,isChoiceVisible:c,isFormVisible:a,canRollback:l,form:f,overlayStack:u=[],dialogueHistory:d=[],saveSlots:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:b,animations:A}=e;return u&&u.length>0&&u.forEach((x,S)=>{let P=r.layouts[x.resourceId];if(!P){console.warn(`Overlay layout not found: ${x.resourceId}`);return}Array.isArray(P.transitions)&&(y||gn({animations:A,transitions:P.transitions,defaultTargetId:`overlayStack-${S}`,idPrefix:`overlayStack-${S}`,animationPathPrefix:`overlayStack[${S}]`}));let N={id:`overlayStack-${S}`,type:"container",x:0,y:0,children:[ui({id:`overlayStack-${S}-blocker`,screen:h}),...P.elements||[]]},w=fi(d,r.characters,n),M=we({variables:n,runtime:o,saveSlots:p,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:i,skipMode:s,isChoiceVisible:c,isFormVisible:a,canRollback:l,form:f,historyDialogue:w,characters:r.characters||{},skipTransitionsAndAnimations:y}),F=se(N,M,{functions:Re}),[G,...j]=F.children||[],H=Oe(Ve({...F,children:j},{isLineCompleted:g,skipMode:s,skipTransitionsAndAnimations:y}),r);b.push({...H,children:G?[G,...H.children||[]]:H.children})}),e},vl=(e,{presentationState:t,resources:r={},variables:n,runtime:o,saveSlots:i=[],autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:f,form:u,confirmDialog:d,dialogueHistory:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:b,animations:A}=e;if(!d?.resourceId)return e;let x=r.layouts?.[d.resourceId];if(!x)return console.warn(`ConfirmDialog layout not found: ${d.resourceId}`),e;Array.isArray(x.transitions)&&!y&&gn({animations:A,transitions:x.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let S={id:"confirmDialog",type:"container",x:0,y:0,children:[ui({id:"confirmDialog-blocker",screen:h}),...x.elements||[]]},P=fi(p,r.characters,n),N=se(S,we({variables:n,runtime:o,saveSlots:i,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:s,skipMode:c,isChoiceVisible:a,isFormVisible:l,canRollback:f,form:u,confirmDialog:d,historyDialogue:P,characters:r.characters||{},skipTransitionsAndAnimations:y}),{functions:Re}),[w,...M]=N.children||[],F=Oe(Ve({...N,children:M},{isLineCompleted:g,skipMode:c,skipTransitionsAndAnimations:y}),r);return b.push({...F,children:w?[w,...F.children||[]]:F.children}),e},Ct=e=>(t,r)=>ul(t,{...r,visualLayer:e}),Cl=Ct(_e.BEHIND_BACKGROUND),Sl=Ct(_e.BEHIND_CHARACTER),_l=Ct(_e.BEHIND_DIALOGUE),Rl=Ct(_e.BEHIND_CHOICE),Ol=Ct(_e.FOREGROUND),hi=e=>Bt(sl,[ml,Cl,al,Sl,cl,_l,dl,Rl,pl,hl,Al,Ol,El,wl,gl,yl,Il,xl,vl])(e);function mi(e,t=""){let r=[],n=e.length,o=0,i=0,s=-1,c=()=>{let a=0,l=0,f;do f=parseInt(e[o++],36),a+=(f&15)<<l,l+=4;while(f&16);return a};for(;o<n;){let a=s+1+c();s=a+c(),r.push([a,s,t?parseInt(t[i++],36):0])}return r}function gi(e,t,r){let n=0,o=t.length-1;for(;n<=o;){let i=n+o>>>1,s=r[i];if(e<t[i])o=i-1;else if(e>s>>>5)n=i+1;else return s&31}return 0}var yi="090001000h1v5g2903000hl2v6jh16ng1s210111110o35aa10u2k1g10l6600152113h2010u1q1r5aq3890o13181214r22k3158q2n1000v100h1k20000001207030001160721k171001h1j11610332010010321210090411021c1c02100o301201412230u1130b100h1j116111420120411001100k11l10051001h1j11611142011000321210072411021d0g10r3000000132120090o200200g1j11f2012031213711271t1001o301001000001121371b1f0c101h1l2011001031212000080a1t1001m40400102101600i11t301006c7i601008b6p41r10101041h3d0004115a1j290p3q223000511010100g1501010302003172030c0010016000e0i6v50n40n5tl12ir33s12t11u11cj30100060700010a90t220000l71i20m7203010241000502rd101004k300000006101027050920g3t22bk1300616g209030207u18c1000t10003010501b2o20000102000004g37070101o921c000640602001mcv3rg20000001o16d0c0m1fg6g2h30m10q55f1vm11c0ma0p1a42nc0ne1a090q3314902021204020112030318250105bb1201110i1021i15101131502141b15120511011k1155132040202510201010603060a1f02040104210b1g3290e0e0kn11vs12j11j3040pp12t80g6v1vmo7319g21g51gh103040n11010040j51i3f01q1h1d0m27p1a0000cs13200523j200010301010100v140018a4q2501010101c08000i1f12601011g3012215110u1a0001015000pcq181000100011000iji5fvc0u91g5bhg20ie0l94lo6002115303121s12240la1tj23h44tj11t45m4ah33q700000l3ep2021a200t220301012040a0i320j2040007f00100r20c100g3208000011531000s520201036020t900207l1101n311000000321210090a12634b910201l22001051020120011020000e1i520701020000n10h5001050000010000010001re0010323010001r11i520701000001q6000000107l600000230004gg12080001lc62027111n1000411230000000000t820321030030r10090n205001380800501020n2050c0001mc00002000000nc006150000i5l1100600010001q753011160000i441111000000rl11019100000c1h201043102n10ltk1f006eoss2b0202gs94r36si2033ku101m373h50b1rqs4113sli1t22m1uh2435070726u13k92rr7m34h380e0m141egl561g1261114k60ga6nn10t33sv13uf1jf0207150qt16t66pr60n23k6bf1f0e1l29g71c1e029j1n30p11ea0k1028139m16rb2v621122i52213040tf1u3b51n17127c0232041d120819052c28220104060306l5g3l4572g130152cqdl2c3o37a5o27u11c32d9m2cu2191obo57eh9gg1tv3",bi="262122424333333393233393339333333333393393bf3b3b3b3b3f3f3bffff33b3bb33ff3f33b3b3333333bffff3b33bb33f33bffff33b3bb33ff3f33b3bbb333b3ff33b333f33b3b3b3b3333b3bf33b3bb39333b33b33b3b3b333b333333b3b33333f3b33b3ffb3f3fff3f3b33f35dc33333f3b3b3b33323333b3bb3b33b3fb3b3333b33333bff3b3f33bfb3b3ff3b3b3b3b3b333b333b3323e22442344444444444444444444444444444444444444444444444444444444444444444444444444444443333333333b3b3bb33333b353bff3b3b3b3f3ff3b3b333bfff3f33333fb3bb3fb3b3bb33232333f333fff333333333b3b3333bb3b39393f3b3fbf33bb3b393b3b3b3333b33b33b3bbb33b33ffff3b3333bb3933b3b3b333b3b3b3b3b33b3b3b33b3b3b33b3b33b33b3b3b3fffff3bb39b9b3b33b3bf3f3b33f3b3f93b33b3b3bb33b33b3b3b3333393b3b3b33b39bffb3b332333b333dd3b3333233332333333333333333333333333333444444444444a4444444444444344444444444444444444444444444444444444444444",Ii="0001000000010010000000100000000000000000000000000001000000010014000100000001001000010101100101100000000000000000000100000001111000010000000110101001110111111111000100000021001000010000000100100001000000011010000100000001111000013000000100140001000000010010";var Ai=65535,xn=40960,nr=126976,xi=new Uint8Array(12288),vi=new Uint8Array(3072),Ci=new Uint8Array(2816),Si,_i;{let e=(o,i,s,c,a)=>{let l=i+o.length-1;for(let f=s<i?i:s,u=c>l?l:c;f<=u;f++)o[f-i]=a},t=new Uint32Array(320),r=new Uint32Array(320),n=0;for(let[o,i,s]of mi(yi,bi))e(xi,0,o,i,s),e(vi,xn,o,i,s),e(Ci,nr,o,i,s),i>=65040&&!(o>=nr&&i<=129791)&&(t[n]=o,r[n++]=i<<5|s);Si=t.slice(0,n),_i=r.slice(0,n)}function wi(e){return e<12288?xi[e]:e<xn?e<12336?e>=12330?3:0:e<12443?e===12336||e===12349?4:e>=12441?3:0:e===12951||e===12953?4:0:e<44032?vi[e-xn]:e<55204?(e-44032)%28?8:7:e<57344?e<=55238?e>=55216?13:0:e>=55243&&e<=55291?12:0:e<65024?e===64286?3:0:e<65040?3:e>=nr&&e<129792?Ci[e-nr]:e>=917504?e>921599?0:e>=917536&&e<917632||e>=917760&&e<918e3?3:2:gi(e,Si,_i)}var Ri=Uint8Array.from(Ii,Number);function Ll(e){return e===2381||e===2509||e===2637||e===2765||e===2893||e===3149||e===3405||e===4153||e===6098||e===6752||e===6980||e===7083||e===43456||e===43766||e===68159||e===69939||e===70608||e===71998||e===72263||e===72345||e===73538}function Ei(e,t,r){switch(t){case 3:return e&24?r===8204?e&6:(e&24)===16||Ll(r)?e&6|16:e&6|8:e&6;case 4:return 2;case 10:return e&1^1;case 14:return(e&2)<<1|e&24;default:return 8}}function*Oi(e){let t=e.length;if(t===0)return;let r=e.codePointAt(0),n=r>Ai?2:1,o=wi(r),i=50200>>o&1?Ei(0,o,r):0,s=0,c=r,a=o;for(;n<t;){r=e.codePointAt(n);let l=r>Ai?2:1,f=wi(r),u=Ri[o<<4|f],d;u===0?d=!0:u===1?d=!1:u===2?d=!(i&1):u===3?d=!(i&4):d=(i&24)!==16,i=50200>>f&1&&(i!==0||f!==3)?Ei(i,f,r):0,d&&(yield{segment:e.slice(s,n),index:s,input:e,_hd:c,_catBegin:a===15?0:a,_catEnd:o===15?0:o},s=n,c=r,a=f),n+=l,o=f}yield{segment:e.slice(s),index:s,input:e,_hd:c,_catBegin:a===15?0:a,_catEnd:o===15?0:o}}function*Li(e){for(let t of Oi(e))yield t.segment}{let e=Oi("_");Ri._keep=[e,e.next()]}var $i=1e3,$l=1,kl=60,Dl=3,Tl=.5,Pl=2e4,Nl=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,Vl=/^\s+$/u,ki,jl=e=>{let t=`${e??""}`.normalize("NFC"),r=globalThis.Intl?.Segmenter;return typeof r!="function"?Array.from(Li(t)):(ki??=new r(void 0,{granularity:"grapheme"}),Array.from(ki.segment(t),({segment:n})=>n))},Fl=e=>jl(e).reduce((t,r)=>Vl.test(r)?t+Tl:Nl.test(r)?t+Dl:t+1,0),Di=({text:e="",baseDelay:t=$i,speed:r=$l}={})=>{let n=Number.isFinite(t)?Math.max(0,t):$i,o=Number.isFinite(r)&&r>0?r:1,i=Fl(e)*kl/o,s=Math.max(n,Pl);return Math.min(n+i,s)};var or={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},ji=1,cr="choice",ir="form",lr=()=>({manual:{...or.manual},auto:{...or.auto},applyMode:or.applyMode}),vn=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let r=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...lr()},r&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},T=e=>{let t=de(e)?ze(e):e;return structuredClone(t)},D=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),ur=e=>String(e),Fi=()=>({sections:[],resources:[]}),Ml=e=>D(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):Fi(),Ul=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",Bl=({sectionId:e,lineId:t,content:r,dialogueState:n,characterName:o})=>({sectionId:e,lineId:t,content:r,text:Ul(r),characterId:n.characterId,character:{...n.character||{},name:o},characterName:o}),zl=()=>({resourceId:void 0}),Wl=e=>{if(!D(e))return e;let t={...e};return Object.prototype.hasOwnProperty.call(t,"requireComplete")&&!Object.prototype.hasOwnProperty.call(t,"requireLineCompleted")&&(t.requireLineCompleted=t.requireComplete),delete t.requireComplete,t},Cn=(e,t)=>{let r=e?.story?.scenes??{};for(let[n,o]of Object.entries(r))if(o?.sections?.[t])return{sceneId:n,section:o.sections[t]};return{sceneId:void 0,section:void 0}},Mi=e=>{let t=e?.story?.scenes??{},r=new Map;for(let[n,o]of Object.entries(t)){let i=o?.sections??{};for(let s of Object.keys(i)){let c=r.get(s);if(c!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${c}" and "${n}". Section IDs must be globally unique.`);r.set(s,n)}}},Ui=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},Bi=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==ji)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},ql=(e,t={})=>{let r;try{r=Bi(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let n={...t,formatVersion:r,slotId:Ui(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete n.slotKey,delete n.date,n},Hl=(e={})=>Object.fromEntries(Object.entries(e).map(([t,r])=>[t,ql(t,r)])),zi=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:r})=>Mf(r));return t.length>0?t:void 0},Yl=e=>{!D(e)||!Array.isArray(e.timeline)||e.timeline.forEach(t=>{if(!D(t))return;let r=zi(t.executedActions);if(r){t.executedActions=r;return}delete t.executedActions})},Ti=(e,t,r,n="viewedRegistry")=>{let o=t==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[o]:String(e)};if(!D(e))throw new Error(`Malformed ${n}.${t}[${r}] entry.`);if(typeof e[o]!="string"||e[o].length===0)throw new Error(`Malformed ${n}.${t}[${r}] 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 ${n}.sections[${r}] entry: invalid lastLineId.`);return typeof e.lastLineId=="string"&&e.lastLineId.length>0&&(i.lastLineId=e.lastLineId),i}return{resourceId:e.resourceId}},Gl=(e,t="viewedRegistry")=>{if(e===void 0)return Fi();if(!D(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 r=e.sections??[],n=e.resources??[];return{sections:Object.values(Object.fromEntries(r.map((o,i)=>{let s=Ti(o,"sections",i,t);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(n.map((o,i)=>{let s=Ti(o,"resources",i,t);return[s.resourceId,s]})))}},Wi=(e,t,r)=>{if(!D(e))throw new Error(`Malformed save slot ${r}.`);let{sectionId:n,lineId:o}=e;if(typeof n!="string"||n.length===0)throw new Error(`Malformed save slot ${r}: missing sectionId.`);if(typeof o!="string"||o.length===0)throw new Error(`Malformed save slot ${r}: missing lineId.`);let{sceneId:i,section:s}=Cn(t,n);if(!s)throw new Error(`Malformed save slot ${r}: section "${n}" does not exist in projectData.`);if(!s.lines?.some(a=>a.id===o))throw new Error(`Malformed save slot ${r}: line "${o}" does not exist in section "${n}".`);return{sceneId:i,sectionId:n,lineId:o}},Kl=(e,t,r)=>{if(!D(e)||!Array.isArray(e.timeline))return St({pointer:t,replayStartIndex:1});let n=e.timeline.flatMap((c,a)=>{if(!D(c))return[];try{let l=Wi(c,r,`rollback.timeline[${a}]`),f=ar({sectionId:l.sectionId,lineId:l.lineId,rollbackPolicy:c.rollbackPolicy}),u=zi(T(c.executedActions));return u&&(f.executedActions=u),[f]}catch{return[]}});if(n.length===0)return St({pointer:t,replayStartIndex:1});let o=typeof e.currentIndex=="number"?Math.trunc(e.currentIndex):n.length-1;(o<0||o>=n.length)&&(o=n.length-1);let i=n[o];if(i?.sectionId!==t.sectionId||i?.lineId!==t.lineId){let c=n.findLastIndex(a=>a.sectionId===t.sectionId&&a.lineId===t.lineId);c>=0?o=c:(n.push(ar({sectionId:t.sectionId,lineId:t.lineId})),o=n.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:n}},Jl=(e,t,r)=>{if(!D(e))throw new Error(`Malformed save slot contexts[${r}] entry.`);let n=Rn(t),o=Wi(e.pointers?.read,t,`contexts[${r}].pointers.read`);if(e.variables!==void 0&&!D(e.variables))throw new Error(`Malformed save slot contexts[${r}].variables entry.`);if(e.runtime!==void 0&&!D(e.runtime))throw new Error(`Malformed save slot contexts[${r}].runtime entry.`);let i=e.variables?ot(T(e.variables),t.resources?.variables??{}):{},s=lu({loadedContextRuntime:D(e.runtime)?T(e.runtime):{}}),c={currentPointerMode:"read",pointers:{read:o},configuration:D(e.configuration)?T(e.configuration):{},views:Array.isArray(e.views)?T(e.views):[],bgm:D(e.bgm)?T(e.bgm):{resourceId:void 0},variables:{...n,...i},rollback:Kl(e.rollback,o,t)};return s&&(c.runtime=s),c},Xl=(e,t)=>{if(!D(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((r,n)=>Jl(r,t,n))}},Ql=(e,t)=>{if(!D(e))throw new Error("Malformed save slot.");let r=Bi(e.formatVersion);return{...e,formatVersion:r,state:Xl(e.state,t)}},Pi=(e,t,{required:r=!1}={})=>{if(e===void 0){if(r)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 n=T(e);return Object.prototype.hasOwnProperty.call(n,"hideConfirmDialog")||(n.hideConfirmDialog={}),n},Zl=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:Pi(e.confirmActions,"confirmActions",{required:!0}),cancelActions:Pi(e.cancelActions,"cancelActions")}},lt=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},eu=e=>(D(e.global.formDrafts)||(e.global.formDrafts={}),e.global.formDrafts),ut=e=>{Object.prototype.hasOwnProperty.call(e.global,"formDrafts")&&(e.global.formDrafts={})},qi=e=>{if(!(!D(e)||!e.animations))return{animations:T(e.animations)}},tu=(e,t)=>{let r=qi(t);if(r){e.global.pendingScreenTransition=r;return}delete e.global.pendingScreenTransition},ru=e=>{let t=e?.id??e?.resourceId;return typeof t=="string"&&t.length>0?t:void 0},nu=(e,t)=>{let r=e?.sectionId,n=e?.lineId;if(!(!r||!n||!t))return`${r}:${n}:${t}`},sr=e=>String(e??""),Hi=(e,t)=>{let r=sr(t);return e?.trim===!0?r.trim():r},ou=e=>D(e?.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,t])=>D(t)).map(([t,r])=>[t,{id:t,...T(r)}])):{},iu=(e,t)=>{if(!t||!D(e.global.formDrafts))return;let r=e.global.formDrafts[t];return D(r)?r:void 0},Yi=(e,t)=>{let r=eu(e);D(r[t])||(r[t]={values:{},touched:{},errors:{},submitted:!1});let n=r[t];return D(n.values)||(n.values={}),D(n.touched)||(n.touched={}),D(n.errors)||(n.errors={}),typeof n.submitted!="boolean"&&(n.submitted=!1),n},Sn=(e,t)=>{let r=Hi(e,t);return e?.required===!0&&r.length===0?"required":null},su=({state:e,pointer:t})=>{if(!t?.sectionId||!t?.lineId)return{};let n=ae({state:e},{sectionId:t.sectionId})?.lines||[],o=n.findIndex(i=>i.id===t.lineId);return o<0?{}:qe(n.slice(0,o+1).map(i=>i.actions||{}))},au=({state:e,form:t,pointer:r})=>{if(!t?.resourceId)return null;let n=ru(t),o=nu(r,n);if(!n||!o)return null;let i=iu(e,o),s=ou(t),c=dr({state:e}),a={},l=[],f={},u=!0;return Object.entries(s).forEach(([d,p])=>{let h=sr(c?.[p.variableId]),g=Object.prototype.hasOwnProperty.call(i?.values??{},d)?sr(i.values[d]):h,y=i?.touched?.[d]===!0,b=Sn(p,g),A=i?.submitted||y?b:null,x=typeof p.maxLength=="number"?Math.max(0,Math.round(p.maxLength)):void 0,S={id:d,variableId:p.variableId,value:g,initialValue:h,valid:!b,error:A,touched:y,required:p.required===!0,trim:p.trim===!0,placeholder:p.placeholder===void 0?"":String(p.placeholder),multiline:p.multiline===!0,...x!==void 0?{maxLength:x}:{}};b&&(u=!1),a[d]=S,l.push(S),f[d]=g}),{id:n,key:o,resourceId:t.resourceId,animations:t.animations,valid:u,submitted:i?.submitted===!0,fields:a,fieldList:l,values:f,submitActions:{submitForm:{formKey:o,actions:T(t.submitActions??{})}},cancelActions:{cancelForm:{formKey:o,actions:T(t.cancelActions??{})}}}},Xe=[],Ni="line",_n="interaction",ar=({sectionId:e,lineId:t,rollbackPolicy:r})=>({sectionId:e,lineId:t,rollbackPolicy:r??"free"}),Rn=e=>{let{contextVariableDefaultValues:t}=Wt(e??{});return T(t)},Gi=()=>({...T(At)}),Ki=({loadedRuntime:e,runtimeIds:t,defaults:r={},path:n})=>{if(e===void 0)return{runtimeState:T(r),hasLoadedValues:!1};if(!D(e))throw new Error(`Malformed ${n}.`);let o=T(r),i=!1;return t.forEach(s=>{e[s]!==void 0&&(o[s]=Ji(s,T(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},cu=({loadedGlobalRuntime:e={}})=>Ki({loadedRuntime:e,runtimeIds:Gr,defaults:He,path:"global.runtime"}).runtimeState,lu=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:r}=Ki({loadedRuntime:e,runtimeIds:Kr,defaults:Gi(),path:"context.runtime"});return r?t:void 0},fr=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},uu=e=>e.runtime?(Kr.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=T(At[t]))}),e.runtime):(e.runtime=Gi(),e.runtime),fu=e=>jo(e.global),du=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:fu(e)}})},pu=e=>Vo[e],hu=(e,t)=>{let r=pu(e);if(r==="number"){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} requires a finite numeric value`);return}if(r==="boolean"){if(typeof t!="boolean")throw new Error(`${e} requires a boolean value`);return}if(r==="string"){if(typeof t!="string")throw new Error(`${e} requires a string value`);return}throw new Error(`Unsupported runtime field "${e}"`)},Ji=(e,t)=>{if(hu(e,t),e==="autoForwardSpeed"&&t<=0)throw new Error("autoForwardSpeed requires a value greater than 0");return e==="saveLoadPagination"?Math.max(1,Math.trunc(t)):t},Xi=(e,t,r)=>{let n=Ji(t,r);if(t in At){let o=fr(e);if(!o)return n;let i=uu(o);return i[t]=n,n}return e.global[t]=n,n},Qi=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:T(e)},configuration:{},views:[],bgm:zl(),variables:Rn(t),rollback:St({pointer:e})}),ft=e=>e?(e.currentPointerMode="read",D(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,mu=(e,{queueRender:t=!0}={})=>{let r=e.contexts?.[e.contexts.length-1],n=r?.pointers?.read;if(!r||!n?.sectionId||!n?.lineId)return null;let o=Qi({pointer:n,projectData:e.projectData});return e.contexts[e.contexts.length-1]=o,gu(e,{queueRender:t}),o},gu=(e,{queueRender:t=!0}={})=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,lt(e),ut(e),e.global.nextLineConfig=lr(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"}),t&&e.global.pendingEffects.push({name:"render"})},Zi=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},St=({pointer:e,replayStartIndex:t=0})=>{let r=e?.sectionId&&e?.lineId;return{currentIndex:r?0:-1,isRestoring:!1,replayStartIndex:t,timeline:r?[ar({sectionId:e.sectionId,lineId:e.lineId})]:[]}},et=(e,t={})=>{if(e?.rollback)return Zi(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 r=e?.pointers?.read;return e.rollback=St({pointer:r,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},On=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return;let n=et(r);if(n.isRestoring)return;n.currentIndex<n.timeline.length-1&&(n.timeline=n.timeline.slice(0,n.currentIndex+1));let o=n.timeline[n.timeline.length-1];if(o?.sectionId===t.sectionId&&o?.lineId===t.lineId&&(o?.rollbackPolicy??"free")===(t.rollbackPolicy??"free")){n.currentIndex=n.timeline.length-1;return}n.timeline.push(ar(t)),n.currentIndex=n.timeline.length-1},yu=e=>{let r=e.contexts?.[e.contexts.length-1]?.rollback;if(!r||r.isRestoring||!Array.isArray(r.timeline)||typeof r.currentIndex!="number")return null;let n=Xe[Xe.length-1],o=typeof n?.checkpointIndex=="number"?n.checkpointIndex:r.currentIndex;return o<0||o>=r.timeline.length?null:(typeof n?.checkpointIndex!="number"&&o<r.timeline.length-1&&(r.timeline=r.timeline.slice(0,o+1)),r.timeline[o]??null)},bu=({state:e},t={})=>{let r=t?.source===Ni?Ni:_n,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:r}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),Xe.push({checkpointIndex:o.currentIndex,source:r}),e)},Iu=({state:e})=>(Xe.pop(),e),Se=(e,t,r)=>{let o=Xe[Xe.length-1]?.source??_n;if(!Uf(t,o))return;let i=yu(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:T(r)}))},Vi=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return;let n=t?.operations??[];for(let{variableId:o,op:i,value:s,roundTo:c}of n){let a=e.projectData.resources?.variables?.[o],l=a?.scope,f=a?.type;if(Te(a))throw new Error(`Cannot update computed variable: ${o}`);if(a?.readonly===!0)throw new Error(`Cannot update readonly variable: ${o}`);qt(l,o),Ht(f,i,o),zr(f,i,s,o,{roundTo:c}),l==="context"&&(r.variables[o]=Yt(r.variables[o],i,s,{roundTo:c}))}},Au=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:r,payload:n})=>{Bf(e,r,n)})},wu=(e,t)=>{let{sectionId:r,lineId:n}=t,s=ae({state:e},{sectionId:r})?.lines?.find(c=>c.id===n)?.actions;s&&Object.entries(s).forEach(([c,a])=>{gs(e,c,a)})},es=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let n=et(r),o=n.timeline[t];if(!o)return e;e.global.autoMode&&gr({state:e}),e.global.skipMode&&Qe({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),n.isRestoring=!0,n.currentIndex=t;try{r.variables=Rn(e.projectData),delete r.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=T(or),e.global.overlayStack=[],lt(e),ut(e),e.global.isLineCompleted=!0;let i=n.replayStartIndex??0;for(let c=i;c<=t;c++)c>i&&vn(e),wu(e,n.timeline[c]),Au(e,n.timeline[c]);let s=ft(r);s.read={sectionId:o.sectionId,lineId:o.lineId},e.global.pendingEffects=e.global.pendingEffects.filter(c=>c?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{n.isRestoring=!1}return e},Eu=e=>{let{projectData:t}=e,r=e.global??{},{saveSlots:n={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=r;Mi(t);let c=t.story.initialSceneId,a=t.story.scenes[c],l=a.initialSectionId,f=a.sections[l],u={sceneId:c,sectionId:l,lineId:f.initialLineId??f.lines[0].id},{globalVariablesDefaultValues:d}=Wt(t),p={...d,...ot(o,t.resources?.variables??{})};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,formDrafts:{},accountViewedRegistry:Gl(s,"accountViewedRegistry"),nextLineConfig:lr(),saveSlots:Hl(n),overlayStack:[],variables:p,...cu({loadedGlobalRuntime:i})},contexts:[Qi({pointer:u,projectData:t})]}},xu=({state:e})=>e.global.overlayStack||[],vu=({state:e})=>e.global.pendingEffects,ts=({state:e})=>e.global.skipMode,Cu=({state:e})=>e.global.autoMode,rs=({state:e})=>e.global.dialogueUIHidden,ns=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],r=t[t.length-1];if(!r)return[];let{sectionId:n,lineId:o}=r.pointers.read,i=ae({state:e},{sectionId:n});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(u=>u.id===o),c=i.lines.slice(0,s+1),a=[],l={},f=bt({variables:{...e.global?.variables??{},...fr(e)?.variables??{}},runtime:Ye(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1});for(let u of c){let d=u.actions||{};if(l=qe([l,d]),!d.dialogue)continue;let p=l.dialogue||{},h=zt({characterId:p.characterId,character:p.character,characters:e.projectData.resources?.characters??{},variables:f}),g=Bl({sectionId:n,lineId:u.id,content:d.dialogue.append===!0?p.content:d.dialogue.content,dialogueState:p,characterName:h});if(d.dialogue.append===!0&&a.length>0){a[a.length-1]={...a[a.length-1],content:g.content,text:g.text,characterId:g.characterId,character:g.character,characterName:g.characterName};continue}a.push(g)}return a},Su=({state:e})=>e.global.confirmDialog??null,_t=({state:e},{pointer:t}={})=>{let r=t??Ee({state:e})?.pointer,n=su({state:e,pointer:r});return au({state:e,form:n.form,pointer:r})},_u=({state:e},{pointer:t}={})=>!!_t({state:e},{pointer:t}),ye=({state:e},{pointer:t}={})=>{let r=_t({state:e},{pointer:t});if(r)return{source:ir,formId:r.id,formKey:r.key};let n=os({state:e,pointer:t});return n?{source:cr,resourceId:n}:null},Ru=({state:e,registry:t},r)=>{let{sectionId:n,lineId:o}=r,s=(Array.isArray(t?.sections)?t.sections:[]).find(f=>f.sectionId===n);if(!s)return!1;if(s.lastLineId===void 0||o===void 0)return!0;let c=ae({state:e},{sectionId:n});if(!c||!c.lines||!Array.isArray(c.lines))return s.lastLineId===o;let a=c.lines.findIndex(f=>f.id===s.lastLineId),l=c.lines.findIndex(f=>f.id===o);return a===-1||l===-1?s.lastLineId===o:l<=a},Ou=({registry:e},t)=>{let{resourceId:r}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===r)},Ln=({state:e},t)=>Ru({state:e,registry:e.global.accountViewedRegistry},t),Lu=({state:e},t)=>Ou({registry:e.global.accountViewedRegistry},t),$u=({state:e})=>e.global.nextLineConfig,os=({state:e,pointer:t}={})=>{let r=t??Ee({state:e})?.pointer;if(!r)return;let n=r?.sectionId,o=r?.lineId,s=ae({state:e},{sectionId:n})?.lines||[],c=s.findIndex(l=>l.id===o);if(c<0)return;let a;for(let l of s.slice(0,c+1)){let f=l?.actions;if(f?.cleanAll&&(a=void 0),!f||!Object.prototype.hasOwnProperty.call(f,"choice")){a=void 0;continue}let u=f.choice;if(u?.resourceId){a=u.resourceId;continue}u?.animations||(a=void 0)}return a},is=({state:e})=>!!os({state:e}),ku=({state:e})=>structuredClone(e),ss=({state:e})=>e.global.saveSlots,Du=({state:e},t)=>{let r=t?.slotId,n=ur(r);return e.global.saveSlots[n]},$n=({state:e})=>Ye(e),Tu=({state:e},t)=>Pe(e,t?.runtimeId),dr=({state:e})=>{let t={...e.global?.variables??{},...fr(e)?.variables??{}};return bt({variables:t,runtime:Ye(e),variableConfigs:e.projectData.resources?.variables??{}})},Ee=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],r=t[t.length-1];if(r)return{currentPointerMode:"read",pointer:r.pointers?.read}},ae=({state:e},t)=>{let{sectionId:r}=t;return Cn(e.projectData,r).section},pr=({state:e})=>{let t=Ee({state:e});if(!t?.pointer)return;let{sectionId:r,lineId:n}=t.pointer,o=ae({state:e},{sectionId:r});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===n)},as=({state:e})=>{let{sectionId:t,lineId:r}=Ee({state:e}).pointer,o=ae({state:e},{sectionId:t})?.lines||[],i=o.findIndex(l=>l.id===r),c=o.slice(0,i+1).map(l=>{let f=l.actions||{},u={};return Object.keys(f).forEach(d=>{u[d]=f[d]}),u});return qe(c)},Pu=e=>{let t=pr({state:e})?.actions?.dialogue;if(t?.clear===!0||!Array.isArray(t?.content))return"";let r=dr({state:e});return t.content.map(n=>`${it(n?.text,{variables:r})??""}`).join("")},hr=({state:e})=>Di({text:Pu(e),baseDelay:Pe(e,"autoForwardDelay"),speed:Pe(e,"autoForwardSpeed")}),Nu=({state:e})=>{let t=cs({state:e}),n=pr({state:e})?.actions??{},o=qe([t??{},n]);return Wr(t??{},o??{})},Vu=({state:e},{sectionId:t})=>{let r=ae({state:e},{sectionId:t});if(!r?.lines)return[];let n=[],o={};for(let i of r.lines){let s=i.actions||{},c=qe([o,s]),a=Wr(o,c);n.push({id:i.id,changes:a,presentationState:c}),o=qr(c)}return n},ju=({state:e},{sectionId:t,includePresentationState:r=!1})=>{let n=Vu({state:e},{sectionId:t});return r?{lines:n}:{lines:n.map(({presentationState:o,...i})=>i)}},cs=({state:e})=>{let{sectionId:t,lineId:r}=Ee({state:e}).pointer,o=ae({state:e},{sectionId:t})?.lines||[],i=o.findIndex(a=>a.id===r);if(i<=0)return null;let c=o.slice(0,i).map(a=>{let l=a.actions||{},f={};return Object.keys(l).forEach(u=>{f[u]=l[u]}),f});return qr(qe(c))},kn=({state:e},{slotsPerPage:t=6}={})=>{let o=(($n({state:e}).saveLoadPagination??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let c=o+s,a=e.global.saveSlots&&e.global.saveSlots[ur(c)]||{};i.push({...a,slotId:c})}return{saveSlots:i}},Fu=ss,Mu=kn,Uu=e=>{let r=e.contexts?.[e.contexts.length-1]?.rollback;return!r||!Array.isArray(r.timeline)||typeof r.currentIndex!="number"?!1:r.currentIndex>=0&&r.currentIndex<r.timeline.length-1},Bu=({state:e},t={})=>{let r=as({state:e}),n=cs({state:e}),o=pr({state:e})?.actions??{},i=e.global.pendingScreenTransition,s=i?.animations?{...o,screen:T(i)}:o,c=i?.animations&&n===null?{}:n,{sectionId:a}=Ee({state:e}).pointer,{sceneId:l}=Cn(e.projectData,a),f=$n({state:e}),u=t?.activePersistentAnimations??[],d=t?.restoredPersistentAnimations??[],p=_t({state:e}),h=is({state:e}),g=dr({state:e}),{saveSlots:y}=kn({state:e}),b=Uu(e);return hi({presentationState:r,previousPresentationState:c,currentLineActions:s,resources:e.projectData.resources,currentSceneId:l,screen:e.projectData.screen,dialogueUIHidden:f.dialogueUIHidden,autoMode:f.autoMode,skipMode:f.skipMode,isChoiceVisible:h,isFormVisible:!!p,canRollback:bs({state:e}),skipOnlyViewedLines:!f.skipUnseenText,isLineCompleted:f.isLineCompleted,skipTransitionsAndAnimations:!!f.skipTransitionsAndAnimations||b,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,form:p,dialogueHistory:ns({state:e}),saveSlots:y,variables:g,runtime:f,activePersistentAnimations:u,restoredPersistentAnimations:d})},zu=({state:e},t)=>(e.global.confirmDialog=Zl(t),e.global.pendingEffects.push({name:"render"}),e),Wu=({state:e})=>(e.global.confirmDialog&&(lt(e),e.global.pendingEffects.push({name:"render"})),e),qu=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),Se(e,"pushOverlay",t),e),Hu=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),Se(e,"popOverlay",void 0),e),Yu=({state:e},t)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=t),e.global.pendingEffects.push({name:"render"}),Se(e,"replaceLastOverlay",t),e),Gu=({state:e})=>(e.global.overlayStack=[],lt(e),ut(e),e.global.pendingEffects.push({name:"render"}),Se(e,"clearOverlays",void 0),e),Ku=e=>{e.global.autoMode&&e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.skipMode&&e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.nextLineConfig?.auto?.enabled&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},mr=(e,t,{screenTransition:r}={})=>{e.global.isLineCompleted=!1,tu(e,r),ut(e);let n=ye({state:e},{pointer:t}),o=n?.source===cr,i=n?.source===ir;return n&&Ku(e),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:o,isFormVisible:i,activeInteraction:n}},Dn=(e,t,r)=>{t?.source!==cr||r||!e.global.skipMode||e.global.pendingEffects.push({name:"startSkipNextTimer"})},ls=({state:e})=>(ye({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:hr({state:e})}}),e.global.pendingEffects.push({name:"render"})),e),gr=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Ju=({state:e})=>{let t=e.global.autoMode;return ye({state:e})&&!t||(t?gr({state:e}):ls({state:e})),e},us=({state:e})=>(ye({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),Qe=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Xu=({state:e})=>{let t=ts({state:e});return ye({state:e})&&!t||(t?Qe({state:e}):us({state:e})),e},yr=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),Se(e,"showDialogueUI",void 0),e),fs=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),Se(e,"hideDialogueUI",void 0),e),Qu=({state:e})=>(rs({state:e})?yr({state:e}):fs({state:e}),e),je=(e,t,r)=>(Xi(e,t,r),du(e),e.global.pendingEffects.push({name:"render"}),e),Rt=(e,t,r,n)=>{let o=Xi(e,t,r);return e.global.pendingEffects.push({name:"render"}),Se(e,n,{value:o}),e},Zu=({state:e},t)=>je(e,"dialogueTextSpeed",t?.value),ef=({state:e},t)=>je(e,"autoForwardDelay",t?.value),tf=({state:e},t)=>je(e,"autoForwardSpeed",t?.value),rf=({state:e},t)=>je(e,"skipUnseenText",t?.value),nf=({state:e},t)=>je(e,"skipTransitionsAndAnimations",t?.value),of=({state:e},t)=>je(e,"soundVolume",t?.value),sf=({state:e},t)=>je(e,"musicVolume",t?.value),af=({state:e},t)=>je(e,"muteAll",t?.value),cf=({state:e},t)=>Rt(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),lf=({state:e})=>{let t=Pe(e,"saveLoadPagination")+1;return Rt(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},uf=({state:e})=>{let t=Pe(e,"saveLoadPagination")-1;return Rt(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},ff=({state:e},t)=>Rt(e,"menuPage",t?.value,"setMenuPage"),df=({state:e},t)=>Rt(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),pf=({state:e})=>(e.global.pendingEffects=[],e),hf=({state:e},t)=>(e.global.pendingEffects.push(t),e),ds=(e,{sectionId:t,resetStoryState:r=!1,screen:n})=>{let o=!!qi(n),i=ae({state:e},{sectionId:t});if(!i)return console.warn(`Section not found: ${t}`),e;let s=i.lines?.[0];if(!s)return console.warn(`Section ${t} has no lines`),e;if(r&&!mu(e,{queueRender:!o}))return e;let c=ye({state:e});r&&e.global.skipMode&&Qe({state:e});let a=e.contexts?.[e.contexts.length-1];if(a){let f=ft(a),u=f.read;r||Ze(e,{sectionId:u?.sectionId,lineId:u?.lineId}),a.rollback||et(a,{compatibilityAnchor:!0}),f.read={sectionId:t,lineId:s.id},r?a.rollback=St({pointer:f.read}):On(e,{sectionId:t,lineId:s.id})}let{activeInteraction:l}=mr(e,a?.pointers?.read,{screenTransition:n});return Dn(e,c,l),!r&&e.global.autoMode&&!c&&!l&&e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e},mf=({state:e},t)=>ds(e,{sectionId:t?.sectionId,resetStoryState:!0,screen:t?.screen}),ps=e=>(e.global.accountViewedRegistry=Ml(e.global.accountViewedRegistry),e.global.accountViewedRegistry),Tn=(e,t)=>{!Array.isArray(t)||t.length===0||e.global.pendingEffects.push({name:"applyScopedDataUpdates",payload:{updates:t.map(r=>({scope:r.scope,path:r.path,op:r.op,value:T(r.value)}))}})},hs=(e,t)=>{Tn(e,[{scope:"account",path:"viewedRegistry",op:"markViewed",value:{sections:(Array.isArray(t?.sections)?t.sections:[]).map(r=>({sectionId:r.sectionId,...r.lastLineId===void 0?{}:{lineId:r.lastLineId}})),resources:Array.isArray(t?.resources)?t.resources:[]}}])},gf=(e,t,{sectionId:r,lineId:n})=>{if(!r||!n)return!1;let o=D(t)?t:{};Array.isArray(o.sections)||(o.sections=[]);let i=o.sections.find(s=>s.sectionId===r);if(i){if(i.lastLineId===void 0)return!1;let s=ae({state:e},{sectionId:r});if(s?.lines){let c=s.lines.findIndex(l=>l.id===i.lastLineId),a=s.lines.findIndex(l=>l.id===n);if(c===-1||a>c)return i.lastLineId===n?!1:(i.lastLineId=n,!0)}else return i.lastLineId===n?!1:(i.lastLineId=n,!0);return!1}else return o.sections.push({sectionId:r,lastLineId:n}),!0},Ze=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;gf(e,ps(e),t)&&hs(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},yf=({state:e},t)=>(Ze(e,t),e.global.pendingEffects.push({name:"render"}),e),bf=({state:e},t)=>{let{resourceId:r}=t;if(e.global.accountViewedRegistry!==void 0){let n=ps(e);n.resources.find(i=>i.resourceId===r)||(n.resources.push({resourceId:r}),hs(e,{sections:[],resources:[{resourceId:r}]}))}return e.global.pendingEffects.push({name:"render"}),e},ms=({state:e},t)=>{let r=Wl(t.manual),{auto:n,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,c=e.contexts?.[e.contexts.length-1]?.rollback?.isRestoring===!0;r&&n?(e.global.nextLineConfig={manual:r,auto:n},o!==void 0?e.global.nextLineConfig.applyMode=o:s!==void 0&&(e.global.nextLineConfig.applyMode=s)):(r&&(e.global.nextLineConfig.manual=r),n&&(e.global.nextLineConfig.auto=n),o!==void 0&&(e.global.nextLineConfig.applyMode=o));let a=e.global.nextLineConfig.auto?.enabled,l=ye({state:e});return!c&&!l&&a===!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}}):!c&&a===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),Se(e,"setNextLineConfig",t),e},If=({state:e},t)=>{let r=t?.slotId;if(r==null||r==="")throw new Error("saveSlot requires slotId");let{thumbnailImage:n}=t,o=t?.savedAt,i=ur(r),s=T(e.contexts);s?.forEach(l=>{ft(l),Zi(l.rollback),Yl(l.rollback)});let c={contexts:s},a={formatVersion:ji,slotId:Ui(r),savedAt:typeof o=="number"?o:Date.now(),image:n,state:c};return e.global.saveSlots[i]=a,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},Af=({state:e},t)=>{let r=t?.slotId;if(r==null||r==="")throw new Error("loadSlot requires slotId");let n=ur(r),o=e.global.saveSlots[n];if(o){let i=Ql(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=lr(),e.global.overlayStack=[],e.global.isLineCompleted=!0,lt(e),ut(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},wf=({state:e},t)=>{let{projectData:r}=t;Mi(r),e.projectData=r;let n=r?.resources?.variables??{},{contextVariableDefaultValues:o,globalVariablesDefaultValues:i}=Wt(r??{});return Object.prototype.hasOwnProperty.call(e.global??{},"variables")&&(e.global.variables={...i,...ot(e.global.variables,n)}),e.contexts?.forEach(s=>{Object.prototype.hasOwnProperty.call(s??{},"variables")&&(s.variables={...o,...ot(s.variables,n)})}),lt(e),ut(e),e.global.pendingEffects.push({name:"render"}),e},Ef=({state:e},t)=>{let{sectionId:r,lineId:n}=t;if(!n)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=r||o.pointers.read?.sectionId;if(r&&!ae({state:e},{sectionId:r}))return console.warn(`Section not found: ${r}`),e;let s=ae({state:e},{sectionId:i});if(!s?.lines||!Array.isArray(s.lines))return console.warn(`Section ${i} has no lines`),e;if(!s.lines.find(u=>u.id===n))return console.warn(`Line not found: ${n} in section ${i}`),e;let a=ye({state:e}),l=ft(o);l.read={sectionId:i,lineId:n};let{activeInteraction:f}=mr(e,l.read);return Dn(e,a,f),e},xf=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return yr({state:e}),e;let r=ye({state:e});if(r?.source===cr&&t?.bypassChoice!==!0||r?.source===ir&&t?._interactionSource!==ir)return e;let n=Ee({state:e})?.pointer,o=n?.sectionId,s=ae({state:e},{sectionId:o})?.lines||[],a=s.findIndex(u=>u.id===n?.lineId)+1,l=t?._advanceImmediately===!0&&a<s.length;if(!e.global.isLineCompleted&&!l){e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let u=n?.lineId;o&&u&&Ze(e,{sectionId:o,lineId:u}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&!r&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:hr({state:e})}});let d=e.global.nextLineConfig;return d?.auto?.enabled&&!r&&d.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:d.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e}let f=e.contexts[e.contexts.length-1];if(a<s.length){let u=s[a],d=!Pe(e,"skipUnseenText");if(e.global.skipMode&&d&&!Ln({state:e},{sectionId:o,lineId:u.id}))return Qe({state:e}),e;if(f&&!f.rollback&&et(f,{compatibilityAnchor:!0}),f){let g=ft(f),y=g.read?.lineId;y&&o&&Ze(e,{sectionId:o,lineId:y}),g.read={sectionId:o,lineId:u.id}}On(e,{sectionId:o,lineId:u.id}),vn(e);let{activeInteraction:p}=mr(e,{sectionId:o,lineId:u.id});Dn(e,r,p);let h=e.global.nextLineConfig;h?.auto?.enabled&&!p&&h.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:h.auto.delay}})}else e.global.autoMode&&gr({state:e}),e.global.skipMode&&Qe({state:e});return e},vf=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=ye({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:hr({state:e})}});let r=Ee({state:e})?.pointer,n=r?.sectionId,o=r?.lineId;n&&o&&Ze(e,{sectionId:n,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},Cf=({state:e},t)=>ds(e,{sectionId:t?.sectionId,screen:t?.screen}),Sf=({state:e})=>{if(e.global.dialogueUIHidden)return yr({state:e}),e;if(ye({state:e}))return e;let t=Ee({state:e})?.pointer,r=t?.sectionId,n=ae({state:e},{sectionId:r}),o=e.contexts[e.contexts.length-1],i=n?.lines||[],c=i.findIndex(a=>a.id===t?.lineId)+1;if(c<i.length){let a=i[c],l=!Pe(e,"skipUnseenText");if(e.global.skipMode&&l&&!Ln({state:e},{sectionId:r,lineId:a.id}))return Qe({state:e}),e;if(o&&!o.rollback&&et(o,{compatibilityAnchor:!0}),o){let u=ft(o),d=u.read?.lineId;d&&r&&Ze(e,{sectionId:r,lineId:d}),u.read={sectionId:r,lineId:a.id}}On(e,{sectionId:r,lineId:a.id}),vn(e);let{activeInteraction:f}=mr(e,{sectionId:r,lineId:a.id});e.global.nextLineConfig.auto?.enabled&&!f&&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},Pn=(e,t={})=>{let r=_t({state:e});return!r||t.formKey&&t.formKey!==r.key||t.formId&&t.formId!==r.id?null:r},_f=(e,t)=>{if(!t.variableId)throw new Error(`form field "${t.id}" requires variableId`);let r=e.projectData.resources?.variables?.[t.variableId],n=r?.scope,o=r?.type;if(Te(r))throw new Error(`Cannot update computed variable: ${t.variableId}`);if(r?.readonly===!0)throw new Error(`Cannot update readonly variable: ${t.variableId}`);return qt(n,t.variableId),Ht(o,"set",t.variableId),{variableConfig:r,scope:n}},Rf=(e,t)=>({id:e.id,key:e.key,valid:!0,values:T(t),fields:T(e.fields),fieldList:T(e.fieldList)}),Of=e=>{if(e.global.isLineCompleted)return;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=Ee({state:e})?.pointer,r=t?.sectionId,n=t?.lineId;r&&n&&Ze(e,{sectionId:r,lineId:n})},Lf=({state:e},t={})=>{let r=Pn(e,t),n=t.field;if(!r?.fields?.[n])return e;let o=Yi(e,r.key),i=sr(t.value),s=r.fields[n],c=Sn(s,i);return o.values[n]=i,o.touched[n]=!0,c?o.errors[n]=c:delete o.errors[n],e.global.pendingEffects.push({name:"render"}),e},$f=({state:e},t={})=>{let r=Pn(e,t);if(!r)return{submitted:!1,valid:!1,reason:"inactive"};let n=Yi(e,r.key);n.submitted=!0;let o={},i={};if(Object.entries(r.fields).forEach(([u,d])=>{let p=Object.prototype.hasOwnProperty.call(n.values,u)?n.values[u]:d.value,h=Sn(d,p);n.touched[u]=!0,h&&(i[u]=h),o[u]=Hi(d,p)}),n.errors=i,Object.keys(i).length>0)return e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!1,errors:T(i),form:{id:r.id,key:r.key,values:T(o)}};let s=e.contexts[e.contexts.length-1];if(s?.rollback?.isRestoring)return{submitted:!1,valid:!1,reason:"restoring"};let c=!1,a=[],l=[];Object.entries(r.fields).forEach(([u,d])=>{let{scope:p}=_f(e,d),h=p==="context"?s.variables:e.global.variables,g=o[u];h[d.variableId]=Yt(h[d.variableId],"set",g),p==="context"&&(c=!0,l.push({variableId:d.variableId,op:"set",value:g})),(p==="device"||p==="account")&&a.push({scope:p,path:`variables.${d.variableId}`,op:"set",value:T(h[d.variableId])})}),c&&Se(e,"updateVariable",{id:"submitForm",operations:l}),Tn(e,a);let f=Rf(r,o);return Of(e),delete e.global.formDrafts[r.key],e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!0,form:f}},kf=({state:e},t={})=>{let r=Pn(e,t);return r?(delete e.global.formDrafts?.[r.key],e.global.pendingEffects.push({name:"render"}),{cancelled:!0,form:{id:r.id,key:r.key,values:T(r.values),fields:T(r.fields),fieldList:T(r.fieldList)}}):{cancelled:!1,reason:"inactive"}},Df=({state:e},t)=>{let{id:r,operations:n=[]}=t;if(!r)throw new Error("updateVariable requires an id field");if(typeof r!="string"||!/^[a-zA-Z0-9]+$/.test(r))throw new Error(`updateVariable id must be alphanumeric, got: "${r}"`);let o=e.contexts[e.contexts.length-1];if(o?.rollback?.isRestoring)return e;let i=!1,s=[],c=[];return n.forEach(({variableId:a,op:l,value:f,roundTo:u})=>{let d=e.projectData.resources?.variables?.[a],p=d?.scope,h=d?.type;if(Te(d))throw new Error(`Cannot update computed variable: ${a}`);if(d?.readonly===!0)throw new Error(`Cannot update readonly variable: ${a}`);qt(p,a),Ht(h,l,a),zr(h,l,f,a,{roundTo:u});let g=p==="context"?o.variables:e.global.variables;if(p==="context"){i=!0;let y={variableId:a,op:l,value:f};u!==void 0&&(y.roundTo=u),c.push(y)}g[a]=Yt(g[a],l,f,{roundTo:u}),(p==="device"||p==="account")&&s.push({scope:p,path:`variables.${a}`,op:"set",value:T(g[a])})}),i&&Se(e,"updateVariable",{id:r,operations:c}),Tn(e,s),e.global.pendingEffects.push({name:"render"}),e},Tf=e=>(t,r)=>e({state:t},r),Pf=e=>({variables:bt({variables:{...e.global?.variables??{},...fr(e)?.variables??{}},runtime:Ye(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1}),runtime:Ye(e)}),Nf=e=>{if(!D(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")},Vf=(e,t,r)=>{if(!D(e))throw new Error(`conditional branch at index ${t} must be an object`);if(!D(e.actions))throw new Error(`conditional branch at index ${t} requires actions object`);if(!Object.prototype.hasOwnProperty.call(e,"when")&&t!==r-1)throw new Error("conditional else branch must be the last branch")},jf=(e,t)=>{Nf(t);for(let r=0;r<t.branches.length;r+=1){let n=t.branches[r];if(Vf(n,r,t.branches.length),!(Object.prototype.hasOwnProperty.call(n,"when")&&!yt(n.when,Pf(e)))){Object.entries(n.actions).forEach(([i,s])=>{gs(e,i,s)});return}}},Ff={conditional:{replayLine:jf},updateVariable:{recordSources:[_n],replayLine:Vi,replayRecorded:Vi,persistInSaveSlot:!0},setNextLineConfig:{replayLine:Tf(ms)}},br=e=>Ff[e]??null,Mf=e=>br(e)?.persistInSaveSlot===!0,Uf=(e,t)=>{let r=br(e)?.recordSources;return Array.isArray(r)&&r.includes(t)},Bf=(e,t,r)=>{br(t)?.replayRecorded?.(e,r)},gs=(e,t,r)=>{br(t)?.replayLine?.(e,r)},ys=({state:e},t)=>{let{offset:r}=t;if(r===void 0||typeof r!="number")return console.warn("selectLineIdByOffset requires a numeric offset"),null;let n=e.contexts[e.contexts.length-1];if(!n)return null;let o=n.rollback;if(!Array.isArray(o?.timeline)||typeof o?.currentIndex!="number")return null;let i=o.currentIndex+r;if(i<0||i>=o.timeline.length)return null;let s=o.timeline[i];return{sectionId:s.sectionId,lineId:s.lineId}},bs=({state:e})=>ys({state:e},{offset:-1})!==null,zf=({state:e},t)=>{let{offset:r=-1}=t;if(r>=0)throw new Error("rollbackByOffset requires a negative offset");let n=e.contexts?.[e.contexts.length-1];if(!n)return e;let o=et(n,{compatibilityAnchor:!n.rollback}),i=o.currentIndex+r;return i<0||i>=o.timeline.length?e:es(e,i)},Wf=({state:e},t)=>{let{sectionId:r,lineId:n}=t,o=e.contexts[e.contexts.length-1];if(!o)throw new Error("No context available for rollbackToLine");let i=et(o,{compatibilityAnchor:!o.rollback}),c=i.timeline.slice(0,i.currentIndex+1).findLastIndex(a=>a.sectionId===r&&a.lineId===n);if(c===-1)throw new Error(`Line ${n} not found in section ${r} rollback timeline`);return c===i.currentIndex?e:es(e,c)},Is=e=>{let t=Eu(e);return wo(t,{selectPendingEffects:vu,selectSkipMode:ts,selectAutoMode:Cu,selectIsChoiceVisible:is,selectIsFormVisible:_u,selectActiveInteraction:ye,selectActiveForm:_t,selectDialogueUIHidden:rs,selectDialogueHistory:ns,selectConfirmDialog:Su,selectIsLineAccountViewed:Ln,selectIsResourceAccountViewed:Lu,selectNextLineConfig:$u,selectSystemState:ku,selectSaveSlotMap:ss,selectSaveSlots:Fu,selectSaveSlot:Du,selectRuntime:$n,selectRuntimeValue:Tu,selectAllVariables:dr,selectCurrentPointer:Ee,selectSection:ae,selectCurrentLine:pr,selectPresentationState:as,selectAutoForwardTimerDelay:hr,selectPresentationChanges:Nu,selectSectionLineChanges:ju,selectSaveSlotPage:kn,selectCurrentPageSlots:Mu,selectRenderState:Bu,selectOverlayStack:xu,selectLineIdByOffset:ys,selectCanRollback:bs,startAutoMode:ls,stopAutoMode:gr,toggleAutoMode:Ju,startSkipMode:us,stopSkipMode:Qe,toggleSkipMode:Xu,showDialogueUI:yr,hideDialogueUI:fs,toggleDialogueUI:Qu,setDialogueTextSpeed:Zu,setAutoForwardDelay:ef,setAutoForwardSpeed:tf,setSkipUnseenText:rf,setSkipTransitionsAndAnimations:nf,setSoundVolume:of,setMusicVolume:sf,setMuteAll:af,setSaveLoadPagination:cf,incrementSaveLoadPagination:lf,decrementSaveLoadPagination:uf,setMenuPage:ff,setMenuEntryPoint:df,showConfirmDialog:zu,hideConfirmDialog:Wu,resetStoryAtSection:mf,clearPendingEffects:pf,appendPendingEffect:hf,beginRollbackActionBatch:bu,endRollbackActionBatch:Iu,addViewedLine:yf,addViewedResource:bf,setNextLineConfig:ms,saveSlot:If,loadSlot:Af,updateProjectData:wf,sectionTransition:Cf,jumpToLine:Ef,nextLine:xf,markLineCompleted:vf,rollbackToLine:Wf,rollbackByOffset:zf,pushOverlay:qu,popOverlay:Hu,replaceLastOverlay:Yu,clearOverlays:Gu,updateFormField:Lf,submitForm:$f,cancelForm:kf,updateVariable:Df,nextLineFromSystem:Sf},{transformActionFirstArgument:n=>({state:n}),transformSelectorFirstArgument:n=>({state:n})})};var qf="route-engine",Hf="projectPersistence";var ws=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),te=e=>Object.prototype.toString.call(e)==="[object Object]",As="variables.",Yf=(e={})=>{let t=te(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!te(r)||typeof r.sectionId!="string"||r.sectionId.length===0?null:{sectionId:r.sectionId,...typeof r.lineId=="string"?{lineId:r.lineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(r=>typeof r=="string"||typeof r=="number"?{resourceId:String(r)}:!te(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},Gf=(e={})=>{let t=te(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!te(r)||typeof r.sectionId!="string"||r.sectionId.length===0?null:{sectionId:r.sectionId,...typeof r.lastLineId=="string"?{lastLineId:r.lastLineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(r=>typeof r=="string"||typeof r=="number"?{resourceId:String(r)}:!te(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},Kf=(e,t)=>{let r=Gf(e),n=Yf(t),o=r.sections.map(s=>({...s})),i=r.resources.map(s=>({...s}));return n.sections.forEach(s=>{let c=o.find(a=>a.sectionId===s.sectionId);if(!c){o.push({sectionId:s.sectionId,...s.lineId===void 0?{}:{lastLineId:s.lineId}});return}if(c.lastLineId!==void 0){if(s.lineId===void 0){delete c.lastLineId;return}c.lastLineId=s.lineId}}),n.resources.forEach(s=>{i.find(a=>a.resourceId===s.resourceId)||i.push({...s})}),{sections:o,resources:i}},Es=(e={})=>{let t=te(e)?e:{};return{saveSlots:te(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:te(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:te(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:te(t.globalRuntime)?t.globalRuntime:{},accountViewedRegistry:te(t.accountViewedRegistry)?t.accountViewedRegistry:{}}},Jf=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((t,r)=>{if(!te(t))throw new Error(`Malformed applyScopedDataUpdates.updates[${r}] entry.`);let n=t.path?.startsWith(As)?t.path.slice(As.length):null;if(n!==null){if(!["device","account"].includes(t.scope))throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${r}].`);if(n.length===0)throw new Error(`Malformed applyScopedDataUpdates path "${t.path}" at updates[${r}].`);if(t.op!=="set")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${r}].`);return{scope:t.scope,path:t.path,op:t.op,value:t.value,variableId:n}}if(t.path==="viewedRegistry"){if(t.scope!=="account")throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${r}].`);if(t.op!=="markViewed")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${r}].`);return t}throw typeof t.path!="string"?new Error(`Malformed applyScopedDataUpdates path at updates[${r}].`):new Error(`Unsupported applyScopedDataUpdates path "${t.path}" at updates[${r}].`)})},Xf=(e,t)=>{let r={};return Jf(t).forEach(n=>{if(n.path==="viewedRegistry"){r.accountViewedRegistry=Kf(r.accountViewedRegistry??e.accountViewedRegistry,n.value);return}let o=n.scope==="device"?"globalDeviceVariables":"globalAccountVariables";r[o]={...e[o],...r[o],[n.variableId]:n.value}}),r},Nn=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},Qf=e=>{let t=Nn(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},Zf=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},ed=({indexedDB:e,databaseName:t,objectStoreName:r})=>new Promise((n,o)=>{let i=e.open(t,1);i.onupgradeneeded=()=>{let s=i.result;s.objectStoreNames.contains(r)||s.createObjectStore(r,{keyPath:"namespace"})},i.onsuccess=()=>{n(i.result)},i.onerror=()=>{o(i.error??new Error(`Failed to open IndexedDB database "${t}".`))}}),td=async({databasePromise:e,objectStoreName:t,namespace:r})=>{let n=await e;return new Promise((o,i)=>{let a=n.transaction(t,"readonly").objectStore(t).get(r);a.onsuccess=()=>{o(a.result??null)},a.onerror=()=>{i(a.error??new Error(`Failed to read persisted namespace "${r}" from IndexedDB.`))}})},Ot=async({databasePromise:e,objectStoreName:t,namespace:r,patch:n})=>{let o=await e;return new Promise((i,s)=>{let c=o.transaction(t,"readwrite"),a=c.objectStore(t),l=a.get(r),f=!1,u=p=>{f||(f=!0,s(p))},d=()=>{f||(f=!0,i())};l.onerror=()=>{u(l.error??new Error(`Failed to read persisted namespace "${r}" before updating IndexedDB.`))},l.onsuccess=()=>{let p=Es(l.result),h=typeof n=="function"?n(p):n,g={namespace:r,version:1,...ws(),...p,...h},y=a.put(g);y.onerror=()=>{u(y.error??new Error(`Failed to persist namespace "${r}" to IndexedDB.`))}},c.oncomplete=()=>{d()},c.onerror=()=>{u(c.error??new Error(`IndexedDB transaction failed while updating namespace "${r}".`))},c.onabort=()=>{u(c.error??new Error(`IndexedDB transaction aborted while updating namespace "${r}".`))}})},rd=async({databasePromise:e,objectStoreName:t,namespace:r})=>{let n=await e;return new Promise((o,i)=>{let s=n.transaction(t,"readwrite"),a=s.objectStore(t).delete(r),l=!1,f=d=>{l||(l=!0,i(d))},u=()=>{l||(l=!0,o())};a.onerror=()=>{f(a.error??new Error(`Failed to clear persisted namespace "${r}" from IndexedDB.`))},s.oncomplete=()=>{u()},s.onerror=()=>{f(s.error??new Error(`IndexedDB transaction failed while clearing namespace "${r}".`))},s.onabort=()=>{f(s.error??new Error(`IndexedDB transaction aborted while clearing namespace "${r}".`))}})},Vn=(e={})=>{let{indexedDB:t,databaseName:r=qf,objectStoreName:n=Hf,namespace:o}=e,i=Zf(t),s=Qf(o),c=ed({indexedDB:i,databaseName:r,objectStoreName:n});return{namespace:s,load:async()=>{let a=await td({databasePromise:c,objectStoreName:n,namespace:s});return{...ws(),...Es(a)}},clear:async()=>rd({databasePromise:c,objectStoreName:n,namespace:s}),saveSlots:async a=>Ot({databasePromise:c,objectStoreName:n,namespace:s,patch:{saveSlots:te(a)?a:{}}}),saveGlobalDeviceVariables:async a=>Ot({databasePromise:c,objectStoreName:n,namespace:s,patch:{globalDeviceVariables:te(a)?a:{}}}),saveGlobalAccountVariables:async a=>Ot({databasePromise:c,objectStoreName:n,namespace:s,patch:{globalAccountVariables:te(a)?a:{}}}),saveGlobalRuntime:async a=>Ot({databasePromise:c,objectStoreName:n,namespace:s,patch:{globalRuntime:te(a)?a:{}}}),applyScopedDataUpdates:async a=>Ot({databasePromise:c,objectStoreName:n,namespace:s,patch:l=>Xf(l,a)})}},nd=Vn;var od=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),id=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),xs="conditional",jn="form",sd=new Set(["submitForm","cancelForm"]),Lt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function Fn(e){let t,r=0,n=null,o=0,i=!1,s=new Map,c=new Map,a=new Map,{handlePendingEffects:l}=e,f=(I=new Map,C=Date.now())=>new Map(Array.from(I.entries()).filter(([,R])=>C<R.expiresAt).map(([R,L])=>[R,{animation:structuredClone(L.animation),startedAt:L.startedAt,expiresAt:L.expiresAt}])),u=(I=new Map)=>Array.from(I.values()).map(C=>structuredClone(C.animation)),d=(I=Date.now())=>{s=new Map(Array.from(s.entries()).filter(([,C])=>I<C.expiresAt))},p=()=>{if(!(o>0||i)){i=!0;try{for(;t.selectPendingEffects().length>0;){let I=[...t.selectPendingEffects()];t.clearPendingEffects();try{l(I)}catch(C){throw t.clearPendingEffects(),I.forEach(R=>{t.appendPendingEffect(R)}),C}}}finally{i=!1}}},h=I=>{o+=1;try{return I()}finally{o-=1,p()}},g=({initialState:I,namespace:C})=>{t=Is(I),r=0,n=Nn(C),o=0,i=!1,s=new Map,c=new Map,a=new Map,t.appendPendingEffect({name:"handleLineActions"}),p()},y=()=>n,b=()=>t.selectPresentationState(),A=()=>t.selectPresentationChanges(),x=I=>t.selectSectionLineChanges(I),S=(I={})=>{r+=1;let C=Date.now();d(C);let R=c.size>0,L=f(s,C),z=R?f(c,C):new Map,ve={...t.selectRenderState({activePersistentAnimations:u(L),restoredPersistentAnimations:u(z)}),id:`render-${r}`};return a.set(ve.id,{builtAt:C,persistentAnimationSessions:new Map([...z.entries(),...L.entries()]),usedRestoredPersistentAnimationSessions:R}),ve},P=(I={})=>S(I),N=(I={})=>S(I),w=I=>{let C=typeof I?.id=="string"&&I.id.length>0?I.id:null,R=C?a.get(C):null;C&&a.delete(C);let L=new Map;Qo(I?.animations).forEach(z=>{let he=Zt(z);if(!he)return;let ve=R?.persistentAnimationSessions?.get(he)??s.get(he),$t=Math.max(0,ei(z)),Bn=ve?.startedAt??R?.builtAt??Date.now();L.set(he,{animation:structuredClone(z),startedAt:Bn,expiresAt:Bn+$t})}),s=L,R?.usedRestoredPersistentAnimationSessions&&(c=new Map)},M=()=>t.selectSystemState(),F=()=>t.selectSaveSlotMap(),G=I=>t.selectSaveSlot(I),j=I=>t.selectSaveSlotPage(I),H=()=>t.selectSkipMode(),K=()=>t.selectAutoMode(),X=()=>t.selectRuntime(),xe=()=>t.selectIsChoiceVisible(),re=()=>t.selectIsFormVisible(),Q=()=>t.selectActiveInteraction(),ne=()=>t.selectPendingEffects().some(I=>I?.name==="handleLineActions"||I?.name==="render"),ce=(I,C,R={})=>{if(!Lt(C)||I!=="nextLine")return C;let L=C;return R.bypassChoice===!0&&(L={...L,bypassChoice:!0}),R.interactionSource===jn&&(L={...L,_interactionSource:jn}),R.advanceConditionalNextLine===!0&&(L={...L,_advanceImmediately:!0}),L},q=(I,C)=>{if(!t[I])return;od.has(I)&&(id.has(I)?c=f(s):c=new Map,s=new Map);let R=t[I](C);return p(),R},Z=(I,C={})=>h(()=>{t.beginRollbackActionBatch({source:C.rollbackSource});try{return I()}finally{t.endRollbackActionBatch({})}}),oe=(I,C,R,L={})=>{if(I===xs)return Z(()=>{let z=_(R),he=Hr({[I]:C},z);ee(he[I],R,L)},L);q(I,C)},v=(I,C)=>{oe(I,C)},_=I=>{if(!I)return{variables:t.selectAllVariables?t.selectAllVariables():void 0,runtime:t.selectRuntime?t.selectRuntime():{}};if(Object.prototype.hasOwnProperty.call(I,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:C,...R}=I,L=t.selectAllVariables?t.selectAllVariables():void 0;return{...R,_event:C,variables:L,runtime:t.selectRuntime?t.selectRuntime():{}}},V=I=>{if(!Lt(I))throw new Error("conditional action payload must be an object");if(!Array.isArray(I.branches))throw new Error("conditional action requires branches array");if(I.branches.length===0)throw new Error("conditional action requires at least one branch")},le=(I,C,R)=>{if(!Lt(I))throw new Error(`conditional branch at index ${C} must be an object`);if(!Lt(I.actions))throw new Error(`conditional branch at index ${C} requires actions object`);if(!Object.prototype.hasOwnProperty.call(I,"when")&&C!==R-1)throw new Error("conditional else branch must be the last branch")},ee=(I,C,R)=>{V(I);for(let L=0;L<I.branches.length;L+=1){let z=I.branches[L];le(z,L,I.branches.length);let he=_(C);if(!(Object.prototype.hasOwnProperty.call(z,"when")&&!yt(z.when,he))){Ar(z.actions,C,{...R,advanceConditionalNextLine:!0});return}}},U=(I,C)=>({...I??{},_form:C}),Fe=(I,C,R,L)=>{let z=q(I,C),he=z?.submitted===!0&&z.valid===!0,ve=z?.cancelled===!0;!he&&!ve||Lt(C.actions)&&Ar(C.actions,U(R,z.form),{...L,interactionSource:jn})},tt=(I,C,R,L)=>{let z=_(R),ve=Hr({[I]:C},z)[I];if(I===xs){ee(ve,R,L);return}let $t=ce(I,ve,L);if(sd.has(I)){Fe(I,$t,R,L);return}q(I,$t)},Ar=(I,C,R)=>{Object.entries(I).forEach(([L,z])=>{tt(L,z,C,R)})},Un=(I,C,R={})=>Z(()=>Ar(I,C,R),R);return{init:g,handleAction:oe,handleInternalAction:v,handleActions:Un,selectRenderState:P,prepareRenderState:N,commitRenderState:w,selectPresentationState:b,selectPresentationChanges:A,selectSectionLineChanges:x,selectSystemState:M,selectSaveSlotMap:F,selectSaveSlot:G,selectSaveSlotPage:j,selectSaveSlots:F,selectRuntime:X,selectIsChoiceVisible:xe,selectIsFormVisible:re,selectActiveInteraction:Q,selectHasPendingRenderWork:ne,handleLineActions:()=>{let I=t.selectCurrentLine();return I?.actions?(Un(I.actions,void 0,{rollbackSource:"line"}),!0):!1},getNamespace:y}}var Mn=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:r=>{e=r},addElapsed:r=>{e+=r},getCallback:()=>t,setCallback:r=>{t=r}}},ad=80,Cs=({engine:e,routeGraphics:t,trackRenderDispatch:r},n)=>{if(e.selectHasPendingRenderWork?.())return;let o=e.prepareRenderState?.(n)??e.selectRenderState(n);r?.(o),t.render(o),e.commitRenderState?.(o)},cd=({engine:e,routeGraphics:t,trackRenderDispatch:r,getRenderDispatchCount:n},o)=>{let i=n?.()??0,s=e.handleLineActions();(n?.()??0)===i&&Cs({engine:e,routeGraphics:t,trackRenderDispatch:r},o)},ld=({engine:e,ticker:t,autoTimer:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let c=n.delay??1e3;r.getElapsed()>=c&&(t.remove(i),r.setCallback(null),r.setElapsed(0),Ir(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},ud=({ticker:e,autoTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},fd=({engine:e,ticker:t,skipTimer:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let c=n?.delay??ad;r.getElapsed()>=c&&(r.setElapsed(0),Ir(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},dd=({ticker:e,skipTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},pd=({engine:e,ticker:t,nextLineConfigTimerState:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let c=n.delay??1e3;r.getElapsed()>=c&&(r.setElapsed(0),Ir(e,"nextLineFromSystem",{}),t.remove(i),r.setCallback(null))};r.setCallback(i),t.add(i)},hd=({ticker:e,nextLineConfigTimerState:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},md=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveSlots(t?.saveSlots))},gd=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalDeviceVariables(t?.globalDeviceVariables))},yd=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalAccountVariables(t?.globalAccountVariables))},bd=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalRuntime(t?.globalRuntime))},Id=({enqueuePersistenceWrite:e},t)=>{e(r=>{if(typeof r.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return r.applyScopedDataUpdates(t?.updates)})},vs={render:Cs,saveSlots:md,saveGlobalDeviceVariables:gd,saveGlobalAccountVariables:yd,saveGlobalRuntime:bd,applyScopedDataUpdates:Id,handleLineActions:cd,startAutoNextTimer:ld,clearAutoNextTimer:ud,startSkipNextTimer:fd,clearSkipNextTimer:dd,nextLineConfigTimer:pd,clearNextLineConfigTimer:hd},Ad=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),Ir=(e,t,r)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,r)},wd=(e=[])=>{let t=new Set,r=[];for(let n=e.length-1;n>=0;n-=1){let o=e[n];if(typeof o?.name!="string"||o.name.length===0)throw new Error("Pending effect is missing a valid name.");if(!Ad.has(o.name)){r.unshift(o);continue}t.has(o.name)||(t.add(o.name),r.unshift(o))}return r},Ed=({getEngine:e,routeGraphics:t,ticker:r,handleUnhandledEffect:n,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:c})=>{let a=Mn(),l=Mn(),f=Mn(),u=s??null,d=Promise.resolve(),p=null,h=null,g=!1,y=0,b=v=>{if(o){o(v);return}console.error("RouteEngine persistence write failed.",v)},A=()=>{if(u)return u;let v=e();return u=Vn({indexedDB:i,namespace:c??v?.getNamespace?.()}),u},x=v=>{d=d.catch(()=>{}).then(()=>{let _=A();return v(_)}).catch(_=>{b(_)})},S=v=>{let _=typeof v?.id=="string"&&v.id.length>0?v.id:null;y+=1,p=_,g=!1},P=()=>y,N=(v={})=>{if(v?.aborted===!0)return!1;let _=typeof v?.id=="string"&&v.id.length>0?v.id:null;return _?_!==p||_===h?!1:(h=_,!0):p!==null||g?!1:(g=!0,!0)},w=(v,_={})=>{if(v!=="renderComplete"||!N(_))return!1;let V=e();return Ir(V,"markLineCompleted",{}),!0},M=new Set(["updateFormField","submitForm","cancelForm"]),F=new Set(["updateVariable"]),G=v=>typeof v?.selectActiveInteraction=="function"?v.selectActiveInteraction():typeof v?.selectIsChoiceVisible=="function"&&v.selectIsChoiceVisible()?{source:"choice"}:null,j=v=>v?._formKey??v?.formKey,H=(v,_)=>j(v)===_?.formKey,K=(v,_)=>!v||typeof v!="object"||Array.isArray(v)?!1:v._interactionSource===_?.source,X=(v,_)=>K(v,_)?_.source==="form"?H(v,_):!0:!1,xe=(v,_)=>!v||typeof v!="object"||Array.isArray(v)||_?.source!=="form"?!1:H(v,_),re=(v={})=>Object.keys(v).some(_=>M.has(_)),Q=(v={},_)=>Object.entries(v).some(([V,le])=>M.has(V)&&xe(le,_)),ne=(v={})=>Object.keys(v).length>0&&Object.keys(v).every(_=>F.has(_)),ce=(v={},_)=>{let V=v?.actions;return _?.source==="form"?!V||typeof V!="object"||Array.isArray(V)?!1:Q(V,_)?!0:re(V)?!1:ne(V):X(v,_)?!0:!V||typeof V!="object"||Array.isArray(V)?!1:Object.values(V).some(le=>X(le,_))},q=(v,_={})=>{if(!_?.actions)return!1;let V=G(v);return!V||V.source==="choice"?!1:!ce(_,V)},Z=({preprocessPayload:v,onEvent:_}={})=>async(V,le={})=>{let ee=e();if(q(ee,le))return _?.(V,le);let U=await v?.(V,le)??le;if(q(ee,U))return _?.(V,U);if(w(V,U),U?.actions){let Fe=U?._event?{_event:U._event}:U?.event?{_event:U.event}:void 0,tt;U?.bypassChoice===!0?tt={bypassChoice:!0}:U?._interactionSource&&(tt={interactionSource:U._interactionSource}),tt?ee.handleActions(U.actions,Fe,tt):ee.handleActions(U.actions,Fe)}return _?.(V,U)},oe=v=>{let _=e(),V=wd(v),le=V.some(U=>U.name==="handleLineActions");V.forEach(U=>{if(!vs[U.name]&&!n)throw new Error(`Unhandled pending effect "${U.name}".`)});let ee={engine:_,routeGraphics:t,ticker:r,autoTimer:a,skipTimer:l,nextLineConfigTimerState:f,trackRenderDispatch:S,getRenderDispatchCount:P,enqueuePersistenceWrite:x};for(let U of V){if(le&&U.name==="render")continue;let Fe=vs[U.name];if(Fe){Fe(ee,U.payload);continue}n(U,ee)}};return oe.handleRouteGraphicsEvent=w,oe.createRouteGraphicsEventHandler=Z,oe},xd=Ed;var vd=(e,t={})=>{let{resources:r={}}=t;return bn(e,r)};var rh=Fn;export{Jr as DEFAULT_VISUAL_LAYER,st as RENDER_LAYER,_e as VISUAL_LAYER,xd as createEffectsHandler,nd as createIndexedDbPersistence,rh as default,Da as resolveComputedVariables,vd as resolveLayoutReferences};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "route-engine-js",
3
- "version": "1.28.0",
3
+ "version": "1.29.1",
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",