route-engine-js 1.17.0 → 1.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- var _i=Object.defineProperty;var Ri=(e,t)=>{for(var r in t)_i(e,r,{get:t[r],enumerable:!0})};var wn=Symbol.for("immer-nothing"),gn=Symbol.for("immer-draftable"),te=Symbol.for("immer-state");function ae(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var Be=Object.getPrototypeOf;function re(e){return!!e&&!!e[te]}function $e(e){return e?En(e)||Array.isArray(e)||!!e[gn]||!!e.constructor?.[gn]||wt(e)||Et(e):!1}var Oi=Object.prototype.constructor.toString();function En(e){if(!e||typeof e!="object")return!1;let t=Be(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)===Oi}function yt(e,t){At(e)===0?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,n)=>t(n,r,e))}function At(e){let t=e[te];return t?t.type_:Array.isArray(e)?1:wt(e)?2:Et(e)?3:0}function Xt(e,t){return At(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function vn(e,t,r){let n=At(e);n===2?e.set(t,r):n===3?e.add(r):e[t]=r}function Li(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function wt(e){return e instanceof Map}function Et(e){return e instanceof Set}function Le(e){return e.copy_||e.base_}function Qt(e,t){if(wt(e))return new Map(e);if(Et(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=En(e);if(t===!0||t==="class_only"&&!r){let n=Object.getOwnPropertyDescriptors(e);delete n[te];let o=Reflect.ownKeys(n);for(let i=0;i<o.length;i++){let s=o[i],l=n[s];l.writable===!1&&(l.writable=!0,l.configurable=!0),(l.get||l.set)&&(n[s]={configurable:!0,writable:!0,enumerable:l.enumerable,value:e[s]})}return Object.create(Be(e),n)}else{let n=Be(e);if(n!==null&&r)return{...e};let o=Object.create(n);return Object.assign(o,e)}}function nr(e,t=!1){return vt(e)||re(e)||!$e(e)||(At(e)>1&&(e.set=e.add=e.clear=e.delete=$i),Object.freeze(e),t&&Object.entries(e).forEach(([r,n])=>nr(n,!0))),e}function $i(){ae(2)}function vt(e){return Object.isFrozen(e)}var ki={};function ke(e){let t=ki[e];return t||ae(0,e),t}var Ze;function xn(){return Ze}function Di(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function yn(e,t){t&&(ke("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Zt(e){er(e),e.drafts_.forEach(Pi),e.drafts_=null}function er(e){e===Ze&&(Ze=e.parent_)}function bn(e){return Ze=Di(Ze,e)}function Pi(e){let t=e[te];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function In(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[te].modified_&&(Zt(t),ae(4)),$e(e)&&(e=bt(t,e),t.parent_||It(t,e)),t.patches_&&ke("Patches").generateReplacementPatches_(r[te].base_,e,t.patches_,t.inversePatches_)):e=bt(t,r,[]),Zt(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==wn?e:void 0}function bt(e,t,r){if(vt(t))return t;let n=t[te];if(!n)return yt(t,(o,i)=>An(e,n,t,o,i,r)),t;if(n.scope_!==e)return t;if(!n.modified_)return It(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),yt(i,(l,c)=>An(e,n,o,l,c,r,s)),It(e,o,!1),r&&e.patches_&&ke("Patches").generatePatches_(n,r,e.patches_,e.inversePatches_)}return n.copy_}function An(e,t,r,n,o,i,s){if(re(o)){let l=i&&t&&t.type_!==3&&!Xt(t.assigned_,n)?i.concat(n):void 0,c=bt(e,o,l);if(vn(r,n,c),re(c))e.canAutoFreeze_=!1;else return}else s&&r.add(o);if($e(o)&&!vt(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;bt(e,o),(!t||!t.scope_.parent_)&&typeof n!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,n)&&It(e,o)}}function It(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&nr(t,r)}function Ti(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=or;r&&(o=[n],i=et);let{revoke:s,proxy:l}=Proxy.revocable(o,i);return n.draft_=l,n.revoke_=s,l}var or={get(e,t){if(t===te)return e;let r=Le(e);if(!Xt(r,t))return Ni(e,r,t);let n=r[t];return e.finalized_||!$e(n)?n:n===Gt(e.base_,t)?(Jt(e),e.copy_[t]=rr(n,e)):n},has(e,t){return t in Le(e)},ownKeys(e){return Reflect.ownKeys(Le(e))},set(e,t,r){let n=Cn(Le(e),t);if(n?.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){let o=Gt(Le(e),t),i=o?.[te];if(i&&i.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(Li(r,o)&&(r!==void 0||Xt(e.base_,t)))return!0;Jt(e),tr(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 Gt(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,Jt(e),tr(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=Le(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:n.enumerable,value:r[t]}},defineProperty(){ae(11)},getPrototypeOf(e){return Be(e.base_)},setPrototypeOf(){ae(12)}},et={};yt(or,(e,t)=>{et[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});et.deleteProperty=function(e,t){return et.set.call(this,e,t,void 0)};et.set=function(e,t,r){return or.set.call(this,e[0],t,r,e[0])};function Gt(e,t){let r=e[te];return(r?Le(r):e)[t]}function Ni(e,t,r){let n=Cn(t,r);return n?"value"in n?n.value:n.get?.call(e.draft_):void 0}function Cn(e,t){if(!(t in e))return;let r=Be(e);for(;r;){let n=Object.getOwnPropertyDescriptor(r,t);if(n)return n;r=Be(r)}}function tr(e){e.modified_||(e.modified_=!0,e.parent_&&tr(e.parent_))}function Jt(e){e.copy_||(e.copy_=Qt(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Vi=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(c=i,...a){return s.produce(c,u=>r.call(this,u,...a))}}typeof r!="function"&&ae(6),n!==void 0&&typeof n!="function"&&ae(7);let o;if($e(t)){let i=bn(this),s=rr(t,void 0),l=!0;try{o=r(s),l=!1}finally{l?Zt(i):er(i)}return yn(i,n),In(o,i)}else if(!t||typeof t!="object"){if(o=r(t),o===void 0&&(o=t),o===wn&&(o=void 0),this.autoFreeze_&&nr(o,!0),n){let i=[],s=[];ke("Patches").generateReplacementPatches_(t,o,i,s),n(i,s)}return o}else ae(1,t)},this.produceWithPatches=(t,r)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,c=>t(c,...l));let n,o;return[this.produce(t,r,(s,l)=>{n=s,o=l}),n,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){$e(e)||ae(8),re(e)&&(e=De(e));let t=bn(this),r=rr(e,void 0);return r[te].isManual_=!0,er(t),r}finishDraft(e,t){let r=e&&e[te];(!r||!r.isManual_)&&ae(9);let{scope_:n}=r;return yn(n,t),In(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=ke("Patches").applyPatches_;return re(e)?n(e,t):this.produce(e,o=>n(o,t))}};function rr(e,t){let r=wt(e)?ke("MapSet").proxyMap_(e,t):Et(e)?ke("MapSet").proxySet_(e,t):Ti(e,t);return(t?t.scope_:xn()).drafts_.push(r),r}function De(e){return re(e)||ae(10,e),Sn(e)}function Sn(e){if(!$e(e)||vt(e))return e;let t=e[te],r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=Qt(e,t.scope_.immer_.useStrictShallowCopy_)}else r=Qt(e,!0);return yt(r,(n,o)=>{vn(r,n,Sn(o))}),t&&(t.finalized_=!1),r}var ne=new Vi,ir=ne.produce,qu=ne.produceWithPatches.bind(ne),Yu=ne.setAutoFreeze.bind(ne),Hu=ne.setUseStrictShallowCopy.bind(ne),Ku=ne.applyPatches.bind(ne),Gu=ne.createDraft.bind(ne),Ju=ne.finishDraft.bind(ne);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},L={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},ze={NOT:0};var w=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},Q=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var sr=e=>{if(!e||e.trim()==="")throw new w("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let r=e.includes("===")?"==":"!=";throw new w(`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 w(`Incomplete comparison expression - missing right operand (got: '${e}')`)},_n=e=>{if(e.trim().endsWith(" in"))throw new w(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new w(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,r]=e.split(" in ");if(!r||r.trim()==="")throw new w(`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 w(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new w(`Invalid loop syntax (got: '$for ${e}')`)}};var Rn=(e,t,r=!1)=>{if(t===null)return new Q(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new Q(`Cannot iterate over undefined value at '$for ${e}'`);let n=typeof t;return r?new Q(`Cannot iterate over non-array value in loop '${e}' - got ${n} instead`):new Q(`Cannot iterate over non-array value (got: ${n}) at '$for ${e}'`)},On=(e,t)=>{let r=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new Q(`Unknown function '${e}' (${r})`)};var ji=(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 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 Fi(e.parts,t,r,n);switch(e.type){case m.FUNCTION:return $n(e,t,r,n);case m.BINARY:return kn(e,t,r,n);case m.UNARY:return Dn(e,t,r,n);case m.CONDITIONAL:return Bi(e,t,r,n);case m.LOOP:return Hi(e,t,r,n);case m.OBJECT:return Gi(e,t,r,n);case m.ARRAY:return Ji(e,t,r,n);case m.PARTIAL:return Xi(e,t,r,n);case m.PATH_REFERENCE:return Qi(e,t,r,n);default:throw new Error(`Unknown node type: ${e.type}`)}},Ln=new Map,Mi=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 l=s.slice(1,-1);t.push({type:"property",value:l})}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=Ln.get(e);if(!n){let i=[],s="",l=0;for(let c=0;c<e.length;c++){let a=e[c];a==="["?(l++,s+=a):a==="]"?(l--,s+=a):a==="."&&l===0?s&&(i.push(s),s=""):s+=a}s&&i.push(s),n=[];for(let c of i){let a=Mi(c.trim());n.push(...a)}Ln.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},Fi=(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("")},$n=(e,t,r,n)=>{let o=t.functions||t,i=o[e.name];if(!i)throw On(e.name,o);let s=e.args.map(l=>$(l,t,r,n));return i(...s)},Ee=(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 kn(e,t,r,n);case m.UNARY:return Dn(e,t,r,n);case m.FUNCTION:return $n(e,t,r,n);default:return $(e,t,r,n)}},kn=(e,t,r,n)=>{if(e.op===L.AND||e.op===L.OR){let s=Ee(e.left,t,r,n),l=Ee(e.right,t,r,n);switch(e.op){case L.AND:return s&&l;case L.OR:return s||l}}let o=$(e.left,t,r,n),i=$(e.right,t,r,n);switch(e.op){case L.EQ:return o==i;case L.NEQ:return o!=i;case L.GT:return o>i;case L.LT:return o<i;case L.GTE:return o>=i;case L.LTE:return o<=i;case L.IN:return Array.isArray(i)?i.includes(o):!1;case L.ADD:if(typeof o!="number"||typeof i!="number")throw new Q(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case L.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new Q(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},Dn=(e,t,r,n)=>{let o=e.op===ze.NOT?Ee(e.operand,t,r,n):$(e.operand,t,r,n);if(e.op===ze.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},Ui=(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 l={};for(let c of s.properties){let a=c.parsedKey?$(c.parsedKey,t,r,n):c.key,u=c.value;if(u.type===m.LITERAL)l[a]=u.value;else if(u.type===m.VARIABLE)l[a]=H(u.path,r,n);else if(u.type===m.INTERPOLATION){let d=[];for(let f of u.parts)if(typeof f=="string")d.push(f);else if(f.type===m.VARIABLE){let p=H(f.path,r,n);d.push(p!=null?String(p):"")}else{let p=$(f,t,r,n);d.push(p!=null?String(p):"")}l[a]=d.join("")}else l[a]=$(u,t,r,n)}return l}}else{let s=e.bodies[1];if(s.type===m.OBJECT&&s.properties.length<=5){let l={};for(let c of s.properties){let a=c.parsedKey?$(c.parsedKey,t,r,n):c.key,u=c.value;if(u.type===m.LITERAL)l[a]=u.value;else if(u.type===m.VARIABLE)l[a]=H(u.path,r,n);else if(u.type===m.INTERPOLATION){let d=[];for(let f of u.parts)if(typeof f=="string")d.push(f);else if(f.type===m.VARIABLE){let p=H(f.path,r,n);d.push(p!=null?String(p):"")}else{let p=$(f,t,r,n);d.push(p!=null?String(p):"")}l[a]=d.join("")}else l[a]=$(u,t,r,n)}return l}}}return null},Bi=(e,t,r,n)=>{let o=Ui(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||Ee(s,t,r,n))return $(e.bodies[i],t,r,n)}return Pn},zi=(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 c of i.properties)if(c.parsedKey)return null;let l=[];for(let c=0;c<t.length;c++){let a=t[c];if(a[s]){let u={};for(let d of i.properties){let f=d.key,p=d.value;if(p.type===m.LITERAL)u[f]=p.value;else if(p.type===m.VARIABLE){let h=p.path;if(h===n)u[f]=a;else if(h.startsWith(n+".")){let g=h.substring(n.length+1);u[f]=a[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(a!=null?String(a):"");else if(b.startsWith(n+".")){let A=b.substring(n.length+1),x=a[A];h.push(x!=null?String(x):"")}else{g=!1;break}}else{g=!1;break}if(!g)return null;u[f]=h.join("")}else return null}l.push(u)}}return l}}}return null},Wi=(e,t)=>{let r=e.body,n=e.itemVar,o=zi(e,t);if(o!==null)return o;if(r.type===m.OBJECT&&r.properties.length<=5&&!r.whenCondition){for(let l of r.properties)if(l.parsedKey)return null;let i=[],s=!0;for(let l of r.properties){let c=l.key,a=l.value;if(a.type===m.LITERAL)i.push({key:c,type:"literal",value:a.value});else if(a.type===m.VARIABLE){let u=a.path;if(u===n)i.push({key:c,type:"item"});else if(u.startsWith(n+".")){let d=u.substring(n.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:c,type:"prop",prop:d});else{s=!1;break}}else{s=!1;break}}else if(a.type===m.INTERPOLATION&&a.parts.length===1){let u=a.parts[0];if(u.type===m.VARIABLE){let d=u.path;if(d===n)i.push({key:c,type:"item_string"});else if(d.startsWith(n+".")){let f=d.substring(n.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:c,type:"prop_string",prop:f});else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}if(s){let l=new Array(t.length);if(i.length===3&&i[0].type==="prop"&&i[0].key==="id"&&i[1].type==="prop_string"&&i[1].key==="title"&&i[2].type==="prop"&&i[2].key==="completed")for(let c=0;c<t.length;c++){let a=t[c];l[c]={id:a.id,title:a.title!=null?String(a.title):"",completed:a.completed}}else for(let c=0;c<t.length;c++){let a=t[c],u={};for(let d of i)if(d.type==="literal")u[d.key]=d.value;else if(d.type==="item")u[d.key]=a;else if(d.type==="prop")u[d.key]=a[d.prop];else if(d.type==="item_string")u[d.key]=a!=null?String(a):"";else if(d.type==="prop_string"){let f=a[d.prop];u[d.key]=f!=null?String(f):""}l[c]=u}return l}}return null},qi=(e,t,r,n,o)=>{let i=[],s=e.body;if(s.type===m.OBJECT&&s.fast!==!1){let l=e.itemVar,c=e.indexVar;for(let a=0;a<o.length;a++){let u=o[a],d={},f={...n,[l]:u,...c&&{[c]:a}};f.__paths__||(f.__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(".")))}f.__paths__={...f.__paths__,[l]:`${p}[${a}]`,...c&&{[c]:a}};for(let h of s.properties){let g=h.parsedKey?$(h.parsedKey,t,r,f):h.key,y=h.value;if(y.type===m.LITERAL)d[g]=y.value;else if(y.type===m.VARIABLE){let b=y.path;if(b===l)d[g]=u;else if(b===c)d[g]=a;else if(b.startsWith(l+".")){let A=b.substring(l.length+1);!A.includes(".")&&!A.includes("[")?d[g]=u[A]:d[g]=H(b,r,{...n,[l]:u,...c&&{[c]:a}})}else d[g]=H(b,r,{...n,[l]:u,...c&&{[c]:a}})}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===l)S=u;else if(x===c)S=a;else if(x.startsWith(l+".")){let T=x.substring(l.length+1);!T.includes(".")&&!T.includes("[")?S=u[T]:S=H(x,r,{...n,[l]:u,...c&&{[c]:a}})}else S=H(x,r,{...n,[l]:u,...c&&{[c]:a}});b.push(S!=null?String(S):"")}else{let x={...n,[l]:u,...c&&{[c]:a}},S=$(A,t,r,x);b.push(S!=null?String(S):"")}d[g]=b.join("")}else{let b={...n,[l]:u,...c&&{[c]:a}};d[g]=$(y,t,r,b)}}i.push(d)}return i}return null},Yi=(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 l=s.properties[0],c=s.properties[1];if(l.key==="id"&&l.value.type===m.VARIABLE&&l.value.path==="item.id"&&c.key==="$if item.highlighted"&&c.value.type===m.CONDITIONAL){let a=[];for(let u=0;u<t.length;u++){let d=t[u];if(d.visible){let f={id:d.id};d.highlighted?(f.highlight=!0,f.message=`This item is highlighted: ${d.name}`):(f.highlight=!1,f.message=d.name),a.push(f)}}return a}}}}return null},Hi=(e,t,r,n)=>{let o=$(e.iterable,t,r,n);if(!Array.isArray(o)){let a,u=!1;if(e.iterable.type===m.FUNCTION){u=!0;let f=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(", ");a=`${e.iterable.name}(${f})`}else a=e.iterable.path||"undefined";let d=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${a}`;throw Rn(d,o,u)}if(!e.indexVar){let a=Yi(e,o,e.itemVar);if(a!==null)return a}if(!e.indexVar){let a=Wi(e,o);if(a!==null)return a}let i=qi(e,t,r,n,o);if(i!==null)return i;let s=[],l=e.iterable.path||"";if(n&&n.__paths__&&l){let a=l.split("."),u=a[0];u in n.__paths__&&(l=n.__paths__[u],a.length>1&&(l+="."+a.slice(1).join(".")))}let c=!1;e.body.type===m.ARRAY&&(e.body.items.length<=1?c=!1:c=e.body._shouldPreserveArray??=e.body.items.some(a=>a.type===m.OBJECT&&a.properties.some(u=>u.key.startsWith("$if ")||u.key.startsWith("$when "))));for(let a=0;a<o.length;a++){let u=e.indexVar?{...n,[e.itemVar]:o[a],[e.indexVar]:a}:{...n,[e.itemVar]:o[a]};u.__paths__||(u.__paths__=n.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${l}[${a}]`},e.indexVar&&(u.__paths__[e.indexVar]=a);let d=$(e.body,t,r,u);if(Array.isArray(d)&&d.length===1&&!c){let f=d[0];s.push(f===void 0?{}:f)}else s.push(d===void 0?{}:d)}return s},Ki=(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 l={},c={},a=!0;for(let u of s.properties){let d=u.parsedKey?$(u.parsedKey,t,r,n):u.key,f=u.value;if(f.type===m.LITERAL)c[d]=f.value;else if(f.type===m.VARIABLE)c[d]=H(f.path,r,n);else if(f.type===m.INTERPOLATION){let p=[];for(let h of f.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{a=!1;break}if(!a)break;c[d]=p.join("")}else if(f.type===m.OBJECT&&f.properties.length<=5){let p={};for(let h of f.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{a=!1;break}if(!a)break;p[g]=b.join("")}else{a=!1;break}}if(!a)break;c[d]=p}else{a=!1;break}}if(a)return l[i]=c,l}}return null},Gi=(e,t,r,n)=>{let o=t.functions||t;if(e.whenCondition&&!Ee(e.whenCondition,o,r,n))return;let i=Ki(e,t,r,n);if(i!==null)return i;if(e.fast){let a={};for(let u of e.properties){let d=u.parsedKey?$(u.parsedKey,t,r,n):u.key,f=u.value;if(f.type===m.LITERAL)a[d]=f.value;else if(f.type===m.VARIABLE)a[d]=H(f.path,r,n);else if(f.type===m.INTERPOLATION){let p=[];for(let h of f.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=$(h,t,r,n);p.push(g!=null?String(g):"")}a[d]=p.join("")}else a[d]=$(f,t,r,n)}return a}let s={},l=null,c=!1;for(let a of e.properties)if(!a.key.startsWith("$if ")&&!a.key.match(/^\$if\s+\w+.*:?$/)&&!a.key.startsWith("$elif")&&!a.key.startsWith("$else")&&!a.key.startsWith("$for ")){c=!0;break}for(let a of e.properties)if(a.key.startsWith("$if ")||a.key.match(/^\$if\s+\w+.*:?$/)){let u=$(a.value,t,r,n);if(!c&&u!==null&&u!==void 0)return Array.isArray(u)&&u.length===1?u[0]:u;typeof u=="object"&&u!==null&&!Array.isArray(u)&&Object.assign(s,u)}else if(a.key.startsWith("$for ")){if(e.properties.length===1)return $(a.value,t,r,n)}else{let u=a.value;if(u&&u.type===m.OBJECT&&u.properties){let d=u.properties.find(f=>f.key.startsWith("$for "));if(d){let f=$(d.value,t,r,n);f!==void 0&&(s[a.key]=f)}else{let f=$(a.value,t,r,n);f!==void 0&&(s[a.key]=f)}}else{let d=a.parsedKey?$(a.parsedKey,t,r,n):a.key,f=$(a.value,t,r,n);f!==void 0&&(s[d]=f)}}return s},Pn={},Ji=(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!==Pn&&s!==void 0&&o.push(s)}return o},Xi=(e,t,r,n)=>{let{name:o,data:i,whenCondition:s}=e,l=t.partials||{},c=t.functions||t;if(s&&!Ee(s,c,r,n))return;if(!l[o])throw new Q(`Partial '${o}' is not defined`);let a=n._partialStack||[];if(a.includes(o))throw new Q(`Circular partial reference detected: ${o}`);let u=l[o],d=r,f={...n,_partialStack:[...a,o]};if(n){d={...r};for(let p of Object.keys(n))p.startsWith("_")||(d[p]=n[p])}if(i){let p=$(i,t,r,n);d={...d,...p}}return $(u,t,d,f)},Qi=(e,t,r,n)=>{let{path:o}=e,i=o.split("."),s=i[0],l=i.slice(1);if(!n||!(s in n))throw new Q(`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 Q(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let c=n.__paths__[s];if(typeof c=="number"){if(l.length>0)throw new Q(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(c)}return l.length>0&&(c+="."+l.join(".")),c};var ar=ji;var Zi=/\$\{([^}]*)\}/g,es=/#\{([^}]*)\}/g,Nn=(e,t={})=>{let r=e.match(/^(\w+)\((.*)\)$/);if(!r)return{isFunction:!1};let[,n,o]=r,i=ts(o,t);return{isFunction:!0,type:m.FUNCTION,name:n,args:i}},ts=(e,t={})=>e.trim()?rs(e).map(n=>ns(n.trim(),t)):[],rs=e=>{let t=[],r="",n=0,o=!1,i="";for(let s=0;s<e.length;s++){let l=e[s],c=s>0?e[s-1]:"";!o&&(l==='"'||l==="'")?(o=!0,i=l,r+=l):o&&l===i&&c!=="\\"?(o=!1,i="",r+=l):!o&&l==="("?(n++,r+=l):!o&&l===")"?(n--,r+=l):!o&&l===","&&n===0?(t.push(r),r=""):r+=l}return r&&t.push(r),t},ns=(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=Nn(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:l,type:c}of o){let a=0;for(;a<n.length;){let u=Pe(n.substring(a),l);if(u===-1)break;let d=a+u;d>i&&(i=d,s={op:l,type:c}),a=d+l.length}}if(i!==-1)try{return K(n,t)}catch{return{type:m.VARIABLE,path:n}}return{type:m.VARIABLE,path:n}},Vn=/^\w+\(.*\)$/,os=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,is=e=>{if(!(!e||e.trim()===""||Vn.test(e))&&os.test(e))throw e.includes("?")&&e.includes(":")?new w(`Complex expressions not supported in variable replacements - consider calculating the value in your data instead. Offending expression: "${e}"`):e.includes("||")||e.includes("&&")||e.includes("??")?new w(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new w(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},Tn=e=>{let t=e.trim();if(Vn.test(t))throw new w(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new w(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new w(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new w(`Logical operators not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("?")&&t.includes(":"))throw new w(`Complex expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);return{type:m.PATH_REFERENCE,path:t}},tt=(e,t={})=>{let r=e.trim();is(r);let n=Nn(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}},cr=(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,(a,u)=>{let d=`__ESCAPED_${n.length}__`;return n.push(u),d}),r=r.replace(/\\(#\{[^}]*\})/g,(a,u)=>{let d=`__ESCAPED_${n.length}__`;return n.push(u),d}),r=r.replace(/\\DOUBLE_ESC_VAR/g,"\\"),r=r.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...r.matchAll(Zi)],i=[...r.matchAll(es)],s=[...o.map(a=>({match:a,type:"variable"})),...i.map(a=>({match:a,type:"pathref"}))].sort((a,u)=>a.match.index-u.match.index);if(s.length===0){let a=r;for(let u=0;u<n.length;u++)a=a.replace(`__ESCAPED_${u}__`,n[u]);return{type:m.LITERAL,value:a}}if(s.length===1&&s[0].match[0]===r&&n.length===0){let{match:a,type:u}=s[0];try{return u==="variable"?tt(a[1],t):Tn(a[1])}catch(d){if(d.message==="Invalid array index syntax")return{type:m.LITERAL,value:r};throw d}}let l=[],c=0;for(let{match:a,type:u}of s){let[d,f]=a,p=a.index;if(p>c){let h=r.substring(c,p);for(let g=0;g<n.length;g++)h=h.replace(`__ESCAPED_${g}__`,n[g]);h&&l.push(h)}try{let h;u==="variable"?h=tt(f.trim(),t):h=Tn(f.trim()),l.push(h)}catch(h){if(h.message==="Invalid array index syntax")l.push(d);else throw h}c=p+d.length}if(c<r.length){let a=r.substring(c);for(let u=0;u<n.length;u++)a=a.replace(`__ESCAPED_${u}__`,n[u]);a&&l.push(a)}return{type:m.INTERPOLATION,parts:l}};var dr=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Fn=e=>Object.keys(e),J=e=>e.join("."),ve=(e,t,r)=>{let n=Fn(e).filter(o=>!t.has(o));if(n.length>0)throw new w(`Unexpected key '${n[0]}' in condition JSON at '${J(r)}'`)},xe=(e,t)=>typeof e=="string"?cr(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?as(e,t):cs(e,t):{type:m.LITERAL,value:e},ss=e=>{let{$each:t,...r}=e;if(typeof t!="string")throw new w("$each value must be a non-empty string");let n=t.trim();if(n==="")throw new w("$each value must be a non-empty string");if(Object.keys(r).length===0)throw new w("Empty $each body not allowed");if(r.$partial!==void 0)throw new w("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${n}`]:r}},as=(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 c=ss(i),a=Object.keys(c);if(a.length===1&&/^\$for(?::\w+)?\s/.test(a[0])){let u=Mn(a[0],c[a[0]],t,!0);r.push(u),n=!0;continue}}catch(c){throw c instanceof w?c:new w(c.message)}let l=Object.keys(i);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let c=Mn(l[0],i[l[0]],t);r.push(c),n=!0;continue}}let s=xe(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}},cs=(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 w("$partial value must be a string");if(e.$partial.trim()==="")throw new w("$partial value cannot be an empty string");let c=["$if","$elif","$else","$for"],a=[];for(let[b]of i)for(let A of c)if(b===A||b.startsWith(A+" ")||b.startsWith(A+"#")){a.push(A);break}if(a.length>0)throw new w(`Cannot use $partial with ${a.join(", ")} at the same level. Wrap $partial in a parent object if you need conditionals.`);let{$partial:u,$when:d,...f}=e,p={},h=!1;for(let[b,A]of Object.entries(f)){let x=b;(b.startsWith("\\$")||b.startsWith("$$"))&&(x=b.slice(1)),p[x]=A,h=!0}let g=null;if(h&&(g=xe(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:u,data:g};return d!==void 0&&(y.whenCondition=jn(d,t)),y}for(let[c,a]of i)if(c==="$when"){if(o!==null)throw new w("Multiple '$when' directives on the same object are not allowed");if(a==null)throw new w("Missing condition expression after '$when'");o=jn(a,t),n=!0}else if(c.startsWith("$when#")||c.startsWith("$when "))throw new w("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<i.length;){let[c,a]=i[s];if(c==="$when"){s++;continue}if(c==="$each")throw new w("$each can only be used inside arrays");if(c.startsWith("$if ")||c.match(/^\$if#\w+\s/)||c.match(/^\$if\s+\w+.*:$/)){let u=ls(i,s,t);r.push({key:c,value:u.node}),n=!0,s=u.nextIndex}else if(/^\$for(?::\w+)?\s/.test(c)){let u=c.match(/^\$for(?::(\w+))?\s/)?.[1]||"",d=u?`:${u}`:"";throw new w(`$for loops must be inside arrays - use '- $for${d} item in items:' instead of '$for${d} item in items:'. For cleaner object generation syntax, consider using $each.`)}else{if(c.startsWith("$elif ")||c.startsWith("$else"))throw new w(`'${c.split(" ")[0]}' without matching '$if'`);if(c==="$if"||c==="$if:")throw new w("Missing condition expression after '$if'");{let u=xe(a,t);(u.type===m.FUNCTION||u.type===m.CONDITIONAL||u.type===m.PARTIAL||u.type===m.OBJECT&&!u.fast||u.type===m.ARRAY&&!u.fast)&&(n=!0);let d=cr(c,t),f={key:c,value:u};(d.type!==m.LITERAL||d.value!==c)&&(f.parsedKey=d),r.push(f),s++}}}let l={type:m.OBJECT,properties:r,fast:!n};return o&&(l.whenCondition=o),l},ls=(e,t,r={})=>{let n=[],o=[],i=t,[s,l]=e[i],c=null,a;if(s.startsWith("$if#")){let d=s.match(/^\$if#(\w+)\s+(.+)$/);if(d)c=d[1],a=d[2];else throw new w(`Invalid conditional syntax: ${s}`)}else a=s.substring(4),a.endsWith(":")&&(a=a.slice(0,-1).trim());sr(a);let u=K(a,r);for(n.push(u),o.push(xe(l,r)),i++;i<e.length;){let[d,f]=e[i],p=!1,h;if(c?d.startsWith(`$elif#${c} `)?(h=d.substring(`$elif#${c} `.length),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(d===`$else#${c}`||d===`$else#${c}:`)&&(p=!0,h=null):d.startsWith("$elif ")?(h=d.substring(6),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(d==="$else"||d==="$else:")&&(p=!0,h=null),p){if(h===null)n.push(null);else{sr(h);let g=K(h,r);n.push(g)}if(o.push(xe(f,r)),i++,h===null)break}else break}return{node:{type:m.CONDITIONAL,conditions:n,bodies:o,id:c},nextIndex:i}},lr={eq:L.EQ,neq:L.NEQ,gt:L.GT,gte:L.GTE,lt:L.LT,lte:L.LTE,in:L.IN,add:L.ADD,sub:L.SUBTRACT},ur={all:L.AND,any:L.OR},us=new Set(["var","literal","call","not",...Object.keys(lr),...Object.keys(ur)]),ds=(e,t,r)=>{if(!Array.isArray(e))throw new w(`Condition JSON operator '${t}' at '${J(r)}' requires an array`);if(e.length!==2)throw new w(`Condition JSON operator '${t}' at '${J(r)}' requires exactly 2 operands`);return e},fs=(e,t,r,n,o)=>{if(!Array.isArray(e))throw new w(`Condition JSON operator '${t}' at '${J(o)}' requires an array`);if(e.length===0)throw new w(`Condition JSON operator '${t}' at '${J(o)}' requires at least 1 condition`);return e.map((s,l)=>ge(s,n,[...o,l])).reduce((s,l)=>({type:m.BINARY,op:r,left:s,right:l}))},ps=(e,t,r)=>{let n,o;if(typeof e.call=="string")n=e.call,o=e.args??[],ve(e,new Set(["call","args"]),r);else if(dr(e.call))n=e.call.name,o=e.call.args??[],ve(e,new Set(["call"]),r),ve(e.call,new Set(["name","args"]),[...r,"call"]);else throw new w(`Condition JSON call at '${J(r)}' requires a function name`);if(typeof n!="string"||n.trim()==="")throw new w(`Condition JSON call at '${J(r)}' requires a non-empty function name`);if(!/^\w+$/.test(n))throw new w(`Invalid condition JSON function name '${n}' at '${J(r)}'`);if(!Array.isArray(o))throw new w(`Condition JSON call '${n}' at '${J(r)}' requires args to be an array`);return{type:m.FUNCTION,name:n,args:o.map((i,s)=>ge(i,t,[...r,"args",s]))}},ge=(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 w(`Condition JSON array at '${J(r)}' must be wrapped in an operator or { literal: [...] }`);if(!dr(e))throw new w(`Invalid condition JSON value at '${J(r)}'`);let n=Fn(e);if(n.length===0)throw new w(`Condition JSON object at '${J(r)}' must contain an operator`);let o=n.filter(s=>us.has(s));if(o.length===0)throw new w(`Unknown condition JSON operator '${n[0]}' at '${J(r)}'`);if(o.length>1)throw new w(`Condition JSON at '${J(r)}' must contain exactly one operator`);let i=o.includes("call")?"call":o[0];if(i==="var"){if(ve(e,new Set(["var"]),r),typeof e.var!="string"||e.var.trim()==="")throw new w(`Condition JSON var at '${J(r)}' requires a non-empty path`);return{type:m.VARIABLE,path:e.var}}if(i==="literal")return ve(e,new Set(["literal"]),r),{type:m.LITERAL,value:e.literal};if(i==="call")return ps(e,t,r);if(i==="not")return ve(e,new Set(["not"]),r),{type:m.UNARY,op:ze.NOT,operand:ge(e.not,t,[...r,"not"])};if(i in ur)return ve(e,new Set([i]),r),fs(e[i],i,ur[i],t,[...r,i]);if(i in lr){ve(e,new Set([i]),r);let s=ds(e[i],i,[...r,i]);return{type:m.BINARY,op:lr[i],left:ge(s[0],t,[...r,i,0]),right:ge(s[1],t,[...r,i,1])}}throw new w(`Unknown condition JSON operator '${i}' at '${J(r)}'`)},jn=(e,t={})=>{if(e==null)throw new w("Missing condition expression after '$when'");if(typeof e=="string"){if(e.trim()==="")throw new w("Empty condition expression after '$when'");return K(e,t)}return dr(e)||Array.isArray(e)?ge(e,t):{type:m.LITERAL,value:e}},K=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let a=e.slice(1,-1),u=0,d=!0;for(let f=0;f<a.length;f++)if(a[f]==="("?u++:a[f]===")"&&u--,u<0){d=!1;break}if(d&&u===0)return K(a,t)}let r=Pe(e,"||");if(r!==-1)return{type:m.BINARY,op:L.OR,left:K(e.substring(0,r).trim(),t),right:K(e.substring(r+2).trim(),t)};let n=Pe(e,"&&");if(n!==-1)return{type:m.BINARY,op:L.AND,left:K(e.substring(0,n).trim(),t),right:K(e.substring(n+2).trim(),t)};let o=[{op:">=",type:L.GTE},{op:"<=",type:L.LTE},{op:"==",type:L.EQ},{op:"!=",type:L.NEQ},{op:">",type:L.GT},{op:"<",type:L.LT},{op:" in ",type:L.IN}];for(let{op:a,type:u}of o){let d=Pe(e,a);if(d!==-1)return{type:m.BINARY,op:u,left:K(e.substring(0,d).trim(),t),right:K(e.substring(d+a.length).trim(),t)}}let i=-1,s=null,l=[{op:" + ",type:L.ADD},{op:" - ",type:L.SUBTRACT}];for(let{op:a,type:u}of l){let d=0;for(;d<e.length;){let f=Pe(e.substring(d),a);if(f===-1)break;let p=d+f;p>i&&(i=p,s={op:a,type:u}),d=p+a.length}}if(i!==-1&&s)return{type:m.BINARY,op:s.type,left:K(e.substring(0,i).trim(),t),right:K(e.substring(i+s.op.length).trim(),t)};let c=[" * "," / "," % "];for(let a of c)if(Pe(e,a)!==-1)throw new w(`Arithmetic operations are not allowed in conditionals: "${a}"`);return e.startsWith("!")?{type:m.UNARY,op:ze.NOT,operand:K(e.substring(1).trim(),t)}:Un(e,t)},Pe=(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},hs=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}},Un=(e,t)=>{let r=e.trim();if(r.match(/^(\w+)\((.*)\)$/))return tt(r,t);let o=hs(r);if(o.type===m.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(r))return{type:m.VARIABLE,path:r};try{return tt(r,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},ms=(e,t=!1)=>{let r=t?"$each":"$for";try{_n(e)}catch(n){if(n instanceof w&&t){let o=n.message.replace(/\$for/g,"$each");throw new w(o.replace("Parse Error: ",""))}throw n}},Mn=(e,t,r,n=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let y=n?"$each":"$for";throw new w(`Invalid loop syntax (got: '${e.replace("$for",y)}')`)}let s=i[1],l=i[2].trim();ms(l,n);let c=l.match(/^(.+?)\s+in\s+(.+)$/);if(!c){let y=n?"$each":"$for";throw new w(`Invalid loop syntax - missing 'in' keyword (got: '${y} ${l}')`)}let a=c[1].trim(),u=c[2].trim(),d,f=null;if(a.includes(",")){let y=a.split(",").map(b=>b.trim());if(y.length!==2)throw new w(`Invalid loop variables: ${a}. Expected format: "item" or "item, index"`);d=y[0],f=y[1]}else d=a;let p=["this","undefined","null","true","false"];if(p.includes(d))throw new w(`Reserved variable name: ${d}`);if(f&&p.includes(f))throw new w(`Reserved variable name: ${f}`);let h=Un(u,r),g=xe(t,r);return{type:m.LOOP,itemVar:d,indexVar:f,iterable:h,body:g,flatten:s!=="nested"}};var gs=(e,t={})=>{let{functions:r={}}=t;return xe(e,r)},xt=gs;var rt={};Ri(rt,{now:()=>ys});var ys=()=>Date.now();var bs=(e,t,r={})=>{let{functions:n={},partials:o={}}=r,i={...rt,...n},s=xt(e,{functions:i}),l={};for(let[c,a]of Object.entries(o))l[c]=xt(a,{functions:i});return ar(s,t,{functions:i,partials:l})},ee=bs;var Is=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",As=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,ws=(e,t)=>{if(Is(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new w("Empty condition expression");return K(e,t)}return ge(e,t)},Es=(e,t={},r={})=>{let n=As(r),o={...rt,...n},i=ws(e,o);return!!Ee(i,{functions:o,partials:{}},t,{})},fr=Es;var ot=(e,t={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return fr(e,t)},Hn=(e,t,r={})=>{let n=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=c=>c,transformActionFirstArgument:l=c=>c}=r;for(let[c,a]of Object.entries(t))c!=="createInitialState"&&(c.startsWith("select")?o[c]=(...u)=>a(s(n),...u):i[c]=(...u)=>{let d;return n=ir(n,p=>{let h=a(l(p),...u);d=h!==void 0&&!re(h)?h:void 0}),d});return{...o,...i}},_t=(e,t)=>r=>{let n=e(),o=Array.isArray(r)?r:[r];return ir(n,i=>{o.forEach(s=>{t.forEach(l=>{l(i,s)})})})};var vs=(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{}}},le=(e,t)=>Object.prototype.hasOwnProperty.call(e??{},t),nt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Kn=e=>{let t=re(e)?De(e):e;return structuredClone(t)},Ce=e=>le(e,"computed"),We=(e={},t={})=>Object.fromEntries(Object.entries(e??{}).filter(([r])=>!Ce(t[r]))),xs=e=>String(e).replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean),pr=(e,t)=>{let r=e;for(let n of t){if(r==null)return;r=r[n]}return r},Cs=(e,t={})=>{if(typeof e!="string"||e.trim()==="")throw new Error("Computed expression var requires a non-empty string path");let r=xs(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 pr(s,i)}return n==="runtime"?pr(t.runtime,r.slice(1)):pr(t,r)},Ss=(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)`)},Bn=(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`)},_s=(e,t)=>{if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Computed expression operator "${e}" requires finite numeric operands`)},ce=(e,t,r,n)=>(Ss(e,t,n),t.map(o=>St(o,r))),se=(e,t,r,n)=>{let o=ce(e,t,r,n);return o.forEach(i=>_s(e,i)),o},Rs=(e,t,r)=>{switch(e){case"var":return Cs(t,r);case"add":{let[n,o]=se(e,t,r,2);return n+o}case"sub":{let[n,o]=se(e,t,r,2);return n-o}case"mul":{let[n,o]=se(e,t,r,2);return n*o}case"div":{let[n,o]=se(e,t,r,2);return n/o}case"mod":{let[n,o]=se(e,t,r,2);return n%o}case"neg":{let[n]=se(e,t,r,1);return-n}case"round":{let[n]=se(e,t,r,1);return Math.round(n)}case"floor":{let[n]=se(e,t,r,1);return Math.floor(n)}case"ceil":{let[n]=se(e,t,r,1);return Math.ceil(n)}case"min":{let[n,o]=se(e,t,r,2);return Math.min(n,o)}case"max":{let[n,o]=se(e,t,r,2);return Math.max(n,o)}case"clamp":{let[n,o,i]=se(e,t,r,3);return Math.min(i,Math.max(o,n))}case"eq":{let[n,o]=ce(e,t,r,2);return n==o}case"neq":{let[n,o]=ce(e,t,r,2);return n!=o}case"gt":{let[n,o]=ce(e,t,r,2);return n>o}case"gte":{let[n,o]=ce(e,t,r,2);return n>=o}case"lt":{let[n,o]=ce(e,t,r,2);return n<o}case"lte":{let[n,o]=ce(e,t,r,2);return n<=o}case"in":{let[n,o]=ce(e,t,r,2);return Array.isArray(o)?o.includes(n):!1}case"and":case"all":return Bn(e,t),t.every(n=>!!St(n,r));case"or":case"any":return Bn(e,t),t.some(n=>!!St(n,r));case"not":{let[n]=ce(e,t,r,1);return!n}case"length":{let[n]=ce(e,t,r,1);return typeof n=="string"||Array.isArray(n)?n.length:nt(n)?Object.keys(n).length:0}case"includes":{let[n,o]=ce(e,t,r,2);return typeof n=="string"||Array.isArray(n)?n.includes(o):!1}case"literal":return Kn(t);default:throw new Error(`Unknown computed expression operator: ${e}`)}},St=(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 Rs(n,o,t)},Os=(e,t={})=>ot(e,{variables:t.variables,runtime:t.runtime}),Ls=(e,t)=>{if(!nt(e))throw new Error(`${t} must be an object`);let r=le(e,"expr"),n=le(e,"value");if(r===n)throw new Error(`${t} must contain exactly one of expr or value`)},hr=(e,t,r)=>(Ls(e,t),le(e,"value")?Kn(e.value):St(e.expr,r)),$s=(e,t={},r="unknown")=>{if(!nt(e))throw new Error(`Computed variable "${r}" computed must be an object`);let n=le(e,"expr"),o=le(e,"value");if(le(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(!nt(e.default))throw new Error(`Computed variable "${r}" requires default`);for(let s=0;s<e.branches.length;s+=1){let l=e.branches[s];if(!nt(l))throw new Error(`Computed variable "${r}" branch ${s} must be an object`);if(!le(l,"when"))throw new Error(`Computed variable "${r}" branch ${s} requires when`);if(Os(l.when,t))return hr(l,`Computed variable "${r}" branch ${s}`,t)}return hr(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 hr(e,`Computed variable "${r}"`,t)},ks=(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}`)}},Rt=({variables:e={},runtime:t={},variableConfigs:r={},eager:n=!0}={})=>{let o=We(e,r),i=Object.entries(r).filter(([,d])=>Ce(d)).map(([d])=>d),s={},l=[],c=d=>{if(le(s,d))return s[d];let f=r[d];if(!Ce(f))return o[d];let p=l.indexOf(d);if(p>=0){let h=[...l.slice(p),d].join(" -> ");throw new Error(`Computed variable cycle detected: ${h}`)}l.push(d);try{let h=$s(f.computed,u,d);return ks(d,f.type,h),s[d]=h,h}finally{l.pop()}},a=new Proxy({},{get:(d,f)=>{if(typeof f=="string")return c(f)},has:(d,f)=>typeof f=="string"&&(le(o,f)||i.includes(f)),ownKeys:()=>[...new Set([...Object.keys(o),...i])],getOwnPropertyDescriptor:(d,f)=>{if(!(typeof f!="string"||!le(o,f)&&!i.includes(f)))return{enumerable:!0,configurable:!0}}}),u={variables:a,runtime:t,resolveVariable:c};return n?(i.forEach(d=>{c(d)}),{...o,...s}):a},Ds=({variables:e={},runtime:t={},variableConfigs:r,projectData:n}={})=>Rt({variables:e,runtime:t,variableConfigs:r??n?.resources?.variables??{},eager:!0}),yr=e=>{let t={},r={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([n,o])=>{if(Ce(o))return;let i=vs(o,n);o.scope==="context"?t[n]=i:r[n]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}},Ot=(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(", ")}`)},Lt=(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(", ")}`)},Ps=2,zn=12,Gn=(e=Ps)=>{if(!Number.isInteger(e)||e<0||e>zn)throw new Error(`Operation "divide" requires roundTo to be an integer between 0 and ${zn}.`);return e},Ts=(e,t)=>{let r=10**t;return Math.round((e+Number.EPSILON)*r)/r},Ct=e=>typeof e=="number"&&Number.isFinite(e),br=(e,t,r,n,o={})=>{if(e==="number"){if(t==="set"&&!Ct(r))throw new Error(`Operation "set" requires value to be a number for variable "${n}".`);if(t==="multiply"&&!Ct(r))throw new Error(`Operation "multiply" requires value to be a number for variable "${n}".`);if(t==="divide"&&!Ct(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}".`);Gn(o.roundTo)}}},$t=(e,t,r,n={})=>{let o=(s,l,c)=>{let a=s??l;if(!Ct(a))throw new Error(`Operation "${t}" requires ${c} to be a number.`);return a},i=s=>{let l=o(s,void 0,"value");if(l===0)throw new Error(`Operation "${t}" requires value to be a non-zero number.`);return l};switch(t){case"set":return r;case"multiply":return o(e,1,"current value")*o(r,void 0,"value");case"divide":return Ts(o(e,0,"current value")/i(r),Gn(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 Jn=(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()))},Ns=(e,t)=>{let r=i=>{if(!i)return;let s={};i.ui&&(s.ui=i.ui);let l=i.character?.sprite;return l&&Object.keys(l).length>0&&(s.sprite=l),Object.keys(s).length>0?s:void 0},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},Wn=e=>{if(e?.resourceId===void 0)return;let t={resourceId:e.resourceId};return e.transformId!==void 0&&(t.transformId=e.transformId),e.loop!==void 0&&(t.loop=e.loop),t},qn=e=>{if(e?.colorId!==void 0)return{colorId:e.colorId}},Yn=(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,Vs=(e,t)=>{let r={},n=Yn(Wn(e),Wn(t)),o=Yn(qn(e),qn(t));return n&&(r.resource=n),o&&(r.color=o),Object.keys(r).length>0?r:null},Ir=(e={},t={})=>{let r={},n=["sfx","voice"],o=l=>{let c=e[l],a=t[l];a&&!c?r[l]={changeType:"add",data:a}:c&&!a?n.includes(l)||(r[l]={changeType:"delete",data:c}):c&&a&&JSON.stringify(c)!==JSON.stringify(a)&&(r[l]={changeType:"update",data:a})},i=Vs(e.background,t.background);i&&(r.background=i),o("bgm"),o("voice");let s=Ns(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},Ar=(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"),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(l=>{let c={...l};return delete c.animations,i(c)?c: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},js=(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},Ms=(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=js(t,r);if(n===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return n},Fs={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"])},Xn=(e,t)=>{let r=e[e.length-1];return r?Fs[r]?.has(t)===!0:!1},mr=(e,t,r=[])=>Array.isArray(e)?e.map(n=>mr(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,Xn(r,n)?o:mr(o,t,[...r,n])])):Ms(e,t),gr=(e,t,r=[])=>Array.isArray(e)?e.map(n=>gr(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,Xn(r,n)?o:gr(o,t,[...r,n])])):typeof e=="string"?ee(e,t):e,wr=(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=mr(e,t._event);return gr(r,t)};var ue=e=>structuredClone(re(e)?De(e):e),it=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:ue(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},eo=(e,t)=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let r=e.map(n=>ue(n)).filter(n=>t(n)||n.animations);return{hasValidItems:r.length>0,processedItems:r}},oe=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Qn=e=>e?.animations?.playback?.continuity==="persistent",ye=(e,t)=>oe(e??{},t)&&e[t]!==void 0,Us=e=>{if(e){if(e.character&&oe(e.character,"name"))return e.character.name;if(oe(e,"characterName"))return e.characterName}},to=e=>!!e?.character&&oe(e.character,"sprite"),Bs=e=>{let t={},r=!1,n=Us(e);return n!==void 0&&(t.name=n,r=!0),to(e)&&(t.sprite=ue(e.character.sprite),r=!0),r?t:void 0},Zn=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},zs=({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=>ue(o)):delete e.initialRevealedContent,e.content=[...n,...t]},Ws=()=>({}),qs=(e,t)=>{if(t.background){let r=ye(t.background,"resourceId"),n=ye(t.background,"colorId"),o=ye(t.background,"opacity"),i=ye(t.background,"blur"),{animationsOnly:s,state:l}=it(t.background,u=>ye(u,"resourceId")||ye(u,"colorId")||ye(u,"opacity")||ye(u,"blur"));if(s){e.background=e.background?{...ue(e.background),...l}:l;return}if(!r&&!n&&!o&&!i){delete e.background;return}let c=e.background,a=ue(t.background);if(!r&&c?.resourceId&&(a.resourceId=c.resourceId,!oe(a,"transformId")&&c.transformId&&(a.transformId=c.transformId)),!n&&c?.colorId&&(a.colorId=c.colorId),!o&&ye(c,"opacity")&&(a.opacity=c.opacity),!i&&ye(c,"blur")&&(a.blur=ue(c.blur)),oe(a,"resourceId")&&a.resourceId===void 0&&delete a.resourceId,oe(a,"colorId")&&a.colorId===void 0&&delete a.colorId,oe(a,"animations")&&a.animations===void 0&&delete a.animations,oe(a,"opacity")&&a.opacity===void 0&&delete a.opacity,oe(a,"blur")&&a.blur===void 0&&delete a.blur,!a.resourceId&&!a.colorId){delete e.background;return}c?.resourceId===a.resourceId&&c?.transformId===a.transformId&&!oe(a,"animations")&&Qn(c)&&(a.animations=ue(c.animations)),e.background=a}else e.background?.animations&&!Qn(e.background)&&(e.background.animations={})},Ys=(e,t)=>{if(!t.dialogue){e.dialogue&&(Zn(e.dialogue),e.dialogue.mode==="adv"&&(e.dialogue.content=void 0,delete e.dialogue.initialRevealedContent,e.dialogue.persistCharacter!==!0&&(delete e.dialogue.characterId,delete e.dialogue.character)));return}e.dialogue||(e.dialogue={});let r=e.dialogue.mode;if(t.dialogue.ui){let{animationsOnly:a,state:u}=it(t.dialogue.ui,d=>!!d.resourceId);a?e.dialogue.ui={...e.dialogue.ui,...u}:e.dialogue.ui={...t.dialogue.ui}}else e.dialogue?.ui?.animations&&(e.dialogue.ui.animations={});t.dialogue.mode==="adv"&&(e.dialogue.content=e.dialogue.content||void 0,e.dialogue.characterId=e.dialogue.characterId||void 0,e.dialogue.mode="adv"),t.dialogue.mode==="nvl"&&(e.dialogue?.mode!=="nvl"&&(e.dialogue.lines=[]),e.dialogue.mode="nvl");let n=t.dialogue.append===!0&&r!=="nvl"&&e.dialogue?.mode!=="nvl"&&Array.isArray(t.dialogue.content);t.dialogue.content!==void 0&&zs({dialogueState:e.dialogue,content:t.dialogue.content,append:n});let o=oe(t.dialogue,"persistCharacter")?t.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;o?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let i=oe(t.dialogue,"characterId"),s=Bs(t.dialogue),l=s!==void 0,c=to(t.dialogue);if(i?t.dialogue.characterId?e.dialogue.characterId=t.dialogue.characterId:delete e.dialogue.characterId:!o&&!n&&delete e.dialogue.characterId,l?e.dialogue.character=!i&&o&&e.dialogue.character?{...ue(e.dialogue.character),...s}:s:(i||!o&&!n)&&delete e.dialogue.character,c||Zn(e.dialogue),t.dialogue.clear){delete e.dialogue;return}if(t.dialogue?.clearPage&&e.dialogue?.mode==="nvl"&&(e.dialogue.lines=[]),e.dialogue?.mode==="nvl"&&t.dialogue.content!==void 0){let a={content:t.dialogue.content,characterId:e.dialogue.characterId??null};e.dialogue.character&&(a.character=ue(e.dialogue.character)),e.dialogue.lines.push(a)}},Hs=(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},Ks=(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}}},Gs=(e,t)=>{if(t.visual){let{hasValidItems:r,processedItems:n}=eo(t.visual.items,o=>!!o.resourceId);r?e.visual={items:n}:delete e.visual}else e.visual?.items&&(e.visual.items=e.visual.items.map(r=>r.animations?{...r,animations:{}}:r))},Js=(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}=eo(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId);r?e.character={items:n}:delete e.character},Xs=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},Qs=(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},Zs=(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},ea=(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=ue(t.form)}else e.form&&delete e.form},ta=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},ra=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},na=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(r=>{delete e[r]})},Te=e=>_t(Ws,[na,qs,Hs,Ks,Gs,Ys,Js,Xs,Qs,Zs,ea,ta,ra])(e);var oa=Object.freeze({dialogueTextSpeed:{source:"global.dialogueTextSpeed"},autoForwardDelay:{source:"global.autoForwardDelay"},skipUnseenText:{source:"global.skipUnseenText"},skipTransitionsAndAnimations:{source:"global.skipTransitionsAndAnimations"},soundVolume:{source:"global.soundVolume"},musicVolume:{source:"global.musicVolume"},muteAll:{source:"global.muteAll"},saveLoadPagination:{source:"context.runtime.saveLoadPagination"},menuPage:{source:"context.runtime.menuPage"},menuEntryPoint:{source:"context.runtime.menuEntryPoint"},autoMode:{source:"global.autoMode"},skipMode:{source:"global.skipMode"},dialogueUIHidden:{source:"global.dialogueUIHidden"},isLineCompleted:{source:"global.isLineCompleted"}}),Ne=Object.freeze({dialogueTextSpeed:50,autoForwardDelay:1e3,skipUnseenText:!1,skipTransitionsAndAnimations:!1,soundVolume:50,musicVolume:50,muteAll:!1,autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isLineCompleted:!1}),st=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),ro=Object.freeze({dialogueTextSpeed:"number",autoForwardDelay:"number",skipUnseenText:"boolean",skipTransitionsAndAnimations:"boolean",soundVolume:"number",musicVolume:"number",muteAll:"boolean",saveLoadPagination:"number",menuPage:"string",menuEntryPoint:"string",autoMode:"boolean",skipMode:"boolean",dialogueUIHidden:"boolean",isLineCompleted:"boolean"}),Er=Object.freeze(["dialogueTextSpeed","autoForwardDelay","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),vr=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),ia=(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]}},qe=e=>Object.fromEntries(Object.entries(oa).map(([t,r])=>{let n=ia(e,r.source),o=n!==void 0?n:Ne[t]??st[t];return[t,o]})),Ae=(e,t)=>qe(e)[t],no=(e={})=>Object.fromEntries(Er.map(t=>[t,e[t]??Ne[t]]));var at=Object.freeze({VISUAL_BEHIND_BACKGROUND:10,BACKGROUND:20,VISUAL_BEHIND_CHARACTER:30,CHARACTER:40,VISUAL_BEHIND_DIALOGUE:50,DIALOGUE:60,VISUAL_FOREGROUND:70}),Se=Object.freeze({BEHIND_BACKGROUND:at.VISUAL_BEHIND_BACKGROUND,BEHIND_CHARACTER:at.VISUAL_BEHIND_CHARACTER,BEHIND_DIALOGUE:at.VISUAL_BEHIND_DIALOGUE,FOREGROUND:at.VISUAL_FOREGROUND}),xr=Se.BEHIND_DIALOGUE,Cr=Object.freeze(Object.values(Se).sort((e,t)=>e-t));var _e={objectValues:e=>Object.entries(e).map(([t,r])=>({id:t,...r})),formatDate:Jn},sa=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,aa=(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},Dt=(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),l=sa.exec(s);if(l){let[,c,a,u]=l,d=aa(t,u);if(!Array.isArray(d))continue;let f=Array.isArray(i[s])?i[s]:[];d.forEach((p,h)=>{let g={...t,[c]:p};a&&(g[a]=h),f.forEach(y=>{let b=Dt(y,g,r),A=ee(b,g,r);Array.isArray(A)?o.push(...A):o.push(A)})});continue}}o.push(Dt(i,t,r))}return o}if(!e||typeof e!="object")return e;let n={};return Object.entries(e).forEach(([o,i])=>{n[o]=Dt(i,t,r)}),n},Br=({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".`)},ca=({id:e,targetId:t,animation:r,playback:n,animationPath:o="animation"})=>{let i=structuredClone(r);return Br({animationType:i.type,animationId:e,animationPath:o}),delete i.name,delete i.playback,i.id=e,i.targetId=t,n&&(i.playback=structuredClone(n)),i},la=(e,{animationId:t="animation",animationPath:r="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return Br({animationType:e.type,animationId:t,animationPath:r}),e.type},ua=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},da=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},yo=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),bo=e=>e?.playback?.continuity==="persistent",$r=e=>Array.isArray(e)?e.map($r):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((t,r)=>(t[r]=$r(e[r]),t),{}),Pt=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let t=structuredClone(e);return delete t.playback,JSON.stringify($r(t))},Io=(e=[])=>e.filter(t=>bo(t)).map(t=>structuredClone(t)),Ao=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,Sr=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((t,r)=>Math.max(t,Ao(r)),0),wo=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max(Sr(e.tween),Sr(e.prev?.tween),Sr(e.next?.tween),Ao(e.mask?.progress)),oo=({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(Pt).filter(Boolean));return e.some(n=>{if(!bo(n))return!1;let o=Pt(n);return o?r.has(o):!1})},de=({animationInstances:e,isLineCompleted:t,skipTransitionsAndAnimations:r,activePersistentAnimations:n,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||r?!1:i&&!t||oo({animationInstances:e,activePersistentAnimations:n})?!0:i?!1:oo({animationInstances:e,activePersistentAnimations:o}),fa=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),pa=(e,t)=>{if(fa(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},ha=({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?ca({id:n,targetId:o,animation:s,playback:r,animationPath:i}):null},ma=(e,{defaultTargetId:t,defaultId:r,animationPath:n="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return Br({animationType:o.type,animationId:o.id??r,animationPath:n}),o.id??=r,o.targetId??=t,o},zr=({animations:e,transitions:t,defaultTargetId:r,idPrefix:n,animationPathPrefix:o=n})=>{t.forEach((i,s)=>{e.push(ma(i,{defaultTargetId:r,defaultId:`${n}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},kr=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let r=ee(e,t);return r&&typeof r=="object"?e:r},Dr=(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},ga=({content:e,path:t,variables:r})=>Dr(e,t).reduce((n,o)=>{let i=kr(o.text,{variables:r});return n+`${i??""}`.length},0),io=(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))},kt=(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("-")}`},_r=(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},ya=(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},ba=(e={},t)=>{if(t){if(e.images?.[t])return"sprite";if(e.videos?.[t])return"video";if(e.layouts?.[t])return"container"}},Pr=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},Ia=(e={})=>e.textStyles||{},Aa=(e={})=>e.images||{},wa=(e={})=>e.colors||{},Ea=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,ct=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,He=(e,t,r)=>{if(typeof e!="string"||e.length===0)throw new Error(`${r} at "${t}" must resolve to a non-empty string`)},so=(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},Wr=(e,t)=>{if(typeof e!="string"||!Ea.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},ao=(e,t,r)=>{let n=Wr(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})`},va=(e={},t)=>{let r=Ia(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=so(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:ao(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 l=e.colors?.[r.strokeColorId];if(!l)throw new Error(`Stroke color "${r.strokeColorId}" not found for text style "${t}"`);let c=so(r.strokeAlpha,"strokeAlpha",t);s.strokeColor=ao(l.hex,c,`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},Tr=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>Tr(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]=Tr(i,t,ct(r,o)));return e.textStyleId!==void 0&&(He(e.textStyleId,r,"textStyleId"),n.textStyle=va(t,e.textStyleId)),n},qr=(e={},t)=>{let r=wa(e)?.[t];if(!r)throw new Error(`Color "${t}" not found`);return Wr(r.hex,`Color "${t}"`)},Eo=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",Rr=(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 ${Eo(`${t}.fill`)} instead`)},xa=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>lt(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]=lt(i,t,ct(r,o)));return e.colorId!==void 0&&(He(e.colorId,r,"colorId"),n.fill=qr(t,e.colorId)),n},lt=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>lt(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 ${Eo("fill")} instead`);Rr(e,"hover",r),Rr(e,"click",r),Rr(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]=xa(i,t,ct(r,o));continue}n[o]=lt(i,t,ct(r,o))}return e.type==="rect"&&e.colorId!==void 0&&(He(e.colorId,r,"colorId"),n.fill=qr(t,e.colorId)),n},Or=(e={},t)=>{let r=Aa(e)?.[t];return r||null},vo=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",co=(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 ${vo(`${t}.${n}`)} instead`)},lo=(e,t,r)=>{let n=e[t];e[t]={...n&&typeof n=="object"&&!Array.isArray(n)?n:{},src:r}},Nr=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>Nr(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 ${vo(o)} instead`);co(e,"hover",r,"src"),co(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]=Nr(i,t,ct(r,o)));if(e.type==="sprite"&&e.imageId!==void 0){He(e.imageId,r,"imageId");let o=Or(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&&(He(e.hoverImageId,r,"hoverImageId"),lo(n,"hover",Or(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(He(e.clickImageId,r,"clickImageId"),lo(n,"click",Or(t,e.clickImageId)?.fileId??e.clickImageId)),n},Yr=(e,t={},r="root")=>Nr(lt(Tr(e,t,r),t,r),t,r),Re=Yr,Ke=(e=[])=>e.find(t=>t.id==="story"),Ca="#000000",Vr="bg-cg-background-color",Sa=({resources:e={},background:t={},screen:r})=>t?.colorId===void 0?Wr(r?.backgroundColor??Ca,"screen.backgroundColor"):qr(e,t.colorId),xo=(e={})=>{if(yo(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},_a=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},uo=(e={},{includeDefaultAlpha:t=!1}={})=>{let r=xo(e),n=_a(e),o={};return(t||r!==void 0)&&(o.alpha=r??1),n&&(o.blur=n),o},Ra=({resources:e,background:t,screen:r={width:1920,height:1080},includeOpacity:n=!1})=>{let o={id:Vr,type:"rect",x:0,y:0,width:r?.width??1920,height:r?.height??1080,fill:Sa({resources:e,background:t,screen:r})};if(n){let i=xo(t);i!==void 0&&(o.alpha=i)}return o},Oa=(e={},t)=>t?!!(e.images?.[t]||e.videos?.[t]||e.layouts?.[t]):!1,fo=({resources:e={},resourceId:t,colorId:r})=>{let n=ba(e,t);return t&&(n||r===void 0)?{resourceId:t,targetId:Pr({resourceId:t,kind:n})}:r!==void 0?{resourceId:Vr,targetId:Vr}:{resourceId:void 0,targetId:void 0}},Co=100,Nt=Co,So=(e,t)=>e*t/Co,La=(e={},t=Nt)=>e?.muteAll?0:So(t,e?.soundVolume??Ne.soundVolume),$a=(e={},t=Nt)=>e?.muteAll?0:So(t,e?.musicVolume??Ne.musicVolume),ka=({item:e,index:t}={})=>`sfx:${t}:${e?.resourceId}`,fe=({variables:e,runtime:t,saveSlots:r=[],dialogueState:n,includeInactiveAdvDialogue:o=!1,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,confirmDialog:d,form:f,historyDialogue:p=[],characters:h={},dialogueUIHidden:g,skipOnlyViewedLines:y,skipTransitionsAndAnimations:b}={})=>{let A={dialogueTextSpeed:t?.dialogueTextSpeed??50,autoForwardDelay:t?.autoForwardDelay??1e3,skipUnseenText:t?.skipUnseenText??!1,skipTransitionsAndAnimations:t?.skipTransitionsAndAnimations??!1,soundVolume:t?.soundVolume??50,musicVolume:t?.musicVolume??50,muteAll:t?.muteAll??!1,saveLoadPagination:t?.saveLoadPagination??1,menuPage:t?.menuPage??"",menuEntryPoint:t?.menuEntryPoint??"",autoMode:t?.autoMode??s??!1,skipMode:t?.skipMode??l??!1,dialogueUIHidden:t?.dialogueUIHidden??g??!1,isLineCompleted:t?.isLineCompleted??i??!1},x=Va({dialogueState:n,includeInactiveAdvDialogue:o,characters:h,variables:e}),S={variables:e,runtime:A,saveSlots:r,isChoiceVisible:c,isFormVisible:a,canRollback:u,confirmDialog:d,form:f,historyDialogue:p,characters:h};return x&&(S.dialogue=x,S.dialogueLines=x.lines),S},po=100,Tt=(e,t)=>{if(Array.isArray(e))return e.map(n=>Tt(n,t));if(!e||typeof e!="object")return e;let r={...e};return Object.keys(r).forEach(n=>{r[n]=Tt(r[n],t)}),r.type==="text-revealing"?t(r):r},Da=e=>Tt(e,t=>({...t,revealEffect:"none"})),Pa=e=>Tt(e,t=>{let r=Number(t.speed??t.displaySpeed),n=Number.isFinite(r)?Math.max(r,po):po;return{...t,speed:n,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:n}:{}}}),Oe=(e,{isLineCompleted:t=!1,skipMode:r=!1,skipTransitionsAndAnimations:n=!1}={})=>t||n?Da(e):r?Pa(e):e,_o=({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:{}}}}),jr=e=>{if(Array.isArray(e))return e.map(jr);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=jr(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}}:{}}}}},Ta=new Set(["click","change","submit","focusEvent","blurEvent","selectionChange","compositionStart","compositionUpdate","compositionEnd"]),ho=(e,t)=>{let r=e?.payload&&typeof e.payload=="object"&&!Array.isArray(e.payload)?e.payload:{},n=r.actions&&typeof r.actions=="object"?r.actions:{};return{...e||{},payload:{...r,actions:{...n,...t}}}},Mr=(e,t)=>{if(Array.isArray(e))return e.map(i=>Mr(i,t));if(!e||typeof e!="object")return e;let r={};for(let[i,s]of Object.entries(e))r[i]=Mr(s,t);if(r.type!=="input"||typeof r.field!="string")return r;let n=t?.fields?.[r.field];if(!n)return r;let o={updateFormField:{formId:t.id,formKey:t.key,field:n.id,value:"_event.value",_interactionSource:"form"}};return{...r,value:n.value,placeholder:r.placeholder===void 0?n.placeholder:r.placeholder,multiline:r.multiline===void 0?n.multiline:r.multiline,...r.maxLength===void 0&&n.maxLength!==void 0?{maxLength:n.maxLength}:{},change:ho(r.change,o),submit:ho(r.submit,t.submitActions)}},Fr=(e,t)=>{if(Array.isArray(e))return e.map(n=>Fr(n,t));if(!e||typeof e!="object")return e;let r={};for(let[n,o]of Object.entries(e))r[n]=Fr(o,t);for(let n of Ta){let o=r[n]?.payload;!o||typeof o!="object"||Array.isArray(o)||(r[n]={...r[n],payload:{...o,_interactionSource:"form",_formId:t.id,_formKey:t.key}})}return r},Ur=({characterId:e,character:t,characterName:r,characters:n={}}={})=>{let o=e?n?.[e]:void 0,i=t?.name!==void 0?t.name:r!==void 0?r:o?.name||"";return{...o||{},...t||{},name:i}},Ro=(e=[],t={})=>e.map(r=>{let n=Ur({characterId:r.characterId,character:r.character,characterName:r.characterName,characters:t}),o=typeof r.text=="string"?r.text:Array.isArray(r.content)?r.content.map(i=>i?.text??"").join(""):"";return{...r,text:o,character:n,characterName:n.name}}),Na=e=>!(!e||e.mode==="adv"&&e.content===void 0),Va=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:r={},variables:n}={})=>{if(!t&&!Na(e))return;let o=e.content===void 0?[{text:""}]:Dr(e.content,"dialogue.content"),i=e.content===void 0?0:ga({content:e.initialRevealedContent,path:"dialogue.initialRevealedContent",variables:n}),s=(e.lines||[]).map((c,a)=>{let u=Dr(c.content,`dialogue.lines[${a}].content`),d=Ur({characterId:c.characterId,character:c.character,characterName:c.characterName,characters:r});return{...c,content:u.map(f=>({...f,text:kr(f.text,{variables:n})})),character:d,characterName:d.name}}),l=Ur({characterId:e.characterId,character:e.character,characters:r});return{characterId:e.characterId,persistCharacter:e.persistCharacter,character:l,content:o.map(c=>({...c,text:kr(c.text,{variables:n})})),initialRevealedCharacters:i,lines:s}},Oo=({container:e,resources:t,templateData:r,isLineCompleted:n=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=ee(e,r,{functions:_e});return Re(Oe(s,{isLineCompleted:n,skipMode:o,skipTransitionsAndAnimations:i}),t)},Lr=(e,t={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(t),mo=({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:Lr(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[n].keyup={payload:Lr(o.keyup)});return}e[n]={...i,[r]:{payload:Lr(o)}}})},ja=(e={},t={})=>{let r={};return mo({renderStateKeyboard:r,keyboard:e,phase:"keydown"}),mo({renderStateKeyboard:r,keyboard:t,phase:"keyup"}),Object.keys(r).length>0?r:void 0},we=({animationsDef:e,resources:t,previousResourceId:r,currentResourceId:n,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:l})=>{if(!e)return[];let c=[],a=({instanceId:b,targetId:A})=>{let x=ha({resources:t,animationId:p,playback:h,instanceId:b,targetId:A,animationPath:s});x&&c.push(x)},u=r!=null&&r!==!1,d=n!=null&&n!==!1,f=o&&i&&o===i;pa(e,s);let p=ua(e),h=da(e),g=t?.animations?.[p],y=la(g,{animationId:p,animationPath:s});if(y==="update")return d&&i?a({instanceId:`${l}-animation-update`,targetId:i}):u&&o&&a({instanceId:`${l}-animation-update`,targetId:o}),c;if(y==="transition"){let b=`${l}-animation-transition`,A=h?.continuity==="persistent"?b:`${l}-animation-in`;if(u&&d&&f)return a({instanceId:b,targetId:i}),c;u&&a({instanceId:`${l}-animation-out`,targetId:o}),d&&a({instanceId:A,targetId:i})}return c},Ma=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),Fa=(e,{presentationState:t,previousPresentationState:r,currentLineActions:n,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:l,variables:c,runtime:a,activePersistentAnimations:u,restoredPersistentAnimations:d,autoMode:f,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:b,saveSlots:A=[]})=>{let{elements:x,animations:S}=e;if(t.background){let T=n===void 0?!0:yo(n?.background??{},"animations"),E=x.find(z=>z.id==="story");if(!E)return e;let N=ya(o,t.background),B=r?.background?.resourceId,k=r?.background?.colorId,j=t.background.resourceId??(t.background.animations?B:void 0),F=t.background.colorId??(t.background.animations?k:void 0),M=Oa(o,j),q={...t.background,colorId:F};if((F!==void 0||M)&&E.children.push(Ra({resources:o,background:q,screen:i,includeOpacity:!M})),j){let{images:z={},videos:Y={}}=o,V=z[j]||Y[j];if(V){let he=Y[j]!==void 0,Z={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...N},Ue={id:Pr({resourceId:j,kind:he?"video":"sprite"}),type:he?"video":"sprite",x:Z.x,y:Z.y,src:V.fileId,width:V.width,height:V.height,...uo(t.background,{includeDefaultAlpha:!0}),anchorX:Z.anchorX,anchorY:Z.anchorY,rotation:Z.rotation,scaleX:Z.scaleX,scaleY:Z.scaleY};he&&(Ue.loop=t.background.loop??!1,Ue.volume=V.volume??50),E.children.push(Ue)}}if(j){let{layouts:z={}}=o,Y=z[j];if(Y){let V={id:Pr({resourceId:j,kind:"container"}),type:"container",children:Y.elements,...uo(t.background)};N&&Object.assign(V,{x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...N});let he=ee(V,fe({variables:c,runtime:a,saveSlots:A,dialogueState:t.dialogue,isLineCompleted:s,autoMode:f,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:b,characters:o.characters||{},skipTransitionsAndAnimations:l}),{functions:_e});E.children.push(Re(Oe(he,{isLineCompleted:s,skipMode:p,skipTransitionsAndAnimations:l}),o))}}let v=fo({resources:o,resourceId:B,colorId:k}),_=fo({resources:o,resourceId:j,colorId:F}),R=we({animationsDef:t.background.animations,resources:o,previousResourceId:v.resourceId,currentResourceId:_.resourceId,previousTargetId:v.targetId,currentTargetId:_.targetId,animationPath:"background.animations",idPrefix:"bg-cg"});de({animationInstances:R,isLineCompleted:s,skipTransitionsAndAnimations:l,activePersistentAnimations:u,restoredPersistentAnimations:d,isAuthoredOnCurrentLine:T})&&S.push(...R)}return e},Ua=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:l,animations:c}=e;if(t.character&&n){let a=l.find(h=>h.id==="story");if(!a)return e;let u=t.character.items||[],d=r?.character?.items||[],f=io(u),p=io(d);for(let h=0;h<u.length;h++){let g=u[h],{transformId:y,sprites:b}=g,A=d.find(F=>F.id===g.id),x=d.findIndex(F=>F.id===g.id),S=A?.sprites&&A.sprites.length>0,T=b&&b.length>0,E=x>=0?kt(A,x,p):void 0,N=we({animationsDef:g.animations,resources:n,previousResourceId:E,currentResourceId:T?kt(g,h,f):void 0,previousTargetId:E,currentTargetId:T?kt(g,h,f):void 0,animationPath:`character.items[${h}].animations`,idPrefix:"character"});if(g.animations&&!b&&!y&&S&&de({animationInstances:N,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){c.push(...N);continue}if(g.animations&&!b&&!y)continue;if(!b||b.length===0||!y){console.warn("Character item missing sprites or transformId:",g);continue}let B=kt(g,h,f),k=n.transforms[y];if(!k){console.warn("Transform not found:",y);continue}let j={type:"container",id:B,x:g.x??k.x,y:g.y??k.y,anchorX:k.anchorX,anchorY:k.anchorY,rotation:k.rotation,scaleX:k.scaleX,scaleY:k.scaleY,children:[]};for(let F of b){let M=n.images[F.resourceId];if(!M){console.warn(`Image resource not found: ${F.resourceId}`);continue}j.children.push({type:"sprite",id:`${B}-${F.id}`,src:M.fileId,width:M.width,height:M.height,x:0,y:0})}a.children.push(j),de({animationInstances:N,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...N)}}return e},Lo=(e,t)=>{if(!Cr.includes(e))throw new Error(`${t} must be one of: ${Cr.join(", ")}.`)},Ba=(e,t)=>{let r=e.layer??(e.resourceId?void 0:t?.layer)??xr;return Lo(r,`Visual item "${e.id}" layer`),r},za=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,runtime:l,activePersistentAnimations:c,autoMode:a,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,form:h,saveSlots:g=[],visualLayer:y})=>{let{elements:b,animations:A}=e;if(t.visual&&n){let x=b.find(E=>E.id==="story");if(!x)return e;let S=t.visual.items,T=r?.visual?.items||[];y!==void 0&&Lo(y,"visualLayer");for(let E of S){let N=T.find(j=>j.id===E.id),B=Ba(E,N);if(y!==void 0&&B!==y)continue;if(E.resourceId){let{images:j={},videos:F={},spritesheets:M={}}=n,q=M[E.resourceId];if(q){let v=_r(n,E),_=E.animationName;if(_){let R=q.animations?.[_];if(!R)throw new Error(`Animation '${_}' not found in spritesheet resource '${E.resourceId}'`);let z={id:`visual-${E.id}`,type:"animated-sprite",x:E.x??v.x,y:E.y??v.y,width:E.width??q.width,height:E.height??q.height,alpha:E.alpha??1,anchorX:v.anchorX,anchorY:v.anchorY,rotation:v.rotation,scaleX:v.scaleX,scaleY:v.scaleY,spritesheetSrc:q.fileId,spritesheetData:q.jsonData,animation:{frames:R.frames,animationSpeed:E.animationSpeed??R.animationSpeed??.5,loop:E.loop??R.loop??!0}};x.children.push(structuredClone(z))}}else{let v=j[E.resourceId]||F[E.resourceId];if(v){let _=F[E.resourceId]!==void 0,R=_r(n,E),z={id:`visual-${E.id}`,type:_?"video":"sprite",src:v.fileId,width:v.width,height:v.height,x:R.x,y:R.y,anchorX:R.anchorX,anchorY:R.anchorY,rotation:R.rotation,scaleX:R.scaleX,scaleY:R.scaleY};_&&(z.loop=v.loop??!1,z.volume=v.volume??50),x.children.push(z)}}}if(E.resourceId){let{layouts:j={}}=n,F=j[E.resourceId];if(F){let M=_r(n,E),q={id:`visual-${E.id}`,type:"container",children:structuredClone(F.elements),x:M.x,y:M.y,anchorX:M.anchorX,anchorY:M.anchorY,rotation:M.rotation,scaleX:M.scaleX,scaleY:M.scaleY},v=ee(q,fe({variables:s,runtime:l,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:o,autoMode:a,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:i}),{functions:_e});x.children.push(Re(Oe(v,{isLineCompleted:o,skipMode:u,skipTransitionsAndAnimations:i}),n))}}let k=we({animationsDef:E.animations,resources:n,previousResourceId:N?.resourceId,currentResourceId:E.resourceId,previousTargetId:N?.resourceId?`visual-${E.id}`:void 0,currentTargetId:E.resourceId?`visual-${E.id}`:void 0,animationPath:`visual.items[${E.id}].animations`,idPrefix:E.id});de({animationInstances:k,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:c})&&A.push(...k)}}return e},Ye="dialogue-character-sprite",go=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,Wa=(e,{presentationState:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:l}=e,c=Ke(e.elements);if(!c)return e;let a=t.dialogue?.character?.sprite,u=r?.dialogue?.character?.sprite,d=go(a),f=go(u),p=we({animationsDef:a?.animations,resources:n,previousResourceId:f?Ye:void 0,currentResourceId:d?Ye:void 0,previousTargetId:f?Ye:void 0,currentTargetId:d?Ye:void 0,animationPath:"dialogue.character.sprite.animations",idPrefix:"dialogue-character-sprite"});if(!d)return a?.animations&&f&&de({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...p),e;let h=n.transforms?.[a.transformId];if(!h)return console.warn("Transform not found:",a.transformId),e;let g={type:"container",id:Ye,x:h.x,y:h.y,anchorX:h.anchorX,anchorY:h.anchorY,rotation:h.rotation,scaleX:h.scaleX,scaleY:h.scaleY,children:[]};for(let y of a.items){let b=n.images?.[y.resourceId];if(!b){console.warn(`Image resource not found: ${y.resourceId}`);continue}g.children.push({type:"sprite",id:`${Ye}-${y.id}`,src:b.fileId,width:b.width,height:b.height,x:0,y:0})}return c.children.push(g),de({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...p),e},qa=(e,{presentationState:t,previousPresentationState:r,resources:n={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:c,canRollback:a,form:u,skipOnlyViewedLines:d,isLineCompleted:f,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(E=>E.id==="story");if(!S)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:E={}}=n,N=E[t.dialogue.ui.resourceId];if(N){let B={elements:N.elements},k=fe({variables:h,runtime:g,saveSlots:b,dialogueState:t.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:f,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:c,canRollback:a,form:u,characters:n.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:d,skipTransitionsAndAnimations:p}),j={functions:_e},F=Dt(B,k,j),M=ee(F,k,j),q=Re(Oe(M?.elements,{isLineCompleted:f,skipMode:s,skipTransitionsAndAnimations:p}),n);if(Array.isArray(q))for(let v of q)S.children.push(v);else q&&S.children.push(q)}}Wa(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:f,skipTransitionsAndAnimations:p,activePersistentAnimations:y});let T=we({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 de({animationInstances:T,isLineCompleted:f,skipTransitionsAndAnimations:p,activePersistentAnimations:y})&&x.push(...T),e},Ya=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,runtime:c,autoMode:a,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,form:h,activePersistentAnimations:g,saveSlots:y=[]})=>{let{elements:b,animations:A}=e;if(t.choice&&n){let x=Ke(b);if(!x)return e;let S=n?.layouts[t.choice.resourceId];if(S&&S.elements){let E={elements:S.elements},N=ee(E,{...fe({variables:l,runtime:c,saveSlots:y,dialogueState:t.dialogue,isLineCompleted:i,autoMode:a,skipMode:u,isChoiceVisible:d??!!t.choice,isFormVisible:f,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}},{functions:_e}),B=jr(Re(Oe(N?.elements,{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),n));if(Array.isArray(B))for(let k of B)x.children.push(k);else B&&x.children.push(B)}let T=we({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"});de({animationInstances:T,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:g})&&A.push(...T)}return e},Ha=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,runtime:c,autoMode:a,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,activePersistentAnimations:h,saveSlots:g=[],form:y})=>{let{elements:b,animations:A}=e;if(!y?.resourceId||!n)return e;let x=Ke(b);if(!x)return e;let S=n?.layouts?.[y.resourceId];if(!S)return console.warn(`Form layout not found: ${y.resourceId}`),e;let T={id:"form-container",type:"container",x:0,y:0,children:S.elements||[]},E={...fe({variables:l,runtime:c,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:i,autoMode:a,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,characters:n.characters||{},skipTransitionsAndAnimations:s,form:y}),form:y},N=ee(T,E,{functions:_e}),B=Fr(Re(Oe(Mr(N,y),{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),n),y);B&&x.children.push(B);let k=we({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 de({animationInstances:k,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:h})&&A.push(...k),e},Ka=(e,{presentationState:t,resources:r={},variables:n,runtime:o,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,form:d,saveSlots:f=[],skipTransitionsAndAnimations:p})=>{if(!t.control?.resourceId)return e;let h=r.controls?.[t.control.resourceId];if(!h)return e;let g=ja(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=Ke(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(Oo({container:b,resources:r,templateData:fe({variables:n,runtime:o,saveSlots:f,dialogueState:t.dialogue,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,form:d,characters:r.characters||{},skipTransitionsAndAnimations:p}),isLineCompleted:i,skipMode:l,skipTransitionsAndAnimations:p})),e},Ga=(e,{presentationState:t,resources:r,runtime:n,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&r){if(!Ke(i))return e;let c=r.sounds[t.bgm.resourceId];if(!c)return e;let a=fe({variables:o,runtime:n}).runtime;s.push({id:"bgm",type:"sound",src:c.fileId,loop:t.bgm.loop??!0,volume:$a(a,t.bgm.volume??c.volume??Nt),startDelayMs:t.bgm.startDelayMs??null})}return e},Ja=(e,{presentationState:t,resources:r,runtime:n})=>{let{audio:o}=e;if(t.sfx&&r){let i=t.sfx.items;for(let[s,l]of i.entries()){let c=r.sounds?.[l.resourceId];c&&o.push({id:ka({item:l,index:s}),type:"sound",src:c.fileId,loop:l.loop??c.loop??!1,volume:La(n,l.volume??c.volume??Nt),startDelayMs:l.startDelayMs??c.startDelayMs??null})}}return e},Xa=(e,t,r)=>{if(!(!t||!r))return e?.voices?.[t]?.[r]},Qa=(e={},t={})=>t.muteAll?0:e.volume??t.soundVolume??50,Za=(e,{presentationState:t,resources:r,currentSceneId:n,runtime:o,variables:i})=>{let{audio:s}=e;if(!t?.voice)return e;let l=t.voice,{resourceId:c,loop:a,startDelayMs:u}=l,d=Xa(r,n,c);if(!d)return e;let f=fe({variables:i,runtime:o}).runtime;return s.push({id:`voice-${n}-${c}`,type:"sound",src:d.fileId,volume:Qa(l,f),loop:a??!1,startDelayMs:u??null}),e},ec=(e,{presentationState:t,previousPresentationState:r,resources:n={},variables:o,runtime:i,autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,form:d,saveSlots:f=[],isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})=>{let{elements:y,animations:b}=e;if(t.layout){let T=Ke(y);if(!T)return e;let E=n.layouts[t.layout.resourceId];if(!E)return e;Array.isArray(E.transitions)&&!p&&!h&&zr({animations:b,transitions:E.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let N={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:E.elements||[]};T.children.push(Oo({container:N,resources:n,templateData:fe({variables:o,runtime:i,saveSlots:f,dialogueState:t.dialogue,isLineCompleted:p,autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,form:d,characters:n.characters||{},skipTransitionsAndAnimations:h}),isLineCompleted:p,skipMode:l,skipTransitionsAndAnimations:h}))}let A=r?.layout?.resourceId,x=t.layout?.resourceId,S=we({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 de({animationInstances:S,isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})&&b.push(...S),e},tc=(e,{currentLineActions:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:l}=e,c=t?.screen?.animations;if(!c)return e;let a=r!=null,u=we({animationsDef:c,resources:n,previousResourceId:a?"story":void 0,currentResourceId:"story",previousTargetId:a?"story":void 0,currentTargetId:"story",animationPath:"screen.animations",idPrefix:"screen"});return de({animationInstances:u,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...u),e},rc=(e,{presentationState:t,resources:r={},variables:n,runtime:o,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:c,canRollback:a,form:u,overlayStack:d=[],dialogueHistory:f=[],saveSlots:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:b,animations:A}=e;return d&&d.length>0&&d.forEach((x,S)=>{let T=r.layouts[x.resourceId];if(!T){console.warn(`Overlay layout not found: ${x.resourceId}`);return}Array.isArray(T.transitions)&&(y||zr({animations:A,transitions:T.transitions,defaultTargetId:`overlayStack-${S}`,idPrefix:`overlayStack-${S}`,animationPathPrefix:`overlayStack[${S}]`}));let E={id:`overlayStack-${S}`,type:"container",x:0,y:0,children:[_o({id:`overlayStack-${S}-blocker`,screen:h}),...T.elements||[]]},N=Ro(f,r.characters),B=fe({variables:n,runtime:o,saveSlots:p,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:c,canRollback:a,form:u,historyDialogue:N,characters:r.characters||{},skipTransitionsAndAnimations:y}),k=ee(E,B,{functions:_e}),[j,...F]=k.children||[],M=Re(Oe({...k,children:F},{isLineCompleted:g,skipMode:s,skipTransitionsAndAnimations:y}),r);b.push({...M,children:j?[j,...M.children||[]]:M.children})}),e},nc=(e,{presentationState:t,resources:r={},variables:n,runtime:o,saveSlots:i=[],autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,form:d,confirmDialog:f,dialogueHistory:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:b,animations:A}=e;if(!f?.resourceId)return e;let x=r.layouts?.[f.resourceId];if(!x)return console.warn(`ConfirmDialog layout not found: ${f.resourceId}`),e;Array.isArray(x.transitions)&&!y&&zr({animations:A,transitions:x.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let S={id:"confirmDialog",type:"container",x:0,y:0,children:[_o({id:"confirmDialog-blocker",screen:h}),...x.elements||[]]},T=Ro(p,r.characters),E=ee(S,fe({variables:n,runtime:o,saveSlots:i,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,form:d,confirmDialog:f,historyDialogue:T,characters:r.characters||{},skipTransitionsAndAnimations:y}),{functions:_e}),[N,...B]=E.children||[],k=Re(Oe({...E,children:B},{isLineCompleted:g,skipMode:l,skipTransitionsAndAnimations:y}),r);return b.push({...k,children:N?[N,...k.children||[]]:k.children}),e},Vt=e=>(t,r)=>za(t,{...r,visualLayer:e}),oc=Vt(Se.BEHIND_BACKGROUND),ic=Vt(Se.BEHIND_CHARACTER),sc=Vt(Se.BEHIND_DIALOGUE),ac=Vt(Se.FOREGROUND),$o=e=>_t(Ma,[Ka,oc,Fa,ic,Ua,sc,qa,Ya,Ha,ec,ac,tc,Ga,Ja,Za,rc,nc])(e);var jt={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},No=1,Hr="choice",Mt="form",Bt=()=>({manual:{...jt.manual},auto:{...jt.auto},applyMode:jt.applyMode}),Kr=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let r=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...Bt()},r&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},P=e=>{let t=re(e)?De(e):e;return structuredClone(t)},D=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),zt=e=>String(e),Vo=()=>({sections:[],resources:[]}),cc=e=>D(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):Vo(),lc=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",uc=({sectionId:e,lineId:t,content:r,dialogueState:n,characterName:o})=>({sectionId:e,lineId:t,content:r,text:lc(r),characterId:n.characterId,character:{...n.character||{},name:o},characterName:o}),dc=()=>({resourceId:void 0}),fc=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},Gr=(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}},jo=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 l=r.get(s);if(l!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${l}" and "${n}". Section IDs must be globally unique.`);r.set(s,n)}}},Mo=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},Fo=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==No)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},pc=(e,t={})=>{let r;try{r=Fo(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let n={...t,formatVersion:r,slotId:Mo(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete n.slotKey,delete n.date,n},hc=(e={})=>Object.fromEntries(Object.entries(e).map(([t,r])=>[t,pc(t,r)])),Uo=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:r})=>ou(r));return t.length>0?t:void 0},mc=e=>{!D(e)||!Array.isArray(e.timeline)||e.timeline.forEach(t=>{if(!D(t))return;let r=Uo(t.executedActions);if(r){t.executedActions=r;return}delete t.executedActions})},ko=(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}},gc=(e,t="viewedRegistry")=>{if(e===void 0)return Vo();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=ko(o,"sections",i,t);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(n.map((o,i)=>{let s=ko(o,"resources",i,t);return[s.resourceId,s]})))}},Bo=(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}=Gr(t,n);if(!s)throw new Error(`Malformed save slot ${r}: section "${n}" does not exist in projectData.`);if(!s.lines?.some(c=>c.id===o))throw new Error(`Malformed save slot ${r}: line "${o}" does not exist in section "${n}".`);return{sceneId:i,sectionId:n,lineId:o}},yc=(e,t,r)=>{if(!D(e)||!Array.isArray(e.timeline))return ut({pointer:t,replayStartIndex:1});let n=e.timeline.flatMap((l,c)=>{if(!D(l))return[];try{let a=Bo(l,r,`rollback.timeline[${c}]`),u=Ut({sectionId:a.sectionId,lineId:a.lineId,rollbackPolicy:l.rollbackPolicy}),d=Uo(P(l.executedActions));return d&&(u.executedActions=d),[u]}catch{return[]}});if(n.length===0)return ut({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 l=n.findLastIndex(c=>c.sectionId===t.sectionId&&c.lineId===t.lineId);l>=0?o=l:(n.push(Ut({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}},bc=(e,t,r)=>{if(!D(e))throw new Error(`Malformed save slot contexts[${r}] entry.`);let n=Qr(t),o=Bo(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?We(P(e.variables),t.resources?.variables??{}):{},s=$c({loadedContextRuntime:D(e.runtime)?P(e.runtime):{}}),l={currentPointerMode:"read",pointers:{read:o},configuration:D(e.configuration)?P(e.configuration):{},views:Array.isArray(e.views)?P(e.views):[],bgm:D(e.bgm)?P(e.bgm):{resourceId:void 0},variables:{...n,...i},rollback:yc(e.rollback,o,t)};return s&&(l.runtime=s),l},Ic=(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)=>bc(r,t,n))}},Ac=(e,t)=>{if(!D(e))throw new Error("Malformed save slot.");let r=Fo(e.formatVersion);return{...e,formatVersion:r,state:Ic(e.state,t)}},Do=(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=P(e);return Object.prototype.hasOwnProperty.call(n,"hideConfirmDialog")||(n.hideConfirmDialog={}),n},wc=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:Do(e.confirmActions,"confirmActions",{required:!0}),cancelActions:Do(e.cancelActions,"cancelActions")}},Je=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},Ec=e=>(D(e.global.formDrafts)||(e.global.formDrafts={}),e.global.formDrafts),Xe=e=>{Object.prototype.hasOwnProperty.call(e.global,"formDrafts")&&(e.global.formDrafts={})},zo=e=>{if(!(!D(e)||!e.animations))return{animations:P(e.animations)}},vc=(e,t)=>{let r=zo(t);if(r){e.global.pendingScreenTransition=r;return}delete e.global.pendingScreenTransition},xc=e=>{let t=e?.id??e?.resourceId;return typeof t=="string"&&t.length>0?t:void 0},Cc=(e,t)=>{let r=e?.sectionId,n=e?.lineId;if(!(!r||!n||!t))return`${r}:${n}:${t}`},Ft=e=>String(e??""),Wo=(e,t)=>{let r=Ft(t);return e?.trim===!0?r.trim():r},Sc=e=>D(e?.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,t])=>D(t)).map(([t,r])=>[t,{id:t,...P(r)}])):{},_c=(e,t)=>{if(!t||!D(e.global.formDrafts))return;let r=e.global.formDrafts[t];return D(r)?r:void 0},qo=(e,t)=>{let r=Ec(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},Jr=(e,t)=>{let r=Wo(e,t);return e?.required===!0&&r.length===0?"required":null},Rc=({state:e,pointer:t})=>{if(!t?.sectionId||!t?.lineId)return{};let n=X({state:e},{sectionId:t.sectionId})?.lines||[],o=n.findIndex(i=>i.id===t.lineId);return o<0?{}:Te(n.slice(0,o+1).map(i=>i.actions||{}))},Oc=({state:e,form:t,pointer:r})=>{if(!t?.resourceId)return null;let n=xc(t),o=Cc(r,n);if(!n||!o)return null;let i=_c(e,o),s=Sc(t),l=nn({state:e}),c={},a=[],u={},d=!0;return Object.entries(s).forEach(([f,p])=>{let h=Ft(l?.[p.variableId]),g=Object.prototype.hasOwnProperty.call(i?.values??{},f)?Ft(i.values[f]):h,y=i?.touched?.[f]===!0,b=Jr(p,g),A=i?.submitted||y?b:null,x=typeof p.maxLength=="number"?Math.max(0,Math.round(p.maxLength)):void 0,S={id:f,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&&(d=!1),c[f]=S,a.push(S),u[f]=g}),{id:n,key:o,resourceId:t.resourceId,animations:t.animations,valid:d,submitted:i?.submitted===!0,fields:c,fieldList:a,values:u,submitActions:{submitForm:{formId:n,formKey:o,actions:P(t.submitActions??{})}},cancelActions:{cancelForm:{formId:n,formKey:o,actions:P(t.cancelActions??{})}}}},Ve=[],Po="line",Xr="interaction",Ut=({sectionId:e,lineId:t,rollbackPolicy:r})=>({sectionId:e,lineId:t,rollbackPolicy:r??"free"}),Qr=e=>{let{contextVariableDefaultValues:t}=yr(e??{});return P(t)},Yo=()=>({...P(st)}),Ho=({loadedRuntime:e,runtimeIds:t,defaults:r={},path:n})=>{if(e===void 0)return{runtimeState:P(r),hasLoadedValues:!1};if(!D(e))throw new Error(`Malformed ${n}.`);let o=P(r),i=!1;return t.forEach(s=>{e[s]!==void 0&&(o[s]=Ko(s,P(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},Lc=({loadedGlobalRuntime:e={}})=>Ho({loadedRuntime:e,runtimeIds:Er,defaults:Ne,path:"global.runtime"}).runtimeState,$c=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:r}=Ho({loadedRuntime:e,runtimeIds:vr,defaults:Yo(),path:"context.runtime"});return r?t:void 0},Zr=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},kc=e=>e.runtime?(vr.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=P(st[t]))}),e.runtime):(e.runtime=Yo(),e.runtime),Dc=e=>no(e.global),Pc=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:Dc(e)}})},Tc=e=>ro[e],Nc=(e,t)=>{let r=Tc(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}"`)},Ko=(e,t)=>(Nc(e,t),e==="saveLoadPagination"?Math.max(1,Math.trunc(t)):t),Go=(e,t,r)=>{let n=Ko(t,r);if(t in st){let o=Zr(e);if(!o)return n;let i=kc(o);return i[t]=n,n}return e.global[t]=n,n},Jo=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:P(e)},configuration:{},views:[],bgm:dc(),variables:Qr(t),rollback:ut({pointer:e})}),Qe=e=>e?(e.currentPointerMode="read",D(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,Vc=(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=Jo({pointer:n,projectData:e.projectData});return e.contexts[e.contexts.length-1]=o,jc(e,{queueRender:t}),o},jc=(e,{queueRender:t=!0}={})=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,Je(e),Xe(e),e.global.nextLineConfig=Bt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"}),t&&e.global.pendingEffects.push({name:"render"})},Xo=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},ut=({pointer:e,replayStartIndex:t=0})=>{let r=e?.sectionId&&e?.lineId;return{currentIndex:r?0:-1,isRestoring:!1,replayStartIndex:t,timeline:r?[Ut({sectionId:e.sectionId,lineId:e.lineId})]:[]}},Me=(e,t={})=>{if(e?.rollback)return Xo(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=ut({pointer:r,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},en=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return;let n=Me(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(Ut(t)),n.currentIndex=n.timeline.length-1},Mc=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=Ve[Ve.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)},Fc=({state:e},t={})=>{let r=t?.source===Po?Po:Xr,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?(Ve.push({checkpointIndex:null,source:r}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),Ve.push({checkpointIndex:o.currentIndex,source:r}),e)},Uc=({state:e})=>(Ve.pop(),e),be=(e,t,r)=>{let o=Ve[Ve.length-1]?.source??Xr;if(!iu(t,o))return;let i=Mc(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:P(r)}))},To=(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:l}of n){let c=e.projectData.resources?.variables?.[o],a=c?.scope,u=c?.type;if(Ce(c))throw new Error(`Cannot update computed variable: ${o}`);if(c?.readonly===!0)throw new Error(`Cannot update readonly variable: ${o}`);Ot(a,o),Lt(u,i,o),br(u,i,s,o,{roundTo:l}),a==="context"&&(r.variables[o]=$t(r.variables[o],i,s,{roundTo:l}))}},Bc=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:r,payload:n})=>{su(e,r,n)})},zc=(e,t)=>{let{sectionId:r,lineId:n}=t,s=X({state:e},{sectionId:r})?.lines?.find(l=>l.id===n)?.actions;s&&Object.entries(s).forEach(([l,c])=>{hi(e,l,c)})},Qo=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let n=Me(r),o=n.timeline[t];if(!o)return e;e.global.autoMode&&ft({state:e}),e.global.skipMode&&je({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),n.isRestoring=!0,n.currentIndex=t;try{r.variables=Qr(e.projectData),delete r.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=P(jt),e.global.overlayStack=[],Je(e),Xe(e),e.global.isLineCompleted=!0;let i=n.replayStartIndex??0;for(let l=i;l<=t;l++)l>i&&Kr(e),zc(e,n.timeline[l]),Bc(e,n.timeline[l]);let s=Qe(r);s.read={sectionId:o.sectionId,lineId:o.lineId},e.global.pendingEffects=e.global.pendingEffects.filter(l=>l?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{n.isRestoring=!1}return e},Wc=e=>{let{projectData:t}=e,r=e.global??{},{saveSlots:n={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=r;jo(t);let l=t.story.initialSceneId,c=t.story.scenes[l],a=c.initialSectionId,u=c.sections[a],d={sceneId:l,sectionId:a,lineId:u.initialLineId??u.lines[0].id},{globalVariablesDefaultValues:f}=yr(t),p={...f,...We(o,t.resources?.variables??{})};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,formDrafts:{},accountViewedRegistry:gc(s,"accountViewedRegistry"),nextLineConfig:Bt(),saveSlots:hc(n),overlayStack:[],variables:p,...Lc({loadedGlobalRuntime:i})},contexts:[Jo({pointer:d,projectData:t})]}},qc=({state:e})=>e.global.overlayStack||[],Yc=({state:e})=>e.global.pendingEffects,Zo=({state:e})=>e.global.skipMode,Hc=({state:e})=>e.global.autoMode,ei=({state:e})=>e.global.dialogueUIHidden,ti=({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=X({state:e},{sectionId:n});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(u=>u.id===o),l=i.lines.slice(0,s+1),c=[],a={};for(let u of l){let d=u.actions||{};if(a=Te([a,d]),!d.dialogue)continue;let f=a.dialogue||{},p="";f.character?.name!==void 0?p=f.character.name:f.characterId&&(p=e.projectData.resources?.characters?.[f.characterId]?.name||"");let h=uc({sectionId:n,lineId:u.id,content:d.dialogue.append===!0?f.content:d.dialogue.content,dialogueState:f,characterName:p});if(d.dialogue.append===!0&&c.length>0){c[c.length-1]={...c[c.length-1],content:h.content,text:h.text,characterId:h.characterId,character:h.character,characterName:h.characterName};continue}c.push(h)}return c},Kc=({state:e})=>e.global.confirmDialog??null,dt=({state:e},{pointer:t}={})=>{let r=t??pe({state:e})?.pointer,n=Rc({state:e,pointer:r});return Oc({state:e,form:n.form,pointer:r})},Gc=({state:e},{pointer:t}={})=>!!dt({state:e},{pointer:t}),Ie=({state:e},{pointer:t}={})=>{let r=dt({state:e},{pointer:t});if(r)return{source:Mt,formId:r.id,formKey:r.key};let n=ri({state:e,pointer:t});return n?{source:Hr,resourceId:n}:null},Jc=({state:e,registry:t},r)=>{let{sectionId:n,lineId:o}=r,s=(Array.isArray(t?.sections)?t.sections:[]).find(u=>u.sectionId===n);if(!s)return!1;if(s.lastLineId===void 0||o===void 0)return!0;let l=X({state:e},{sectionId:n});if(!l||!l.lines||!Array.isArray(l.lines))return s.lastLineId===o;let c=l.lines.findIndex(u=>u.id===s.lastLineId),a=l.lines.findIndex(u=>u.id===o);return c===-1||a===-1?s.lastLineId===o:a<=c},Xc=({registry:e},t)=>{let{resourceId:r}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===r)},tn=({state:e},t)=>Jc({state:e,registry:e.global.accountViewedRegistry},t),Qc=({state:e},t)=>Xc({registry:e.global.accountViewedRegistry},t),Zc=({state:e})=>e.global.nextLineConfig,ri=({state:e,pointer:t}={})=>{let r=t??pe({state:e})?.pointer;if(!r)return;let n=r?.sectionId,o=r?.lineId,s=X({state:e},{sectionId:n})?.lines||[],l=s.findIndex(a=>a.id===o);if(l<0)return;let c;for(let a of s.slice(0,l+1)){let u=a?.actions;if(u?.cleanAll&&(c=void 0),!u||!Object.prototype.hasOwnProperty.call(u,"choice")){c=void 0;continue}let d=u.choice;if(d?.resourceId){c=d.resourceId;continue}d?.animations||(c=void 0)}return c},ni=({state:e})=>!!ri({state:e}),el=({state:e})=>structuredClone(e),oi=({state:e})=>e.global.saveSlots,tl=({state:e},t)=>{let r=t?.slotId,n=zt(r);return e.global.saveSlots[n]},rn=({state:e})=>qe(e),rl=({state:e},t)=>Ae(e,t?.runtimeId),nn=({state:e})=>{let t={...e.global?.variables??{},...Zr(e)?.variables??{}};return Rt({variables:t,runtime:qe(e),variableConfigs:e.projectData.resources?.variables??{}})},pe=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],r=t[t.length-1];if(r)return{currentPointerMode:"read",pointer:r.pointers?.read}},X=({state:e},t)=>{let{sectionId:r}=t;return Gr(e.projectData,r).section},on=({state:e})=>{let t=pe({state:e});if(!t?.pointer)return;let{sectionId:r,lineId:n}=t.pointer,o=X({state:e},{sectionId:r});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===n)},ii=({state:e})=>{let{sectionId:t,lineId:r}=pe({state:e}).pointer,o=X({state:e},{sectionId:t})?.lines||[],i=o.findIndex(a=>a.id===r),l=o.slice(0,i+1).map(a=>{let u=a.actions||{},d={};return Object.keys(u).forEach(f=>{d[f]=u[f]}),d});return Te(l)},nl=({state:e})=>{let t=si({state:e}),n=on({state:e})?.actions??{},o=Te([t??{},n]);return Ir(t??{},o??{})},ol=({state:e},{sectionId:t})=>{let r=X({state:e},{sectionId:t});if(!r?.lines)return[];let n=[],o={};for(let i of r.lines){let s=i.actions||{},l=Te([o,s]),c=Ir(o,l);n.push({id:i.id,changes:c,presentationState:l}),o=Ar(l)}return n},il=({state:e},{sectionId:t,includePresentationState:r=!1})=>{let n=ol({state:e},{sectionId:t});return r?{lines:n}:{lines:n.map(({presentationState:o,...i})=>i)}},si=({state:e})=>{let{sectionId:t,lineId:r}=pe({state:e}).pointer,o=X({state:e},{sectionId:t})?.lines||[],i=o.findIndex(c=>c.id===r);if(i<=0)return null;let l=o.slice(0,i).map(c=>{let a=c.actions||{},u={};return Object.keys(a).forEach(d=>{u[d]=a[d]}),u});return Ar(Te(l))},sn=({state:e},{slotsPerPage:t=6}={})=>{let o=((rn({state:e}).saveLoadPagination??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let l=o+s,c=e.global.saveSlots&&e.global.saveSlots[zt(l)]||{};i.push({...c,slotId:l})}return{saveSlots:i}},sl=oi,al=sn,cl=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},ll=({state:e},t={})=>{let r=ii({state:e}),n=si({state:e}),o=on({state:e})?.actions??{},i=e.global.pendingScreenTransition,s=i?.animations?{...o,screen:P(i)}:o,l=i?.animations&&n===null?{}:n,{sectionId:c}=pe({state:e}).pointer,{sceneId:a}=Gr(e.projectData,c),u=rn({state:e}),d=t?.activePersistentAnimations??[],f=t?.restoredPersistentAnimations??[],p=dt({state:e}),h=ni({state:e}),g=nn({state:e}),{saveSlots:y}=sn({state:e}),b=cl(e);return $o({presentationState:r,previousPresentationState:l,currentLineActions:s,resources:e.projectData.resources,currentSceneId:a,screen:e.projectData.screen,dialogueUIHidden:u.dialogueUIHidden,autoMode:u.autoMode,skipMode:u.skipMode,isChoiceVisible:h,isFormVisible:!!p,canRollback:gi({state:e}),skipOnlyViewedLines:!u.skipUnseenText,isLineCompleted:u.isLineCompleted,skipTransitionsAndAnimations:!!u.skipTransitionsAndAnimations||b,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,form:p,dialogueHistory:ti({state:e}),saveSlots:y,variables:g,runtime:u,activePersistentAnimations:d,restoredPersistentAnimations:f})},ul=({state:e},t)=>(e.global.confirmDialog=wc(t),e.global.pendingEffects.push({name:"render"}),e),dl=({state:e})=>(e.global.confirmDialog&&(Je(e),e.global.pendingEffects.push({name:"render"})),e),fl=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),be(e,"pushOverlay",t),e),pl=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),be(e,"popOverlay",void 0),e),hl=({state:e},t)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=t),e.global.pendingEffects.push({name:"render"}),be(e,"replaceLastOverlay",t),e),ml=({state:e})=>(e.global.overlayStack=[],Je(e),Xe(e),e.global.pendingEffects.push({name:"render"}),be(e,"clearOverlays",void 0),e),gl=e=>{e.global.autoMode&&(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"})),e.global.skipMode&&(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"})),e.global.nextLineConfig?.auto?.enabled&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},Wt=(e,t,{screenTransition:r}={})=>{e.global.isLineCompleted=!1,vc(e,r),Xe(e);let n=Ie({state:e},{pointer:t}),o=n?.source===Hr,i=n?.source===Mt;return n&&gl(e),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:o,isFormVisible:i,activeInteraction:n}},ai=({state:e})=>(Ie({state:e})||(e.global.skipMode&&(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"})),e.global.autoMode=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.isLineCompleted&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:Ae(e,"autoForwardDelay")}}),e.global.pendingEffects.push({name:"render"})),e),ft=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),yl=({state:e})=>{let t=e.global.autoMode;return Ie({state:e})&&!t||(t?ft({state:e}):ai({state:e})),e},ci=({state:e})=>(Ie({state:e})||(e.global.autoMode&&(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"})),e.global.skipMode=!0,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"startSkipNextTimer"}),e.global.pendingEffects.push({name:"render"})),e),je=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),bl=({state:e})=>{let t=Zo({state:e});return Ie({state:e})&&!t||(t?je({state:e}):ci({state:e})),e},qt=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),be(e,"showDialogueUI",void 0),e),li=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),be(e,"hideDialogueUI",void 0),e),Il=({state:e})=>(ei({state:e})?qt({state:e}):li({state:e}),e),Fe=(e,t,r)=>(Go(e,t,r),Pc(e),e.global.pendingEffects.push({name:"render"}),e),pt=(e,t,r,n)=>{let o=Go(e,t,r);return e.global.pendingEffects.push({name:"render"}),be(e,n,{value:o}),e},Al=({state:e},t)=>Fe(e,"dialogueTextSpeed",t?.value),wl=({state:e},t)=>Fe(e,"autoForwardDelay",t?.value),El=({state:e},t)=>Fe(e,"skipUnseenText",t?.value),vl=({state:e},t)=>Fe(e,"skipTransitionsAndAnimations",t?.value),xl=({state:e},t)=>Fe(e,"soundVolume",t?.value),Cl=({state:e},t)=>Fe(e,"musicVolume",t?.value),Sl=({state:e},t)=>Fe(e,"muteAll",t?.value),_l=({state:e},t)=>pt(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),Rl=({state:e})=>{let t=Ae(e,"saveLoadPagination")+1;return pt(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},Ol=({state:e})=>{let t=Ae(e,"saveLoadPagination")-1;return pt(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},Ll=({state:e},t)=>pt(e,"menuPage",t?.value,"setMenuPage"),$l=({state:e},t)=>pt(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),kl=({state:e})=>(e.global.pendingEffects=[],e),Dl=({state:e},t)=>(e.global.pendingEffects.push(t),e),ui=(e,{sectionId:t,resetStoryState:r=!1,screen:n})=>{let o=!!zo(n),i=X({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&&!Vc(e,{queueRender:!o}))return e;e.global.autoMode&&ft({state:e}),r&&e.global.skipMode&&je({state:e});let l=e.contexts?.[e.contexts.length-1];if(l){let c=Qe(l),a=c.read;r||Ge(e,{sectionId:a?.sectionId,lineId:a?.lineId}),l.rollback||Me(l,{compatibilityAnchor:!0}),c.read={sectionId:t,lineId:s.id},r?l.rollback=ut({pointer:c.read}):en(e,{sectionId:t,lineId:s.id})}return Wt(e,l?.pointers?.read,{screenTransition:n}),e},Pl=({state:e},t)=>ui(e,{sectionId:t?.sectionId,resetStoryState:!0,screen:t?.screen}),di=e=>(e.global.accountViewedRegistry=cc(e.global.accountViewedRegistry),e.global.accountViewedRegistry),an=(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:P(r.value)}))}})},fi=(e,t)=>{an(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:[]}}])},Tl=(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=X({state:e},{sectionId:r});if(s?.lines){let l=s.lines.findIndex(a=>a.id===i.lastLineId),c=s.lines.findIndex(a=>a.id===n);if(l===-1||c>l)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},Ge=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;Tl(e,di(e),t)&&fi(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},Nl=({state:e},t)=>(Ge(e,t),e.global.pendingEffects.push({name:"render"}),e),Vl=({state:e},t)=>{let{resourceId:r}=t;if(e.global.accountViewedRegistry!==void 0){let n=di(e);n.resources.find(i=>i.resourceId===r)||(n.resources.push({resourceId:r}),fi(e,{sections:[],resources:[{resourceId:r}]}))}return e.global.pendingEffects.push({name:"render"}),e},pi=({state:e},t)=>{let r=fc(t.manual),{auto:n,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,l=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 c=e.global.nextLineConfig.auto?.enabled,a=Ie({state:e});return!l&&!a&&c===!0&&!i?e.global.nextLineConfig.auto?.trigger==="fromStart"?e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):e.global.isLineCompleted&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):!l&&c===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),be(e,"setNextLineConfig",t),e},jl=({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=zt(r),s=P(e.contexts);s?.forEach(a=>{Qe(a),Xo(a.rollback),mc(a.rollback)});let l={contexts:s},c={formatVersion:No,slotId:Mo(r),savedAt:typeof o=="number"?o:Date.now(),image:n,state:l};return e.global.saveSlots[i]=c,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},Ml=({state:e},t)=>{let r=t?.slotId;if(r==null||r==="")throw new Error("loadSlot requires slotId");let n=zt(r),o=e.global.saveSlots[n];if(o){let i=Ac(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=Bt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,Je(e),Xe(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},Fl=({state:e},t)=>{let{projectData:r}=t;jo(r),e.projectData=r;let n=r?.resources?.variables??{};return Object.prototype.hasOwnProperty.call(e.global??{},"variables")&&(e.global.variables=We(e.global.variables,n)),e.contexts?.forEach(o=>{Object.prototype.hasOwnProperty.call(o??{},"variables")&&(o.variables=We(o.variables,n))}),Je(e),Xe(e),e.global.pendingEffects.push({name:"render"}),e},Ul=({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&&!X({state:e},{sectionId:r}))return console.warn(`Section not found: ${r}`),e;let s=X({state:e},{sectionId:i});if(!s?.lines||!Array.isArray(s.lines))return console.warn(`Section ${i} has no lines`),e;if(!s.lines.find(a=>a.id===n))return console.warn(`Line not found: ${n} in section ${i}`),e;let c=Qe(o);return c.read={sectionId:i,lineId:n},Wt(e,c.read),e},Bl=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return qt({state:e}),e;let r=Ie({state:e});if(r?.source===Hr&&t?.bypassChoice!==!0||r?.source===Mt&&t?._interactionSource!==Mt)return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let u=pe({state:e})?.pointer,d=u?.sectionId,f=u?.lineId;d&&f&&Ge(e,{sectionId:d,lineId:f}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:Ae(e,"autoForwardDelay")}});let p=e.global.nextLineConfig;return p?.auto?.enabled&&p.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:p.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e}let n=pe({state:e})?.pointer,o=n?.sectionId,i=X({state:e},{sectionId:o}),s=e.contexts[e.contexts.length-1],l=i?.lines||[],a=l.findIndex(u=>u.id===n?.lineId)+1;if(a<l.length){let u=l[a],d=!Ae(e,"skipUnseenText");if(e.global.skipMode&&d&&!tn({state:e},{sectionId:o,lineId:u.id}))return je({state:e}),e;if(s&&!s.rollback&&Me(s,{compatibilityAnchor:!0}),s){let h=Qe(s),g=h.read?.lineId;g&&o&&Ge(e,{sectionId:o,lineId:g}),h.read={sectionId:o,lineId:u.id}}en(e,{sectionId:o,lineId:u.id}),Kr(e);let{activeInteraction:f}=Wt(e,{sectionId:o,lineId:u.id}),p=e.global.nextLineConfig;p?.auto?.enabled&&!f&&p.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:p.auto.delay}})}else e.global.autoMode&&ft({state:e}),e.global.skipMode&&je({state:e});return e},zl=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=Ie({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:Ae(e,"autoForwardDelay")}});let r=pe({state:e})?.pointer,n=r?.sectionId,o=r?.lineId;n&&o&&Ge(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},Wl=({state:e},t)=>ui(e,{sectionId:t?.sectionId,screen:t?.screen}),ql=({state:e})=>{if(e.global.dialogueUIHidden)return qt({state:e}),e;if(Ie({state:e}))return e;let t=pe({state:e})?.pointer,r=t?.sectionId,n=X({state:e},{sectionId:r}),o=e.contexts[e.contexts.length-1],i=n?.lines||[],l=i.findIndex(c=>c.id===t?.lineId)+1;if(l<i.length){let c=i[l],a=!Ae(e,"skipUnseenText");if(e.global.skipMode&&a&&!tn({state:e},{sectionId:r,lineId:c.id}))return je({state:e}),e;if(o&&!o.rollback&&Me(o,{compatibilityAnchor:!0}),o){let d=Qe(o),f=d.read?.lineId;f&&r&&Ge(e,{sectionId:r,lineId:f}),d.read={sectionId:r,lineId:c.id}}en(e,{sectionId:r,lineId:c.id}),Kr(e);let{activeInteraction:u}=Wt(e,{sectionId:r,lineId:c.id});e.global.nextLineConfig.auto?.enabled&&!u&&e.global.nextLineConfig.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}})}else e.global.nextLineConfig.auto?.enabled&&(e.global.nextLineConfig.auto.enabled=!1,e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}));return e},cn=(e,t={})=>{let r=dt({state:e});return!r||t.formKey&&t.formKey!==r.key||t.formId&&t.formId!==r.id?null:r},Yl=(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(Ce(r))throw new Error(`Cannot update computed variable: ${t.variableId}`);if(r?.readonly===!0)throw new Error(`Cannot update readonly variable: ${t.variableId}`);return Ot(n,t.variableId),Lt(o,"set",t.variableId),{variableConfig:r,scope:n}},Hl=(e,t)=>({id:e.id,key:e.key,valid:!0,values:P(t),fields:P(e.fields),fieldList:P(e.fieldList)}),Kl=({state:e},t={})=>{let r=cn(e,t),n=t.field;if(!r?.fields?.[n])return e;let o=qo(e,r.key),i=Ft(t.value),s=r.fields[n],l=Jr(s,i);return o.values[n]=i,o.touched[n]=!0,l?o.errors[n]=l:delete o.errors[n],e.global.pendingEffects.push({name:"render"}),e},Gl=({state:e},t={})=>{let r=cn(e,t);if(!r)return{submitted:!1,valid:!1,reason:"inactive"};let n=qo(e,r.key);n.submitted=!0;let o={},i={};if(Object.entries(r.fields).forEach(([d,f])=>{let p=Object.prototype.hasOwnProperty.call(n.values,d)?n.values[d]:f.value,h=Jr(f,p);n.touched[d]=!0,h&&(i[d]=h),o[d]=Wo(f,p)}),n.errors=i,Object.keys(i).length>0)return e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!1,errors:P(i),form:{id:r.id,key:r.key,values:P(o)}};let s=e.contexts[e.contexts.length-1];if(s?.rollback?.isRestoring)return{submitted:!1,valid:!1,reason:"restoring"};let l=!1,c=[],a=[];Object.entries(r.fields).forEach(([d,f])=>{let{scope:p}=Yl(e,f),h=p==="context"?s.variables:e.global.variables,g=o[d];h[f.variableId]=$t(h[f.variableId],"set",g),p==="context"&&(l=!0,a.push({variableId:f.variableId,op:"set",value:g})),(p==="device"||p==="account")&&c.push({scope:p,path:`variables.${f.variableId}`,op:"set",value:P(h[f.variableId])})}),l&&be(e,"updateVariable",{id:"submitForm",operations:a}),an(e,c);let u=Hl(r,o);return delete e.global.formDrafts[r.key],e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!0,form:u}},Jl=({state:e},t={})=>{let r=cn(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:P(r.values),fields:P(r.fields),fieldList:P(r.fieldList)}}):{cancelled:!1,reason:"inactive"}},Xl=({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=[],l=[];return n.forEach(({variableId:c,op:a,value:u,roundTo:d})=>{let f=e.projectData.resources?.variables?.[c],p=f?.scope,h=f?.type;if(Ce(f))throw new Error(`Cannot update computed variable: ${c}`);if(f?.readonly===!0)throw new Error(`Cannot update readonly variable: ${c}`);Ot(p,c),Lt(h,a,c),br(h,a,u,c,{roundTo:d});let g=p==="context"?o.variables:e.global.variables;if(p==="context"){i=!0;let y={variableId:c,op:a,value:u};d!==void 0&&(y.roundTo=d),l.push(y)}g[c]=$t(g[c],a,u,{roundTo:d}),(p==="device"||p==="account")&&s.push({scope:p,path:`variables.${c}`,op:"set",value:P(g[c])})}),i&&be(e,"updateVariable",{id:r,operations:l}),an(e,s),e.global.pendingEffects.push({name:"render"}),e},Ql=e=>(t,r)=>e({state:t},r),Zl=e=>({variables:Rt({variables:{...e.global?.variables??{},...Zr(e)?.variables??{}},runtime:qe(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1}),runtime:qe(e)}),eu=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")},tu=(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")},ru=(e,t)=>{eu(t);for(let r=0;r<t.branches.length;r+=1){let n=t.branches[r];if(tu(n,r,t.branches.length),!(Object.prototype.hasOwnProperty.call(n,"when")&&!ot(n.when,Zl(e)))){Object.entries(n.actions).forEach(([i,s])=>{hi(e,i,s)});return}}},nu={conditional:{replayLine:ru},updateVariable:{recordSources:[Xr],replayLine:To,replayRecorded:To,persistInSaveSlot:!0},setNextLineConfig:{replayLine:Ql(pi)}},Yt=e=>nu[e]??null,ou=e=>Yt(e)?.persistInSaveSlot===!0,iu=(e,t)=>{let r=Yt(e)?.recordSources;return Array.isArray(r)&&r.includes(t)},su=(e,t,r)=>{Yt(t)?.replayRecorded?.(e,r)},hi=(e,t,r)=>{Yt(t)?.replayLine?.(e,r)},mi=({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}},gi=({state:e})=>mi({state:e},{offset:-1})!==null,au=({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=Me(n,{compatibilityAnchor:!n.rollback}),i=o.currentIndex+r;return i<0||i>=o.timeline.length?e:Qo(e,i)},cu=({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=Me(o,{compatibilityAnchor:!o.rollback}),l=i.timeline.slice(0,i.currentIndex+1).findLastIndex(c=>c.sectionId===r&&c.lineId===n);if(l===-1)throw new Error(`Line ${n} not found in section ${r} rollback timeline`);return l===i.currentIndex?e:Qo(e,l)},yi=e=>{let t=Wc(e);return Hn(t,{selectPendingEffects:Yc,selectSkipMode:Zo,selectAutoMode:Hc,selectIsChoiceVisible:ni,selectIsFormVisible:Gc,selectActiveInteraction:Ie,selectActiveForm:dt,selectDialogueUIHidden:ei,selectDialogueHistory:ti,selectConfirmDialog:Kc,selectIsLineAccountViewed:tn,selectIsResourceAccountViewed:Qc,selectNextLineConfig:Zc,selectSystemState:el,selectSaveSlotMap:oi,selectSaveSlots:sl,selectSaveSlot:tl,selectRuntime:rn,selectRuntimeValue:rl,selectAllVariables:nn,selectCurrentPointer:pe,selectSection:X,selectCurrentLine:on,selectPresentationState:ii,selectPresentationChanges:nl,selectSectionLineChanges:il,selectSaveSlotPage:sn,selectCurrentPageSlots:al,selectRenderState:ll,selectOverlayStack:qc,selectLineIdByOffset:mi,selectCanRollback:gi,startAutoMode:ai,stopAutoMode:ft,toggleAutoMode:yl,startSkipMode:ci,stopSkipMode:je,toggleSkipMode:bl,showDialogueUI:qt,hideDialogueUI:li,toggleDialogueUI:Il,setDialogueTextSpeed:Al,setAutoForwardDelay:wl,setSkipUnseenText:El,setSkipTransitionsAndAnimations:vl,setSoundVolume:xl,setMusicVolume:Cl,setMuteAll:Sl,setSaveLoadPagination:_l,incrementSaveLoadPagination:Rl,decrementSaveLoadPagination:Ol,setMenuPage:Ll,setMenuEntryPoint:$l,showConfirmDialog:ul,hideConfirmDialog:dl,resetStoryAtSection:Pl,clearPendingEffects:kl,appendPendingEffect:Dl,beginRollbackActionBatch:Fc,endRollbackActionBatch:Uc,addViewedLine:Nl,addViewedResource:Vl,setNextLineConfig:pi,saveSlot:jl,loadSlot:Ml,updateProjectData:Fl,sectionTransition:Wl,jumpToLine:Ul,nextLine:Bl,markLineCompleted:zl,rollbackToLine:cu,rollbackByOffset:au,pushOverlay:fl,popOverlay:pl,replaceLastOverlay:hl,clearOverlays:ml,updateFormField:Kl,submitForm:Gl,cancelForm:Jl,updateVariable:Xl,nextLineFromSystem:ql},{transformActionFirstArgument:n=>({state:n}),transformSelectorFirstArgument:n=>({state:n})})};var lu="route-engine",uu="projectPersistence";var Ii=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),G=e=>Object.prototype.toString.call(e)==="[object Object]",bi="variables.",du=(e={})=>{let t=G(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!G(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)}:!G(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},fu=(e={})=>{let t=G(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!G(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)}:!G(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},pu=(e,t)=>{let r=fu(e),n=du(t),o=r.sections.map(s=>({...s})),i=r.resources.map(s=>({...s}));return n.sections.forEach(s=>{let l=o.find(c=>c.sectionId===s.sectionId);if(!l){o.push({sectionId:s.sectionId,...s.lineId===void 0?{}:{lastLineId:s.lineId}});return}if(l.lastLineId!==void 0){if(s.lineId===void 0){delete l.lastLineId;return}l.lastLineId=s.lineId}}),n.resources.forEach(s=>{i.find(c=>c.resourceId===s.resourceId)||i.push({...s})}),{sections:o,resources:i}},Ai=(e={})=>{let t=G(e)?e:{};return{saveSlots:G(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:G(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:G(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:G(t.globalRuntime)?t.globalRuntime:{},accountViewedRegistry:G(t.accountViewedRegistry)?t.accountViewedRegistry:{}}},hu=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((t,r)=>{if(!G(t))throw new Error(`Malformed applyScopedDataUpdates.updates[${r}] entry.`);let n=t.path?.startsWith(bi)?t.path.slice(bi.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}].`)})},mu=(e,t)=>{let r={};return hu(t).forEach(n=>{if(n.path==="viewedRegistry"){r.accountViewedRegistry=pu(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},ln=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},gu=e=>{let t=ln(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},yu=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},bu=({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}".`))}}),Iu=async({databasePromise:e,objectStoreName:t,namespace:r})=>{let n=await e;return new Promise((o,i)=>{let c=n.transaction(t,"readonly").objectStore(t).get(r);c.onsuccess=()=>{o(c.result??null)},c.onerror=()=>{i(c.error??new Error(`Failed to read persisted namespace "${r}" from IndexedDB.`))}})},ht=async({databasePromise:e,objectStoreName:t,namespace:r,patch:n})=>{let o=await e;return new Promise((i,s)=>{let l=o.transaction(t,"readwrite"),c=l.objectStore(t),a=c.get(r),u=!1,d=p=>{u||(u=!0,s(p))},f=()=>{u||(u=!0,i())};a.onerror=()=>{d(a.error??new Error(`Failed to read persisted namespace "${r}" before updating IndexedDB.`))},a.onsuccess=()=>{let p=Ai(a.result),h=typeof n=="function"?n(p):n,g={namespace:r,version:1,...Ii(),...p,...h},y=c.put(g);y.onerror=()=>{d(y.error??new Error(`Failed to persist namespace "${r}" to IndexedDB.`))}},l.oncomplete=()=>{f()},l.onerror=()=>{d(l.error??new Error(`IndexedDB transaction failed while updating namespace "${r}".`))},l.onabort=()=>{d(l.error??new Error(`IndexedDB transaction aborted while updating namespace "${r}".`))}})},Au=async({databasePromise:e,objectStoreName:t,namespace:r})=>{let n=await e;return new Promise((o,i)=>{let s=n.transaction(t,"readwrite"),c=s.objectStore(t).delete(r),a=!1,u=f=>{a||(a=!0,i(f))},d=()=>{a||(a=!0,o())};c.onerror=()=>{u(c.error??new Error(`Failed to clear persisted namespace "${r}" from IndexedDB.`))},s.oncomplete=()=>{d()},s.onerror=()=>{u(s.error??new Error(`IndexedDB transaction failed while clearing namespace "${r}".`))},s.onabort=()=>{u(s.error??new Error(`IndexedDB transaction aborted while clearing namespace "${r}".`))}})},un=(e={})=>{let{indexedDB:t,databaseName:r=lu,objectStoreName:n=uu,namespace:o}=e,i=yu(t),s=gu(o),l=bu({indexedDB:i,databaseName:r,objectStoreName:n});return{namespace:s,load:async()=>{let c=await Iu({databasePromise:l,objectStoreName:n,namespace:s});return{...Ii(),...Ai(c)}},clear:async()=>Au({databasePromise:l,objectStoreName:n,namespace:s}),saveSlots:async c=>ht({databasePromise:l,objectStoreName:n,namespace:s,patch:{saveSlots:G(c)?c:{}}}),saveGlobalDeviceVariables:async c=>ht({databasePromise:l,objectStoreName:n,namespace:s,patch:{globalDeviceVariables:G(c)?c:{}}}),saveGlobalAccountVariables:async c=>ht({databasePromise:l,objectStoreName:n,namespace:s,patch:{globalAccountVariables:G(c)?c:{}}}),saveGlobalRuntime:async c=>ht({databasePromise:l,objectStoreName:n,namespace:s,patch:{globalRuntime:G(c)?c:{}}}),applyScopedDataUpdates:async c=>ht({databasePromise:l,objectStoreName:n,namespace:s,patch:a=>mu(a,c)})}},wu=un;var Eu=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),vu=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),wi="conditional",dn="form",xu=new Set(["submitForm","cancelForm"]),mt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function fn(e){let t,r=0,n=null,o=new Map,i=new Map,s=new Map,{handlePendingEffects:l}=e,c=(I=new Map,C=Date.now())=>new Map(Array.from(I.entries()).filter(([,O])=>C<O.expiresAt).map(([O,U])=>[O,{animation:structuredClone(U.animation),startedAt:U.startedAt,expiresAt:U.expiresAt}])),a=(I=new Map)=>Array.from(I.values()).map(C=>structuredClone(C.animation)),u=(I=Date.now())=>{o=new Map(Array.from(o.entries()).filter(([,C])=>I<C.expiresAt))},d=()=>{for(;t.selectPendingEffects().length>0;){let I=[...t.selectPendingEffects()];t.clearPendingEffects();try{l(I)}catch(C){throw t.clearPendingEffects(),I.forEach(O=>{t.appendPendingEffect(O)}),C}}},f=({initialState:I,namespace:C})=>{t=yi(I),r=0,n=ln(C),o=new Map,i=new Map,s=new Map,t.appendPendingEffect({name:"handleLineActions"}),d()},p=()=>n,h=()=>t.selectPresentationState(),g=()=>t.selectPresentationChanges(),y=I=>t.selectSectionLineChanges(I),b=(I={})=>{r+=1;let C=Date.now();u(C);let O=i.size>0,U=c(o,C),W=O?c(i,C):new Map,me={...t.selectRenderState({activePersistentAnimations:a(U),restoredPersistentAnimations:a(W)}),id:`render-${r}`};return s.set(me.id,{builtAt:C,persistentAnimationSessions:new Map([...W.entries(),...U.entries()]),usedRestoredPersistentAnimationSessions:O}),me},A=(I={})=>b(I),x=(I={})=>b(I),S=I=>{let C=typeof I?.id=="string"&&I.id.length>0?I.id:null,O=C?s.get(C):null;C&&s.delete(C);let U=new Map;Io(I?.animations).forEach(W=>{let ie=Pt(W);if(!ie)return;let me=O?.persistentAnimationSessions?.get(ie)??o.get(ie),gt=Math.max(0,wo(W)),mn=me?.startedAt??O?.builtAt??Date.now();U.set(ie,{animation:structuredClone(W),startedAt:mn,expiresAt:mn+gt})}),o=U,O?.usedRestoredPersistentAnimationSessions&&(i=new Map)},T=()=>t.selectSystemState(),E=()=>t.selectSaveSlotMap(),N=I=>t.selectSaveSlot(I),B=I=>t.selectSaveSlotPage(I),k=()=>t.selectSkipMode(),j=()=>t.selectAutoMode(),F=()=>t.selectRuntime(),M=()=>t.selectIsChoiceVisible(),q=()=>t.selectIsFormVisible(),v=()=>t.selectActiveInteraction(),_=(I,C,O={})=>I!=="nextLine"||!mt(C)?C:O.bypassChoice===!0?{...C,bypassChoice:!0}:O.interactionSource===dn?{...C,_interactionSource:dn}:C,R=(I,C)=>{if(!t[I])return;Eu.has(I)&&(vu.has(I)?i=c(o):i=new Map,o=new Map);let O=t[I](C);return d(),O},z=(I,C,O,U={})=>{if(I===wi){let W=V(O),ie=wr({[I]:C},W);Ue(ie[I],O,U);return}R(I,C)},Y=(I,C)=>{z(I,C)},V=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,...O}=I,U=t.selectAllVariables?t.selectAllVariables():void 0;return{...O,_event:C,variables:U,runtime:t.selectRuntime?t.selectRuntime():{}}},he=I=>{if(!mt(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")},Z=(I,C,O)=>{if(!mt(I))throw new Error(`conditional branch at index ${C} must be an object`);if(!mt(I.actions))throw new Error(`conditional branch at index ${C} requires actions object`);if(!Object.prototype.hasOwnProperty.call(I,"when")&&C!==O-1)throw new Error("conditional else branch must be the last branch")},Ue=(I,C,O)=>{he(I);for(let U=0;U<I.branches.length;U+=1){let W=I.branches[U];Z(W,U,I.branches.length);let ie=V(C);if(!(Object.prototype.hasOwnProperty.call(W,"when")&&!ot(W.when,ie))){Kt(W.actions,C,O);return}}},xi=(I,C)=>({...I??{},_form:C}),Ci=(I,C,O,U)=>{let W=R(I,C),ie=W?.submitted===!0&&W.valid===!0,me=W?.cancelled===!0;!ie&&!me||mt(C.actions)&&Kt(C.actions,xi(O,W.form),{...U,interactionSource:dn})},Si=(I,C,O,U)=>{let W=V(O),me=wr({[I]:C},W)[I];if(I===wi){Ue(me,O,U);return}let gt=_(I,me,U);if(xu.has(I)){Ci(I,gt,O,U);return}R(I,gt)},Kt=(I,C,O)=>{Object.entries(I).forEach(([U,W])=>{Si(U,W,C,O)})},hn=(I,C,O={})=>{t.beginRollbackActionBatch({source:O.rollbackSource});try{Kt(I,C,O)}finally{t.endRollbackActionBatch({})}};return{init:f,handleAction:z,handleInternalAction:Y,handleActions:hn,selectRenderState:A,prepareRenderState:x,commitRenderState:S,selectPresentationState:h,selectPresentationChanges:g,selectSectionLineChanges:y,selectSystemState:T,selectSaveSlotMap:E,selectSaveSlot:N,selectSaveSlotPage:B,selectSaveSlots:E,selectRuntime:F,selectIsChoiceVisible:M,selectIsFormVisible:q,selectActiveInteraction:v,handleLineActions:()=>{let I=t.selectCurrentLine();return I?.actions?(hn(I.actions,void 0,{rollbackSource:"line"}),!0):!1},getNamespace:p}}var pn=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:r=>{e=r},addElapsed:r=>{e+=r},getCallback:()=>t,setCallback:r=>{t=r}}},Cu=80,vi=({engine:e,routeGraphics:t,trackRenderDispatch:r},n)=>{let o=e.prepareRenderState?.(n)??e.selectRenderState(n);r?.(o),t.render(o),e.commitRenderState?.(o)},Su=({engine:e,routeGraphics:t,trackRenderDispatch:r,getRenderDispatchCount:n},o)=>{let i=n?.()??0,s=e.handleLineActions();(n?.()??0)===i&&vi({engine:e,routeGraphics:t,trackRenderDispatch:r},o)},_u=({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 l=n.delay??1e3;r.getElapsed()>=l&&(t.remove(i),r.setCallback(null),r.setElapsed(0),Ht(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},Ru=({ticker:e,autoTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},Ou=({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 l=n?.delay??Cu;r.getElapsed()>=l&&(r.setElapsed(0),Ht(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},Lu=({ticker:e,skipTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},$u=({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 l=n.delay??1e3;r.getElapsed()>=l&&(r.setElapsed(0),Ht(e,"nextLineFromSystem",{}),t.remove(i),r.setCallback(null))};r.setCallback(i),t.add(i)},ku=({ticker:e,nextLineConfigTimerState:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},Du=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveSlots(t?.saveSlots))},Pu=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalDeviceVariables(t?.globalDeviceVariables))},Tu=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalAccountVariables(t?.globalAccountVariables))},Nu=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalRuntime(t?.globalRuntime))},Vu=({enqueuePersistenceWrite:e},t)=>{e(r=>{if(typeof r.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return r.applyScopedDataUpdates(t?.updates)})},Ei={render:vi,saveSlots:Du,saveGlobalDeviceVariables:Pu,saveGlobalAccountVariables:Tu,saveGlobalRuntime:Nu,applyScopedDataUpdates:Vu,handleLineActions:Su,startAutoNextTimer:_u,clearAutoNextTimer:Ru,startSkipNextTimer:Ou,clearSkipNextTimer:Lu,nextLineConfigTimer:$u,clearNextLineConfigTimer:ku},ju=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),Ht=(e,t,r)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,r)},Mu=(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(!ju.has(o.name)){r.unshift(o);continue}t.has(o.name)||(t.add(o.name),r.unshift(o))}return r},Fu=({getEngine:e,routeGraphics:t,ticker:r,handleUnhandledEffect:n,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:l})=>{let c=pn(),a=pn(),u=pn(),d=s??null,f=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(d)return d;let v=e();return d=un({indexedDB:i,namespace:l??v?.getNamespace?.()}),d},x=v=>{f=f.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},T=()=>y,E=(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)},N=(v,_={})=>{if(v!=="renderComplete"||!E(_))return!1;let R=e();return Ht(R,"markLineCompleted",{}),!0},B=v=>typeof v?.selectActiveInteraction=="function"?v.selectActiveInteraction():typeof v?.selectIsChoiceVisible=="function"&&v.selectIsChoiceVisible()?{source:"choice"}:null,k=(v,_)=>!(!v||typeof v!="object"||Array.isArray(v)||v._interactionSource!==_?.source||_.source==="form"&&v._formKey&&v._formKey!==_.formKey||_.source==="form"&&v.formKey&&v.formKey!==_.formKey),j=(v={},_)=>{if(k(v,_))return!0;let R=v?.actions;return!R||typeof R!="object"||Array.isArray(R)?!1:Object.values(R).some(z=>k(z,_))},F=(v,_={})=>{if(!_?.actions)return!1;let R=B(v);return!R||R.source==="choice"?!1:!j(_,R)},M=({preprocessPayload:v,onEvent:_}={})=>async(R,z={})=>{let Y=e();if(F(Y,z))return _?.(R,z);let V=await v?.(R,z)??z;if(F(Y,V))return _?.(R,V);if(N(R,V),V?.actions){let he=V?._event?{_event:V._event}:V?.event?{_event:V.event}:void 0,Z;V?.bypassChoice===!0?Z={bypassChoice:!0}:V?._interactionSource&&(Z={interactionSource:V._interactionSource}),Z?Y.handleActions(V.actions,he,Z):Y.handleActions(V.actions,he)}return _?.(R,V)},q=v=>{let _=e(),R=Mu(v);R.forEach(Y=>{if(!Ei[Y.name]&&!n)throw new Error(`Unhandled pending effect "${Y.name}".`)});let z={engine:_,routeGraphics:t,ticker:r,autoTimer:c,skipTimer:a,nextLineConfigTimerState:u,trackRenderDispatch:S,getRenderDispatchCount:T,enqueuePersistenceWrite:x};for(let Y of R){let V=Ei[Y.name];if(V){V(z,Y.payload);continue}n(Y,z)}};return q.handleRouteGraphicsEvent=N,q.createRouteGraphicsEventHandler=M,q},Uu=Fu;var Bu=(e,t={})=>{let{resources:r={}}=t;return Yr(e,r)};var cf=fn;export{xr as DEFAULT_VISUAL_LAYER,at as RENDER_LAYER,Se as VISUAL_LAYER,Uu as createEffectsHandler,wu as createIndexedDbPersistence,cf as default,Ds as resolveComputedVariables,Bu as resolveLayoutReferences};
1
+ var Oi=Object.defineProperty;var Li=(e,t)=>{for(var r in t)Oi(e,r,{get:t[r],enumerable:!0})};var vn=Symbol.for("immer-nothing"),bn=Symbol.for("immer-draftable"),oe=Symbol.for("immer-state");function le(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var ze=Object.getPrototypeOf;function ie(e){return!!e&&!!e[oe]}function $e(e){return e?xn(e)||Array.isArray(e)||!!e[bn]||!!e.constructor?.[bn]||wt(e)||Et(e):!1}var $i=Object.prototype.constructor.toString();function xn(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)===$i}function yt(e,t){At(e)===0?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,n)=>t(n,r,e))}function At(e){let t=e[oe];return t?t.type_:Array.isArray(e)?1:wt(e)?2:Et(e)?3:0}function Qt(e,t){return At(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Cn(e,t,r){let n=At(e);n===2?e.set(t,r):n===3?e.add(r):e[t]=r}function ki(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function wt(e){return e instanceof Map}function Et(e){return e instanceof Set}function Le(e){return e.copy_||e.base_}function Zt(e,t){if(wt(e))return new Map(e);if(Et(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=xn(e);if(t===!0||t==="class_only"&&!r){let n=Object.getOwnPropertyDescriptors(e);delete n[oe];let o=Reflect.ownKeys(n);for(let i=0;i<o.length;i++){let s=o[i],l=n[s];l.writable===!1&&(l.writable=!0,l.configurable=!0),(l.get||l.set)&&(n[s]={configurable:!0,writable:!0,enumerable:l.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 or(e,t=!1){return vt(e)||ie(e)||!$e(e)||(At(e)>1&&(e.set=e.add=e.clear=e.delete=Di),Object.freeze(e),t&&Object.entries(e).forEach(([r,n])=>or(n,!0))),e}function Di(){le(2)}function vt(e){return Object.isFrozen(e)}var Pi={};function ke(e){let t=Pi[e];return t||le(0,e),t}var Ze;function Sn(){return Ze}function Ti(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function In(e,t){t&&(ke("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function er(e){tr(e),e.drafts_.forEach(Ni),e.drafts_=null}function tr(e){e===Ze&&(Ze=e.parent_)}function An(e){return Ze=Ti(Ze,e)}function Ni(e){let t=e[oe];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function wn(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[oe].modified_&&(er(t),le(4)),$e(e)&&(e=bt(t,e),t.parent_||It(t,e)),t.patches_&&ke("Patches").generateReplacementPatches_(r[oe].base_,e,t.patches_,t.inversePatches_)):e=bt(t,r,[]),er(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==vn?e:void 0}function bt(e,t,r){if(vt(t))return t;let n=t[oe];if(!n)return yt(t,(o,i)=>En(e,n,t,o,i,r)),t;if(n.scope_!==e)return t;if(!n.modified_)return It(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),yt(i,(l,c)=>En(e,n,o,l,c,r,s)),It(e,o,!1),r&&e.patches_&&ke("Patches").generatePatches_(n,r,e.patches_,e.inversePatches_)}return n.copy_}function En(e,t,r,n,o,i,s){if(ie(o)){let l=i&&t&&t.type_!==3&&!Qt(t.assigned_,n)?i.concat(n):void 0,c=bt(e,o,l);if(Cn(r,n,c),ie(c))e.canAutoFreeze_=!1;else return}else s&&r.add(o);if($e(o)&&!vt(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;bt(e,o),(!t||!t.scope_.parent_)&&typeof n!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,n)&&It(e,o)}}function It(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&or(t,r)}function Vi(e,t){let r=Array.isArray(e),n={type_:r?1:0,scope_:t?t.scope_:Sn(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=n,i=ir;r&&(o=[n],i=et);let{revoke:s,proxy:l}=Proxy.revocable(o,i);return n.draft_=l,n.revoke_=s,l}var ir={get(e,t){if(t===oe)return e;let r=Le(e);if(!Qt(r,t))return ji(e,r,t);let n=r[t];return e.finalized_||!$e(n)?n:n===Jt(e.base_,t)?(Xt(e),e.copy_[t]=nr(n,e)):n},has(e,t){return t in Le(e)},ownKeys(e){return Reflect.ownKeys(Le(e))},set(e,t,r){let n=_n(Le(e),t);if(n?.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){let o=Jt(Le(e),t),i=o?.[oe];if(i&&i.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(ki(r,o)&&(r!==void 0||Qt(e.base_,t)))return!0;Xt(e),rr(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 Jt(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,Xt(e),rr(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=Le(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:n.enumerable,value:r[t]}},defineProperty(){le(11)},getPrototypeOf(e){return ze(e.base_)},setPrototypeOf(){le(12)}},et={};yt(ir,(e,t)=>{et[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});et.deleteProperty=function(e,t){return et.set.call(this,e,t,void 0)};et.set=function(e,t,r){return ir.set.call(this,e[0],t,r,e[0])};function Jt(e,t){let r=e[oe];return(r?Le(r):e)[t]}function ji(e,t,r){let n=_n(t,r);return n?"value"in n?n.value:n.get?.call(e.draft_):void 0}function _n(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 rr(e){e.modified_||(e.modified_=!0,e.parent_&&rr(e.parent_))}function Xt(e){e.copy_||(e.copy_=Zt(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Mi=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(c=i,...a){return s.produce(c,u=>r.call(this,u,...a))}}typeof r!="function"&&le(6),n!==void 0&&typeof n!="function"&&le(7);let o;if($e(t)){let i=An(this),s=nr(t,void 0),l=!0;try{o=r(s),l=!1}finally{l?er(i):tr(i)}return In(i,n),wn(o,i)}else if(!t||typeof t!="object"){if(o=r(t),o===void 0&&(o=t),o===vn&&(o=void 0),this.autoFreeze_&&or(o,!0),n){let i=[],s=[];ke("Patches").generateReplacementPatches_(t,o,i,s),n(i,s)}return o}else le(1,t)},this.produceWithPatches=(t,r)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,c=>t(c,...l));let n,o;return[this.produce(t,r,(s,l)=>{n=s,o=l}),n,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){$e(e)||le(8),ie(e)&&(e=De(e));let t=An(this),r=nr(e,void 0);return r[oe].isManual_=!0,tr(t),r}finishDraft(e,t){let r=e&&e[oe];(!r||!r.isManual_)&&le(9);let{scope_:n}=r;return In(n,t),wn(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=ke("Patches").applyPatches_;return ie(e)?n(e,t):this.produce(e,o=>n(o,t))}};function nr(e,t){let r=wt(e)?ke("MapSet").proxyMap_(e,t):Et(e)?ke("MapSet").proxySet_(e,t):Vi(e,t);return(t?t.scope_:Sn()).drafts_.push(r),r}function De(e){return ie(e)||le(10,e),Rn(e)}function Rn(e){if(!$e(e)||vt(e))return e;let t=e[oe],r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=Zt(e,t.scope_.immer_.useStrictShallowCopy_)}else r=Zt(e,!0);return yt(r,(n,o)=>{Cn(r,n,Rn(o))}),t&&(t.finalized_=!1),r}var se=new Mi,sr=se.produce,ef=se.produceWithPatches.bind(se),tf=se.setAutoFreeze.bind(se),rf=se.setUseStrictShallowCopy.bind(se),nf=se.applyPatches.bind(se),of=se.createDraft.bind(se),sf=se.finishDraft.bind(se);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},L={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},We={NOT:0};var E=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},ee=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var ar=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}')`)},On=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 Ln=(e,t,r=!1)=>{if(t===null)return new ee(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new ee(`Cannot iterate over undefined value at '$for ${e}'`);let n=typeof t;return r?new ee(`Cannot iterate over non-array value in loop '${e}' - got ${n} instead`):new ee(`Cannot iterate over non-array value (got: ${n}) at '$for ${e}'`)},$n=(e,t)=>{let r=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new ee(`Unknown function '${e}' (${r})`)};var Fi=(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 K(e.var,r,n);if(e.type===m.LITERAL)return e.value;if(e.type===m.VARIABLE)return K(e.path,r,n);if(e.type===m.INTERPOLATION)return Bi(e.parts,t,r,n);switch(e.type){case m.FUNCTION:return Dn(e,t,r,n);case m.BINARY:return Pn(e,t,r,n);case m.UNARY:return Tn(e,t,r,n);case m.CONDITIONAL:return Wi(e,t,r,n);case m.LOOP:return Gi(e,t,r,n);case m.OBJECT:return Xi(e,t,r,n);case m.ARRAY:return Qi(e,t,r,n);case m.PARTIAL:return Zi(e,t,r,n);case m.PATH_REFERENCE:return es(e,t,r,n);default:throw new Error(`Unknown node type: ${e.type}`)}},kn=new Map,Ui=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 l=s.slice(1,-1);t.push({type:"property",value:l})}else t.push({type:"property",value:s});r=""}n=!1}else r+=i}return r&&t.push({type:"property",value:r}),t},K=(e,t,r)=>{if(!e)return;if(e in r)return r[e];let n=kn.get(e);if(!n){let i=[],s="",l=0;for(let c=0;c<e.length;c++){let a=e[c];a==="["?(l++,s+=a):a==="]"?(l--,s+=a):a==="."&&l===0?s&&(i.push(s),s=""):s+=a}s&&i.push(s),n=[];for(let c of i){let a=Ui(c.trim());n.push(...a)}kn.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},Bi=(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("")},Dn=(e,t,r,n)=>{let o=t.functions||t,i=o[e.name];if(!i)throw $n(e.name,o);let s=e.args.map(l=>$(l,t,r,n));return i(...s)},Ee=(e,t,r,n)=>{if(e.var&&!e.type)return K(e.var,r,n);switch(e.type){case m.VARIABLE:return K(e.path,r,n);case m.LITERAL:return e.value;case m.BINARY:return Pn(e,t,r,n);case m.UNARY:return Tn(e,t,r,n);case m.FUNCTION:return Dn(e,t,r,n);default:return $(e,t,r,n)}},Pn=(e,t,r,n)=>{if(e.op===L.AND||e.op===L.OR){let s=Ee(e.left,t,r,n),l=Ee(e.right,t,r,n);switch(e.op){case L.AND:return s&&l;case L.OR:return s||l}}let o=$(e.left,t,r,n),i=$(e.right,t,r,n);switch(e.op){case L.EQ:return o==i;case L.NEQ:return o!=i;case L.GT:return o>i;case L.LT:return o<i;case L.GTE:return o>=i;case L.LTE:return o<=i;case L.IN:return Array.isArray(i)?i.includes(o):!1;case L.ADD:if(typeof o!="number"||typeof i!="number")throw new ee(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case L.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new ee(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},Tn=(e,t,r,n)=>{let o=e.op===We.NOT?Ee(e.operand,t,r,n):$(e.operand,t,r,n);if(e.op===We.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},zi=(e,t,r,n)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===m.VARIABLE)if(K(o.path,r,n)){let s=e.bodies[0];if(s.type===m.OBJECT&&s.properties.length<=5){let l={};for(let c of s.properties){let a=c.parsedKey?$(c.parsedKey,t,r,n):c.key,u=c.value;if(u.type===m.LITERAL)l[a]=u.value;else if(u.type===m.VARIABLE)l[a]=K(u.path,r,n);else if(u.type===m.INTERPOLATION){let f=[];for(let d of u.parts)if(typeof d=="string")f.push(d);else if(d.type===m.VARIABLE){let p=K(d.path,r,n);f.push(p!=null?String(p):"")}else{let p=$(d,t,r,n);f.push(p!=null?String(p):"")}l[a]=f.join("")}else l[a]=$(u,t,r,n)}return l}}else{let s=e.bodies[1];if(s.type===m.OBJECT&&s.properties.length<=5){let l={};for(let c of s.properties){let a=c.parsedKey?$(c.parsedKey,t,r,n):c.key,u=c.value;if(u.type===m.LITERAL)l[a]=u.value;else if(u.type===m.VARIABLE)l[a]=K(u.path,r,n);else if(u.type===m.INTERPOLATION){let f=[];for(let d of u.parts)if(typeof d=="string")f.push(d);else if(d.type===m.VARIABLE){let p=K(d.path,r,n);f.push(p!=null?String(p):"")}else{let p=$(d,t,r,n);f.push(p!=null?String(p):"")}l[a]=f.join("")}else l[a]=$(u,t,r,n)}return l}}}return null},Wi=(e,t,r,n)=>{let o=zi(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||Ee(s,t,r,n))return $(e.bodies[i],t,r,n)}return Nn},qi=(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 c of i.properties)if(c.parsedKey)return null;let l=[];for(let c=0;c<t.length;c++){let a=t[c];if(a[s]){let u={};for(let f of i.properties){let d=f.key,p=f.value;if(p.type===m.LITERAL)u[d]=p.value;else if(p.type===m.VARIABLE){let h=p.path;if(h===n)u[d]=a;else if(h.startsWith(n+".")){let g=h.substring(n.length+1);u[d]=a[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(a!=null?String(a):"");else if(b.startsWith(n+".")){let A=b.substring(n.length+1),x=a[A];h.push(x!=null?String(x):"")}else{g=!1;break}}else{g=!1;break}if(!g)return null;u[d]=h.join("")}else return null}l.push(u)}}return l}}}return null},Yi=(e,t)=>{let r=e.body,n=e.itemVar,o=qi(e,t);if(o!==null)return o;if(r.type===m.OBJECT&&r.properties.length<=5&&!r.whenCondition){for(let l of r.properties)if(l.parsedKey)return null;let i=[],s=!0;for(let l of r.properties){let c=l.key,a=l.value;if(a.type===m.LITERAL)i.push({key:c,type:"literal",value:a.value});else if(a.type===m.VARIABLE){let u=a.path;if(u===n)i.push({key:c,type:"item"});else if(u.startsWith(n+".")){let f=u.substring(n.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:c,type:"prop",prop:f});else{s=!1;break}}else{s=!1;break}}else if(a.type===m.INTERPOLATION&&a.parts.length===1){let u=a.parts[0];if(u.type===m.VARIABLE){let f=u.path;if(f===n)i.push({key:c,type:"item_string"});else if(f.startsWith(n+".")){let d=f.substring(n.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:c,type:"prop_string",prop:d});else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}if(s){let l=new Array(t.length);if(i.length===3&&i[0].type==="prop"&&i[0].key==="id"&&i[1].type==="prop_string"&&i[1].key==="title"&&i[2].type==="prop"&&i[2].key==="completed")for(let c=0;c<t.length;c++){let a=t[c];l[c]={id:a.id,title:a.title!=null?String(a.title):"",completed:a.completed}}else for(let c=0;c<t.length;c++){let a=t[c],u={};for(let f of i)if(f.type==="literal")u[f.key]=f.value;else if(f.type==="item")u[f.key]=a;else if(f.type==="prop")u[f.key]=a[f.prop];else if(f.type==="item_string")u[f.key]=a!=null?String(a):"";else if(f.type==="prop_string"){let d=a[f.prop];u[f.key]=d!=null?String(d):""}l[c]=u}return l}}return null},Hi=(e,t,r,n,o)=>{let i=[],s=e.body;if(s.type===m.OBJECT&&s.fast!==!1){let l=e.itemVar,c=e.indexVar;for(let a=0;a<o.length;a++){let u=o[a],f={},d={...n,[l]:u,...c&&{[c]:a}};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__,[l]:`${p}[${a}]`,...c&&{[c]:a}};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)f[g]=y.value;else if(y.type===m.VARIABLE){let b=y.path;if(b===l)f[g]=u;else if(b===c)f[g]=a;else if(b.startsWith(l+".")){let A=b.substring(l.length+1);!A.includes(".")&&!A.includes("[")?f[g]=u[A]:f[g]=K(b,r,{...n,[l]:u,...c&&{[c]:a}})}else f[g]=K(b,r,{...n,[l]:u,...c&&{[c]:a}})}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===l)S=u;else if(x===c)S=a;else if(x.startsWith(l+".")){let T=x.substring(l.length+1);!T.includes(".")&&!T.includes("[")?S=u[T]:S=K(x,r,{...n,[l]:u,...c&&{[c]:a}})}else S=K(x,r,{...n,[l]:u,...c&&{[c]:a}});b.push(S!=null?String(S):"")}else{let x={...n,[l]:u,...c&&{[c]:a}},S=$(A,t,r,x);b.push(S!=null?String(S):"")}f[g]=b.join("")}else{let b={...n,[l]:u,...c&&{[c]:a}};f[g]=$(y,t,r,b)}}i.push(f)}return i}return null},Ki=(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 l=s.properties[0],c=s.properties[1];if(l.key==="id"&&l.value.type===m.VARIABLE&&l.value.path==="item.id"&&c.key==="$if item.highlighted"&&c.value.type===m.CONDITIONAL){let a=[];for(let u=0;u<t.length;u++){let f=t[u];if(f.visible){let d={id:f.id};f.highlighted?(d.highlight=!0,d.message=`This item is highlighted: ${f.name}`):(d.highlight=!1,d.message=f.name),a.push(d)}}return a}}}}return null},Gi=(e,t,r,n)=>{let o=$(e.iterable,t,r,n);if(!Array.isArray(o)){let a,u=!1;if(e.iterable.type===m.FUNCTION){u=!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(", ");a=`${e.iterable.name}(${d})`}else a=e.iterable.path||"undefined";let f=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${a}`;throw Ln(f,o,u)}if(!e.indexVar){let a=Ki(e,o,e.itemVar);if(a!==null)return a}if(!e.indexVar){let a=Yi(e,o);if(a!==null)return a}let i=Hi(e,t,r,n,o);if(i!==null)return i;let s=[],l=e.iterable.path||"";if(n&&n.__paths__&&l){let a=l.split("."),u=a[0];u in n.__paths__&&(l=n.__paths__[u],a.length>1&&(l+="."+a.slice(1).join(".")))}let c=!1;e.body.type===m.ARRAY&&(e.body.items.length<=1?c=!1:c=e.body._shouldPreserveArray??=e.body.items.some(a=>a.type===m.OBJECT&&a.properties.some(u=>u.key.startsWith("$if ")||u.key.startsWith("$when "))));for(let a=0;a<o.length;a++){let u=e.indexVar?{...n,[e.itemVar]:o[a],[e.indexVar]:a}:{...n,[e.itemVar]:o[a]};u.__paths__||(u.__paths__=n.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${l}[${a}]`},e.indexVar&&(u.__paths__[e.indexVar]=a);let f=$(e.body,t,r,u);if(Array.isArray(f)&&f.length===1&&!c){let d=f[0];s.push(d===void 0?{}:d)}else s.push(f===void 0?{}:f)}return s},Ji=(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 l={},c={},a=!0;for(let u of s.properties){let f=u.parsedKey?$(u.parsedKey,t,r,n):u.key,d=u.value;if(d.type===m.LITERAL)c[f]=d.value;else if(d.type===m.VARIABLE)c[f]=K(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=K(h.path,r,n);p.push(g!=null?String(g):"")}else{a=!1;break}if(!a)break;c[f]=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]=K(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=K(A.path,r,n);b.push(x!=null?String(x):"")}else{a=!1;break}if(!a)break;p[g]=b.join("")}else{a=!1;break}}if(!a)break;c[f]=p}else{a=!1;break}}if(a)return l[i]=c,l}}return null},Xi=(e,t,r,n)=>{let o=t.functions||t;if(e.whenCondition&&!Ee(e.whenCondition,o,r,n))return;let i=Ji(e,t,r,n);if(i!==null)return i;if(e.fast){let a={};for(let u of e.properties){let f=u.parsedKey?$(u.parsedKey,t,r,n):u.key,d=u.value;if(d.type===m.LITERAL)a[f]=d.value;else if(d.type===m.VARIABLE)a[f]=K(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=K(h.path,r,n);p.push(g!=null?String(g):"")}else{let g=$(h,t,r,n);p.push(g!=null?String(g):"")}a[f]=p.join("")}else a[f]=$(d,t,r,n)}return a}let s={},l=null,c=!1;for(let a of e.properties)if(!a.key.startsWith("$if ")&&!a.key.match(/^\$if\s+\w+.*:?$/)&&!a.key.startsWith("$elif")&&!a.key.startsWith("$else")&&!a.key.startsWith("$for ")){c=!0;break}for(let a of e.properties)if(a.key.startsWith("$if ")||a.key.match(/^\$if\s+\w+.*:?$/)){let u=$(a.value,t,r,n);if(!c&&u!==null&&u!==void 0)return Array.isArray(u)&&u.length===1?u[0]:u;typeof u=="object"&&u!==null&&!Array.isArray(u)&&Object.assign(s,u)}else if(a.key.startsWith("$for ")){if(e.properties.length===1)return $(a.value,t,r,n)}else{let u=a.value;if(u&&u.type===m.OBJECT&&u.properties){let f=u.properties.find(d=>d.key.startsWith("$for "));if(f){let d=$(f.value,t,r,n);d!==void 0&&(s[a.key]=d)}else{let d=$(a.value,t,r,n);d!==void 0&&(s[a.key]=d)}}else{let f=a.parsedKey?$(a.parsedKey,t,r,n):a.key,d=$(a.value,t,r,n);d!==void 0&&(s[f]=d)}}return s},Nn={},Qi=(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!==Nn&&s!==void 0&&o.push(s)}return o},Zi=(e,t,r,n)=>{let{name:o,data:i,whenCondition:s}=e,l=t.partials||{},c=t.functions||t;if(s&&!Ee(s,c,r,n))return;if(!l[o])throw new ee(`Partial '${o}' is not defined`);let a=n._partialStack||[];if(a.includes(o))throw new ee(`Circular partial reference detected: ${o}`);let u=l[o],f=r,d={...n,_partialStack:[...a,o]};if(n){f={...r};for(let p of Object.keys(n))p.startsWith("_")||(f[p]=n[p])}if(i){let p=$(i,t,r,n);f={...f,...p}}return $(u,t,f,d)},es=(e,t,r,n)=>{let{path:o}=e,i=o.split("."),s=i[0],l=i.slice(1);if(!n||!(s in n))throw new ee(`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 ee(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let c=n.__paths__[s];if(typeof c=="number"){if(l.length>0)throw new ee(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(c)}return l.length>0&&(c+="."+l.join(".")),c};var cr=Fi;var ts=/\$\{([^}]*)\}/g,rs=/#\{([^}]*)\}/g,jn=(e,t={})=>{let r=e.match(/^(\w+)\((.*)\)$/);if(!r)return{isFunction:!1};let[,n,o]=r,i=ns(o,t);return{isFunction:!0,type:m.FUNCTION,name:n,args:i}},ns=(e,t={})=>e.trim()?os(e).map(n=>is(n.trim(),t)):[],os=e=>{let t=[],r="",n=0,o=!1,i="";for(let s=0;s<e.length;s++){let l=e[s],c=s>0?e[s-1]:"";!o&&(l==='"'||l==="'")?(o=!0,i=l,r+=l):o&&l===i&&c!=="\\"?(o=!1,i="",r+=l):!o&&l==="("?(n++,r+=l):!o&&l===")"?(n--,r+=l):!o&&l===","&&n===0?(t.push(r),r=""):r+=l}return r&&t.push(r),t},is=(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=jn(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:l,type:c}of o){let a=0;for(;a<n.length;){let u=Pe(n.substring(a),l);if(u===-1)break;let f=a+u;f>i&&(i=f,s={op:l,type:c}),a=f+l.length}}if(i!==-1)try{return J(n,t)}catch{return{type:m.VARIABLE,path:n}}return{type:m.VARIABLE,path:n}},Mn=/^\w+\(.*\)$/,ss=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,as=e=>{if(!(!e||e.trim()===""||Mn.test(e))&&ss.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}"`)},Vn=e=>{let t=e.trim();if(Mn.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}},tt=(e,t={})=>{let r=e.trim();as(r);let n=jn(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}},lr=(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,(a,u)=>{let f=`__ESCAPED_${n.length}__`;return n.push(u),f}),r=r.replace(/\\(#\{[^}]*\})/g,(a,u)=>{let f=`__ESCAPED_${n.length}__`;return n.push(u),f}),r=r.replace(/\\DOUBLE_ESC_VAR/g,"\\"),r=r.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...r.matchAll(ts)],i=[...r.matchAll(rs)],s=[...o.map(a=>({match:a,type:"variable"})),...i.map(a=>({match:a,type:"pathref"}))].sort((a,u)=>a.match.index-u.match.index);if(s.length===0){let a=r;for(let u=0;u<n.length;u++)a=a.replace(`__ESCAPED_${u}__`,n[u]);return{type:m.LITERAL,value:a}}if(s.length===1&&s[0].match[0]===r&&n.length===0){let{match:a,type:u}=s[0];try{return u==="variable"?tt(a[1],t):Vn(a[1])}catch(f){if(f.message==="Invalid array index syntax")return{type:m.LITERAL,value:r};throw f}}let l=[],c=0;for(let{match:a,type:u}of s){let[f,d]=a,p=a.index;if(p>c){let h=r.substring(c,p);for(let g=0;g<n.length;g++)h=h.replace(`__ESCAPED_${g}__`,n[g]);h&&l.push(h)}try{let h;u==="variable"?h=tt(d.trim(),t):h=Vn(d.trim()),l.push(h)}catch(h){if(h.message==="Invalid array index syntax")l.push(f);else throw h}c=p+f.length}if(c<r.length){let a=r.substring(c);for(let u=0;u<n.length;u++)a=a.replace(`__ESCAPED_${u}__`,n[u]);a&&l.push(a)}return{type:m.INTERPOLATION,parts:l}};var dr=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Bn=e=>Object.keys(e),Q=e=>e.join("."),ve=(e,t,r)=>{let n=Bn(e).filter(o=>!t.has(o));if(n.length>0)throw new E(`Unexpected key '${n[0]}' in condition JSON at '${Q(r)}'`)},xe=(e,t)=>typeof e=="string"?lr(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?ls(e,t):us(e,t):{type:m.LITERAL,value:e},cs=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}},ls=(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 c=cs(i),a=Object.keys(c);if(a.length===1&&/^\$for(?::\w+)?\s/.test(a[0])){let u=Un(a[0],c[a[0]],t,!0);r.push(u),n=!0;continue}}catch(c){throw c instanceof E?c:new E(c.message)}let l=Object.keys(i);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let c=Un(l[0],i[l[0]],t);r.push(c),n=!0;continue}}let s=xe(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}},us=(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 c=["$if","$elif","$else","$for"],a=[];for(let[b]of i)for(let A of c)if(b===A||b.startsWith(A+" ")||b.startsWith(A+"#")){a.push(A);break}if(a.length>0)throw new E(`Cannot use $partial with ${a.join(", ")} at the same level. Wrap $partial in a parent object if you need conditionals.`);let{$partial:u,$when:f,...d}=e,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=xe(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:u,data:g};return f!==void 0&&(y.whenCondition=Fn(f,t)),y}for(let[c,a]of i)if(c==="$when"){if(o!==null)throw new E("Multiple '$when' directives on the same object are not allowed");if(a==null)throw new E("Missing condition expression after '$when'");o=Fn(a,t),n=!0}else if(c.startsWith("$when#")||c.startsWith("$when "))throw new E("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<i.length;){let[c,a]=i[s];if(c==="$when"){s++;continue}if(c==="$each")throw new E("$each can only be used inside arrays");if(c.startsWith("$if ")||c.match(/^\$if#\w+\s/)||c.match(/^\$if\s+\w+.*:$/)){let u=fs(i,s,t);r.push({key:c,value:u.node}),n=!0,s=u.nextIndex}else if(/^\$for(?::\w+)?\s/.test(c)){let u=c.match(/^\$for(?::(\w+))?\s/)?.[1]||"",f=u?`:${u}`:"";throw new E(`$for loops must be inside arrays - use '- $for${f} item in items:' instead of '$for${f} item in items:'. For cleaner object generation syntax, consider using $each.`)}else{if(c.startsWith("$elif ")||c.startsWith("$else"))throw new E(`'${c.split(" ")[0]}' without matching '$if'`);if(c==="$if"||c==="$if:")throw new E("Missing condition expression after '$if'");{let u=xe(a,t);(u.type===m.FUNCTION||u.type===m.CONDITIONAL||u.type===m.PARTIAL||u.type===m.OBJECT&&!u.fast||u.type===m.ARRAY&&!u.fast)&&(n=!0);let f=lr(c,t),d={key:c,value:u};(f.type!==m.LITERAL||f.value!==c)&&(d.parsedKey=f),r.push(d),s++}}}let l={type:m.OBJECT,properties:r,fast:!n};return o&&(l.whenCondition=o),l},fs=(e,t,r={})=>{let n=[],o=[],i=t,[s,l]=e[i],c=null,a;if(s.startsWith("$if#")){let f=s.match(/^\$if#(\w+)\s+(.+)$/);if(f)c=f[1],a=f[2];else throw new E(`Invalid conditional syntax: ${s}`)}else a=s.substring(4),a.endsWith(":")&&(a=a.slice(0,-1).trim());ar(a);let u=J(a,r);for(n.push(u),o.push(xe(l,r)),i++;i<e.length;){let[f,d]=e[i],p=!1,h;if(c?f.startsWith(`$elif#${c} `)?(h=f.substring(`$elif#${c} `.length),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(f===`$else#${c}`||f===`$else#${c}:`)&&(p=!0,h=null):f.startsWith("$elif ")?(h=f.substring(6),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(f==="$else"||f==="$else:")&&(p=!0,h=null),p){if(h===null)n.push(null);else{ar(h);let g=J(h,r);n.push(g)}if(o.push(xe(d,r)),i++,h===null)break}else break}return{node:{type:m.CONDITIONAL,conditions:n,bodies:o,id:c},nextIndex:i}},ur={eq:L.EQ,neq:L.NEQ,gt:L.GT,gte:L.GTE,lt:L.LT,lte:L.LTE,in:L.IN,add:L.ADD,sub:L.SUBTRACT},fr={all:L.AND,any:L.OR},ds=new Set(["var","literal","call","not",...Object.keys(ur),...Object.keys(fr)]),ps=(e,t,r)=>{if(!Array.isArray(e))throw new E(`Condition JSON operator '${t}' at '${Q(r)}' requires an array`);if(e.length!==2)throw new E(`Condition JSON operator '${t}' at '${Q(r)}' requires exactly 2 operands`);return e},hs=(e,t,r,n,o)=>{if(!Array.isArray(e))throw new E(`Condition JSON operator '${t}' at '${Q(o)}' requires an array`);if(e.length===0)throw new E(`Condition JSON operator '${t}' at '${Q(o)}' requires at least 1 condition`);return e.map((s,l)=>ye(s,n,[...o,l])).reduce((s,l)=>({type:m.BINARY,op:r,left:s,right:l}))},ms=(e,t,r)=>{let n,o;if(typeof e.call=="string")n=e.call,o=e.args??[],ve(e,new Set(["call","args"]),r);else if(dr(e.call))n=e.call.name,o=e.call.args??[],ve(e,new Set(["call"]),r),ve(e.call,new Set(["name","args"]),[...r,"call"]);else throw new E(`Condition JSON call at '${Q(r)}' requires a function name`);if(typeof n!="string"||n.trim()==="")throw new E(`Condition JSON call at '${Q(r)}' requires a non-empty function name`);if(!/^\w+$/.test(n))throw new E(`Invalid condition JSON function name '${n}' at '${Q(r)}'`);if(!Array.isArray(o))throw new E(`Condition JSON call '${n}' at '${Q(r)}' requires args to be an array`);return{type:m.FUNCTION,name:n,args:o.map((i,s)=>ye(i,t,[...r,"args",s]))}},ye=(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 '${Q(r)}' must be wrapped in an operator or { literal: [...] }`);if(!dr(e))throw new E(`Invalid condition JSON value at '${Q(r)}'`);let n=Bn(e);if(n.length===0)throw new E(`Condition JSON object at '${Q(r)}' must contain an operator`);let o=n.filter(s=>ds.has(s));if(o.length===0)throw new E(`Unknown condition JSON operator '${n[0]}' at '${Q(r)}'`);if(o.length>1)throw new E(`Condition JSON at '${Q(r)}' must contain exactly one operator`);let i=o.includes("call")?"call":o[0];if(i==="var"){if(ve(e,new Set(["var"]),r),typeof e.var!="string"||e.var.trim()==="")throw new E(`Condition JSON var at '${Q(r)}' requires a non-empty path`);return{type:m.VARIABLE,path:e.var}}if(i==="literal")return ve(e,new Set(["literal"]),r),{type:m.LITERAL,value:e.literal};if(i==="call")return ms(e,t,r);if(i==="not")return ve(e,new Set(["not"]),r),{type:m.UNARY,op:We.NOT,operand:ye(e.not,t,[...r,"not"])};if(i in fr)return ve(e,new Set([i]),r),hs(e[i],i,fr[i],t,[...r,i]);if(i in ur){ve(e,new Set([i]),r);let s=ps(e[i],i,[...r,i]);return{type:m.BINARY,op:ur[i],left:ye(s[0],t,[...r,i,0]),right:ye(s[1],t,[...r,i,1])}}throw new E(`Unknown condition JSON operator '${i}' at '${Q(r)}'`)},Fn=(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 dr(e)||Array.isArray(e)?ye(e,t):{type:m.LITERAL,value:e}},J=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let a=e.slice(1,-1),u=0,f=!0;for(let d=0;d<a.length;d++)if(a[d]==="("?u++:a[d]===")"&&u--,u<0){f=!1;break}if(f&&u===0)return J(a,t)}let r=Pe(e,"||");if(r!==-1)return{type:m.BINARY,op:L.OR,left:J(e.substring(0,r).trim(),t),right:J(e.substring(r+2).trim(),t)};let n=Pe(e,"&&");if(n!==-1)return{type:m.BINARY,op:L.AND,left:J(e.substring(0,n).trim(),t),right:J(e.substring(n+2).trim(),t)};let o=[{op:">=",type:L.GTE},{op:"<=",type:L.LTE},{op:"==",type:L.EQ},{op:"!=",type:L.NEQ},{op:">",type:L.GT},{op:"<",type:L.LT},{op:" in ",type:L.IN}];for(let{op:a,type:u}of o){let f=Pe(e,a);if(f!==-1)return{type:m.BINARY,op:u,left:J(e.substring(0,f).trim(),t),right:J(e.substring(f+a.length).trim(),t)}}let i=-1,s=null,l=[{op:" + ",type:L.ADD},{op:" - ",type:L.SUBTRACT}];for(let{op:a,type:u}of l){let f=0;for(;f<e.length;){let d=Pe(e.substring(f),a);if(d===-1)break;let p=f+d;p>i&&(i=p,s={op:a,type:u}),f=p+a.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 c=[" * "," / "," % "];for(let a of c)if(Pe(e,a)!==-1)throw new E(`Arithmetic operations are not allowed in conditionals: "${a}"`);return e.startsWith("!")?{type:m.UNARY,op:We.NOT,operand:J(e.substring(1).trim(),t)}:zn(e,t)},Pe=(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},gs=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}},zn=(e,t)=>{let r=e.trim();if(r.match(/^(\w+)\((.*)\)$/))return tt(r,t);let o=gs(r);if(o.type===m.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(r))return{type:m.VARIABLE,path:r};try{return tt(r,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},ys=(e,t=!1)=>{let r=t?"$each":"$for";try{On(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}},Un=(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],l=i[2].trim();ys(l,n);let c=l.match(/^(.+?)\s+in\s+(.+)$/);if(!c){let y=n?"$each":"$for";throw new E(`Invalid loop syntax - missing 'in' keyword (got: '${y} ${l}')`)}let a=c[1].trim(),u=c[2].trim(),f,d=null;if(a.includes(",")){let y=a.split(",").map(b=>b.trim());if(y.length!==2)throw new E(`Invalid loop variables: ${a}. Expected format: "item" or "item, index"`);f=y[0],d=y[1]}else f=a;let p=["this","undefined","null","true","false"];if(p.includes(f))throw new E(`Reserved variable name: ${f}`);if(d&&p.includes(d))throw new E(`Reserved variable name: ${d}`);let h=zn(u,r),g=xe(t,r);return{type:m.LOOP,itemVar:f,indexVar:d,iterable:h,body:g,flatten:s!=="nested"}};var bs=(e,t={})=>{let{functions:r={}}=t;return xe(e,r)},xt=bs;var rt={};Li(rt,{now:()=>Is});var Is=()=>Date.now();var As=(e,t,r={})=>{let{functions:n={},partials:o={}}=r,i={...rt,...n},s=xt(e,{functions:i}),l={};for(let[c,a]of Object.entries(o))l[c]=xt(a,{functions:i});return cr(s,t,{functions:i,partials:l})},ne=As;var ws=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",Es=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,vs=(e,t)=>{if(ws(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new E("Empty condition expression");return J(e,t)}return ye(e,t)},xs=(e,t={},r={})=>{let n=Es(r),o={...rt,...n},i=vs(e,o);return!!Ee(i,{functions:o,partials:{}},t,{})},pr=xs;var ot=(e,t={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return pr(e,t)},Gn=(e,t,r={})=>{let n=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=c=>c,transformActionFirstArgument:l=c=>c}=r;for(let[c,a]of Object.entries(t))c!=="createInitialState"&&(c.startsWith("select")?o[c]=(...u)=>a(s(n),...u):i[c]=(...u)=>{let f;return n=sr(n,p=>{let h=a(l(p),...u);f=h!==void 0&&!ie(h)?h:void 0}),f});return{...o,...i}},_t=(e,t)=>r=>{let n=e(),o=Array.isArray(r)?r:[r];return sr(n,i=>{o.forEach(s=>{t.forEach(l=>{l(i,s)})})})};var Cs=(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{}}},fe=(e,t)=>Object.prototype.hasOwnProperty.call(e??{},t),nt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Jn=e=>{let t=ie(e)?De(e):e;return structuredClone(t)},Ce=e=>fe(e,"computed"),qe=(e={},t={})=>Object.fromEntries(Object.entries(e??{}).filter(([r])=>!Ce(t[r]))),Ss=e=>String(e).replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean),hr=(e,t)=>{let r=e;for(let n of t){if(r==null)return;r=r[n]}return r},_s=(e,t={})=>{if(typeof e!="string"||e.trim()==="")throw new Error("Computed expression var requires a non-empty string path");let r=Ss(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 hr(s,i)}return n==="runtime"?hr(t.runtime,r.slice(1)):hr(t,r)},Rs=(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)`)},Wn=(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`)},Os=(e,t)=>{if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Computed expression operator "${e}" requires finite numeric operands`)},ue=(e,t,r,n)=>(Rs(e,t,n),t.map(o=>St(o,r))),ce=(e,t,r,n)=>{let o=ue(e,t,r,n);return o.forEach(i=>Os(e,i)),o},Ls=(e,t,r)=>{switch(e){case"var":return _s(t,r);case"add":{let[n,o]=ce(e,t,r,2);return n+o}case"sub":{let[n,o]=ce(e,t,r,2);return n-o}case"mul":{let[n,o]=ce(e,t,r,2);return n*o}case"div":{let[n,o]=ce(e,t,r,2);return n/o}case"mod":{let[n,o]=ce(e,t,r,2);return n%o}case"neg":{let[n]=ce(e,t,r,1);return-n}case"round":{let[n]=ce(e,t,r,1);return Math.round(n)}case"floor":{let[n]=ce(e,t,r,1);return Math.floor(n)}case"ceil":{let[n]=ce(e,t,r,1);return Math.ceil(n)}case"min":{let[n,o]=ce(e,t,r,2);return Math.min(n,o)}case"max":{let[n,o]=ce(e,t,r,2);return Math.max(n,o)}case"clamp":{let[n,o,i]=ce(e,t,r,3);return Math.min(i,Math.max(o,n))}case"eq":{let[n,o]=ue(e,t,r,2);return n==o}case"neq":{let[n,o]=ue(e,t,r,2);return n!=o}case"gt":{let[n,o]=ue(e,t,r,2);return n>o}case"gte":{let[n,o]=ue(e,t,r,2);return n>=o}case"lt":{let[n,o]=ue(e,t,r,2);return n<o}case"lte":{let[n,o]=ue(e,t,r,2);return n<=o}case"in":{let[n,o]=ue(e,t,r,2);return Array.isArray(o)?o.includes(n):!1}case"and":case"all":return Wn(e,t),t.every(n=>!!St(n,r));case"or":case"any":return Wn(e,t),t.some(n=>!!St(n,r));case"not":{let[n]=ue(e,t,r,1);return!n}case"length":{let[n]=ue(e,t,r,1);return typeof n=="string"||Array.isArray(n)?n.length:nt(n)?Object.keys(n).length:0}case"includes":{let[n,o]=ue(e,t,r,2);return typeof n=="string"||Array.isArray(n)?n.includes(o):!1}case"literal":return Jn(t);default:throw new Error(`Unknown computed expression operator: ${e}`)}},St=(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 Ls(n,o,t)},$s=(e,t={})=>ot(e,{variables:t.variables,runtime:t.runtime}),ks=(e,t)=>{if(!nt(e))throw new Error(`${t} must be an object`);let r=fe(e,"expr"),n=fe(e,"value");if(r===n)throw new Error(`${t} must contain exactly one of expr or value`)},mr=(e,t,r)=>(ks(e,t),fe(e,"value")?Jn(e.value):St(e.expr,r)),Ds=(e,t={},r="unknown")=>{if(!nt(e))throw new Error(`Computed variable "${r}" computed must be an object`);let n=fe(e,"expr"),o=fe(e,"value");if(fe(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(!nt(e.default))throw new Error(`Computed variable "${r}" requires default`);for(let s=0;s<e.branches.length;s+=1){let l=e.branches[s];if(!nt(l))throw new Error(`Computed variable "${r}" branch ${s} must be an object`);if(!fe(l,"when"))throw new Error(`Computed variable "${r}" branch ${s} requires when`);if($s(l.when,t))return mr(l,`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)},Ps=(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}`)}},Rt=({variables:e={},runtime:t={},variableConfigs:r={},eager:n=!0}={})=>{let o=qe(e,r),i=Object.entries(r).filter(([,f])=>Ce(f)).map(([f])=>f),s={},l=[],c=f=>{if(fe(s,f))return s[f];let d=r[f];if(!Ce(d))return o[f];let p=l.indexOf(f);if(p>=0){let h=[...l.slice(p),f].join(" -> ");throw new Error(`Computed variable cycle detected: ${h}`)}l.push(f);try{let h=Ds(d.computed,u,f);return Ps(f,d.type,h),s[f]=h,h}finally{l.pop()}},a=new Proxy({},{get:(f,d)=>{if(typeof d=="string")return c(d)},has:(f,d)=>typeof d=="string"&&(fe(o,d)||i.includes(d)),ownKeys:()=>[...new Set([...Object.keys(o),...i])],getOwnPropertyDescriptor:(f,d)=>{if(!(typeof d!="string"||!fe(o,d)&&!i.includes(d)))return{enumerable:!0,configurable:!0}}}),u={variables:a,runtime:t,resolveVariable:c};return n?(i.forEach(f=>{c(f)}),{...o,...s}):a},Ts=({variables:e={},runtime:t={},variableConfigs:r,projectData:n}={})=>Rt({variables:e,runtime:t,variableConfigs:r??n?.resources?.variables??{},eager:!0}),br=e=>{let t={},r={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([n,o])=>{if(Ce(o))return;let i=Cs(o,n);o.scope==="context"?t[n]=i:r[n]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}},Ot=(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(", ")}`)},Lt=(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(", ")}`)},Ns=2,qn=12,Xn=(e=Ns)=>{if(!Number.isInteger(e)||e<0||e>qn)throw new Error(`Operation "divide" requires roundTo to be an integer between 0 and ${qn}.`);return e},Vs=(e,t)=>{let r=10**t;return Math.round((e+Number.EPSILON)*r)/r},Ct=e=>typeof e=="number"&&Number.isFinite(e),Ir=(e,t,r,n,o={})=>{if(e==="number"){if(t==="set"&&!Ct(r))throw new Error(`Operation "set" requires value to be a number for variable "${n}".`);if(t==="multiply"&&!Ct(r))throw new Error(`Operation "multiply" requires value to be a number for variable "${n}".`);if(t==="divide"&&!Ct(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}".`);Xn(o.roundTo)}}},$t=(e,t,r,n={})=>{let o=(s,l,c)=>{let a=s??l;if(!Ct(a))throw new Error(`Operation "${t}" requires ${c} to be a number.`);return a},i=s=>{let l=o(s,void 0,"value");if(l===0)throw new Error(`Operation "${t}" requires value to be a non-zero number.`);return l};switch(t){case"set":return r;case"multiply":return o(e,1,"current value")*o(r,void 0,"value");case"divide":return Vs(o(e,0,"current value")/i(r),Xn(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 Qn=(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()))},js=(e,t)=>{let r=i=>{if(!i)return;let s={};i.ui&&(s.ui=i.ui);let l=i.character?.sprite;return l&&Object.keys(l).length>0&&(s.sprite=l),Object.keys(s).length>0?s:void 0},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},Yn=e=>{if(e?.resourceId===void 0)return;let t={resourceId:e.resourceId};return e.transformId!==void 0&&(t.transformId=e.transformId),e.loop!==void 0&&(t.loop=e.loop),t},Hn=e=>{if(e?.colorId!==void 0)return{colorId:e.colorId}},Kn=(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,Ms=(e,t)=>{let r={},n=Kn(Yn(e),Yn(t)),o=Kn(Hn(e),Hn(t));return n&&(r.resource=n),o&&(r.color=o),Object.keys(r).length>0?r:null},Ar=(e={},t={})=>{let r={},n=["sfx","voice"],o=l=>{let c=e[l],a=t[l];a&&!c?r[l]={changeType:"add",data:a}:c&&!a?n.includes(l)||(r[l]={changeType:"delete",data:c}):c&&a&&JSON.stringify(c)!==JSON.stringify(a)&&(r[l]={changeType:"update",data:a})},i=Ms(e.background,t.background);i&&(r.background=i),o("screen"),o("bgm"),o("voice");let s=js(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},wr=(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(l=>{let c={...l};return delete c.animations,i(c)?c: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},Fs=(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},Us=(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=Fs(t,r);if(n===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return n},Bs={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"])},Zn=(e,t)=>{let r=e[e.length-1];return r?Bs[r]?.has(t)===!0:!1},gr=(e,t,r=[])=>Array.isArray(e)?e.map(n=>gr(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,Zn(r,n)?o:gr(o,t,[...r,n])])):Us(e,t),yr=(e,t,r=[])=>Array.isArray(e)?e.map(n=>yr(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,Zn(r,n)?o:yr(o,t,[...r,n])])):typeof e=="string"?ne(e,t):e,Er=(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=gr(e,t._event);return yr(r,t)};var te=e=>structuredClone(ie(e)?De(e):e),G=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),eo=e=>e?.animations?.playback?.continuity==="persistent",H=(e,t)=>G(e??{},t)&&e[t]!==void 0,it=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:te(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},zs=e=>H(e,"opacity")||H(e,"blur"),Ws=(e,t,r)=>{let n=e[r];return n?.id===t?.id?n:e.find(o=>o.id===t?.id)},qs=(e,t)=>(t&&(!H(e,"opacity")&&H(t,"opacity")&&(e.opacity=t.opacity),!H(e,"blur")&&H(t,"blur")&&(e.blur=te(t.blur)),G(e,"opacity")&&e.opacity===void 0&&delete e.opacity,G(e,"blur")&&e.blur===void 0&&delete e.blur),e),ro=(e,t,r=[])=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let n=e.map((o,i)=>{let s=Ws(r,o,i),l=t(o),c=zs(o),a=G(o,"animations"),u=te(o);return!l&&c&&s&&(u={...te(s),...u},a||delete u.animations),qs(u,s)}).filter(o=>t(o)||o.animations);return{hasValidItems:n.length>0,processedItems:n}},Ys=e=>{if(e){if(e.character&&G(e.character,"name"))return e.character.name;if(G(e,"characterName"))return e.characterName}},no=e=>!!e?.character&&G(e.character,"sprite"),Hs=e=>{let t={},r=!1,n=Ys(e);return n!==void 0&&(t.name=n,r=!0),no(e)&&(t.sprite=te(e.character.sprite),r=!0),r?t:void 0},to=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},Ks=({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=>te(o)):delete e.initialRevealedContent,e.content=[...n,...t]},Gs=()=>({}),Js=(e,t)=>{if(!t.screen)return;let r=H(t.screen,"opacity"),n=H(t.screen,"blur"),o=G(t.screen,"animations");if(!r&&!n){o||delete e.screen;return}let i=e.screen,s={};if(r?s.opacity=t.screen.opacity:H(i,"opacity")&&(s.opacity=i.opacity),n?s.blur=te(t.screen.blur):H(i,"blur")&&(s.blur=te(i.blur)),G(s,"opacity")&&s.opacity===void 0&&delete s.opacity,G(s,"blur")&&s.blur===void 0&&delete s.blur,Object.keys(s).length===0){delete e.screen;return}e.screen=s},Xs=(e,t)=>{if(t.background){let r=H(t.background,"resourceId"),n=H(t.background,"colorId"),o=H(t.background,"opacity"),i=H(t.background,"blur"),{animationsOnly:s,state:l}=it(t.background,u=>H(u,"resourceId")||H(u,"colorId")||H(u,"opacity")||H(u,"blur"));if(s){e.background=e.background?{...te(e.background),...l}:l;return}if(!r&&!n&&!o&&!i){delete e.background;return}let c=e.background,a=te(t.background);if(!r&&c?.resourceId&&(a.resourceId=c.resourceId,!G(a,"transformId")&&c.transformId&&(a.transformId=c.transformId)),!n&&c?.colorId&&(a.colorId=c.colorId),!o&&H(c,"opacity")&&(a.opacity=c.opacity),!i&&H(c,"blur")&&(a.blur=te(c.blur)),G(a,"resourceId")&&a.resourceId===void 0&&delete a.resourceId,G(a,"colorId")&&a.colorId===void 0&&delete a.colorId,G(a,"animations")&&a.animations===void 0&&delete a.animations,G(a,"opacity")&&a.opacity===void 0&&delete a.opacity,G(a,"blur")&&a.blur===void 0&&delete a.blur,!a.resourceId&&!a.colorId){delete e.background;return}c?.resourceId===a.resourceId&&c?.transformId===a.transformId&&!G(a,"animations")&&eo(c)&&(a.animations=te(c.animations)),e.background=a}else e.background?.animations&&!eo(e.background)&&(e.background.animations={})},Qs=(e,t)=>{if(!t.dialogue){e.dialogue&&(to(e.dialogue),e.dialogue.mode==="adv"&&(e.dialogue.content=void 0,delete e.dialogue.initialRevealedContent,e.dialogue.persistCharacter!==!0&&(delete e.dialogue.characterId,delete e.dialogue.character)));return}e.dialogue||(e.dialogue={});let r=e.dialogue.mode;if(t.dialogue.ui){let{animationsOnly:a,state:u}=it(t.dialogue.ui,f=>!!f.resourceId);a?e.dialogue.ui={...e.dialogue.ui,...u}:e.dialogue.ui={...t.dialogue.ui}}else e.dialogue?.ui?.animations&&(e.dialogue.ui.animations={});t.dialogue.mode==="adv"&&(e.dialogue.content=e.dialogue.content||void 0,e.dialogue.characterId=e.dialogue.characterId||void 0,e.dialogue.mode="adv"),t.dialogue.mode==="nvl"&&(e.dialogue?.mode!=="nvl"&&(e.dialogue.lines=[]),e.dialogue.mode="nvl");let n=t.dialogue.append===!0&&r!=="nvl"&&e.dialogue?.mode!=="nvl"&&Array.isArray(t.dialogue.content);t.dialogue.content!==void 0&&Ks({dialogueState:e.dialogue,content:t.dialogue.content,append:n});let o=G(t.dialogue,"persistCharacter")?t.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;o?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let i=G(t.dialogue,"characterId"),s=Hs(t.dialogue),l=s!==void 0,c=no(t.dialogue);if(i?t.dialogue.characterId?e.dialogue.characterId=t.dialogue.characterId:delete e.dialogue.characterId:!o&&!n&&delete e.dialogue.characterId,l?e.dialogue.character=!i&&o&&e.dialogue.character?{...te(e.dialogue.character),...s}:s:(i||!o&&!n)&&delete e.dialogue.character,c||to(e.dialogue),t.dialogue.clear){delete e.dialogue;return}if(t.dialogue?.clearPage&&e.dialogue?.mode==="nvl"&&(e.dialogue.lines=[]),e.dialogue?.mode==="nvl"&&t.dialogue.content!==void 0){let a={content:t.dialogue.content,characterId:e.dialogue.characterId??null};e.dialogue.character&&(a.character=te(e.dialogue.character)),e.dialogue.lines.push(a)}},Zs=(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},ea=(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}}},ta=(e,t)=>{if(t.visual){let{hasValidItems:r,processedItems:n}=ro(t.visual.items,o=>!!o.resourceId,e.visual?.items||[]);r?e.visual={items:n}:delete e.visual}else e.visual?.items&&(e.visual.items=e.visual.items.map(r=>r.animations?{...r,animations:{}}:r))},ra=(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}=ro(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},na=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},oa=(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},ia=(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},sa=(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=te(t.form)}else e.form&&delete e.form},aa=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},ca=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},la=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(r=>{delete e[r]})},Te=e=>_t(Gs,[la,Js,Xs,Zs,ea,ta,Qs,ra,na,oa,ia,sa,aa,ca])(e);var ua=Object.freeze({dialogueTextSpeed:{source:"global.dialogueTextSpeed"},autoForwardDelay:{source:"global.autoForwardDelay"},skipUnseenText:{source:"global.skipUnseenText"},skipTransitionsAndAnimations:{source:"global.skipTransitionsAndAnimations"},soundVolume:{source:"global.soundVolume"},musicVolume:{source:"global.musicVolume"},muteAll:{source:"global.muteAll"},saveLoadPagination:{source:"context.runtime.saveLoadPagination"},menuPage:{source:"context.runtime.menuPage"},menuEntryPoint:{source:"context.runtime.menuEntryPoint"},autoMode:{source:"global.autoMode"},skipMode:{source:"global.skipMode"},dialogueUIHidden:{source:"global.dialogueUIHidden"},isLineCompleted:{source:"global.isLineCompleted"}}),Ne=Object.freeze({dialogueTextSpeed:50,autoForwardDelay:1e3,skipUnseenText:!1,skipTransitionsAndAnimations:!1,soundVolume:50,musicVolume:50,muteAll:!1,autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isLineCompleted:!1}),st=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),oo=Object.freeze({dialogueTextSpeed:"number",autoForwardDelay:"number",skipUnseenText:"boolean",skipTransitionsAndAnimations:"boolean",soundVolume:"number",musicVolume:"number",muteAll:"boolean",saveLoadPagination:"number",menuPage:"string",menuEntryPoint:"string",autoMode:"boolean",skipMode:"boolean",dialogueUIHidden:"boolean",isLineCompleted:"boolean"}),vr=Object.freeze(["dialogueTextSpeed","autoForwardDelay","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),xr=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),fa=(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(ua).map(([t,r])=>{let n=fa(e,r.source),o=n!==void 0?n:Ne[t]??st[t];return[t,o]})),Ae=(e,t)=>Ye(e)[t],io=(e={})=>Object.fromEntries(vr.map(t=>[t,e[t]??Ne[t]]));var at=Object.freeze({VISUAL_BEHIND_BACKGROUND:10,BACKGROUND:20,VISUAL_BEHIND_CHARACTER:30,CHARACTER:40,VISUAL_BEHIND_DIALOGUE:50,DIALOGUE:60,VISUAL_FOREGROUND:70}),Se=Object.freeze({BEHIND_BACKGROUND:at.VISUAL_BEHIND_BACKGROUND,BEHIND_CHARACTER:at.VISUAL_BEHIND_CHARACTER,BEHIND_DIALOGUE:at.VISUAL_BEHIND_DIALOGUE,FOREGROUND:at.VISUAL_FOREGROUND}),Cr=Se.BEHIND_DIALOGUE,Sr=Object.freeze(Object.values(Se).sort((e,t)=>e-t));var _e={objectValues:e=>Object.entries(e).map(([t,r])=>({id:t,...r})),formatDate:Qn},da=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,pa=(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},Dt=(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),l=da.exec(s);if(l){let[,c,a,u]=l,f=pa(t,u);if(!Array.isArray(f))continue;let d=Array.isArray(i[s])?i[s]:[];f.forEach((p,h)=>{let g={...t,[c]:p};a&&(g[a]=h),d.forEach(y=>{let b=Dt(y,g,r),A=ne(b,g,r);Array.isArray(A)?o.push(...A):o.push(A)})});continue}}o.push(Dt(i,t,r))}return o}if(!e||typeof e!="object")return e;let n={};return Object.entries(e).forEach(([o,i])=>{n[o]=Dt(i,t,r)}),n},zr=({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".`)},ha=({id:e,targetId:t,animation:r,playback:n,animationPath:o="animation"})=>{let i=structuredClone(r);return zr({animationType:i.type,animationId:e,animationPath:o}),delete i.name,delete i.playback,i.id=e,i.targetId=t,n&&(i.playback=structuredClone(n)),i},ma=(e,{animationId:t="animation",animationPath:r="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return zr({animationType:e.type,animationId:t,animationPath:r}),e.type},ga=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},ya=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},Wr=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Io=e=>e?.playback?.continuity==="persistent",kr=e=>Array.isArray(e)?e.map(kr):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((t,r)=>(t[r]=kr(e[r]),t),{}),Tt=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let t=structuredClone(e);return delete t.playback,JSON.stringify(kr(t))},Ao=(e=[])=>e.filter(t=>Io(t)).map(t=>structuredClone(t)),wo=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,_r=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((t,r)=>Math.max(t,wo(r)),0),Eo=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max(_r(e.tween),_r(e.prev?.tween),_r(e.next?.tween),wo(e.mask?.progress)),so=({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(Tt).filter(Boolean));return e.some(n=>{if(!Io(n))return!1;let o=Tt(n);return o?r.has(o):!1})},de=({animationInstances:e,isLineCompleted:t,skipTransitionsAndAnimations:r,activePersistentAnimations:n,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||r?!1:i&&!t||so({animationInstances:e,activePersistentAnimations:n})?!0:i?!1:so({animationInstances:e,activePersistentAnimations:o}),ba=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),Ia=(e,t)=>{if(ba(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},Aa=({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?ha({id:n,targetId:o,animation:s,playback:r,animationPath:i}):null},wa=(e,{defaultTargetId:t,defaultId:r,animationPath:n="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return zr({animationType:o.type,animationId:o.id??r,animationPath:n}),o.id??=r,o.targetId??=t,o},qr=({animations:e,transitions:t,defaultTargetId:r,idPrefix:n,animationPathPrefix:o=n})=>{t.forEach((i,s)=>{e.push(wa(i,{defaultTargetId:r,defaultId:`${n}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},Dr=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let r=ne(e,t);return r&&typeof r=="object"?e:r},Pr=(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},Ea=({content:e,path:t,variables:r})=>Pr(e,t).reduce((n,o)=>{let i=Dr(o.text,{variables:r});return n+`${i??""}`.length},0),ao=(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))},kt=(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("-")}`},Rr=(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},va=(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},xa=(e={},t)=>{if(t){if(e.images?.[t])return"sprite";if(e.videos?.[t])return"video";if(e.layouts?.[t])return"container"}},Tr=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},Ca=(e={})=>e.textStyles||{},Sa=(e={})=>e.images||{},_a=(e={})=>e.colors||{},Ra=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,ct=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,Ke=(e,t,r)=>{if(typeof e!="string"||e.length===0)throw new Error(`${r} at "${t}" must resolve to a non-empty string`)},co=(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},Yr=(e,t)=>{if(typeof e!="string"||!Ra.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=Yr(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})`},Oa=(e={},t)=>{let r=Ca(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=co(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 l=e.colors?.[r.strokeColorId];if(!l)throw new Error(`Stroke color "${r.strokeColorId}" not found for text style "${t}"`);let c=co(r.strokeAlpha,"strokeAlpha",t);s.strokeColor=lo(l.hex,c,`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},Nr=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>Nr(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]=Nr(i,t,ct(r,o)));return e.textStyleId!==void 0&&(Ke(e.textStyleId,r,"textStyleId"),n.textStyle=Oa(t,e.textStyleId)),n},Hr=(e={},t)=>{let r=_a(e)?.[t];if(!r)throw new Error(`Color "${t}" not found`);return Yr(r.hex,`Color "${t}"`)},vo=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",Or=(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 ${vo(`${t}.fill`)} instead`)},La=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>lt(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]=lt(i,t,ct(r,o)));return e.colorId!==void 0&&(Ke(e.colorId,r,"colorId"),n.fill=Hr(t,e.colorId)),n},lt=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>lt(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 ${vo("fill")} instead`);Or(e,"hover",r),Or(e,"click",r),Or(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]=La(i,t,ct(r,o));continue}n[o]=lt(i,t,ct(r,o))}return e.type==="rect"&&e.colorId!==void 0&&(Ke(e.colorId,r,"colorId"),n.fill=Hr(t,e.colorId)),n},Lr=(e={},t)=>{let r=Sa(e)?.[t];return r||null},xo=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",uo=(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 ${xo(`${t}.${n}`)} instead`)},fo=(e,t,r)=>{let n=e[t];e[t]={...n&&typeof n=="object"&&!Array.isArray(n)?n:{},src:r}},Vr=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>Vr(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 ${xo(o)} instead`);uo(e,"hover",r,"src"),uo(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]=Vr(i,t,ct(r,o)));if(e.type==="sprite"&&e.imageId!==void 0){Ke(e.imageId,r,"imageId");let o=Lr(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&&(Ke(e.hoverImageId,r,"hoverImageId"),fo(n,"hover",Lr(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(Ke(e.clickImageId,r,"clickImageId"),fo(n,"click",Lr(t,e.clickImageId)?.fileId??e.clickImageId)),n},Kr=(e,t={},r="root")=>Vr(lt(Nr(e,t,r),t,r),t,r),Re=Kr,Ve=(e=[])=>e.find(t=>t.id==="story"),$a="#000000",jr="bg-cg-background-color",ka=({resources:e={},background:t={},screen:r})=>t?.colorId===void 0?Yr(r?.backgroundColor??$a,"screen.backgroundColor"):Hr(e,t.colorId),Co=(e={})=>{if(Wr(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},Da=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},po=(e={},{includeDefaultAlpha:t=!1}={})=>{let r=Co(e),n=Da(e),o={};return(t||r!==void 0)&&(o.alpha=r??1),n&&(o.blur=n),o},Pa=(e={})=>{if(Wr(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},Ta=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},So=(e={})=>{let t=Pa(e),r=Ta(e),n={};return t!==void 0&&(n.alpha=t),r&&(n.blur=r),n},Pt=(e={})=>So(e),Na=({resources:e,background:t,screen:r={width:1920,height:1080},includeOpacity:n=!1})=>{let o={id:jr,type:"rect",x:0,y:0,width:r?.width??1920,height:r?.height??1080,fill:ka({resources:e,background:t,screen:r})};if(n){let i=Co(t);i!==void 0&&(o.alpha=i)}return o},Va=(e={},t)=>t?!!(e.images?.[t]||e.videos?.[t]||e.layouts?.[t]):!1,ho=({resources:e={},resourceId:t,colorId:r})=>{let n=xa(e,t);return t&&(n||r===void 0)?{resourceId:t,targetId:Tr({resourceId:t,kind:n})}:r!==void 0?{resourceId:jr,targetId:jr}:{resourceId:void 0,targetId:void 0}},_o=100,Vt=_o,Ro=(e,t)=>e*t/_o,ja=(e={},t=Vt)=>e?.muteAll?0:Ro(t,e?.soundVolume??Ne.soundVolume),Ma=(e={},t=Vt)=>e?.muteAll?0:Ro(t,e?.musicVolume??Ne.musicVolume),Fa=({item:e,index:t}={})=>`sfx:${t}:${e?.resourceId}`,pe=({variables:e,runtime:t,saveSlots:r=[],dialogueState:n,includeInactiveAdvDialogue:o=!1,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,confirmDialog:f,form:d,historyDialogue:p=[],characters:h={},dialogueUIHidden:g,skipOnlyViewedLines:y,skipTransitionsAndAnimations:b}={})=>{let A={dialogueTextSpeed:t?.dialogueTextSpeed??50,autoForwardDelay:t?.autoForwardDelay??1e3,skipUnseenText:t?.skipUnseenText??!1,skipTransitionsAndAnimations:t?.skipTransitionsAndAnimations??!1,soundVolume:t?.soundVolume??50,musicVolume:t?.musicVolume??50,muteAll:t?.muteAll??!1,saveLoadPagination:t?.saveLoadPagination??1,menuPage:t?.menuPage??"",menuEntryPoint:t?.menuEntryPoint??"",autoMode:t?.autoMode??s??!1,skipMode:t?.skipMode??l??!1,dialogueUIHidden:t?.dialogueUIHidden??g??!1,isLineCompleted:t?.isLineCompleted??i??!1},x=qa({dialogueState:n,includeInactiveAdvDialogue:o,characters:h,variables:e}),S={variables:e,runtime:A,saveSlots:r,isChoiceVisible:c,isFormVisible:a,canRollback:u,confirmDialog:f,form:d,historyDialogue:p,characters:h};return x&&(S.dialogue=x,S.dialogueLines=x.lines),S},mo=100,Nt=(e,t)=>{if(Array.isArray(e))return e.map(n=>Nt(n,t));if(!e||typeof e!="object")return e;let r={...e};return Object.keys(r).forEach(n=>{r[n]=Nt(r[n],t)}),r.type==="text-revealing"?t(r):r},Ua=e=>Nt(e,t=>({...t,revealEffect:"none"})),Ba=e=>Nt(e,t=>{let r=Number(t.speed??t.displaySpeed),n=Number.isFinite(r)?Math.max(r,mo):mo;return{...t,speed:n,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:n}:{}}}),Oe=(e,{isLineCompleted:t=!1,skipMode:r=!1,skipTransitionsAndAnimations:n=!1}={})=>t||n?Ua(e):r?Ba(e):e,Oo=({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:{}}}}),Mr=e=>{if(Array.isArray(e))return e.map(Mr);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=Mr(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}}:{}}}}},za=new Set(["click","change","submit","focusEvent","blurEvent","selectionChange","compositionStart","compositionUpdate","compositionEnd"]),go=(e,t)=>{let r=e?.payload&&typeof e.payload=="object"&&!Array.isArray(e.payload)?e.payload:{},n=r.actions&&typeof r.actions=="object"?r.actions:{};return{...e||{},payload:{...r,actions:{...n,...t}}}},Fr=(e,t)=>{if(Array.isArray(e))return e.map(i=>Fr(i,t));if(!e||typeof e!="object")return e;let r={};for(let[i,s]of Object.entries(e))r[i]=Fr(s,t);if(r.type!=="input"||typeof r.field!="string")return r;let n=t?.fields?.[r.field];if(!n)return r;let o={updateFormField:{formId:t.id,formKey:t.key,field:n.id,value:"_event.value",_interactionSource:"form"}};return{...r,value:n.value,placeholder:r.placeholder===void 0?n.placeholder:r.placeholder,multiline:r.multiline===void 0?n.multiline:r.multiline,...r.maxLength===void 0&&n.maxLength!==void 0?{maxLength:n.maxLength}:{},change:go(r.change,o),submit:go(r.submit,t.submitActions)}},Ur=(e,t)=>{if(Array.isArray(e))return e.map(n=>Ur(n,t));if(!e||typeof e!="object")return e;let r={};for(let[n,o]of Object.entries(e))r[n]=Ur(o,t);for(let n of za){let o=r[n]?.payload;!o||typeof o!="object"||Array.isArray(o)||(r[n]={...r[n],payload:{...o,_interactionSource:"form",_formId:t.id,_formKey:t.key}})}return r},Br=({characterId:e,character:t,characterName:r,characters:n={}}={})=>{let o=e?n?.[e]:void 0,i=t?.name!==void 0?t.name:r!==void 0?r:o?.name||"";return{...o||{},...t||{},name:i}},Lo=(e=[],t={})=>e.map(r=>{let n=Br({characterId:r.characterId,character:r.character,characterName:r.characterName,characters:t}),o=typeof r.text=="string"?r.text:Array.isArray(r.content)?r.content.map(i=>i?.text??"").join(""):"";return{...r,text:o,character:n,characterName:n.name}}),Wa=e=>!(!e||e.mode==="adv"&&e.content===void 0),qa=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:r={},variables:n}={})=>{if(!t&&!Wa(e))return;let o=e.content===void 0?[{text:""}]:Pr(e.content,"dialogue.content"),i=e.content===void 0?0:Ea({content:e.initialRevealedContent,path:"dialogue.initialRevealedContent",variables:n}),s=(e.lines||[]).map((c,a)=>{let u=Pr(c.content,`dialogue.lines[${a}].content`),f=Br({characterId:c.characterId,character:c.character,characterName:c.characterName,characters:r});return{...c,content:u.map(d=>({...d,text:Dr(d.text,{variables:n})})),character:f,characterName:f.name}}),l=Br({characterId:e.characterId,character:e.character,characters:r});return{characterId:e.characterId,persistCharacter:e.persistCharacter,character:l,content:o.map(c=>({...c,text:Dr(c.text,{variables:n})})),initialRevealedCharacters:i,lines:s}},$o=({container:e,resources:t,templateData:r,isLineCompleted:n=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=ne(e,r,{functions:_e});return Re(Oe(s,{isLineCompleted:n,skipMode:o,skipTransitionsAndAnimations:i}),t)},$r=(e,t={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(t),yo=({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:$r(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[n].keyup={payload:$r(o.keyup)});return}e[n]={...i,[r]:{payload:$r(o)}}})},Ya=(e={},t={})=>{let r={};return yo({renderStateKeyboard:r,keyboard:e,phase:"keydown"}),yo({renderStateKeyboard:r,keyboard:t,phase:"keyup"}),Object.keys(r).length>0?r:void 0},we=({animationsDef:e,resources:t,previousResourceId:r,currentResourceId:n,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:l})=>{if(!e)return[];let c=[],a=({instanceId:b,targetId:A})=>{let x=Aa({resources:t,animationId:p,playback:h,instanceId:b,targetId:A,animationPath:s});x&&c.push(x)},u=r!=null&&r!==!1,f=n!=null&&n!==!1,d=o&&i&&o===i;Ia(e,s);let p=ga(e),h=ya(e),g=t?.animations?.[p],y=ma(g,{animationId:p,animationPath:s});if(y==="update")return f&&i?a({instanceId:`${l}-animation-update`,targetId:i}):u&&o&&a({instanceId:`${l}-animation-update`,targetId:o}),c;if(y==="transition"){let b=`${l}-animation-transition`,A=h?.continuity==="persistent"?b:`${l}-animation-in`;if(u&&f&&d)return a({instanceId:b,targetId:i}),c;u&&a({instanceId:`${l}-animation-out`,targetId:o}),f&&a({instanceId:A,targetId:i})}return c},Ha=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),Ka=(e,{presentationState:t,previousPresentationState:r,currentLineActions:n,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:l,variables:c,runtime:a,activePersistentAnimations:u,restoredPersistentAnimations:f,autoMode:d,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:b,saveSlots:A=[]})=>{let{elements:x,animations:S}=e;if(t.background){let T=n===void 0?!0:Wr(n?.background??{},"animations"),w=x.find(F=>F.id==="story");if(!w)return e;let N=va(o,t.background),z=r?.background?.resourceId,k=r?.background?.colorId,j=t.background.resourceId??(t.background.animations?z:void 0),U=t.background.colorId??(t.background.animations?k:void 0),M=Va(o,j),W={...t.background,colorId:U};if((U!==void 0||M)&&w.children.push(Na({resources:o,background:W,screen:i,includeOpacity:!M})),j){let{images:F={},videos:q={}}=o,V=F[j]||q[j];if(V){let me=q[j]!==void 0,re={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...N},Be={id:Tr({resourceId:j,kind:me?"video":"sprite"}),type:me?"video":"sprite",x:re.x,y:re.y,src:V.fileId,width:V.width,height:V.height,...po(t.background,{includeDefaultAlpha:!0}),anchorX:re.anchorX,anchorY:re.anchorY,rotation:re.rotation,scaleX:re.scaleX,scaleY:re.scaleY};me&&(Be.loop=t.background.loop??!1,Be.volume=V.volume??50),w.children.push(Be)}}if(j){let{layouts:F={}}=o,q=F[j];if(q){let V={id:Tr({resourceId:j,kind:"container"}),type:"container",children:q.elements,...po(t.background)};N&&Object.assign(V,{x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...N});let me=ne(V,pe({variables:c,runtime:a,saveSlots:A,dialogueState:t.dialogue,isLineCompleted:s,autoMode:d,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:b,characters:o.characters||{},skipTransitionsAndAnimations:l}),{functions:_e});w.children.push(Re(Oe(me,{isLineCompleted:s,skipMode:p,skipTransitionsAndAnimations:l}),o))}}let v=ho({resources:o,resourceId:z,colorId:k}),_=ho({resources:o,resourceId:j,colorId:U}),R=we({animationsDef:t.background.animations,resources:o,previousResourceId:v.resourceId,currentResourceId:_.resourceId,previousTargetId:v.targetId,currentTargetId:_.targetId,animationPath:"background.animations",idPrefix:"bg-cg"});de({animationInstances:R,isLineCompleted:s,skipTransitionsAndAnimations:l,activePersistentAnimations:u,restoredPersistentAnimations:f,isAuthoredOnCurrentLine:T})&&S.push(...R)}return e},Ga=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:l,animations:c}=e;if(t.character&&n){let a=l.find(h=>h.id==="story");if(!a)return e;let u=t.character.items||[],f=r?.character?.items||[],d=ao(u),p=ao(f);for(let h=0;h<u.length;h++){let g=u[h],{transformId:y,sprites:b}=g,A=f.find(U=>U.id===g.id),x=f.findIndex(U=>U.id===g.id),S=A?.sprites&&A.sprites.length>0,T=b&&b.length>0,w=x>=0?kt(A,x,p):void 0,N=we({animationsDef:g.animations,resources:n,previousResourceId:w,currentResourceId:T?kt(g,h,d):void 0,previousTargetId:w,currentTargetId:T?kt(g,h,d):void 0,animationPath:`character.items[${h}].animations`,idPrefix:"character"});if(g.animations&&!b&&!y&&S&&de({animationInstances:N,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){c.push(...N);continue}if(g.animations&&!b&&!y)continue;if(!b||b.length===0||!y){console.warn("Character item missing sprites or transformId:",g);continue}let z=kt(g,h,d),k=n.transforms[y];if(!k){console.warn("Transform not found:",y);continue}let j={type:"container",id:z,x:g.x??k.x,y:g.y??k.y,anchorX:k.anchorX,anchorY:k.anchorY,rotation:k.rotation,scaleX:k.scaleX,scaleY:k.scaleY,...Pt(g),children:[]};for(let U of b){let M=n.images[U.resourceId];if(!M){console.warn(`Image resource not found: ${U.resourceId}`);continue}j.children.push({type:"sprite",id:`${z}-${U.id}`,src:M.fileId,width:M.width,height:M.height,x:0,y:0})}a.children.push(j),de({animationInstances:N,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...N)}}return e},ko=(e,t)=>{if(!Sr.includes(e))throw new Error(`${t} must be one of: ${Sr.join(", ")}.`)},Ja=(e,t)=>{let r=e.layer??(e.resourceId?void 0:t?.layer)??Cr;return ko(r,`Visual item "${e.id}" layer`),r},Xa=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,runtime:l,activePersistentAnimations:c,autoMode:a,skipMode:u,isChoiceVisible:f,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,T=r?.visual?.items||[];y!==void 0&&ko(y,"visualLayer");for(let w of S){let N=T.find(j=>j.id===w.id),z=Ja(w,N);if(y!==void 0&&z!==y)continue;if(w.resourceId){let{images:j={},videos:U={},spritesheets:M={}}=n,W=M[w.resourceId];if(W){let v=Rr(n,w),_=w.animationName;if(_){let R=W.animations?.[_];if(!R)throw new Error(`Animation '${_}' not found in spritesheet resource '${w.resourceId}'`);let F=Pt(w),q={id:`visual-${w.id}`,type:"animated-sprite",x:w.x??v.x,y:w.y??v.y,width:w.width??W.width,height:w.height??W.height,alpha:F.alpha??w.alpha??1,anchorX:v.anchorX,anchorY:v.anchorY,rotation:v.rotation,scaleX:v.scaleX,scaleY:v.scaleY,spritesheetSrc:W.fileId,spritesheetData:W.jsonData,animation:{frames:R.frames,animationSpeed:w.animationSpeed??R.animationSpeed??.5,loop:w.loop??R.loop??!0}};F.blur&&(q.blur=F.blur),x.children.push(structuredClone(q))}}else{let v=j[w.resourceId]||U[w.resourceId];if(v){let _=U[w.resourceId]!==void 0,R=Rr(n,w),F={id:`visual-${w.id}`,type:_?"video":"sprite",src:v.fileId,width:v.width,height:v.height,x:R.x,y:R.y,anchorX:R.anchorX,anchorY:R.anchorY,rotation:R.rotation,scaleX:R.scaleX,scaleY:R.scaleY};Object.assign(F,Pt(w)),_&&(F.loop=v.loop??!1,F.volume=v.volume??50),x.children.push(F)}}}if(w.resourceId){let{layouts:j={}}=n,U=j[w.resourceId];if(U){let M=Rr(n,w),W={id:`visual-${w.id}`,type:"container",children:structuredClone(U.elements),x:M.x,y:M.y,anchorX:M.anchorX,anchorY:M.anchorY,rotation:M.rotation,scaleX:M.scaleX,scaleY:M.scaleY};Object.assign(W,Pt(w));let v=ne(W,pe({variables:s,runtime:l,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:o,autoMode:a,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:i}),{functions:_e});x.children.push(Re(Oe(v,{isLineCompleted:o,skipMode:u,skipTransitionsAndAnimations:i}),n))}}let k=we({animationsDef:w.animations,resources:n,previousResourceId:N?.resourceId,currentResourceId:w.resourceId,previousTargetId:N?.resourceId?`visual-${w.id}`:void 0,currentTargetId:w.resourceId?`visual-${w.id}`:void 0,animationPath:`visual.items[${w.id}].animations`,idPrefix:w.id});de({animationInstances:k,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:c})&&A.push(...k)}}return e},He="dialogue-character-sprite",bo=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,Qa=(e,{presentationState:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:l}=e,c=Ve(e.elements);if(!c)return e;let a=t.dialogue?.character?.sprite,u=r?.dialogue?.character?.sprite,f=bo(a),d=bo(u),p=we({animationsDef:a?.animations,resources:n,previousResourceId:d?He:void 0,currentResourceId:f?He:void 0,previousTargetId:d?He:void 0,currentTargetId:f?He:void 0,animationPath:"dialogue.character.sprite.animations",idPrefix:"dialogue-character-sprite"});if(!f)return a?.animations&&d&&de({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...p),e;let h=n.transforms?.[a.transformId];if(!h)return console.warn("Transform not found:",a.transformId),e;let g={type:"container",id:He,x:h.x,y:h.y,anchorX:h.anchorX,anchorY:h.anchorY,rotation:h.rotation,scaleX:h.scaleX,scaleY:h.scaleY,children:[]};for(let y of a.items){let b=n.images?.[y.resourceId];if(!b){console.warn(`Image resource not found: ${y.resourceId}`);continue}g.children.push({type:"sprite",id:`${He}-${y.id}`,src:b.fileId,width:b.width,height:b.height,x:0,y:0})}return c.children.push(g),de({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...p),e},Za=(e,{presentationState:t,previousPresentationState:r,resources:n={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:c,canRollback:a,form:u,skipOnlyViewedLines:f,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(w=>w.id==="story");if(!S)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:w={}}=n,N=w[t.dialogue.ui.resourceId];if(N){let z={elements:N.elements},k=pe({variables:h,runtime:g,saveSlots:b,dialogueState:t.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:d,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:c,canRollback:a,form:u,characters:n.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:f,skipTransitionsAndAnimations:p}),j={functions:_e},U=Dt(z,k,j),M=ne(U,k,j),W=Re(Oe(M?.elements,{isLineCompleted:d,skipMode:s,skipTransitionsAndAnimations:p}),n);if(Array.isArray(W))for(let v of W)S.children.push(v);else W&&S.children.push(W)}}Qa(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:d,skipTransitionsAndAnimations:p,activePersistentAnimations:y});let T=we({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 de({animationInstances:T,isLineCompleted:d,skipTransitionsAndAnimations:p,activePersistentAnimations:y})&&x.push(...T),e},ec=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,runtime:c,autoMode:a,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,form:h,activePersistentAnimations:g,saveSlots:y=[]})=>{let{elements:b,animations:A}=e;if(t.choice&&n){let x=Ve(b);if(!x)return e;let S=n?.layouts[t.choice.resourceId];if(S&&S.elements){let w={elements:S.elements},N=ne(w,{...pe({variables:l,runtime:c,saveSlots:y,dialogueState:t.dialogue,isLineCompleted:i,autoMode:a,skipMode:u,isChoiceVisible:f??!!t.choice,isFormVisible:d,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}},{functions:_e}),z=Mr(Re(Oe(N?.elements,{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),n));if(Array.isArray(z))for(let k of z)x.children.push(k);else z&&x.children.push(z)}let T=we({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"});de({animationInstances:T,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:g})&&A.push(...T)}return e},tc=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,runtime:c,autoMode:a,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,activePersistentAnimations:h,saveSlots:g=[],form:y})=>{let{elements:b,animations:A}=e;if(!y?.resourceId||!n)return e;let x=Ve(b);if(!x)return e;let S=n?.layouts?.[y.resourceId];if(!S)return console.warn(`Form layout not found: ${y.resourceId}`),e;let T={id:"form-container",type:"container",x:0,y:0,children:S.elements||[]},w={...pe({variables:l,runtime:c,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:i,autoMode:a,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,characters:n.characters||{},skipTransitionsAndAnimations:s,form:y}),form:y},N=ne(T,w,{functions:_e}),z=Ur(Re(Oe(Fr(N,y),{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),n),y);z&&x.children.push(z);let k=we({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 de({animationInstances:k,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:h})&&A.push(...k),e},rc=(e,{presentationState:t,resources:r={},variables:n,runtime:o,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,form:f,saveSlots:d=[],skipTransitionsAndAnimations:p})=>{if(!t.control?.resourceId)return e;let h=r.controls?.[t.control.resourceId];if(!h)return e;let g=Ya(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=Ve(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($o({container:b,resources:r,templateData:pe({variables:n,runtime:o,saveSlots:d,dialogueState:t.dialogue,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,form:f,characters:r.characters||{},skipTransitionsAndAnimations:p}),isLineCompleted:i,skipMode:l,skipTransitionsAndAnimations:p})),e},nc=(e,{presentationState:t,resources:r,runtime:n,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&r){if(!Ve(i))return e;let c=r.sounds[t.bgm.resourceId];if(!c)return e;let a=pe({variables:o,runtime:n}).runtime;s.push({id:"bgm",type:"sound",src:c.fileId,loop:t.bgm.loop??!0,volume:Ma(a,t.bgm.volume??c.volume??Vt),startDelayMs:t.bgm.startDelayMs??null})}return e},oc=(e,{presentationState:t,resources:r,runtime:n})=>{let{audio:o}=e;if(t.sfx&&r){let i=t.sfx.items;for(let[s,l]of i.entries()){let c=r.sounds?.[l.resourceId];c&&o.push({id:Fa({item:l,index:s}),type:"sound",src:c.fileId,loop:l.loop??c.loop??!1,volume:ja(n,l.volume??c.volume??Vt),startDelayMs:l.startDelayMs??c.startDelayMs??null})}}return e},ic=(e,t,r)=>{if(!(!t||!r))return e?.voices?.[t]?.[r]},sc=(e={},t={})=>t.muteAll?0:e.volume??t.soundVolume??50,ac=(e,{presentationState:t,resources:r,currentSceneId:n,runtime:o,variables:i})=>{let{audio:s}=e;if(!t?.voice)return e;let l=t.voice,{resourceId:c,loop:a,startDelayMs:u}=l,f=ic(r,n,c);if(!f)return e;let d=pe({variables:i,runtime:o}).runtime;return s.push({id:`voice-${n}-${c}`,type:"sound",src:f.fileId,volume:sc(l,d),loop:a??!1,startDelayMs:u??null}),e},cc=(e,{presentationState:t,previousPresentationState:r,resources:n={},variables:o,runtime:i,autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,form:f,saveSlots:d=[],isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})=>{let{elements:y,animations:b}=e;if(t.layout){let T=Ve(y);if(!T)return e;let w=n.layouts[t.layout.resourceId];if(!w)return e;Array.isArray(w.transitions)&&!p&&!h&&qr({animations:b,transitions:w.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let N={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:w.elements||[]};T.children.push($o({container:N,resources:n,templateData:pe({variables:o,runtime:i,saveSlots:d,dialogueState:t.dialogue,isLineCompleted:p,autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,form:f,characters:n.characters||{},skipTransitionsAndAnimations:h}),isLineCompleted:p,skipMode:l,skipTransitionsAndAnimations:h}))}let A=r?.layout?.resourceId,x=t.layout?.resourceId,S=we({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 de({animationInstances:S,isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})&&b.push(...S),e},lc=(e,{currentLineActions:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:l}=e,c=t?.screen?.animations;if(!c)return e;let a=r!=null,u=we({animationsDef:c,resources:n,previousResourceId:a?"story":void 0,currentResourceId:"story",previousTargetId:a?"story":void 0,currentTargetId:"story",animationPath:"screen.animations",idPrefix:"screen"});return de({animationInstances:u,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...u),e},uc=(e,{presentationState:t})=>{let r=Ve(e.elements);return!r||!t?.screen||Object.assign(r,So(t.screen)),e},fc=(e,{presentationState:t,resources:r={},variables:n,runtime:o,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:c,canRollback:a,form:u,overlayStack:f=[],dialogueHistory:d=[],saveSlots:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:b,animations:A}=e;return f&&f.length>0&&f.forEach((x,S)=>{let T=r.layouts[x.resourceId];if(!T){console.warn(`Overlay layout not found: ${x.resourceId}`);return}Array.isArray(T.transitions)&&(y||qr({animations:A,transitions:T.transitions,defaultTargetId:`overlayStack-${S}`,idPrefix:`overlayStack-${S}`,animationPathPrefix:`overlayStack[${S}]`}));let w={id:`overlayStack-${S}`,type:"container",x:0,y:0,children:[Oo({id:`overlayStack-${S}-blocker`,screen:h}),...T.elements||[]]},N=Lo(d,r.characters),z=pe({variables:n,runtime:o,saveSlots:p,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:c,canRollback:a,form:u,historyDialogue:N,characters:r.characters||{},skipTransitionsAndAnimations:y}),k=ne(w,z,{functions:_e}),[j,...U]=k.children||[],M=Re(Oe({...k,children:U},{isLineCompleted:g,skipMode:s,skipTransitionsAndAnimations:y}),r);b.push({...M,children:j?[j,...M.children||[]]:M.children})}),e},dc=(e,{presentationState:t,resources:r={},variables:n,runtime:o,saveSlots:i=[],autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,form:f,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&&qr({animations:A,transitions:x.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let S={id:"confirmDialog",type:"container",x:0,y:0,children:[Oo({id:"confirmDialog-blocker",screen:h}),...x.elements||[]]},T=Lo(p,r.characters),w=ne(S,pe({variables:n,runtime:o,saveSlots:i,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,form:f,confirmDialog:d,historyDialogue:T,characters:r.characters||{},skipTransitionsAndAnimations:y}),{functions:_e}),[N,...z]=w.children||[],k=Re(Oe({...w,children:z},{isLineCompleted:g,skipMode:l,skipTransitionsAndAnimations:y}),r);return b.push({...k,children:N?[N,...k.children||[]]:k.children}),e},jt=e=>(t,r)=>Xa(t,{...r,visualLayer:e}),pc=jt(Se.BEHIND_BACKGROUND),hc=jt(Se.BEHIND_CHARACTER),mc=jt(Se.BEHIND_DIALOGUE),gc=jt(Se.FOREGROUND),Do=e=>_t(Ha,[rc,pc,Ka,hc,Ga,mc,Za,ec,tc,cc,gc,uc,lc,nc,oc,ac,fc,dc])(e);var Mt={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},jo=1,Gr="choice",Ft="form",zt=()=>({manual:{...Mt.manual},auto:{...Mt.auto},applyMode:Mt.applyMode}),Jr=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let r=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...zt()},r&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},P=e=>{let t=ie(e)?De(e):e;return structuredClone(t)},D=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Wt=e=>String(e),Mo=()=>({sections:[],resources:[]}),yc=e=>D(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):Mo(),bc=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",Ic=({sectionId:e,lineId:t,content:r,dialogueState:n,characterName:o})=>({sectionId:e,lineId:t,content:r,text:bc(r),characterId:n.characterId,character:{...n.character||{},name:o},characterName:o}),Ac=()=>({resourceId:void 0}),wc=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},Xr=(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}},Fo=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 l=r.get(s);if(l!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${l}" and "${n}". Section IDs must be globally unique.`);r.set(s,n)}}},Uo=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},Bo=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==jo)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},Ec=(e,t={})=>{let r;try{r=Bo(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let n={...t,formatVersion:r,slotId:Uo(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete n.slotKey,delete n.date,n},vc=(e={})=>Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Ec(t,r)])),zo=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:r})=>pu(r));return t.length>0?t:void 0},xc=e=>{!D(e)||!Array.isArray(e.timeline)||e.timeline.forEach(t=>{if(!D(t))return;let r=zo(t.executedActions);if(r){t.executedActions=r;return}delete t.executedActions})},Po=(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}},Cc=(e,t="viewedRegistry")=>{if(e===void 0)return Mo();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=Po(o,"sections",i,t);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(n.map((o,i)=>{let s=Po(o,"resources",i,t);return[s.resourceId,s]})))}},Wo=(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}=Xr(t,n);if(!s)throw new Error(`Malformed save slot ${r}: section "${n}" does not exist in projectData.`);if(!s.lines?.some(c=>c.id===o))throw new Error(`Malformed save slot ${r}: line "${o}" does not exist in section "${n}".`);return{sceneId:i,sectionId:n,lineId:o}},Sc=(e,t,r)=>{if(!D(e)||!Array.isArray(e.timeline))return ut({pointer:t,replayStartIndex:1});let n=e.timeline.flatMap((l,c)=>{if(!D(l))return[];try{let a=Wo(l,r,`rollback.timeline[${c}]`),u=Bt({sectionId:a.sectionId,lineId:a.lineId,rollbackPolicy:l.rollbackPolicy}),f=zo(P(l.executedActions));return f&&(u.executedActions=f),[u]}catch{return[]}});if(n.length===0)return ut({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 l=n.findLastIndex(c=>c.sectionId===t.sectionId&&c.lineId===t.lineId);l>=0?o=l:(n.push(Bt({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}},_c=(e,t,r)=>{if(!D(e))throw new Error(`Malformed save slot contexts[${r}] entry.`);let n=en(t),o=Wo(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?qe(P(e.variables),t.resources?.variables??{}):{},s=Fc({loadedContextRuntime:D(e.runtime)?P(e.runtime):{}}),l={currentPointerMode:"read",pointers:{read:o},configuration:D(e.configuration)?P(e.configuration):{},views:Array.isArray(e.views)?P(e.views):[],bgm:D(e.bgm)?P(e.bgm):{resourceId:void 0},variables:{...n,...i},rollback:Sc(e.rollback,o,t)};return s&&(l.runtime=s),l},Rc=(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)=>_c(r,t,n))}},Oc=(e,t)=>{if(!D(e))throw new Error("Malformed save slot.");let r=Bo(e.formatVersion);return{...e,formatVersion:r,state:Rc(e.state,t)}},To=(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=P(e);return Object.prototype.hasOwnProperty.call(n,"hideConfirmDialog")||(n.hideConfirmDialog={}),n},Lc=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:To(e.confirmActions,"confirmActions",{required:!0}),cancelActions:To(e.cancelActions,"cancelActions")}},Je=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},$c=e=>(D(e.global.formDrafts)||(e.global.formDrafts={}),e.global.formDrafts),Xe=e=>{Object.prototype.hasOwnProperty.call(e.global,"formDrafts")&&(e.global.formDrafts={})},qo=e=>{if(!(!D(e)||!e.animations))return{animations:P(e.animations)}},kc=(e,t)=>{let r=qo(t);if(r){e.global.pendingScreenTransition=r;return}delete e.global.pendingScreenTransition},Dc=e=>{let t=e?.id??e?.resourceId;return typeof t=="string"&&t.length>0?t:void 0},Pc=(e,t)=>{let r=e?.sectionId,n=e?.lineId;if(!(!r||!n||!t))return`${r}:${n}:${t}`},Ut=e=>String(e??""),Yo=(e,t)=>{let r=Ut(t);return e?.trim===!0?r.trim():r},Tc=e=>D(e?.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,t])=>D(t)).map(([t,r])=>[t,{id:t,...P(r)}])):{},Nc=(e,t)=>{if(!t||!D(e.global.formDrafts))return;let r=e.global.formDrafts[t];return D(r)?r:void 0},Ho=(e,t)=>{let r=$c(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},Qr=(e,t)=>{let r=Yo(e,t);return e?.required===!0&&r.length===0?"required":null},Vc=({state:e,pointer:t})=>{if(!t?.sectionId||!t?.lineId)return{};let n=Z({state:e},{sectionId:t.sectionId})?.lines||[],o=n.findIndex(i=>i.id===t.lineId);return o<0?{}:Te(n.slice(0,o+1).map(i=>i.actions||{}))},jc=({state:e,form:t,pointer:r})=>{if(!t?.resourceId)return null;let n=Dc(t),o=Pc(r,n);if(!n||!o)return null;let i=Nc(e,o),s=Tc(t),l=sn({state:e}),c={},a=[],u={},f=!0;return Object.entries(s).forEach(([d,p])=>{let h=Ut(l?.[p.variableId]),g=Object.prototype.hasOwnProperty.call(i?.values??{},d)?Ut(i.values[d]):h,y=i?.touched?.[d]===!0,b=Qr(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&&(f=!1),c[d]=S,a.push(S),u[d]=g}),{id:n,key:o,resourceId:t.resourceId,animations:t.animations,valid:f,submitted:i?.submitted===!0,fields:c,fieldList:a,values:u,submitActions:{submitForm:{formId:n,formKey:o,actions:P(t.submitActions??{})}},cancelActions:{cancelForm:{formId:n,formKey:o,actions:P(t.cancelActions??{})}}}},je=[],No="line",Zr="interaction",Bt=({sectionId:e,lineId:t,rollbackPolicy:r})=>({sectionId:e,lineId:t,rollbackPolicy:r??"free"}),en=e=>{let{contextVariableDefaultValues:t}=br(e??{});return P(t)},Ko=()=>({...P(st)}),Go=({loadedRuntime:e,runtimeIds:t,defaults:r={},path:n})=>{if(e===void 0)return{runtimeState:P(r),hasLoadedValues:!1};if(!D(e))throw new Error(`Malformed ${n}.`);let o=P(r),i=!1;return t.forEach(s=>{e[s]!==void 0&&(o[s]=Jo(s,P(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},Mc=({loadedGlobalRuntime:e={}})=>Go({loadedRuntime:e,runtimeIds:vr,defaults:Ne,path:"global.runtime"}).runtimeState,Fc=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:r}=Go({loadedRuntime:e,runtimeIds:xr,defaults:Ko(),path:"context.runtime"});return r?t:void 0},tn=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},Uc=e=>e.runtime?(xr.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=P(st[t]))}),e.runtime):(e.runtime=Ko(),e.runtime),Bc=e=>io(e.global),zc=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:Bc(e)}})},Wc=e=>oo[e],qc=(e,t)=>{let r=Wc(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}"`)},Jo=(e,t)=>(qc(e,t),e==="saveLoadPagination"?Math.max(1,Math.trunc(t)):t),Xo=(e,t,r)=>{let n=Jo(t,r);if(t in st){let o=tn(e);if(!o)return n;let i=Uc(o);return i[t]=n,n}return e.global[t]=n,n},Qo=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:P(e)},configuration:{},views:[],bgm:Ac(),variables:en(t),rollback:ut({pointer:e})}),Qe=e=>e?(e.currentPointerMode="read",D(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,Yc=(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=Qo({pointer:n,projectData:e.projectData});return e.contexts[e.contexts.length-1]=o,Hc(e,{queueRender:t}),o},Hc=(e,{queueRender:t=!0}={})=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,Je(e),Xe(e),e.global.nextLineConfig=zt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"}),t&&e.global.pendingEffects.push({name:"render"})},Zo=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},ut=({pointer:e,replayStartIndex:t=0})=>{let r=e?.sectionId&&e?.lineId;return{currentIndex:r?0:-1,isRestoring:!1,replayStartIndex:t,timeline:r?[Bt({sectionId:e.sectionId,lineId:e.lineId})]:[]}},Fe=(e,t={})=>{if(e?.rollback)return Zo(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=ut({pointer:r,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},rn=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return;let n=Fe(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(Bt(t)),n.currentIndex=n.timeline.length-1},Kc=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=je[je.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)},Gc=({state:e},t={})=>{let r=t?.source===No?No:Zr,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?(je.push({checkpointIndex:null,source:r}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),je.push({checkpointIndex:o.currentIndex,source:r}),e)},Jc=({state:e})=>(je.pop(),e),be=(e,t,r)=>{let o=je[je.length-1]?.source??Zr;if(!hu(t,o))return;let i=Kc(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:P(r)}))},Vo=(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:l}of n){let c=e.projectData.resources?.variables?.[o],a=c?.scope,u=c?.type;if(Ce(c))throw new Error(`Cannot update computed variable: ${o}`);if(c?.readonly===!0)throw new Error(`Cannot update readonly variable: ${o}`);Ot(a,o),Lt(u,i,o),Ir(u,i,s,o,{roundTo:l}),a==="context"&&(r.variables[o]=$t(r.variables[o],i,s,{roundTo:l}))}},Xc=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:r,payload:n})=>{mu(e,r,n)})},Qc=(e,t)=>{let{sectionId:r,lineId:n}=t,s=Z({state:e},{sectionId:r})?.lines?.find(l=>l.id===n)?.actions;s&&Object.entries(s).forEach(([l,c])=>{gi(e,l,c)})},ei=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let n=Fe(r),o=n.timeline[t];if(!o)return e;e.global.autoMode&&dt({state:e}),e.global.skipMode&&Me({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),n.isRestoring=!0,n.currentIndex=t;try{r.variables=en(e.projectData),delete r.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=P(Mt),e.global.overlayStack=[],Je(e),Xe(e),e.global.isLineCompleted=!0;let i=n.replayStartIndex??0;for(let l=i;l<=t;l++)l>i&&Jr(e),Qc(e,n.timeline[l]),Xc(e,n.timeline[l]);let s=Qe(r);s.read={sectionId:o.sectionId,lineId:o.lineId},e.global.pendingEffects=e.global.pendingEffects.filter(l=>l?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{n.isRestoring=!1}return e},Zc=e=>{let{projectData:t}=e,r=e.global??{},{saveSlots:n={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=r;Fo(t);let l=t.story.initialSceneId,c=t.story.scenes[l],a=c.initialSectionId,u=c.sections[a],f={sceneId:l,sectionId:a,lineId:u.initialLineId??u.lines[0].id},{globalVariablesDefaultValues:d}=br(t),p={...d,...qe(o,t.resources?.variables??{})};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,formDrafts:{},accountViewedRegistry:Cc(s,"accountViewedRegistry"),nextLineConfig:zt(),saveSlots:vc(n),overlayStack:[],variables:p,...Mc({loadedGlobalRuntime:i})},contexts:[Qo({pointer:f,projectData:t})]}},el=({state:e})=>e.global.overlayStack||[],tl=({state:e})=>e.global.pendingEffects,ti=({state:e})=>e.global.skipMode,rl=({state:e})=>e.global.autoMode,ri=({state:e})=>e.global.dialogueUIHidden,ni=({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=Z({state:e},{sectionId:n});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(u=>u.id===o),l=i.lines.slice(0,s+1),c=[],a={};for(let u of l){let f=u.actions||{};if(a=Te([a,f]),!f.dialogue)continue;let d=a.dialogue||{},p="";d.character?.name!==void 0?p=d.character.name:d.characterId&&(p=e.projectData.resources?.characters?.[d.characterId]?.name||"");let h=Ic({sectionId:n,lineId:u.id,content:f.dialogue.append===!0?d.content:f.dialogue.content,dialogueState:d,characterName:p});if(f.dialogue.append===!0&&c.length>0){c[c.length-1]={...c[c.length-1],content:h.content,text:h.text,characterId:h.characterId,character:h.character,characterName:h.characterName};continue}c.push(h)}return c},nl=({state:e})=>e.global.confirmDialog??null,ft=({state:e},{pointer:t}={})=>{let r=t??he({state:e})?.pointer,n=Vc({state:e,pointer:r});return jc({state:e,form:n.form,pointer:r})},ol=({state:e},{pointer:t}={})=>!!ft({state:e},{pointer:t}),Ie=({state:e},{pointer:t}={})=>{let r=ft({state:e},{pointer:t});if(r)return{source:Ft,formId:r.id,formKey:r.key};let n=oi({state:e,pointer:t});return n?{source:Gr,resourceId:n}:null},il=({state:e,registry:t},r)=>{let{sectionId:n,lineId:o}=r,s=(Array.isArray(t?.sections)?t.sections:[]).find(u=>u.sectionId===n);if(!s)return!1;if(s.lastLineId===void 0||o===void 0)return!0;let l=Z({state:e},{sectionId:n});if(!l||!l.lines||!Array.isArray(l.lines))return s.lastLineId===o;let c=l.lines.findIndex(u=>u.id===s.lastLineId),a=l.lines.findIndex(u=>u.id===o);return c===-1||a===-1?s.lastLineId===o:a<=c},sl=({registry:e},t)=>{let{resourceId:r}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===r)},nn=({state:e},t)=>il({state:e,registry:e.global.accountViewedRegistry},t),al=({state:e},t)=>sl({registry:e.global.accountViewedRegistry},t),cl=({state:e})=>e.global.nextLineConfig,oi=({state:e,pointer:t}={})=>{let r=t??he({state:e})?.pointer;if(!r)return;let n=r?.sectionId,o=r?.lineId,s=Z({state:e},{sectionId:n})?.lines||[],l=s.findIndex(a=>a.id===o);if(l<0)return;let c;for(let a of s.slice(0,l+1)){let u=a?.actions;if(u?.cleanAll&&(c=void 0),!u||!Object.prototype.hasOwnProperty.call(u,"choice")){c=void 0;continue}let f=u.choice;if(f?.resourceId){c=f.resourceId;continue}f?.animations||(c=void 0)}return c},ii=({state:e})=>!!oi({state:e}),ll=({state:e})=>structuredClone(e),si=({state:e})=>e.global.saveSlots,ul=({state:e},t)=>{let r=t?.slotId,n=Wt(r);return e.global.saveSlots[n]},on=({state:e})=>Ye(e),fl=({state:e},t)=>Ae(e,t?.runtimeId),sn=({state:e})=>{let t={...e.global?.variables??{},...tn(e)?.variables??{}};return Rt({variables:t,runtime:Ye(e),variableConfigs:e.projectData.resources?.variables??{}})},he=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],r=t[t.length-1];if(r)return{currentPointerMode:"read",pointer:r.pointers?.read}},Z=({state:e},t)=>{let{sectionId:r}=t;return Xr(e.projectData,r).section},an=({state:e})=>{let t=he({state:e});if(!t?.pointer)return;let{sectionId:r,lineId:n}=t.pointer,o=Z({state:e},{sectionId:r});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===n)},ai=({state:e})=>{let{sectionId:t,lineId:r}=he({state:e}).pointer,o=Z({state:e},{sectionId:t})?.lines||[],i=o.findIndex(a=>a.id===r),l=o.slice(0,i+1).map(a=>{let u=a.actions||{},f={};return Object.keys(u).forEach(d=>{f[d]=u[d]}),f});return Te(l)},dl=({state:e})=>{let t=ci({state:e}),n=an({state:e})?.actions??{},o=Te([t??{},n]);return Ar(t??{},o??{})},pl=({state:e},{sectionId:t})=>{let r=Z({state:e},{sectionId:t});if(!r?.lines)return[];let n=[],o={};for(let i of r.lines){let s=i.actions||{},l=Te([o,s]),c=Ar(o,l);n.push({id:i.id,changes:c,presentationState:l}),o=wr(l)}return n},hl=({state:e},{sectionId:t,includePresentationState:r=!1})=>{let n=pl({state:e},{sectionId:t});return r?{lines:n}:{lines:n.map(({presentationState:o,...i})=>i)}},ci=({state:e})=>{let{sectionId:t,lineId:r}=he({state:e}).pointer,o=Z({state:e},{sectionId:t})?.lines||[],i=o.findIndex(c=>c.id===r);if(i<=0)return null;let l=o.slice(0,i).map(c=>{let a=c.actions||{},u={};return Object.keys(a).forEach(f=>{u[f]=a[f]}),u});return wr(Te(l))},cn=({state:e},{slotsPerPage:t=6}={})=>{let o=((on({state:e}).saveLoadPagination??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let l=o+s,c=e.global.saveSlots&&e.global.saveSlots[Wt(l)]||{};i.push({...c,slotId:l})}return{saveSlots:i}},ml=si,gl=cn,yl=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},bl=({state:e},t={})=>{let r=ai({state:e}),n=ci({state:e}),o=an({state:e})?.actions??{},i=e.global.pendingScreenTransition,s=i?.animations?{...o,screen:P(i)}:o,l=i?.animations&&n===null?{}:n,{sectionId:c}=he({state:e}).pointer,{sceneId:a}=Xr(e.projectData,c),u=on({state:e}),f=t?.activePersistentAnimations??[],d=t?.restoredPersistentAnimations??[],p=ft({state:e}),h=ii({state:e}),g=sn({state:e}),{saveSlots:y}=cn({state:e}),b=yl(e);return Do({presentationState:r,previousPresentationState:l,currentLineActions:s,resources:e.projectData.resources,currentSceneId:a,screen:e.projectData.screen,dialogueUIHidden:u.dialogueUIHidden,autoMode:u.autoMode,skipMode:u.skipMode,isChoiceVisible:h,isFormVisible:!!p,canRollback:bi({state:e}),skipOnlyViewedLines:!u.skipUnseenText,isLineCompleted:u.isLineCompleted,skipTransitionsAndAnimations:!!u.skipTransitionsAndAnimations||b,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,form:p,dialogueHistory:ni({state:e}),saveSlots:y,variables:g,runtime:u,activePersistentAnimations:f,restoredPersistentAnimations:d})},Il=({state:e},t)=>(e.global.confirmDialog=Lc(t),e.global.pendingEffects.push({name:"render"}),e),Al=({state:e})=>(e.global.confirmDialog&&(Je(e),e.global.pendingEffects.push({name:"render"})),e),wl=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),be(e,"pushOverlay",t),e),El=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),be(e,"popOverlay",void 0),e),vl=({state:e},t)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=t),e.global.pendingEffects.push({name:"render"}),be(e,"replaceLastOverlay",t),e),xl=({state:e})=>(e.global.overlayStack=[],Je(e),Xe(e),e.global.pendingEffects.push({name:"render"}),be(e,"clearOverlays",void 0),e),Cl=e=>{e.global.autoMode&&(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"})),e.global.skipMode&&(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"})),e.global.nextLineConfig?.auto?.enabled&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},qt=(e,t,{screenTransition:r}={})=>{e.global.isLineCompleted=!1,kc(e,r),Xe(e);let n=Ie({state:e},{pointer:t}),o=n?.source===Gr,i=n?.source===Ft;return n&&Cl(e),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:o,isFormVisible:i,activeInteraction:n}},li=({state:e})=>(Ie({state:e})||(e.global.skipMode&&(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"})),e.global.autoMode=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.isLineCompleted&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:Ae(e,"autoForwardDelay")}}),e.global.pendingEffects.push({name:"render"})),e),dt=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Sl=({state:e})=>{let t=e.global.autoMode;return Ie({state:e})&&!t||(t?dt({state:e}):li({state:e})),e},ui=({state:e})=>(Ie({state:e})||(e.global.autoMode&&(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"})),e.global.skipMode=!0,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"startSkipNextTimer"}),e.global.pendingEffects.push({name:"render"})),e),Me=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),_l=({state:e})=>{let t=ti({state:e});return Ie({state:e})&&!t||(t?Me({state:e}):ui({state:e})),e},Yt=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),be(e,"showDialogueUI",void 0),e),fi=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),be(e,"hideDialogueUI",void 0),e),Rl=({state:e})=>(ri({state:e})?Yt({state:e}):fi({state:e}),e),Ue=(e,t,r)=>(Xo(e,t,r),zc(e),e.global.pendingEffects.push({name:"render"}),e),pt=(e,t,r,n)=>{let o=Xo(e,t,r);return e.global.pendingEffects.push({name:"render"}),be(e,n,{value:o}),e},Ol=({state:e},t)=>Ue(e,"dialogueTextSpeed",t?.value),Ll=({state:e},t)=>Ue(e,"autoForwardDelay",t?.value),$l=({state:e},t)=>Ue(e,"skipUnseenText",t?.value),kl=({state:e},t)=>Ue(e,"skipTransitionsAndAnimations",t?.value),Dl=({state:e},t)=>Ue(e,"soundVolume",t?.value),Pl=({state:e},t)=>Ue(e,"musicVolume",t?.value),Tl=({state:e},t)=>Ue(e,"muteAll",t?.value),Nl=({state:e},t)=>pt(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),Vl=({state:e})=>{let t=Ae(e,"saveLoadPagination")+1;return pt(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},jl=({state:e})=>{let t=Ae(e,"saveLoadPagination")-1;return pt(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},Ml=({state:e},t)=>pt(e,"menuPage",t?.value,"setMenuPage"),Fl=({state:e},t)=>pt(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),Ul=({state:e})=>(e.global.pendingEffects=[],e),Bl=({state:e},t)=>(e.global.pendingEffects.push(t),e),di=(e,{sectionId:t,resetStoryState:r=!1,screen:n})=>{let o=!!qo(n),i=Z({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&&!Yc(e,{queueRender:!o}))return e;e.global.autoMode&&dt({state:e}),r&&e.global.skipMode&&Me({state:e});let l=e.contexts?.[e.contexts.length-1];if(l){let c=Qe(l),a=c.read;r||Ge(e,{sectionId:a?.sectionId,lineId:a?.lineId}),l.rollback||Fe(l,{compatibilityAnchor:!0}),c.read={sectionId:t,lineId:s.id},r?l.rollback=ut({pointer:c.read}):rn(e,{sectionId:t,lineId:s.id})}return qt(e,l?.pointers?.read,{screenTransition:n}),e},zl=({state:e},t)=>di(e,{sectionId:t?.sectionId,resetStoryState:!0,screen:t?.screen}),pi=e=>(e.global.accountViewedRegistry=yc(e.global.accountViewedRegistry),e.global.accountViewedRegistry),ln=(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:P(r.value)}))}})},hi=(e,t)=>{ln(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:[]}}])},Wl=(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=Z({state:e},{sectionId:r});if(s?.lines){let l=s.lines.findIndex(a=>a.id===i.lastLineId),c=s.lines.findIndex(a=>a.id===n);if(l===-1||c>l)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},Ge=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;Wl(e,pi(e),t)&&hi(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},ql=({state:e},t)=>(Ge(e,t),e.global.pendingEffects.push({name:"render"}),e),Yl=({state:e},t)=>{let{resourceId:r}=t;if(e.global.accountViewedRegistry!==void 0){let n=pi(e);n.resources.find(i=>i.resourceId===r)||(n.resources.push({resourceId:r}),hi(e,{sections:[],resources:[{resourceId:r}]}))}return e.global.pendingEffects.push({name:"render"}),e},mi=({state:e},t)=>{let r=wc(t.manual),{auto:n,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,l=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 c=e.global.nextLineConfig.auto?.enabled,a=Ie({state:e});return!l&&!a&&c===!0&&!i?e.global.nextLineConfig.auto?.trigger==="fromStart"?e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):e.global.isLineCompleted&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):!l&&c===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),be(e,"setNextLineConfig",t),e},Hl=({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=Wt(r),s=P(e.contexts);s?.forEach(a=>{Qe(a),Zo(a.rollback),xc(a.rollback)});let l={contexts:s},c={formatVersion:jo,slotId:Uo(r),savedAt:typeof o=="number"?o:Date.now(),image:n,state:l};return e.global.saveSlots[i]=c,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},Kl=({state:e},t)=>{let r=t?.slotId;if(r==null||r==="")throw new Error("loadSlot requires slotId");let n=Wt(r),o=e.global.saveSlots[n];if(o){let i=Oc(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=zt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,Je(e),Xe(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},Gl=({state:e},t)=>{let{projectData:r}=t;Fo(r),e.projectData=r;let n=r?.resources?.variables??{};return Object.prototype.hasOwnProperty.call(e.global??{},"variables")&&(e.global.variables=qe(e.global.variables,n)),e.contexts?.forEach(o=>{Object.prototype.hasOwnProperty.call(o??{},"variables")&&(o.variables=qe(o.variables,n))}),Je(e),Xe(e),e.global.pendingEffects.push({name:"render"}),e},Jl=({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&&!Z({state:e},{sectionId:r}))return console.warn(`Section not found: ${r}`),e;let s=Z({state:e},{sectionId:i});if(!s?.lines||!Array.isArray(s.lines))return console.warn(`Section ${i} has no lines`),e;if(!s.lines.find(a=>a.id===n))return console.warn(`Line not found: ${n} in section ${i}`),e;let c=Qe(o);return c.read={sectionId:i,lineId:n},qt(e,c.read),e},Xl=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return Yt({state:e}),e;let r=Ie({state:e});if(r?.source===Gr&&t?.bypassChoice!==!0||r?.source===Ft&&t?._interactionSource!==Ft)return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let u=he({state:e})?.pointer,f=u?.sectionId,d=u?.lineId;f&&d&&Ge(e,{sectionId:f,lineId:d}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:Ae(e,"autoForwardDelay")}});let p=e.global.nextLineConfig;return p?.auto?.enabled&&p.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:p.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e}let n=he({state:e})?.pointer,o=n?.sectionId,i=Z({state:e},{sectionId:o}),s=e.contexts[e.contexts.length-1],l=i?.lines||[],a=l.findIndex(u=>u.id===n?.lineId)+1;if(a<l.length){let u=l[a],f=!Ae(e,"skipUnseenText");if(e.global.skipMode&&f&&!nn({state:e},{sectionId:o,lineId:u.id}))return Me({state:e}),e;if(s&&!s.rollback&&Fe(s,{compatibilityAnchor:!0}),s){let h=Qe(s),g=h.read?.lineId;g&&o&&Ge(e,{sectionId:o,lineId:g}),h.read={sectionId:o,lineId:u.id}}rn(e,{sectionId:o,lineId:u.id}),Jr(e);let{activeInteraction:d}=qt(e,{sectionId:o,lineId:u.id}),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&&dt({state:e}),e.global.skipMode&&Me({state:e});return e},Ql=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=Ie({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:Ae(e,"autoForwardDelay")}});let r=he({state:e})?.pointer,n=r?.sectionId,o=r?.lineId;n&&o&&Ge(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},Zl=({state:e},t)=>di(e,{sectionId:t?.sectionId,screen:t?.screen}),eu=({state:e})=>{if(e.global.dialogueUIHidden)return Yt({state:e}),e;if(Ie({state:e}))return e;let t=he({state:e})?.pointer,r=t?.sectionId,n=Z({state:e},{sectionId:r}),o=e.contexts[e.contexts.length-1],i=n?.lines||[],l=i.findIndex(c=>c.id===t?.lineId)+1;if(l<i.length){let c=i[l],a=!Ae(e,"skipUnseenText");if(e.global.skipMode&&a&&!nn({state:e},{sectionId:r,lineId:c.id}))return Me({state:e}),e;if(o&&!o.rollback&&Fe(o,{compatibilityAnchor:!0}),o){let f=Qe(o),d=f.read?.lineId;d&&r&&Ge(e,{sectionId:r,lineId:d}),f.read={sectionId:r,lineId:c.id}}rn(e,{sectionId:r,lineId:c.id}),Jr(e);let{activeInteraction:u}=qt(e,{sectionId:r,lineId:c.id});e.global.nextLineConfig.auto?.enabled&&!u&&e.global.nextLineConfig.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}})}else e.global.nextLineConfig.auto?.enabled&&(e.global.nextLineConfig.auto.enabled=!1,e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}));return e},un=(e,t={})=>{let r=ft({state:e});return!r||t.formKey&&t.formKey!==r.key||t.formId&&t.formId!==r.id?null:r},tu=(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(Ce(r))throw new Error(`Cannot update computed variable: ${t.variableId}`);if(r?.readonly===!0)throw new Error(`Cannot update readonly variable: ${t.variableId}`);return Ot(n,t.variableId),Lt(o,"set",t.variableId),{variableConfig:r,scope:n}},ru=(e,t)=>({id:e.id,key:e.key,valid:!0,values:P(t),fields:P(e.fields),fieldList:P(e.fieldList)}),nu=({state:e},t={})=>{let r=un(e,t),n=t.field;if(!r?.fields?.[n])return e;let o=Ho(e,r.key),i=Ut(t.value),s=r.fields[n],l=Qr(s,i);return o.values[n]=i,o.touched[n]=!0,l?o.errors[n]=l:delete o.errors[n],e.global.pendingEffects.push({name:"render"}),e},ou=({state:e},t={})=>{let r=un(e,t);if(!r)return{submitted:!1,valid:!1,reason:"inactive"};let n=Ho(e,r.key);n.submitted=!0;let o={},i={};if(Object.entries(r.fields).forEach(([f,d])=>{let p=Object.prototype.hasOwnProperty.call(n.values,f)?n.values[f]:d.value,h=Qr(d,p);n.touched[f]=!0,h&&(i[f]=h),o[f]=Yo(d,p)}),n.errors=i,Object.keys(i).length>0)return e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!1,errors:P(i),form:{id:r.id,key:r.key,values:P(o)}};let s=e.contexts[e.contexts.length-1];if(s?.rollback?.isRestoring)return{submitted:!1,valid:!1,reason:"restoring"};let l=!1,c=[],a=[];Object.entries(r.fields).forEach(([f,d])=>{let{scope:p}=tu(e,d),h=p==="context"?s.variables:e.global.variables,g=o[f];h[d.variableId]=$t(h[d.variableId],"set",g),p==="context"&&(l=!0,a.push({variableId:d.variableId,op:"set",value:g})),(p==="device"||p==="account")&&c.push({scope:p,path:`variables.${d.variableId}`,op:"set",value:P(h[d.variableId])})}),l&&be(e,"updateVariable",{id:"submitForm",operations:a}),ln(e,c);let u=ru(r,o);return delete e.global.formDrafts[r.key],e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!0,form:u}},iu=({state:e},t={})=>{let r=un(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:P(r.values),fields:P(r.fields),fieldList:P(r.fieldList)}}):{cancelled:!1,reason:"inactive"}},su=({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=[],l=[];return n.forEach(({variableId:c,op:a,value:u,roundTo:f})=>{let d=e.projectData.resources?.variables?.[c],p=d?.scope,h=d?.type;if(Ce(d))throw new Error(`Cannot update computed variable: ${c}`);if(d?.readonly===!0)throw new Error(`Cannot update readonly variable: ${c}`);Ot(p,c),Lt(h,a,c),Ir(h,a,u,c,{roundTo:f});let g=p==="context"?o.variables:e.global.variables;if(p==="context"){i=!0;let y={variableId:c,op:a,value:u};f!==void 0&&(y.roundTo=f),l.push(y)}g[c]=$t(g[c],a,u,{roundTo:f}),(p==="device"||p==="account")&&s.push({scope:p,path:`variables.${c}`,op:"set",value:P(g[c])})}),i&&be(e,"updateVariable",{id:r,operations:l}),ln(e,s),e.global.pendingEffects.push({name:"render"}),e},au=e=>(t,r)=>e({state:t},r),cu=e=>({variables:Rt({variables:{...e.global?.variables??{},...tn(e)?.variables??{}},runtime:Ye(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1}),runtime:Ye(e)}),lu=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")},uu=(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")},fu=(e,t)=>{lu(t);for(let r=0;r<t.branches.length;r+=1){let n=t.branches[r];if(uu(n,r,t.branches.length),!(Object.prototype.hasOwnProperty.call(n,"when")&&!ot(n.when,cu(e)))){Object.entries(n.actions).forEach(([i,s])=>{gi(e,i,s)});return}}},du={conditional:{replayLine:fu},updateVariable:{recordSources:[Zr],replayLine:Vo,replayRecorded:Vo,persistInSaveSlot:!0},setNextLineConfig:{replayLine:au(mi)}},Ht=e=>du[e]??null,pu=e=>Ht(e)?.persistInSaveSlot===!0,hu=(e,t)=>{let r=Ht(e)?.recordSources;return Array.isArray(r)&&r.includes(t)},mu=(e,t,r)=>{Ht(t)?.replayRecorded?.(e,r)},gi=(e,t,r)=>{Ht(t)?.replayLine?.(e,r)},yi=({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}},bi=({state:e})=>yi({state:e},{offset:-1})!==null,gu=({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=Fe(n,{compatibilityAnchor:!n.rollback}),i=o.currentIndex+r;return i<0||i>=o.timeline.length?e:ei(e,i)},yu=({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=Fe(o,{compatibilityAnchor:!o.rollback}),l=i.timeline.slice(0,i.currentIndex+1).findLastIndex(c=>c.sectionId===r&&c.lineId===n);if(l===-1)throw new Error(`Line ${n} not found in section ${r} rollback timeline`);return l===i.currentIndex?e:ei(e,l)},Ii=e=>{let t=Zc(e);return Gn(t,{selectPendingEffects:tl,selectSkipMode:ti,selectAutoMode:rl,selectIsChoiceVisible:ii,selectIsFormVisible:ol,selectActiveInteraction:Ie,selectActiveForm:ft,selectDialogueUIHidden:ri,selectDialogueHistory:ni,selectConfirmDialog:nl,selectIsLineAccountViewed:nn,selectIsResourceAccountViewed:al,selectNextLineConfig:cl,selectSystemState:ll,selectSaveSlotMap:si,selectSaveSlots:ml,selectSaveSlot:ul,selectRuntime:on,selectRuntimeValue:fl,selectAllVariables:sn,selectCurrentPointer:he,selectSection:Z,selectCurrentLine:an,selectPresentationState:ai,selectPresentationChanges:dl,selectSectionLineChanges:hl,selectSaveSlotPage:cn,selectCurrentPageSlots:gl,selectRenderState:bl,selectOverlayStack:el,selectLineIdByOffset:yi,selectCanRollback:bi,startAutoMode:li,stopAutoMode:dt,toggleAutoMode:Sl,startSkipMode:ui,stopSkipMode:Me,toggleSkipMode:_l,showDialogueUI:Yt,hideDialogueUI:fi,toggleDialogueUI:Rl,setDialogueTextSpeed:Ol,setAutoForwardDelay:Ll,setSkipUnseenText:$l,setSkipTransitionsAndAnimations:kl,setSoundVolume:Dl,setMusicVolume:Pl,setMuteAll:Tl,setSaveLoadPagination:Nl,incrementSaveLoadPagination:Vl,decrementSaveLoadPagination:jl,setMenuPage:Ml,setMenuEntryPoint:Fl,showConfirmDialog:Il,hideConfirmDialog:Al,resetStoryAtSection:zl,clearPendingEffects:Ul,appendPendingEffect:Bl,beginRollbackActionBatch:Gc,endRollbackActionBatch:Jc,addViewedLine:ql,addViewedResource:Yl,setNextLineConfig:mi,saveSlot:Hl,loadSlot:Kl,updateProjectData:Gl,sectionTransition:Zl,jumpToLine:Jl,nextLine:Xl,markLineCompleted:Ql,rollbackToLine:yu,rollbackByOffset:gu,pushOverlay:wl,popOverlay:El,replaceLastOverlay:vl,clearOverlays:xl,updateFormField:nu,submitForm:ou,cancelForm:iu,updateVariable:su,nextLineFromSystem:eu},{transformActionFirstArgument:n=>({state:n}),transformSelectorFirstArgument:n=>({state:n})})};var bu="route-engine",Iu="projectPersistence";var wi=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),X=e=>Object.prototype.toString.call(e)==="[object Object]",Ai="variables.",Au=(e={})=>{let t=X(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!X(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)}:!X(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},wu=(e={})=>{let t=X(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!X(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)}:!X(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},Eu=(e,t)=>{let r=wu(e),n=Au(t),o=r.sections.map(s=>({...s})),i=r.resources.map(s=>({...s}));return n.sections.forEach(s=>{let l=o.find(c=>c.sectionId===s.sectionId);if(!l){o.push({sectionId:s.sectionId,...s.lineId===void 0?{}:{lastLineId:s.lineId}});return}if(l.lastLineId!==void 0){if(s.lineId===void 0){delete l.lastLineId;return}l.lastLineId=s.lineId}}),n.resources.forEach(s=>{i.find(c=>c.resourceId===s.resourceId)||i.push({...s})}),{sections:o,resources:i}},Ei=(e={})=>{let t=X(e)?e:{};return{saveSlots:X(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:X(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:X(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:X(t.globalRuntime)?t.globalRuntime:{},accountViewedRegistry:X(t.accountViewedRegistry)?t.accountViewedRegistry:{}}},vu=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((t,r)=>{if(!X(t))throw new Error(`Malformed applyScopedDataUpdates.updates[${r}] entry.`);let n=t.path?.startsWith(Ai)?t.path.slice(Ai.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}].`)})},xu=(e,t)=>{let r={};return vu(t).forEach(n=>{if(n.path==="viewedRegistry"){r.accountViewedRegistry=Eu(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},fn=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},Cu=e=>{let t=fn(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},Su=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},_u=({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}".`))}}),Ru=async({databasePromise:e,objectStoreName:t,namespace:r})=>{let n=await e;return new Promise((o,i)=>{let c=n.transaction(t,"readonly").objectStore(t).get(r);c.onsuccess=()=>{o(c.result??null)},c.onerror=()=>{i(c.error??new Error(`Failed to read persisted namespace "${r}" from IndexedDB.`))}})},ht=async({databasePromise:e,objectStoreName:t,namespace:r,patch:n})=>{let o=await e;return new Promise((i,s)=>{let l=o.transaction(t,"readwrite"),c=l.objectStore(t),a=c.get(r),u=!1,f=p=>{u||(u=!0,s(p))},d=()=>{u||(u=!0,i())};a.onerror=()=>{f(a.error??new Error(`Failed to read persisted namespace "${r}" before updating IndexedDB.`))},a.onsuccess=()=>{let p=Ei(a.result),h=typeof n=="function"?n(p):n,g={namespace:r,version:1,...wi(),...p,...h},y=c.put(g);y.onerror=()=>{f(y.error??new Error(`Failed to persist namespace "${r}" to IndexedDB.`))}},l.oncomplete=()=>{d()},l.onerror=()=>{f(l.error??new Error(`IndexedDB transaction failed while updating namespace "${r}".`))},l.onabort=()=>{f(l.error??new Error(`IndexedDB transaction aborted while updating namespace "${r}".`))}})},Ou=async({databasePromise:e,objectStoreName:t,namespace:r})=>{let n=await e;return new Promise((o,i)=>{let s=n.transaction(t,"readwrite"),c=s.objectStore(t).delete(r),a=!1,u=d=>{a||(a=!0,i(d))},f=()=>{a||(a=!0,o())};c.onerror=()=>{u(c.error??new Error(`Failed to clear persisted namespace "${r}" from IndexedDB.`))},s.oncomplete=()=>{f()},s.onerror=()=>{u(s.error??new Error(`IndexedDB transaction failed while clearing namespace "${r}".`))},s.onabort=()=>{u(s.error??new Error(`IndexedDB transaction aborted while clearing namespace "${r}".`))}})},dn=(e={})=>{let{indexedDB:t,databaseName:r=bu,objectStoreName:n=Iu,namespace:o}=e,i=Su(t),s=Cu(o),l=_u({indexedDB:i,databaseName:r,objectStoreName:n});return{namespace:s,load:async()=>{let c=await Ru({databasePromise:l,objectStoreName:n,namespace:s});return{...wi(),...Ei(c)}},clear:async()=>Ou({databasePromise:l,objectStoreName:n,namespace:s}),saveSlots:async c=>ht({databasePromise:l,objectStoreName:n,namespace:s,patch:{saveSlots:X(c)?c:{}}}),saveGlobalDeviceVariables:async c=>ht({databasePromise:l,objectStoreName:n,namespace:s,patch:{globalDeviceVariables:X(c)?c:{}}}),saveGlobalAccountVariables:async c=>ht({databasePromise:l,objectStoreName:n,namespace:s,patch:{globalAccountVariables:X(c)?c:{}}}),saveGlobalRuntime:async c=>ht({databasePromise:l,objectStoreName:n,namespace:s,patch:{globalRuntime:X(c)?c:{}}}),applyScopedDataUpdates:async c=>ht({databasePromise:l,objectStoreName:n,namespace:s,patch:a=>xu(a,c)})}},Lu=dn;var $u=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),ku=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),vi="conditional",pn="form",Du=new Set(["submitForm","cancelForm"]),mt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function hn(e){let t,r=0,n=null,o=new Map,i=new Map,s=new Map,{handlePendingEffects:l}=e,c=(I=new Map,C=Date.now())=>new Map(Array.from(I.entries()).filter(([,O])=>C<O.expiresAt).map(([O,B])=>[O,{animation:structuredClone(B.animation),startedAt:B.startedAt,expiresAt:B.expiresAt}])),a=(I=new Map)=>Array.from(I.values()).map(C=>structuredClone(C.animation)),u=(I=Date.now())=>{o=new Map(Array.from(o.entries()).filter(([,C])=>I<C.expiresAt))},f=()=>{for(;t.selectPendingEffects().length>0;){let I=[...t.selectPendingEffects()];t.clearPendingEffects();try{l(I)}catch(C){throw t.clearPendingEffects(),I.forEach(O=>{t.appendPendingEffect(O)}),C}}},d=({initialState:I,namespace:C})=>{t=Ii(I),r=0,n=fn(C),o=new Map,i=new Map,s=new Map,t.appendPendingEffect({name:"handleLineActions"}),f()},p=()=>n,h=()=>t.selectPresentationState(),g=()=>t.selectPresentationChanges(),y=I=>t.selectSectionLineChanges(I),b=(I={})=>{r+=1;let C=Date.now();u(C);let O=i.size>0,B=c(o,C),Y=O?c(i,C):new Map,ge={...t.selectRenderState({activePersistentAnimations:a(B),restoredPersistentAnimations:a(Y)}),id:`render-${r}`};return s.set(ge.id,{builtAt:C,persistentAnimationSessions:new Map([...Y.entries(),...B.entries()]),usedRestoredPersistentAnimationSessions:O}),ge},A=(I={})=>b(I),x=(I={})=>b(I),S=I=>{let C=typeof I?.id=="string"&&I.id.length>0?I.id:null,O=C?s.get(C):null;C&&s.delete(C);let B=new Map;Ao(I?.animations).forEach(Y=>{let ae=Tt(Y);if(!ae)return;let ge=O?.persistentAnimationSessions?.get(ae)??o.get(ae),gt=Math.max(0,Eo(Y)),yn=ge?.startedAt??O?.builtAt??Date.now();B.set(ae,{animation:structuredClone(Y),startedAt:yn,expiresAt:yn+gt})}),o=B,O?.usedRestoredPersistentAnimationSessions&&(i=new Map)},T=()=>t.selectSystemState(),w=()=>t.selectSaveSlotMap(),N=I=>t.selectSaveSlot(I),z=I=>t.selectSaveSlotPage(I),k=()=>t.selectSkipMode(),j=()=>t.selectAutoMode(),U=()=>t.selectRuntime(),M=()=>t.selectIsChoiceVisible(),W=()=>t.selectIsFormVisible(),v=()=>t.selectActiveInteraction(),_=(I,C,O={})=>I!=="nextLine"||!mt(C)?C:O.bypassChoice===!0?{...C,bypassChoice:!0}:O.interactionSource===pn?{...C,_interactionSource:pn}:C,R=(I,C)=>{if(!t[I])return;$u.has(I)&&(ku.has(I)?i=c(o):i=new Map,o=new Map);let O=t[I](C);return f(),O},F=(I,C,O,B={})=>{if(I===vi){let Y=V(O),ae=Er({[I]:C},Y);Be(ae[I],O,B);return}R(I,C)},q=(I,C)=>{F(I,C)},V=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,...O}=I,B=t.selectAllVariables?t.selectAllVariables():void 0;return{...O,_event:C,variables:B,runtime:t.selectRuntime?t.selectRuntime():{}}},me=I=>{if(!mt(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")},re=(I,C,O)=>{if(!mt(I))throw new Error(`conditional branch at index ${C} must be an object`);if(!mt(I.actions))throw new Error(`conditional branch at index ${C} requires actions object`);if(!Object.prototype.hasOwnProperty.call(I,"when")&&C!==O-1)throw new Error("conditional else branch must be the last branch")},Be=(I,C,O)=>{me(I);for(let B=0;B<I.branches.length;B+=1){let Y=I.branches[B];re(Y,B,I.branches.length);let ae=V(C);if(!(Object.prototype.hasOwnProperty.call(Y,"when")&&!ot(Y.when,ae))){Gt(Y.actions,C,O);return}}},Si=(I,C)=>({...I??{},_form:C}),_i=(I,C,O,B)=>{let Y=R(I,C),ae=Y?.submitted===!0&&Y.valid===!0,ge=Y?.cancelled===!0;!ae&&!ge||mt(C.actions)&&Gt(C.actions,Si(O,Y.form),{...B,interactionSource:pn})},Ri=(I,C,O,B)=>{let Y=V(O),ge=Er({[I]:C},Y)[I];if(I===vi){Be(ge,O,B);return}let gt=_(I,ge,B);if(Du.has(I)){_i(I,gt,O,B);return}R(I,gt)},Gt=(I,C,O)=>{Object.entries(I).forEach(([B,Y])=>{Ri(B,Y,C,O)})},gn=(I,C,O={})=>{t.beginRollbackActionBatch({source:O.rollbackSource});try{Gt(I,C,O)}finally{t.endRollbackActionBatch({})}};return{init:d,handleAction:F,handleInternalAction:q,handleActions:gn,selectRenderState:A,prepareRenderState:x,commitRenderState:S,selectPresentationState:h,selectPresentationChanges:g,selectSectionLineChanges:y,selectSystemState:T,selectSaveSlotMap:w,selectSaveSlot:N,selectSaveSlotPage:z,selectSaveSlots:w,selectRuntime:U,selectIsChoiceVisible:M,selectIsFormVisible:W,selectActiveInteraction:v,handleLineActions:()=>{let I=t.selectCurrentLine();return I?.actions?(gn(I.actions,void 0,{rollbackSource:"line"}),!0):!1},getNamespace:p}}var mn=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:r=>{e=r},addElapsed:r=>{e+=r},getCallback:()=>t,setCallback:r=>{t=r}}},Pu=80,Ci=({engine:e,routeGraphics:t,trackRenderDispatch:r},n)=>{let o=e.prepareRenderState?.(n)??e.selectRenderState(n);r?.(o),t.render(o),e.commitRenderState?.(o)},Tu=({engine:e,routeGraphics:t,trackRenderDispatch:r,getRenderDispatchCount:n},o)=>{let i=n?.()??0,s=e.handleLineActions();(n?.()??0)===i&&Ci({engine:e,routeGraphics:t,trackRenderDispatch:r},o)},Nu=({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 l=n.delay??1e3;r.getElapsed()>=l&&(t.remove(i),r.setCallback(null),r.setElapsed(0),Kt(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},Vu=({ticker:e,autoTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},ju=({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 l=n?.delay??Pu;r.getElapsed()>=l&&(r.setElapsed(0),Kt(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},Mu=({ticker:e,skipTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},Fu=({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 l=n.delay??1e3;r.getElapsed()>=l&&(r.setElapsed(0),Kt(e,"nextLineFromSystem",{}),t.remove(i),r.setCallback(null))};r.setCallback(i),t.add(i)},Uu=({ticker:e,nextLineConfigTimerState:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},Bu=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveSlots(t?.saveSlots))},zu=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalDeviceVariables(t?.globalDeviceVariables))},Wu=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalAccountVariables(t?.globalAccountVariables))},qu=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalRuntime(t?.globalRuntime))},Yu=({enqueuePersistenceWrite:e},t)=>{e(r=>{if(typeof r.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return r.applyScopedDataUpdates(t?.updates)})},xi={render:Ci,saveSlots:Bu,saveGlobalDeviceVariables:zu,saveGlobalAccountVariables:Wu,saveGlobalRuntime:qu,applyScopedDataUpdates:Yu,handleLineActions:Tu,startAutoNextTimer:Nu,clearAutoNextTimer:Vu,startSkipNextTimer:ju,clearSkipNextTimer:Mu,nextLineConfigTimer:Fu,clearNextLineConfigTimer:Uu},Hu=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),Kt=(e,t,r)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,r)},Ku=(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(!Hu.has(o.name)){r.unshift(o);continue}t.has(o.name)||(t.add(o.name),r.unshift(o))}return r},Gu=({getEngine:e,routeGraphics:t,ticker:r,handleUnhandledEffect:n,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:l})=>{let c=mn(),a=mn(),u=mn(),f=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(f)return f;let v=e();return f=dn({indexedDB:i,namespace:l??v?.getNamespace?.()}),f},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},T=()=>y,w=(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)},N=(v,_={})=>{if(v!=="renderComplete"||!w(_))return!1;let R=e();return Kt(R,"markLineCompleted",{}),!0},z=v=>typeof v?.selectActiveInteraction=="function"?v.selectActiveInteraction():typeof v?.selectIsChoiceVisible=="function"&&v.selectIsChoiceVisible()?{source:"choice"}:null,k=(v,_)=>!(!v||typeof v!="object"||Array.isArray(v)||v._interactionSource!==_?.source||_.source==="form"&&v._formKey&&v._formKey!==_.formKey||_.source==="form"&&v.formKey&&v.formKey!==_.formKey),j=(v={},_)=>{if(k(v,_))return!0;let R=v?.actions;return!R||typeof R!="object"||Array.isArray(R)?!1:Object.values(R).some(F=>k(F,_))},U=(v,_={})=>{if(!_?.actions)return!1;let R=z(v);return!R||R.source==="choice"?!1:!j(_,R)},M=({preprocessPayload:v,onEvent:_}={})=>async(R,F={})=>{let q=e();if(U(q,F))return _?.(R,F);let V=await v?.(R,F)??F;if(U(q,V))return _?.(R,V);if(N(R,V),V?.actions){let me=V?._event?{_event:V._event}:V?.event?{_event:V.event}:void 0,re;V?.bypassChoice===!0?re={bypassChoice:!0}:V?._interactionSource&&(re={interactionSource:V._interactionSource}),re?q.handleActions(V.actions,me,re):q.handleActions(V.actions,me)}return _?.(R,V)},W=v=>{let _=e(),R=Ku(v);R.forEach(q=>{if(!xi[q.name]&&!n)throw new Error(`Unhandled pending effect "${q.name}".`)});let F={engine:_,routeGraphics:t,ticker:r,autoTimer:c,skipTimer:a,nextLineConfigTimerState:u,trackRenderDispatch:S,getRenderDispatchCount:T,enqueuePersistenceWrite:x};for(let q of R){let V=xi[q.name];if(V){V(F,q.payload);continue}n(q,F)}};return W.handleRouteGraphicsEvent=N,W.createRouteGraphicsEventHandler=M,W},Ju=Gu;var Xu=(e,t={})=>{let{resources:r={}}=t;return Kr(e,r)};var yd=hn;export{Cr as DEFAULT_VISUAL_LAYER,at as RENDER_LAYER,Se as VISUAL_LAYER,Ju as createEffectsHandler,Lu as createIndexedDbPersistence,yd as default,Ts as resolveComputedVariables,Xu as resolveLayoutReferences};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "route-engine-js",
3
- "version": "1.17.0",
3
+ "version": "1.19.0",
4
4
  "description": "A lightweight Visual Novel engine built in JavaScript for creating interactive narrative games with branching storylines",
5
5
  "repository": {
6
6
  "type": "git",
@@ -53,12 +53,12 @@
53
53
  "puty": "^0.1.1"
54
54
  },
55
55
  "devDependencies": {
56
- "@vitest/coverage-v8": "^3.2.4",
57
- "@vitest/ui": "^3.2.4",
56
+ "@vitest/coverage-v8": "4.0.16",
57
+ "@vitest/ui": "4.0.16",
58
58
  "ajv": "^8.18.0",
59
59
  "husky": "^9.1.7",
60
60
  "prettier": "^3.7.4",
61
61
  "route-graphics": "1.17.1",
62
- "vitest": "^4.0.16"
62
+ "vitest": "4.0.16"
63
63
  }
64
64
  }