route-engine-js 1.31.2 → 1.31.3

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,2 @@
1
- var na=Object.defineProperty;var ra=(e,t)=>{for(var n in t)na(e,n,{get:t[n],enumerable:!0})};var ao=Symbol.for("immer-nothing"),no=Symbol.for("immer-draftable"),he=Symbol.for("immer-state");function ge(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var ot=Object.getPrototypeOf;function se(e){return!!e&&!!e[he]}function ze(e){return e?co(e)||Array.isArray(e)||!!e[no]||!!e.constructor?.[no]||Ht(e)||Wt(e):!1}var oa=Object.prototype.constructor.toString();function co(e){if(!e||typeof e!="object")return!1;let t=ot(e);if(t===null)return!0;let n=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return n===Object?!0:typeof n=="function"&&Function.toString.call(n)===oa}function jn(e){return se(e)||ge(15,e),e[he].base_}function Bt(e,t){qt(e)===0?Reflect.ownKeys(e).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function qt(e){let t=e[he];return t?t.type_:Array.isArray(e)?1:Ht(e)?2:Wt(e)?3:0}function $n(e,t){return qt(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function lo(e,t,n){let r=qt(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function ia(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Ht(e){return e instanceof Map}function Wt(e){return e instanceof Set}function Ue(e){return e.copy_||e.base_}function Tn(e,t){if(Ht(e))return new Map(e);if(Wt(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let n=co(e);if(t===!0||t==="class_only"&&!n){let r=Object.getOwnPropertyDescriptors(e);delete r[he];let o=Reflect.ownKeys(r);for(let i=0;i<o.length;i++){let s=o[i],l=r[s];l.writable===!1&&(l.writable=!0,l.configurable=!0),(l.get||l.set)&&(r[s]={configurable:!0,writable:!0,enumerable:l.enumerable,value:e[s]})}return Object.create(ot(e),r)}else{let r=ot(e);if(r!==null&&n)return{...e};let o=Object.create(r);return Object.assign(o,e)}}function Fn(e,t=!1){return Yt(e)||se(e)||!ze(e)||(qt(e)>1&&(e.set=e.add=e.clear=e.delete=sa),Object.freeze(e),t&&Object.entries(e).forEach(([n,r])=>Fn(r,!0))),e}function sa(){ge(2)}function Yt(e){return Object.isFrozen(e)}var aa={};function qe(e){let t=aa[e];return t||ge(0,e),t}var bt;function uo(){return bt}function ca(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function ro(e,t){t&&(qe("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Dn(e){Nn(e),e.drafts_.forEach(la),e.drafts_=null}function Nn(e){e===bt&&(bt=e.parent_)}function oo(e){return bt=ca(bt,e)}function la(e){let t=e[he];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function io(e,t){t.unfinalizedDrafts_=t.drafts_.length;let n=t.drafts_[0];return e!==void 0&&e!==n?(n[he].modified_&&(Dn(t),ge(4)),ze(e)&&(e=Ut(t,e),t.parent_||zt(t,e)),t.patches_&&qe("Patches").generateReplacementPatches_(n[he].base_,e,t.patches_,t.inversePatches_)):e=Ut(t,n,[]),Dn(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==ao?e:void 0}function Ut(e,t,n){if(Yt(t))return t;let r=t[he];if(!r)return Bt(t,(o,i)=>so(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return zt(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;let o=r.copy_,i=o,s=!1;r.type_===3&&(i=new Set(o),o.clear(),s=!0),Bt(i,(l,a)=>so(e,r,o,l,a,n,s)),zt(e,o,!1),n&&e.patches_&&qe("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function so(e,t,n,r,o,i,s){if(se(o)){let l=i&&t&&t.type_!==3&&!$n(t.assigned_,r)?i.concat(r):void 0,a=Ut(e,o,l);if(lo(n,r,a),se(a))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if(ze(o)&&!Yt(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Ut(e,o),(!t||!t.scope_.parent_)&&typeof r!="symbol"&&Object.prototype.propertyIsEnumerable.call(n,r)&&zt(e,o)}}function zt(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&Fn(t,n)}function ua(e,t){let n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:uo(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=r,i=Mn;n&&(o=[r],i=It);let{revoke:s,proxy:l}=Proxy.revocable(o,i);return r.draft_=l,r.revoke_=s,l}var Mn={get(e,t){if(t===he)return e;let n=Ue(e);if(!$n(n,t))return da(e,n,t);let r=n[t];return e.finalized_||!ze(r)?r:r===kn(e.base_,t)?(Ln(e),e.copy_[t]=Vn(r,e)):r},has(e,t){return t in Ue(e)},ownKeys(e){return Reflect.ownKeys(Ue(e))},set(e,t,n){let r=fo(Ue(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){let o=kn(Ue(e),t),i=o?.[he];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(ia(n,o)&&(n!==void 0||$n(e.base_,t)))return!0;Ln(e),Pn(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return kn(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,Ln(e),Pn(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let n=Ue(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){ge(11)},getPrototypeOf(e){return ot(e.base_)},setPrototypeOf(){ge(12)}},It={};Bt(Mn,(e,t)=>{It[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});It.deleteProperty=function(e,t){return It.set.call(this,e,t,void 0)};It.set=function(e,t,n){return Mn.set.call(this,e[0],t,n,e[0])};function kn(e,t){let n=e[he];return(n?Ue(n):e)[t]}function da(e,t,n){let r=fo(t,n);return r?"value"in r?r.value:r.get?.call(e.draft_):void 0}function fo(e,t){if(!(t in e))return;let n=ot(e);for(;n;){let r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=ot(n)}}function Pn(e){e.modified_||(e.modified_=!0,e.parent_&&Pn(e.parent_))}function Ln(e){e.copy_||(e.copy_=Tn(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var fa=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){let i=n;n=t;let s=this;return function(a=i,...c){return s.produce(a,u=>n.call(this,u,...c))}}typeof n!="function"&&ge(6),r!==void 0&&typeof r!="function"&&ge(7);let o;if(ze(t)){let i=oo(this),s=Vn(t,void 0),l=!0;try{o=n(s),l=!1}finally{l?Dn(i):Nn(i)}return ro(i,r),io(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===ao&&(o=void 0),this.autoFreeze_&&Fn(o,!0),r){let i=[],s=[];qe("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else ge(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,a=>t(a,...l));let r,o;return[this.produce(t,n,(s,l)=>{r=s,o=l}),r,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){ze(e)||ge(8),se(e)&&(e=He(e));let t=oo(this),n=Vn(e,void 0);return n[he].isManual_=!0,Nn(t),n}finishDraft(e,t){let n=e&&e[he];(!n||!n.isManual_)&&ge(9);let{scope_:r}=n;return ro(r,t),io(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){let o=t[n];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}n>-1&&(t=t.slice(n+1));let r=qe("Patches").applyPatches_;return se(e)?r(e,t):this.produce(e,o=>r(o,t))}};function Vn(e,t){let n=Ht(e)?qe("MapSet").proxyMap_(e,t):Wt(e)?qe("MapSet").proxySet_(e,t):ua(e,t);return(t?t.scope_:uo()).drafts_.push(n),n}function He(e){return se(e)||ge(10,e),po(e)}function po(e){if(!ze(e)||Yt(e))return e;let t=e[he],n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=Tn(e,t.scope_.immer_.useStrictShallowCopy_)}else n=Tn(e,!0);return Bt(n,(r,o)=>{lo(n,r,po(o))}),t&&(t.finalized_=!1),n}var me=new fa,Bn=me.produce,wp=me.produceWithPatches.bind(me),Ep=me.setAutoFreeze.bind(me),xp=me.setUseStrictShallowCopy.bind(me),vp=me.applyPatches.bind(me),Cp=me.createDraft.bind(me),Sp=me.finishDraft.bind(me);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},k={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},it={NOT:0};var v=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},pe=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var Un=e=>{if(!e||e.trim()==="")throw new v("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let n=e.includes("===")?"==":"!=";throw new v(`Invalid comparison operator '${e.includes("===")?"===":"!=="}' - did you mean '${n}'? (got: '${e}')`)}let t=["<",">","<=",">=","==","!="];for(let n of t)if(e.trim().endsWith(n))throw new v(`Incomplete comparison expression - missing right operand (got: '${e}')`)},ho=e=>{if(e.trim().endsWith(" in"))throw new v(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new v(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,n]=e.split(" in ");if(!n||n.trim()==="")throw new v(`Missing iterable expression after 'in' (got: '$for ${e}')`);let r=t.includes(",")?t.split(",").map(o=>o.trim()):[t.trim()];for(let o of r){if(!o)throw new v(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new v(`Invalid loop syntax (got: '$for ${e}')`)}};var mo=(e,t,n=!1)=>{if(t===null)return new pe(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new pe(`Cannot iterate over undefined value at '$for ${e}'`);let r=typeof t;return n?new pe(`Cannot iterate over non-array value in loop '${e}' - got ${r} instead`):new pe(`Cannot iterate over non-array value (got: ${r}) at '$for ${e}'`)},go=(e,t)=>{let n=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new pe(`Unknown function '${e}' (${n})`)};var pa=(e,t,n={})=>{let r={},o={};n&&typeof n=="object"&&(n.functions!==void 0||n.partials!==void 0?(r=n.functions||{},o=n.partials||{}):typeof n=="object"&&(r=n));let s=L(e,{functions:r,partials:o},t,{});return s===void 0?{}:s},L=(e,t,n,r)=>{let o=t.functions||t;if(e.var&&!e.type)return K(e.var,n,r);if(e.type===m.LITERAL)return e.value;if(e.type===m.VARIABLE)return K(e.path,n,r);if(e.type===m.INTERPOLATION)return ma(e.parts,t,n,r);switch(e.type){case m.FUNCTION:return bo(e,t,n,r);case m.BINARY:return Io(e,t,n,r);case m.UNARY:return Ao(e,t,n,r);case m.CONDITIONAL:return ya(e,t,n,r);case m.LOOP:return Ea(e,t,n,r);case m.OBJECT:return va(e,t,n,r);case m.ARRAY:return Ca(e,t,n,r);case m.PARTIAL:return Sa(e,t,n,r);case m.PATH_REFERENCE:return _a(e,t,n,r);default:throw new Error(`Unknown node type: ${e.type}`)}},yo=new Map,ha=e=>{let t=[],n="",r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(i==="[")n&&(t.push({type:"property",value:n}),n=""),r=!0;else if(i==="]"){if(r&&n){let s=n.trim();if(/^\d+$/.test(s))t.push({type:"index",value:parseInt(s,10)});else if(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'")){let l=s.slice(1,-1);t.push({type:"property",value:l})}else t.push({type:"property",value:s});n=""}r=!1}else n+=i}return n&&t.push({type:"property",value:n}),t},K=(e,t,n)=>{if(!e)return;if(e in n)return n[e];let r=yo.get(e);if(!r){let i=[],s="",l=0;for(let a=0;a<e.length;a++){let c=e[a];c==="["?(l++,s+=c):c==="]"?(l--,s+=c):c==="."&&l===0?s&&(i.push(s),s=""):s+=c}s&&i.push(s),r=[];for(let a of i){let c=ha(a.trim());r.push(...c)}yo.set(e,r)}let o=t;for(let i=0;i<r.length;i++){let s=r[i];if(s.type==="property"&&s.value in n){o=n[s.value];continue}if(o==null)return;(s.type==="property"||s.type==="index")&&(o=o[s.value])}return o},ma=(e,t,n,r)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=L(i,t,n,r);o.push(s!=null?String(s):"")}return o.join("")},bo=(e,t,n,r)=>{let o=t.functions||t,i=o[e.name];if(!i)throw go(e.name,o);let s=e.args.map(l=>L(l,t,n,r));return i(...s)},$e=(e,t,n,r)=>{if(e.var&&!e.type)return K(e.var,n,r);switch(e.type){case m.VARIABLE:return K(e.path,n,r);case m.LITERAL:return e.value;case m.BINARY:return Io(e,t,n,r);case m.UNARY:return Ao(e,t,n,r);case m.FUNCTION:return bo(e,t,n,r);default:return L(e,t,n,r)}},Io=(e,t,n,r)=>{if(e.op===k.AND||e.op===k.OR){let s=$e(e.left,t,n,r),l=$e(e.right,t,n,r);switch(e.op){case k.AND:return s&&l;case k.OR:return s||l}}let o=L(e.left,t,n,r),i=L(e.right,t,n,r);switch(e.op){case k.EQ:return o==i;case k.NEQ:return o!=i;case k.GT:return o>i;case k.LT:return o<i;case k.GTE:return o>=i;case k.LTE:return o<=i;case k.IN:return Array.isArray(i)?i.includes(o):!1;case k.ADD:if(typeof o!="number"||typeof i!="number")throw new pe(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case k.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new pe(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},Ao=(e,t,n,r)=>{let o=e.op===it.NOT?$e(e.operand,t,n,r):L(e.operand,t,n,r);if(e.op===it.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},ga=(e,t,n,r)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===m.VARIABLE)if(K(o.path,n,r)){let s=e.bodies[0];if(s.type===m.OBJECT&&s.properties.length<=5){let l={};for(let a of s.properties){let c=a.parsedKey?L(a.parsedKey,t,n,r):a.key,u=a.value;if(u.type===m.LITERAL)l[c]=u.value;else if(u.type===m.VARIABLE)l[c]=K(u.path,n,r);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=K(f.path,n,r);d.push(p!=null?String(p):"")}else{let p=L(f,t,n,r);d.push(p!=null?String(p):"")}l[c]=d.join("")}else l[c]=L(u,t,n,r)}return l}}else{let s=e.bodies[1];if(s.type===m.OBJECT&&s.properties.length<=5){let l={};for(let a of s.properties){let c=a.parsedKey?L(a.parsedKey,t,n,r):a.key,u=a.value;if(u.type===m.LITERAL)l[c]=u.value;else if(u.type===m.VARIABLE)l[c]=K(u.path,n,r);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=K(f.path,n,r);d.push(p!=null?String(p):"")}else{let p=L(f,t,n,r);d.push(p!=null?String(p):"")}l[c]=d.join("")}else l[c]=L(u,t,n,r)}return l}}}return null},ya=(e,t,n,r)=>{let o=ga(e,t,n,r);if(o!==null)return o;for(let i=0;i<e.conditions.length;i++){let s=e.conditions[i];if(s===null||$e(s,t,n,r))return L(e.bodies[i],t,n,r)}return wo},ba=(e,t)=>{let n=e.body,r=e.itemVar;if(n.type===m.CONDITIONAL&&n.conditions.length===1&&n.conditions[0].type===m.VARIABLE){let o=n.conditions[0].path,i=n.bodies[0];if(o.startsWith(r+".")){let s=o.substring(r.length+1);if(i.type===m.OBJECT&&i.properties.length<=5){for(let a of i.properties)if(a.parsedKey)return null;let l=[];for(let a=0;a<t.length;a++){let c=t[a];if(c[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===r)u[f]=c;else if(h.startsWith(r+".")){let g=h.substring(r.length+1);u[f]=c[g]}else return null}else if(p.type===m.INTERPOLATION){let h=[],g=!0;for(let b of p.parts)if(typeof b=="string")h.push(b);else if(b.type===m.VARIABLE){let A=b.path;if(A===r)h.push(c!=null?String(c):"");else if(A.startsWith(r+".")){let w=A.substring(r.length+1),C=c[w];h.push(C!=null?String(C):"")}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},Ia=(e,t)=>{let n=e.body,r=e.itemVar,o=ba(e,t);if(o!==null)return o;if(n.type===m.OBJECT&&n.properties.length<=5&&!n.whenCondition){for(let l of n.properties)if(l.parsedKey)return null;let i=[],s=!0;for(let l of n.properties){let a=l.key,c=l.value;if(c.type===m.LITERAL)i.push({key:a,type:"literal",value:c.value});else if(c.type===m.VARIABLE){let u=c.path;if(u===r)i.push({key:a,type:"item"});else if(u.startsWith(r+".")){let d=u.substring(r.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:a,type:"prop",prop:d});else{s=!1;break}}else{s=!1;break}}else if(c.type===m.INTERPOLATION&&c.parts.length===1){let u=c.parts[0];if(u.type===m.VARIABLE){let d=u.path;if(d===r)i.push({key:a,type:"item_string"});else if(d.startsWith(r+".")){let f=d.substring(r.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:a,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 a=0;a<t.length;a++){let c=t[a];l[a]={id:c.id,title:c.title!=null?String(c.title):"",completed:c.completed}}else for(let a=0;a<t.length;a++){let c=t[a],u={};for(let d of i)if(d.type==="literal")u[d.key]=d.value;else if(d.type==="item")u[d.key]=c;else if(d.type==="prop")u[d.key]=c[d.prop];else if(d.type==="item_string")u[d.key]=c!=null?String(c):"";else if(d.type==="prop_string"){let f=c[d.prop];u[d.key]=f!=null?String(f):""}l[a]=u}return l}}return null},Aa=(e,t,n,r,o)=>{let i=[],s=e.body;if(s.type===m.OBJECT&&s.fast!==!1){let l=e.itemVar,a=e.indexVar;for(let c=0;c<o.length;c++){let u=o[c],d={},f={...r,[l]:u,...a&&{[a]:c}};f.__paths__||(f.__paths__=r.__paths__||{});let p=e.iterable.path||"";if(r&&r.__paths__&&p){let h=p.split("."),g=h[0];g in r.__paths__&&(p=r.__paths__[g],h.length>1&&(p+="."+h.slice(1).join(".")))}f.__paths__={...f.__paths__,[l]:`${p}[${c}]`,...a&&{[a]:c}};for(let h of s.properties){let g=h.parsedKey?L(h.parsedKey,t,n,f):h.key,b=h.value;if(b.type===m.LITERAL)d[g]=b.value;else if(b.type===m.VARIABLE){let A=b.path;if(A===l)d[g]=u;else if(A===a)d[g]=c;else if(A.startsWith(l+".")){let w=A.substring(l.length+1);!w.includes(".")&&!w.includes("[")?d[g]=u[w]:d[g]=K(A,n,{...r,[l]:u,...a&&{[a]:c}})}else d[g]=K(A,n,{...r,[l]:u,...a&&{[a]:c}})}else if(b.type===m.INTERPOLATION){let A=[];for(let w of b.parts)if(typeof w=="string")A.push(w);else if(w.type===m.VARIABLE){let C=w.path,R;if(C===l)R=u;else if(C===a)R=c;else if(C.startsWith(l+".")){let V=C.substring(l.length+1);!V.includes(".")&&!V.includes("[")?R=u[V]:R=K(C,n,{...r,[l]:u,...a&&{[a]:c}})}else R=K(C,n,{...r,[l]:u,...a&&{[a]:c}});A.push(R!=null?String(R):"")}else{let C={...r,[l]:u,...a&&{[a]:c}},R=L(w,t,n,C);A.push(R!=null?String(R):"")}d[g]=A.join("")}else{let A={...r,[l]:u,...a&&{[a]:c}};d[g]=L(b,t,n,A)}}i.push(d)}return i}return null},wa=(e,t,n)=>{let r=e.body;if(r.type===m.OBJECT&&r.properties.length===1&&r.properties[0].key==="$if item.visible"){let i=r.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],a=s.properties[1];if(l.key==="id"&&l.value.type===m.VARIABLE&&l.value.path==="item.id"&&a.key==="$if item.highlighted"&&a.value.type===m.CONDITIONAL){let c=[];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),c.push(f)}}return c}}}}return null},Ea=(e,t,n,r)=>{let o=L(e.iterable,t,n,r);if(!Array.isArray(o)){let c,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(", ");c=`${e.iterable.name}(${f})`}else c=e.iterable.path||"undefined";let d=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${c}`;throw mo(d,o,u)}if(!e.indexVar){let c=wa(e,o,e.itemVar);if(c!==null)return c}if(!e.indexVar){let c=Ia(e,o);if(c!==null)return c}let i=Aa(e,t,n,r,o);if(i!==null)return i;let s=[],l=e.iterable.path||"";if(r&&r.__paths__&&l){let c=l.split("."),u=c[0];u in r.__paths__&&(l=r.__paths__[u],c.length>1&&(l+="."+c.slice(1).join(".")))}let a=!1;e.body.type===m.ARRAY&&(e.body.items.length<=1?a=!1:a=e.body._shouldPreserveArray??=e.body.items.some(c=>c.type===m.OBJECT&&c.properties.some(u=>u.key.startsWith("$if ")||u.key.startsWith("$when "))));for(let c=0;c<o.length;c++){let u=e.indexVar?{...r,[e.itemVar]:o[c],[e.indexVar]:c}:{...r,[e.itemVar]:o[c]};u.__paths__||(u.__paths__=r.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${l}[${c}]`},e.indexVar&&(u.__paths__[e.indexVar]=c);let d=L(e.body,t,n,u);if(Array.isArray(d)&&d.length===1&&!a){let f=d[0];s.push(f===void 0?{}:f)}else s.push(d===void 0?{}:d)}return s},xa=(e,t,n,r)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?L(o.parsedKey,t,n,r):o.key,s=o.value;if(s.type===m.OBJECT&&s.properties.length<=10&&!s.whenCondition){let l={},a={},c=!0;for(let u of s.properties){let d=u.parsedKey?L(u.parsedKey,t,n,r):u.key,f=u.value;if(f.type===m.LITERAL)a[d]=f.value;else if(f.type===m.VARIABLE)a[d]=K(f.path,n,r);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=K(h.path,n,r);p.push(g!=null?String(g):"")}else{c=!1;break}if(!c)break;a[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,b=h.value;if(b.type===m.LITERAL)p[g]=b.value;else if(b.type===m.VARIABLE)p[g]=K(b.path,n,r);else if(b.type===m.INTERPOLATION){let A=[];for(let w of b.parts)if(typeof w=="string")A.push(w);else if(w.type===m.VARIABLE){let C=K(w.path,n,r);A.push(C!=null?String(C):"")}else{c=!1;break}if(!c)break;p[g]=A.join("")}else{c=!1;break}}if(!c)break;a[d]=p}else{c=!1;break}}if(c)return l[i]=a,l}}return null},va=(e,t,n,r)=>{let o=t.functions||t;if(e.whenCondition&&!$e(e.whenCondition,o,n,r))return;let i=xa(e,t,n,r);if(i!==null)return i;if(e.fast){let c={};for(let u of e.properties){let d=u.parsedKey?L(u.parsedKey,t,n,r):u.key,f=u.value;if(f.type===m.LITERAL)c[d]=f.value;else if(f.type===m.VARIABLE)c[d]=K(f.path,n,r);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=K(h.path,n,r);p.push(g!=null?String(g):"")}else{let g=L(h,t,n,r);p.push(g!=null?String(g):"")}c[d]=p.join("")}else c[d]=L(f,t,n,r)}return c}let s={},l=null,a=!1;for(let c of e.properties)if(!c.key.startsWith("$if ")&&!c.key.match(/^\$if\s+\w+.*:?$/)&&!c.key.startsWith("$elif")&&!c.key.startsWith("$else")&&!c.key.startsWith("$for ")){a=!0;break}for(let c of e.properties)if(c.key.startsWith("$if ")||c.key.match(/^\$if\s+\w+.*:?$/)){let u=L(c.value,t,n,r);if(!a&&u!==null&&u!==void 0)return Array.isArray(u)&&u.length===1?u[0]:u;typeof u=="object"&&u!==null&&!Array.isArray(u)&&Object.assign(s,u)}else if(c.key.startsWith("$for ")){if(e.properties.length===1)return L(c.value,t,n,r)}else{let u=c.value;if(u&&u.type===m.OBJECT&&u.properties){let d=u.properties.find(f=>f.key.startsWith("$for "));if(d){let f=L(d.value,t,n,r);f!==void 0&&(s[c.key]=f)}else{let f=L(c.value,t,n,r);f!==void 0&&(s[c.key]=f)}}else{let d=c.parsedKey?L(c.parsedKey,t,n,r):c.key,f=L(c.value,t,n,r);f!==void 0&&(s[d]=f)}}return s},wo={},Ca=(e,t,n,r)=>{let o=[];for(let i of e.items)if(i.type===m.LOOP){let s=L(i,t,n,r);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=L(i,t,n,r);s!==wo&&s!==void 0&&o.push(s)}return o},Sa=(e,t,n,r)=>{let{name:o,data:i,whenCondition:s}=e,l=t.partials||{},a=t.functions||t;if(s&&!$e(s,a,n,r))return;if(!l[o])throw new pe(`Partial '${o}' is not defined`);let c=r._partialStack||[];if(c.includes(o))throw new pe(`Circular partial reference detected: ${o}`);let u=l[o],d=n,f={...r,_partialStack:[...c,o]};if(r){d={...n};for(let p of Object.keys(r))p.startsWith("_")||(d[p]=r[p])}if(i){let p=L(i,t,n,r);d={...d,...p}}return L(u,t,d,f)},_a=(e,t,n,r)=>{let{path:o}=e,i=o.split("."),s=i[0],l=i.slice(1);if(!r||!(s in r))throw new pe(`Path reference '#{${o}}' refers to '${s}' which is not a loop variable in the current scope`);if(r.__paths__||(r.__paths__={}),!(s in r.__paths__))throw new pe(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let a=r.__paths__[s];if(typeof a=="number"){if(l.length>0)throw new pe(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(a)}return l.length>0&&(a+="."+l.join(".")),a};var zn=pa;var Ra=/\$\{([^}]*)\}/g,Oa=/#\{([^}]*)\}/g,xo=(e,t={})=>{let n=e.match(/^(\w+)\((.*)\)$/);if(!n)return{isFunction:!1};let[,r,o]=n,i=ka(o,t);return{isFunction:!0,type:m.FUNCTION,name:r,args:i}},ka=(e,t={})=>e.trim()?La(e).map(r=>$a(r.trim(),t)):[],La=e=>{let t=[],n="",r=0,o=!1,i="";for(let s=0;s<e.length;s++){let l=e[s],a=s>0?e[s-1]:"";!o&&(l==='"'||l==="'")?(o=!0,i=l,n+=l):o&&l===i&&a!=="\\"?(o=!1,i="",n+=l):!o&&l==="("?(r++,n+=l):!o&&l===")"?(r--,n+=l):!o&&l===","&&r===0?(t.push(n),n=""):n+=l}return n&&t.push(n),t},$a=(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 n=xo(e,t);if(n.isFunction)return{type:n.type,name:n.name,args:n.args};let r=e.trim(),o=[{op:" + ",type:"ADD"},{op:" - ",type:"SUBTRACT"}],i=-1,s=null;for(let{op:l,type:a}of o){let c=0;for(;c<r.length;){let u=We(r.substring(c),l);if(u===-1)break;let d=c+u;d>i&&(i=d,s={op:l,type:a}),c=d+l.length}}if(i!==-1)try{return Z(r,t)}catch{return{type:m.VARIABLE,path:r}}return{type:m.VARIABLE,path:r}},vo=/^\w+\(.*\)$/,Ta=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,Da=e=>{if(!(!e||e.trim()===""||vo.test(e))&&Ta.test(e))throw e.includes("?")&&e.includes(":")?new v(`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 v(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new v(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},Eo=e=>{let t=e.trim();if(vo.test(t))throw new v(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new v(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new v(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new v(`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 v(`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}},At=(e,t={})=>{let n=e.trim();Da(n);let r=xo(n,t);if(r.isFunction)return{type:r.type,name:r.name,args:r.args};if(n.includes("[")&&!/[\s+\-*/%|&?:]/.test(n)){let o=0;for(let i of n)i==="["?o++:i==="]"&&o--;if(o!==0)throw new Error("Invalid array index syntax")}return{type:m.VARIABLE,path:n}},qn=(e,t={})=>{let n=e,r=[];(e.includes("\\${")||e.includes("\\#{"))&&(n=e.replace(/\\\\(\$\{[^}]*\})/g,"\\DOUBLE_ESC_VAR$1"),n=n.replace(/\\\\(#\{[^}]*\})/g,"\\DOUBLE_ESC_PATH$1"),n=n.replace(/\\(\$\{[^}]*\})/g,(c,u)=>{let d=`__ESCAPED_${r.length}__`;return r.push(u),d}),n=n.replace(/\\(#\{[^}]*\})/g,(c,u)=>{let d=`__ESCAPED_${r.length}__`;return r.push(u),d}),n=n.replace(/\\DOUBLE_ESC_VAR/g,"\\"),n=n.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...n.matchAll(Ra)],i=[...n.matchAll(Oa)],s=[...o.map(c=>({match:c,type:"variable"})),...i.map(c=>({match:c,type:"pathref"}))].sort((c,u)=>c.match.index-u.match.index);if(s.length===0){let c=n;for(let u=0;u<r.length;u++)c=c.replace(`__ESCAPED_${u}__`,r[u]);return{type:m.LITERAL,value:c}}if(s.length===1&&s[0].match[0]===n&&r.length===0){let{match:c,type:u}=s[0];try{return u==="variable"?At(c[1],t):Eo(c[1])}catch(d){if(d.message==="Invalid array index syntax")return{type:m.LITERAL,value:n};throw d}}let l=[],a=0;for(let{match:c,type:u}of s){let[d,f]=c,p=c.index;if(p>a){let h=n.substring(a,p);for(let g=0;g<r.length;g++)h=h.replace(`__ESCAPED_${g}__`,r[g]);h&&l.push(h)}try{let h;u==="variable"?h=At(f.trim(),t):h=Eo(f.trim()),l.push(h)}catch(h){if(h.message==="Invalid array index syntax")l.push(d);else throw h}a=p+d.length}if(a<n.length){let c=n.substring(a);for(let u=0;u<r.length;u++)c=c.replace(`__ESCAPED_${u}__`,r[u]);c&&l.push(c)}return{type:m.INTERPOLATION,parts:l}};var Yn=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),_o=e=>Object.keys(e),ae=e=>e.join("."),Te=(e,t,n)=>{let r=_o(e).filter(o=>!t.has(o));if(r.length>0)throw new v(`Unexpected key '${r[0]}' in condition JSON at '${ae(n)}'`)},De=(e,t)=>typeof e=="string"?qn(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?Pa(e,t):Va(e,t):{type:m.LITERAL,value:e},Na=e=>{let{$each:t,...n}=e;if(typeof t!="string")throw new v("$each value must be a non-empty string");let r=t.trim();if(r==="")throw new v("$each value must be a non-empty string");if(Object.keys(n).length===0)throw new v("Empty $each body not allowed");if(n.$partial!==void 0)throw new v("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${r}`]:n}},Pa=(e,t)=>{let n=[],r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(typeof i=="object"&&i!==null&&!Array.isArray(i)){if(i.$each!==void 0)try{let a=Na(i),c=Object.keys(a);if(c.length===1&&/^\$for(?::\w+)?\s/.test(c[0])){let u=So(c[0],a[c[0]],t,!0);n.push(u),r=!0;continue}}catch(a){throw a instanceof v?a:new v(a.message)}let l=Object.keys(i);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let a=So(l[0],i[l[0]],t);n.push(a),r=!0;continue}}let s=De(i,t);n.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)&&(r=!0)}return{type:m.ARRAY,items:n,fast:!r}},Va=(e,t)=>{let n=[],r=!1,o=null,i=Object.entries(e),s=0;if(e.$partial!==void 0){if(typeof e.$partial!="string")throw new v("$partial value must be a string");if(e.$partial.trim()==="")throw new v("$partial value cannot be an empty string");let a=["$if","$elif","$else","$for"],c=[];for(let[A]of i)for(let w of a)if(A===w||A.startsWith(w+" ")||A.startsWith(w+"#")){c.push(w);break}if(c.length>0)throw new v(`Cannot use $partial with ${c.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[A,w]of Object.entries(f)){let C=A;(A.startsWith("\\$")||A.startsWith("$$"))&&(C=A.slice(1)),p[C]=w,h=!0}let g=null;if(h&&(g=De(p,t),g.type===m.OBJECT)){let A=!1;for(let w of g.properties)if(w.value.type===m.VARIABLE||w.value.type===m.INTERPOLATION||w.value.type===m.FUNCTION||w.value.type===m.CONDITIONAL||w.value.type===m.OBJECT&&!w.value.fast||w.value.type===m.ARRAY&&!w.value.fast){A=!0;break}A&&(g.fast=!1)}let b={type:m.PARTIAL,name:u,data:g};return d!==void 0&&(b.whenCondition=Co(d,t)),b}for(let[a,c]of i)if(a==="$when"){if(o!==null)throw new v("Multiple '$when' directives on the same object are not allowed");if(c==null)throw new v("Missing condition expression after '$when'");o=Co(c,t),r=!0}else if(a.startsWith("$when#")||a.startsWith("$when "))throw new v("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<i.length;){let[a,c]=i[s];if(a==="$when"){s++;continue}if(a==="$each")throw new v("$each can only be used inside arrays");if(a.startsWith("$if ")||a.match(/^\$if#\w+\s/)||a.match(/^\$if\s+\w+.*:$/)){let u=ja(i,s,t);n.push({key:a,value:u.node}),r=!0,s=u.nextIndex}else if(/^\$for(?::\w+)?\s/.test(a)){let u=a.match(/^\$for(?::(\w+))?\s/)?.[1]||"",d=u?`:${u}`:"";throw new v(`$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(a.startsWith("$elif ")||a.startsWith("$else"))throw new v(`'${a.split(" ")[0]}' without matching '$if'`);if(a==="$if"||a==="$if:")throw new v("Missing condition expression after '$if'");{let u=De(c,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)&&(r=!0);let d=qn(a,t),f={key:a,value:u};(d.type!==m.LITERAL||d.value!==a)&&(f.parsedKey=d),n.push(f),s++}}}let l={type:m.OBJECT,properties:n,fast:!r};return o&&(l.whenCondition=o),l},ja=(e,t,n={})=>{let r=[],o=[],i=t,[s,l]=e[i],a=null,c;if(s.startsWith("$if#")){let d=s.match(/^\$if#(\w+)\s+(.+)$/);if(d)a=d[1],c=d[2];else throw new v(`Invalid conditional syntax: ${s}`)}else c=s.substring(4),c.endsWith(":")&&(c=c.slice(0,-1).trim());Un(c);let u=Z(c,n);for(r.push(u),o.push(De(l,n)),i++;i<e.length;){let[d,f]=e[i],p=!1,h;if(a?d.startsWith(`$elif#${a} `)?(h=d.substring(`$elif#${a} `.length),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(d===`$else#${a}`||d===`$else#${a}:`)&&(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)r.push(null);else{Un(h);let g=Z(h,n);r.push(g)}if(o.push(De(f,n)),i++,h===null)break}else break}return{node:{type:m.CONDITIONAL,conditions:r,bodies:o,id:a},nextIndex:i}},Hn={eq:k.EQ,neq:k.NEQ,gt:k.GT,gte:k.GTE,lt:k.LT,lte:k.LTE,in:k.IN,add:k.ADD,sub:k.SUBTRACT},Wn={all:k.AND,any:k.OR},Fa=new Set(["var","literal","call","not",...Object.keys(Hn),...Object.keys(Wn)]),Ma=(e,t,n)=>{if(!Array.isArray(e))throw new v(`Condition JSON operator '${t}' at '${ae(n)}' requires an array`);if(e.length!==2)throw new v(`Condition JSON operator '${t}' at '${ae(n)}' requires exactly 2 operands`);return e},Ba=(e,t,n,r,o)=>{if(!Array.isArray(e))throw new v(`Condition JSON operator '${t}' at '${ae(o)}' requires an array`);if(e.length===0)throw new v(`Condition JSON operator '${t}' at '${ae(o)}' requires at least 1 condition`);return e.map((s,l)=>Ce(s,r,[...o,l])).reduce((s,l)=>({type:m.BINARY,op:n,left:s,right:l}))},Ua=(e,t,n)=>{let r,o;if(typeof e.call=="string")r=e.call,o=e.args??[],Te(e,new Set(["call","args"]),n);else if(Yn(e.call))r=e.call.name,o=e.call.args??[],Te(e,new Set(["call"]),n),Te(e.call,new Set(["name","args"]),[...n,"call"]);else throw new v(`Condition JSON call at '${ae(n)}' requires a function name`);if(typeof r!="string"||r.trim()==="")throw new v(`Condition JSON call at '${ae(n)}' requires a non-empty function name`);if(!/^\w+$/.test(r))throw new v(`Invalid condition JSON function name '${r}' at '${ae(n)}'`);if(!Array.isArray(o))throw new v(`Condition JSON call '${r}' at '${ae(n)}' requires args to be an array`);return{type:m.FUNCTION,name:r,args:o.map((i,s)=>Ce(i,t,[...n,"args",s]))}},Ce=(e,t={},n=["$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 v(`Condition JSON array at '${ae(n)}' must be wrapped in an operator or { literal: [...] }`);if(!Yn(e))throw new v(`Invalid condition JSON value at '${ae(n)}'`);let r=_o(e);if(r.length===0)throw new v(`Condition JSON object at '${ae(n)}' must contain an operator`);let o=r.filter(s=>Fa.has(s));if(o.length===0)throw new v(`Unknown condition JSON operator '${r[0]}' at '${ae(n)}'`);if(o.length>1)throw new v(`Condition JSON at '${ae(n)}' must contain exactly one operator`);let i=o.includes("call")?"call":o[0];if(i==="var"){if(Te(e,new Set(["var"]),n),typeof e.var!="string"||e.var.trim()==="")throw new v(`Condition JSON var at '${ae(n)}' requires a non-empty path`);return{type:m.VARIABLE,path:e.var}}if(i==="literal")return Te(e,new Set(["literal"]),n),{type:m.LITERAL,value:e.literal};if(i==="call")return Ua(e,t,n);if(i==="not")return Te(e,new Set(["not"]),n),{type:m.UNARY,op:it.NOT,operand:Ce(e.not,t,[...n,"not"])};if(i in Wn)return Te(e,new Set([i]),n),Ba(e[i],i,Wn[i],t,[...n,i]);if(i in Hn){Te(e,new Set([i]),n);let s=Ma(e[i],i,[...n,i]);return{type:m.BINARY,op:Hn[i],left:Ce(s[0],t,[...n,i,0]),right:Ce(s[1],t,[...n,i,1])}}throw new v(`Unknown condition JSON operator '${i}' at '${ae(n)}'`)},Co=(e,t={})=>{if(e==null)throw new v("Missing condition expression after '$when'");if(typeof e=="string"){if(e.trim()==="")throw new v("Empty condition expression after '$when'");return Z(e,t)}return Yn(e)||Array.isArray(e)?Ce(e,t):{type:m.LITERAL,value:e}},Z=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let c=e.slice(1,-1),u=0,d=!0;for(let f=0;f<c.length;f++)if(c[f]==="("?u++:c[f]===")"&&u--,u<0){d=!1;break}if(d&&u===0)return Z(c,t)}let n=We(e,"||");if(n!==-1)return{type:m.BINARY,op:k.OR,left:Z(e.substring(0,n).trim(),t),right:Z(e.substring(n+2).trim(),t)};let r=We(e,"&&");if(r!==-1)return{type:m.BINARY,op:k.AND,left:Z(e.substring(0,r).trim(),t),right:Z(e.substring(r+2).trim(),t)};let o=[{op:">=",type:k.GTE},{op:"<=",type:k.LTE},{op:"==",type:k.EQ},{op:"!=",type:k.NEQ},{op:">",type:k.GT},{op:"<",type:k.LT},{op:" in ",type:k.IN}];for(let{op:c,type:u}of o){let d=We(e,c);if(d!==-1)return{type:m.BINARY,op:u,left:Z(e.substring(0,d).trim(),t),right:Z(e.substring(d+c.length).trim(),t)}}let i=-1,s=null,l=[{op:" + ",type:k.ADD},{op:" - ",type:k.SUBTRACT}];for(let{op:c,type:u}of l){let d=0;for(;d<e.length;){let f=We(e.substring(d),c);if(f===-1)break;let p=d+f;p>i&&(i=p,s={op:c,type:u}),d=p+c.length}}if(i!==-1&&s)return{type:m.BINARY,op:s.type,left:Z(e.substring(0,i).trim(),t),right:Z(e.substring(i+s.op.length).trim(),t)};let a=[" * "," / "," % "];for(let c of a)if(We(e,c)!==-1)throw new v(`Arithmetic operations are not allowed in conditionals: "${c}"`);return e.startsWith("!")?{type:m.UNARY,op:it.NOT,operand:Z(e.substring(1).trim(),t)}:Ro(e,t)},We=(e,t)=>{let n=0,r=0;for(;r<=e.length-t.length;){if(e[r]==="(")n++;else if(e[r]===")")n--;else if(n===0&&e.substring(r,r+t.length)===t)return r;r++}return-1},za=e=>{if(e=e.trim(),e==="true")return{type:m.LITERAL,value:!0};if(e==="false")return{type:m.LITERAL,value:!1};if(e==="null")return{type:m.LITERAL,value:null};if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:m.LITERAL,value:e.slice(1,-1)};if(e==='""'||e==="''")return{type:m.LITERAL,value:""};if(e==="{}")return{type:m.LITERAL,value:{}};if(e==="[]")return{type:m.LITERAL,value:[]};let t=Number(e);return!isNaN(t)&&isFinite(t)?{type:m.LITERAL,value:t}:{type:m.VARIABLE,path:e}},Ro=(e,t)=>{let n=e.trim();if(n.match(/^(\w+)\((.*)\)$/))return At(n,t);let o=za(n);if(o.type===m.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(n))return{type:m.VARIABLE,path:n};try{return At(n,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},qa=(e,t=!1)=>{let n=t?"$each":"$for";try{ho(e)}catch(r){if(r instanceof v&&t){let o=r.message.replace(/\$for/g,"$each");throw new v(o.replace("Parse Error: ",""))}throw r}},So=(e,t,n,r=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let b=r?"$each":"$for";throw new v(`Invalid loop syntax (got: '${e.replace("$for",b)}')`)}let s=i[1],l=i[2].trim();qa(l,r);let a=l.match(/^(.+?)\s+in\s+(.+)$/);if(!a){let b=r?"$each":"$for";throw new v(`Invalid loop syntax - missing 'in' keyword (got: '${b} ${l}')`)}let c=a[1].trim(),u=a[2].trim(),d,f=null;if(c.includes(",")){let b=c.split(",").map(A=>A.trim());if(b.length!==2)throw new v(`Invalid loop variables: ${c}. Expected format: "item" or "item, index"`);d=b[0],f=b[1]}else d=c;let p=["this","undefined","null","true","false"];if(p.includes(d))throw new v(`Reserved variable name: ${d}`);if(f&&p.includes(f))throw new v(`Reserved variable name: ${f}`);let h=Ro(u,n),g=De(t,n);return{type:m.LOOP,itemVar:d,indexVar:f,iterable:h,body:g,flatten:s!=="nested"}};var Ha=(e,t={})=>{let{functions:n={}}=t;return De(e,n)},Gt=Ha;var wt={};ra(wt,{now:()=>Wa});var Wa=()=>Date.now();var Ya=(e,t,n={})=>{let{functions:r={},partials:o={}}=n,i={...wt,...r},s=Gt(e,{functions:i}),l={};for(let[a,c]of Object.entries(o))l[a]=Gt(c,{functions:i});return zn(s,t,{functions:i,partials:l})},ce=Ya;var Ga=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",Ka=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,Ja=(e,t)=>{if(Ga(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new v("Empty condition expression");return Z(e,t)}return Ce(e,t)},Xa=(e,t={},n={})=>{let r=Ka(n),o={...wt,...r},i=Ja(e,o);return!!$e(i,{functions:o,partials:{}},t,{})},Gn=Xa;var vt=(e,t={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return Gn(e,t)},Qa=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Do=(e,t,n={})=>{let r=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=a=>a,transformActionFirstArgument:l=a=>a}=n;for(let[a,c]of Object.entries(t))a!=="createInitialState"&&(a.startsWith("select")?o[a]=(...u)=>c(s(r),...u):i[a]=(...u)=>{let d;return r=Bn(r,p=>{let h=c(l(p),...u);d=h!==void 0&&!se(h)?h:void 0}),d});return{...o,...i}},Xt=(e,t)=>n=>{let r=e(),o=Array.isArray(n)?n:[n];return Bn(r,i=>{o.forEach(s=>{t.forEach(l=>{l(i,s)})})})};var Za=(e,t)=>{if(e.default!==void 0)return e.default;let n=["number","boolean","string","object"];if(!n.includes(e.type))throw new Error(`Invalid variable type: ${e.type} for variable ${t}. Expected one of: ${n.join(", ")}`);switch(e.type){case"number":return 0;case"boolean":return!1;case"string":return"";case"object":return{}}},be=(e,t)=>Object.prototype.hasOwnProperty.call(e??{},t),Et=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),No=e=>{let t=se(e)?He(e):e;return structuredClone(t)},ec=({characterId:e,resourceCharacter:t,variables:n={}}={})=>{if(!be(t,"nameVariableId"))return;let r=t.nameVariableId,o=n?.[r];if(typeof o!="string")throw new Error(`Character "${e}" nameVariableId "${r}" must resolve to a string variable`);return o},Qt=({characterId:e,character:t,characterName:n,characters:r={},variables:o={}}={})=>{let i=e?r?.[e]:void 0;if(t?.name!==void 0)return t.name;if(n!==void 0)return n;let s=ec({characterId:e,resourceCharacter:i,variables:o});return s!==void 0?s:i?.name||""},Ne=e=>be(e,"computed"),st=(e={},t={})=>Object.fromEntries(Object.entries(e??{}).filter(([n])=>!Ne(t[n]))),tc=e=>String(e).replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean),Kn=(e,t)=>{let n=e;for(let r of t){if(n==null)return;n=n[r]}return n},nc=(e,t={})=>{if(typeof e!="string"||e.trim()==="")throw new Error("Computed expression var requires a non-empty string path");let n=tc(e),[r,o,...i]=n;if(r==="variables"){if(!o)return t.variables;let s=typeof t.resolveVariable=="function"?t.resolveVariable(o):t.variables?.[o];return Kn(s,i)}return r==="runtime"?Kn(t.runtime,n.slice(1)):Kn(t,n)},rc=(e,t,n)=>{if(!Array.isArray(t))throw new Error(`Computed expression operator "${e}" requires an array`);if(n!==void 0&&t.length!==n)throw new Error(`Computed expression operator "${e}" requires ${n} operand(s)`)},Oo=(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`)},oc=(e,t)=>{if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Computed expression operator "${e}" requires finite numeric operands`)},we=(e,t,n,r)=>(rc(e,t,r),t.map(o=>Jt(o,n))),ye=(e,t,n,r)=>{let o=we(e,t,n,r);return o.forEach(i=>oc(e,i)),o},ic=(e,t,n)=>{switch(e){case"var":return nc(t,n);case"add":{let[r,o]=ye(e,t,n,2);return r+o}case"sub":{let[r,o]=ye(e,t,n,2);return r-o}case"mul":{let[r,o]=ye(e,t,n,2);return r*o}case"div":{let[r,o]=ye(e,t,n,2);return r/o}case"mod":{let[r,o]=ye(e,t,n,2);return r%o}case"neg":{let[r]=ye(e,t,n,1);return-r}case"round":{let[r]=ye(e,t,n,1);return Math.round(r)}case"floor":{let[r]=ye(e,t,n,1);return Math.floor(r)}case"ceil":{let[r]=ye(e,t,n,1);return Math.ceil(r)}case"min":{let[r,o]=ye(e,t,n,2);return Math.min(r,o)}case"max":{let[r,o]=ye(e,t,n,2);return Math.max(r,o)}case"clamp":{let[r,o,i]=ye(e,t,n,3);return Math.min(i,Math.max(o,r))}case"eq":{let[r,o]=we(e,t,n,2);return r==o}case"neq":{let[r,o]=we(e,t,n,2);return r!=o}case"gt":{let[r,o]=we(e,t,n,2);return r>o}case"gte":{let[r,o]=we(e,t,n,2);return r>=o}case"lt":{let[r,o]=we(e,t,n,2);return r<o}case"lte":{let[r,o]=we(e,t,n,2);return r<=o}case"in":{let[r,o]=we(e,t,n,2);return Array.isArray(o)?o.includes(r):!1}case"and":case"all":return Oo(e,t),t.every(r=>!!Jt(r,n));case"or":case"any":return Oo(e,t),t.some(r=>!!Jt(r,n));case"not":{let[r]=we(e,t,n,1);return!r}case"length":{let[r]=we(e,t,n,1);return typeof r=="string"||Array.isArray(r)?r.length:Et(r)?Object.keys(r).length:0}case"includes":{let[r,o]=we(e,t,n,2);return typeof r=="string"||Array.isArray(r)?r.includes(o):!1}case"literal":return No(t);default:throw new Error(`Unknown computed expression operator: ${e}`)}},Jt=(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 n=Object.entries(e);if(n.length!==1)throw new Error("Computed expression objects must contain exactly one operator");let[[r,o]]=n;return ic(r,o,t)},sc=(e,t={})=>vt(e,{variables:t.variables,runtime:t.runtime}),ac=(e,t)=>{if(!Et(e))throw new Error(`${t} must be an object`);let n=be(e,"expr"),r=be(e,"value");if(n===r)throw new Error(`${t} must contain exactly one of expr or value`)},Jn=(e,t,n)=>(ac(e,t),be(e,"value")?No(e.value):Jt(e.expr,n)),cc=(e,t={},n="unknown")=>{if(!Et(e))throw new Error(`Computed variable "${n}" computed must be an object`);let r=be(e,"expr"),o=be(e,"value");if(be(e,"branches")){if(r||o)throw new Error(`Computed variable "${n}" cannot combine branches with expr or value`);if(!Array.isArray(e.branches))throw new Error(`Computed variable "${n}" branches must be an array`);if(e.branches.length===0)throw new Error(`Computed variable "${n}" branches must not be empty`);if(!Et(e.default))throw new Error(`Computed variable "${n}" requires default`);for(let s=0;s<e.branches.length;s+=1){let l=e.branches[s];if(!Et(l))throw new Error(`Computed variable "${n}" branch ${s} must be an object`);if(!be(l,"when"))throw new Error(`Computed variable "${n}" branch ${s} requires when`);if(sc(l.when,t))return Jn(l,`Computed variable "${n}" branch ${s}`,t)}return Jn(e.default,`Computed variable "${n}" default`,t)}if(r===o)throw new Error(`Computed variable "${n}" must contain exactly one of expr, value, or branches`);return Jn(e,`Computed variable "${n}"`,t)},lc=(e,t,n)=>{switch(t){case"number":if(typeof n!="number"||!Number.isFinite(n))throw new Error(`Computed variable "${e}" expected type number, got ${Array.isArray(n)?"array":typeof n}`);return;case"boolean":if(typeof n!="boolean")throw new Error(`Computed variable "${e}" expected type boolean, got ${Array.isArray(n)?"array":typeof n}`);return;case"string":if(typeof n!="string")throw new Error(`Computed variable "${e}" expected type string, got ${Array.isArray(n)?"array":typeof n}`);return;case"object":if(n===null||typeof n!="object")throw new Error(`Computed variable "${e}" expected type object, got ${typeof n}`);return;default:throw new Error(`Invalid variable type: ${t} for computed variable ${e}`)}},Ct=({variables:e={},runtime:t={},variableConfigs:n={},eager:r=!0}={})=>{let o=st(e,n),i=Object.entries(n).filter(([,d])=>Ne(d)).map(([d])=>d),s={},l=[],a=d=>{if(be(s,d))return s[d];let f=n[d];if(!Ne(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=cc(f.computed,u,d);return lc(d,f.type,h),s[d]=h,h}finally{l.pop()}},c=new Proxy({},{get:(d,f)=>{if(typeof f=="string")return a(f)},has:(d,f)=>typeof f=="string"&&(be(o,f)||i.includes(f)),ownKeys:()=>[...new Set([...Object.keys(o),...i])],getOwnPropertyDescriptor:(d,f)=>{if(!(typeof f!="string"||!be(o,f)&&!i.includes(f)))return{enumerable:!0,configurable:!0}}}),u={variables:c,runtime:t,resolveVariable:a};return r?(i.forEach(d=>{a(d)}),{...o,...s}):c},uc=({variables:e={},runtime:t={},variableConfigs:n,projectData:r}={})=>Ct({variables:e,runtime:t,variableConfigs:n??r?.resources?.variables??{},eager:!0}),Zt=e=>{let t={},n={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([r,o])=>{if(Ne(o))return;let i=Za(o,r);o.scope==="context"?t[r]=i:n[r]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}},en=(e,t)=>{let n=["context","device","account"];if(!e)throw new Error(`Variable scope is required for variable: ${t}`);if(!n.includes(e))throw new Error(`Invalid variable scope: ${e} for variable ${t}. Expected one of: ${n.join(", ")}`)},tn=(e,t,n)=>{let r={number:["set","increment","decrement","multiply","divide"],boolean:["set","toggle"],string:["set"],object:["set"]},o=r[e];if(!o)throw new Error(`Unknown variable type: ${e} for variable ${n}`);if(!Object.values(r).flat().includes(t))throw new Error(`Unknown operation: ${t}`);if(!o.includes(t))throw new Error(`Operation "${t}" is not valid for variable "${n}" of type "${e}". Valid operations: ${o.join(", ")}`)},dc=2,ko=12,Po=(e=dc)=>{if(!Number.isInteger(e)||e<0||e>ko)throw new Error(`Operation "divide" requires roundTo to be an integer between 0 and ${ko}.`);return e},fc=(e,t)=>{let n=10**t;return Math.round((e+Number.EPSILON)*n)/n},Kt=e=>typeof e=="number"&&Number.isFinite(e),Zn=(e,t,n,r,o={})=>{if(e==="number"){if(t==="set"&&!Kt(n))throw new Error(`Operation "set" requires value to be a number for variable "${r}".`);if(t==="multiply"&&!Kt(n))throw new Error(`Operation "multiply" requires value to be a number for variable "${r}".`);if(t==="divide"&&!Kt(n))throw new Error(`Operation "divide" requires value to be a number for variable "${r}".`);if(t==="divide"){if(n===0)throw new Error(`Operation "divide" requires value to be a non-zero number for variable "${r}".`);Po(o.roundTo)}}},nn=(e,t,n,r={})=>{let o=(s,l,a)=>{let c=s??l;if(!Kt(c))throw new Error(`Operation "${t}" requires ${a} to be a number.`);return c},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 n;case"multiply":return o(e,1,"current value")*o(n,void 0,"value");case"divide":return fc(o(e,0,"current value")/i(n),Po(r.roundTo));case"increment":return o(e,0,"current value")+o(n,1,"value");case"decrement":return o(e,0,"current value")-o(n,1,"value");case"toggle":return!e;default:throw new Error(`Unknown operation: ${t}`)}};var er=(e,t="DD/MM/YYYY - HH:mm")=>{if(!e)return"";let n=new Date(e),r=s=>String(s).padStart(2,"0"),o=String(n.getFullYear()),i={DD:r(n.getDate()),MM:r(n.getMonth()+1),MMM:Qa[n.getMonth()],YYYY:o,YY:o.slice(-2),HH:r(n.getHours()),mm:r(n.getMinutes()),ss:r(n.getSeconds())};return t.replace(/YYYY|MMM|YY|MM|DD|HH|mm|ss/g,s=>i[s])},pc=(e,t)=>{let n=i=>i?.ui,r=n(e),o=n(t);return JSON.stringify(r)===JSON.stringify(o)?null:r&&!o?{changeType:"delete",data:e}:o&&!r?{changeType:"add",data:t}:o&&r?{changeType:"update",data:t}:null},xt=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,hc=(e,t)=>{let n=e?.character?.sprite,r=t?.character?.sprite,o=xt(n)?n:void 0,i=xt(r)?r:void 0;return JSON.stringify(o)===JSON.stringify(i)?null:o&&!i?{changeType:"delete",data:o}:i&&!o?{changeType:"add",data:i}:i&&o?{changeType:"update",data:i}:null},Lo=e=>{if(e?.resourceId===void 0)return;let t={resourceId:e.resourceId};e.transformId!==void 0&&(t.transformId=e.transformId);for(let n of["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"])e[n]!==void 0&&(t[n]=e[n]);for(let n of["animationName","animationSpeed","loop"])e[n]!==void 0&&(t[n]=e[n]);return t},$o=e=>{if(e?.colorId!==void 0)return{colorId:e.colorId}},To=(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,mc=(e,t)=>{let n={},r=To(Lo(e),Lo(t)),o=To($o(e),$o(t));return r&&(n.resource=r),o&&(n.color=o),Object.keys(n).length>0?n:null},tr=(e={},t={})=>{let n={},r=["sfx","voice"],o=a=>{let c=e[a],u=t[a];u&&!c?n[a]={changeType:"add",data:u}:c&&!u?r.includes(a)||(n[a]={changeType:"delete",data:c}):c&&u&&JSON.stringify(c)!==JSON.stringify(u)&&(n[a]={changeType:"update",data:u})},i=mc(e.background,t.background);i&&(n.background=i),o("screen"),o("bgm"),o("voice");let s=pc(e.dialogue,t.dialogue);s&&(n.dialogue=s);let l=hc(e.dialogue,t.dialogue);return l&&(n.dialogueSprite=l),o("choice"),o("form"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),n},nr=(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 n=o=>{t[o]&&(delete t[o].animations,Object.keys(t[o]).length===0&&delete t[o])};n("layout"),n("choice"),n("form"),n("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 r=(o,i)=>{let s=t[o]?.items;Array.isArray(s)&&(t[o].items=s.map(l=>{let a={...l};return delete a.animations,i(a)?a:null}).filter(Boolean),t[o].items.length===0&&delete t[o])};return r("character",o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId),r("visual",o=>o.resourceId||o.transformId),t},gc=(e,t)=>{if(!e||!t)return;let n=e;for(let r of t.split(".")){if(n==null||!(r in Object(n)))return;n=n[r]}return n},yc=(e,t)=>{if(typeof e!="string")return e;if(e==="_event"){if(t==null)throw new Error('Action template binding "_event" requires event context "_event".');return t}if(!e.startsWith("_event."))return e;if(t==null)throw new Error(`Action template binding "${e}" requires event context "_event".`);let n=e.slice(7),r=gc(t,n);if(r===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return r},bc={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"])},Vo=(e,t)=>{let n=e[e.length-1];return n?bc[n]?.has(t)===!0:!1},Xn=(e,t,n=[])=>Array.isArray(e)?e.map(r=>Xn(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,Vo(n,r)?o:Xn(o,t,[...n,r])])):yc(e,t),Qn=(e,t,n=[])=>Array.isArray(e)?e.map(r=>Qn(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,Vo(n,r)?o:Qn(o,t,[...n,r])])):typeof e=="string"?ce(e,t):e,rr=(e,t)=>{if(!t)return e;if(Object.prototype.hasOwnProperty.call(t,"event"))throw new Error('Action template context key "event" is no longer supported. Use "_event".');let n=Xn(e,t._event);return Qn(n,t)};var W=e=>structuredClone(se(e)?He(e):e),P=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),jo=e=>e?.animations?.playback?.continuity==="persistent",N=(e,t)=>P(e??{},t)&&e[t]!==void 0,St=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:W(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},Ic=e=>N(e,"opacity")||N(e,"blur"),qo=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],Ho=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],or=["animationName","animationSpeed","loop"],Ac=e=>qo.some(t=>N(e,t)),Wo=e=>e?.text&&N(e.text,"content")&&N(e.text,"textStyleId"),Yo=e=>N(e,"text"),wc=(e,t)=>e.resourceId?!0:Wo(e)?!t?.text:!1,Ec=(e,t)=>{let n={...W(e),...t};return t.text&&e.text&&(n.text={...W(e.text),...W(t.text)}),n},xc=(e,t)=>{if(Yo(e)){if(e.resourceId)throw new Error(`Visual item "${e.id}" cannot define both resourceId and text`);if(!Wo(e)&&!t?.text)throw new Error(`Visual item "${e.id}" text requires content and textStyleId`)}},Fo=e=>Ho.some(t=>N(e,t)),Mo=e=>or.some(t=>N(e,t)),vc=(e,t,{hasAuthoredTransformId:n=!1}={})=>{if(!t)return e;for(let r of Ho)!n&&!N(e,r)&&N(t,r)&&(e[r]=t[r]),P(e,r)&&e[r]===void 0&&delete e[r];return e},Go=(e,t,n)=>{let r=e[n];return r?.id===t?.id?r:e.find(o=>o.id===t?.id)},Cc=(e,t)=>{if(!t)return e;for(let n of qo)!N(e,n)&&N(t,n)&&(e[n]=t[n]),P(e,n)&&e[n]===void 0&&delete e[n];return e},Sc=(e,t)=>(t&&(!N(e,"opacity")&&N(t,"opacity")&&(e.opacity=t.opacity),!N(e,"blur")&&N(t,"blur")&&(e.blur=W(t.blur)),P(e,"opacity")&&e.opacity===void 0&&delete e.opacity,P(e,"blur")&&e.blur===void 0&&delete e.blur),e),Ko=(e,t,n=[],{hasPatchFn:r=()=>!1,mergeItemFn:o}={})=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let i=e.map((s,l)=>{let a=Go(n,s,l),c=t(s,a),u=Ic(s),d=Ac(s),f=r(s),p=P(s,"animations"),h=W(s);return!c&&(u||d||f)&&a&&(h=o?o(a,h):{...W(a),...h},p||delete h.animations),Sc(Cc(h,a),a)}).filter(s=>t(s)||s.animations);return{hasValidItems:i.length>0,processedItems:i}},_c=e=>{if(e){if(e.character&&P(e.character,"name"))return e.character.name;if(P(e,"characterName"))return e.characterName}},Jo=e=>!!e?.character&&P(e.character,"sprite"),Rc=e=>{let t={},n=!1,r=_c(e);return r!==void 0&&(t.name=r,n=!0),Jo(e)&&(t.sprite=W(e.character.sprite),n=!0),n?t:void 0},Bo=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},Uo=({dialogueState:e,dialogueAction:t,persistCharacter:n})=>P(t,"persistSprite")?t.persistSprite===!0:P(e,"persistSprite")?e.persistSprite===!0:n&&!P(t,"characterId"),zo=({previousCharacter:e,characterFields:t,hasCharacterId:n,persistCharacter:r,persistSprite:o,hasExplicitPersistSprite:i,isAppendingAdvDialogueContent:s})=>{let l={},a=e??{},c=t??{},u=s&&!n,d=u&&!i;return P(c,"name")?l.name=c.name:(r&&!n||u)&&P(a,"name")&&(l.name=W(a.name)),P(c,"sprite")?l.sprite=W(c.sprite):(o||d)&&P(a,"sprite")&&(l.sprite=W(a.sprite)),Object.keys(l).length>0?l:void 0},Oc=({dialogueState:e,content:t,append:n=!1})=>{if(!n||!Array.isArray(t)){e.content=t,delete e.initialRevealedContent;return}let r=Array.isArray(e.content)?e.content:[];r.length>0?e.initialRevealedContent=r.map(o=>W(o)):delete e.initialRevealedContent,e.content=[...r,...t]},kc=()=>({}),Lc=(e,t)=>{if(!t.screen)return;let n=N(t.screen,"opacity"),r=N(t.screen,"blur"),o=P(t.screen,"animations");if(!n&&!r){o||delete e.screen;return}let i=e.screen,s={};if(n?s.opacity=t.screen.opacity:N(i,"opacity")&&(s.opacity=i.opacity),r?s.blur=W(t.screen.blur):N(i,"blur")&&(s.blur=W(i.blur)),P(s,"opacity")&&s.opacity===void 0&&delete s.opacity,P(s,"blur")&&s.blur===void 0&&delete s.blur,Object.keys(s).length===0){delete e.screen;return}e.screen=s},$c=(e,t)=>{if(t.background){let n=N(t.background,"resourceId"),r=N(t.background,"colorId"),o=N(t.background,"opacity"),i=N(t.background,"blur"),s=N(t.background,"transformId"),l=Fo(t.background),a=Mo(t.background),{animationsOnly:c,state:u}=St(t.background,p=>N(p,"resourceId")||N(p,"colorId")||N(p,"opacity")||N(p,"blur")||N(p,"transformId")||Fo(p)||Mo(p));if(c){e.background=e.background?{...W(e.background),...u}:u;return}if(!n&&!r&&!o&&!i&&!s&&!l&&!a){delete e.background;return}let d=e.background,f=W(t.background);if(!n&&d?.resourceId){f.resourceId=d.resourceId,!P(f,"transformId")&&d.transformId&&(f.transformId=d.transformId);for(let p of or)!N(f,p)&&N(d,p)&&(f[p]=d[p])}vc(f,d,{hasAuthoredTransformId:s}),!r&&d?.colorId&&(f.colorId=d.colorId),!o&&N(d,"opacity")&&(f.opacity=d.opacity),!i&&N(d,"blur")&&(f.blur=W(d.blur)),P(f,"resourceId")&&f.resourceId===void 0&&delete f.resourceId,P(f,"colorId")&&f.colorId===void 0&&delete f.colorId,P(f,"animations")&&f.animations===void 0&&delete f.animations,P(f,"transformId")&&f.transformId===void 0&&delete f.transformId,P(f,"opacity")&&f.opacity===void 0&&delete f.opacity,P(f,"blur")&&f.blur===void 0&&delete f.blur;for(let p of or)P(f,p)&&f[p]===void 0&&delete f[p];if(!f.resourceId&&!f.colorId){delete e.background;return}d?.resourceId===f.resourceId&&d?.transformId===f.transformId&&!P(f,"animations")&&jo(d)&&(f.animations=W(d.animations)),e.background=f}else e.background?.animations&&!jo(e.background)&&(e.background.animations={})},Tc=(e,t)=>{if(!t.dialogue){if(e.dialogue&&(Bo(e.dialogue),e.dialogue.mode==="adv")){e.dialogue.content=void 0,delete e.dialogue.initialRevealedContent,delete e.dialogue.textSpeed;let u=e.dialogue.persistCharacter===!0,d=Uo({dialogueState:e.dialogue,dialogueAction:{},persistCharacter:u});u||delete e.dialogue.characterId,e.dialogue.character=zo({previousCharacter:e.dialogue.character,characterFields:{},hasCharacterId:!1,persistCharacter:u,persistSprite:d,hasExplicitPersistSprite:!1,isAppendingAdvDialogueContent:!1}),e.dialogue.character||delete e.dialogue.character}return}e.dialogue||(e.dialogue={});let n=e.dialogue.mode;if(t.dialogue.ui){let{animationsOnly:u,state:d}=St(t.dialogue.ui,f=>!!f.resourceId);u?e.dialogue.ui={...e.dialogue.ui,...d}:e.dialogue.ui={...t.dialogue.ui}}else e.dialogue?.ui?.animations&&(e.dialogue.ui.animations={});t.dialogue.mode==="adv"&&(e.dialogue.content=e.dialogue.content||void 0,e.dialogue.characterId=e.dialogue.characterId||void 0,e.dialogue.mode="adv"),t.dialogue.mode==="nvl"&&(e.dialogue?.mode!=="nvl"&&(e.dialogue.lines=[]),e.dialogue.mode="nvl");let r=t.dialogue.append===!0&&n!=="nvl"&&e.dialogue?.mode!=="nvl"&&Array.isArray(t.dialogue.content);t.dialogue.content!==void 0&&Oc({dialogueState:e.dialogue,content:t.dialogue.content,append:r}),P(t.dialogue,"textSpeed")?e.dialogue.textSpeed=t.dialogue.textSpeed:delete e.dialogue.textSpeed;let o=P(t.dialogue,"persistCharacter")?t.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;o?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let i=Uo({dialogueState:e.dialogue,dialogueAction:t.dialogue,persistCharacter:o});P(t.dialogue,"persistSprite")&&(e.dialogue.persistSprite=i);let s=P(t.dialogue,"characterId"),l=Rc(t.dialogue),a=Jo(t.dialogue);s?t.dialogue.characterId?e.dialogue.characterId=t.dialogue.characterId:delete e.dialogue.characterId:!o&&!r&&delete e.dialogue.characterId;let c=zo({previousCharacter:e.dialogue.character,characterFields:l,hasCharacterId:s,persistCharacter:o,persistSprite:i,hasExplicitPersistSprite:P(t.dialogue,"persistSprite"),isAppendingAdvDialogueContent:r});if(c?e.dialogue.character=c:delete e.dialogue.character,a||Bo(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 u={content:t.dialogue.content,characterId:e.dialogue.characterId??null};e.dialogue.textSpeed!==void 0&&(u.textSpeed=e.dialogue.textSpeed),e.dialogue.character&&(u.character=W(e.dialogue.character)),e.dialogue.lines.push(u)}},Dc=(e,t)=>{if(t.sfx){let n=Array.isArray(t.sfx.items)&&t.sfx.items.length>0,r=Array.isArray(t.sfx.channels)&&t.sfx.channels.length>0;if(!n&&!r){delete e.sfx;return}e.sfx=W(t.sfx)}else e.sfx&&delete e.sfx},Nc=(e,t)=>{if(t.bgm){let n=Array.isArray(t.bgm.sounds);if(!t.bgm.resourceId&&!n||n&&t.bgm.sounds.length===0){e.bgm=void 0;return}e.bgm=W(t.bgm),t.bgm.resourceId&&(e.bgm.loop=t.bgm.loop??!0)}},Pc=(e,t)=>{if(t.visual){let n=e.visual?.items||[];t.visual.items?.forEach((i,s)=>{xc(i,Go(n,i,s))});let{hasValidItems:r,processedItems:o}=Ko(t.visual.items,wc,n,{hasPatchFn:Yo,mergeItemFn:Ec});r?e.visual={items:o}:delete e.visual}else e.visual?.items&&(e.visual.items=e.visual.items.map(n=>n.animations?{...n,animations:{}}:n))},Vc=(e,t)=>{if(!t.character){e.character?.items&&(e.character.items=e.character.items.map(o=>o.animations?{...o,animations:{}}:o));return}let{hasValidItems:n,processedItems:r}=Ko(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId,e.character?.items||[]);n?e.character={items:r}:delete e.character},jc=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},Fc=(e,t)=>{if(t.layout){let{animationsOnly:n,state:r}=St(t.layout,o=>!!o.resourceId);if(n){e.layout=r;return}if(!t.layout.resourceId){delete e.layout;return}e.layout=t.layout}else e.layout&&delete e.layout},Mc=(e,t)=>{if(t.choice){let{animationsOnly:n,state:r}=St(t.choice,o=>!!o.resourceId);if(n){e.choice={...e.choice,...r};return}if(!t.choice.resourceId){delete e.choice;return}e.choice=t.choice}else e.choice&&delete e.choice},Bc=(e,t)=>{if(t.form){let{animationsOnly:n,state:r}=St(t.form,o=>!!o.resourceId);if(n){e.form={...e.form,...r};return}if(!t.form.resourceId){delete e.form;return}e.form=W(t.form)}else e.form&&delete e.form},Uc=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},zc=(e,t)=>{if(t.voice){let n=Array.isArray(t.voice.sounds);if(!t.voice.resourceId&&!n||n&&t.voice.sounds.length===0){delete e.voice;return}e.voice=W(t.voice)}else e.voice&&delete e.voice},qc=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(n=>{delete e[n]})},Ye=e=>Xt(kc,[qc,Lc,$c,Dc,Nc,Pc,Tc,Vc,jc,Fc,Mc,Bc,Uc,zc])(e);var at=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let n=ce(e,t);return n&&typeof n=="object"?e:n};var Hc=Object.freeze({dialogueTextSpeed:{source:"global.dialogueTextSpeed"},autoForwardDelay:{source:"global.autoForwardDelay"},autoForwardSpeed:{source:"global.autoForwardSpeed"},skipUnseenText:{source:"global.skipUnseenText"},skipTransitionsAndAnimations:{source:"global.skipTransitionsAndAnimations"},soundVolume:{source:"global.soundVolume"},musicVolume:{source:"global.musicVolume"},muteAll:{source:"global.muteAll"},saveLoadPagination:{source:"context.runtime.saveLoadPagination"},menuPage:{source:"context.runtime.menuPage"},menuEntryPoint:{source:"context.runtime.menuEntryPoint"},autoMode:{source:"global.autoMode"},skipMode:{source:"global.skipMode"},dialogueUIHidden:{source:"global.dialogueUIHidden"},isLineCompleted:{source:"global.isLineCompleted"}}),Ge=Object.freeze({dialogueTextSpeed:50,autoForwardDelay:1e3,autoForwardSpeed:1,skipUnseenText:!1,skipTransitionsAndAnimations:!1,soundVolume:50,musicVolume:50,muteAll:!1,autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isLineCompleted:!1}),_t=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),Xo=Object.freeze({dialogueTextSpeed:"number",autoForwardDelay:"number",autoForwardSpeed:"number",skipUnseenText:"boolean",skipTransitionsAndAnimations:"boolean",soundVolume:"number",musicVolume:"number",muteAll:"boolean",saveLoadPagination:"number",menuPage:"string",menuEntryPoint:"string",autoMode:"boolean",skipMode:"boolean",dialogueUIHidden:"boolean",isLineCompleted:"boolean"}),ir=Object.freeze(["dialogueTextSpeed","autoForwardDelay","autoForwardSpeed","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),sr=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),Wc=(e,t)=>{if(t.startsWith("global.")){let n=t.slice(7);return e?.global?.[n]}if(t.startsWith("context.runtime.")){let n=t.slice(16),r=Array.isArray(e?.contexts)?e.contexts:[];return r[r.length-1]?.runtime?.[n]}},Ke=e=>Object.fromEntries(Object.entries(Hc).map(([t,n])=>{let r=Wc(e,n.source),o=r!==void 0?r:Ge[t]??_t[t];return[t,o]})),Pe=(e,t)=>Ke(e)[t],Qo=(e={})=>Object.fromEntries(ir.map(t=>[t,e[t]??Ge[t]]));var ct=Object.freeze({VISUAL_BEHIND_BACKGROUND:10,BACKGROUND:20,VISUAL_BEHIND_CHARACTER:30,CHARACTER:40,VISUAL_BEHIND_DIALOGUE:50,DIALOGUE:60,VISUAL_BEHIND_CHOICE:70,CHOICE:80,VISUAL_FOREGROUND:90}),_e=Object.freeze({BEHIND_BACKGROUND:ct.VISUAL_BEHIND_BACKGROUND,BEHIND_CHARACTER:ct.VISUAL_BEHIND_CHARACTER,BEHIND_DIALOGUE:ct.VISUAL_BEHIND_DIALOGUE,BEHIND_CHOICE:ct.VISUAL_BEHIND_CHOICE,FOREGROUND:ct.VISUAL_FOREGROUND}),ar=_e.BEHIND_DIALOGUE,cr=Object.freeze(Object.values(_e).sort((e,t)=>e-t));var Re={objectValues:e=>Object.entries(e).map(([t,n])=>({id:t,...n})),formatDate:er},Yc=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,Gc=(e,t)=>{let n=String(t||"").trim();if(!n)return;let r=n.match(/[A-Za-z_][A-Za-z0-9_]*|\[\d+\]/g)||[],o=e;for(let i of r){if(i.startsWith("[")){let s=Number(i.slice(1,-1));o=Array.isArray(o)?o[s]:void 0;continue}o=o?.[i]}return o},an=(e,t,n)=>{if(Array.isArray(e)){let o=[];for(let i of e){if(i&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===1){let[s]=Object.keys(i),l=Yc.exec(s);if(l){let[,a,c,u]=l,d=Gc(t,u);if(!Array.isArray(d))continue;let f=Array.isArray(i[s])?i[s]:[];d.forEach((p,h)=>{let g={...t,[a]:p};c&&(g[c]=h),f.forEach(b=>{let A=an(b,g,n),w=ce(A,g,n);Array.isArray(w)?o.push(...w):o.push(w)})});continue}}o.push(an(i,t,n))}return o}if(!e||typeof e!="object")return e;let r={};return Object.entries(e).forEach(([o,i])=>{r[o]=an(i,t,n)}),r},Cr=({animationType:e,animationId:t,animationPath:n})=>{if(e!==void 0&&!(e==="update"||e==="transition"))throw new Error(`[${n}] Animation "${t}" has unsupported type "${e}". Use "update" or "transition".`)},Kc=({id:e,targetId:t,animation:n,playback:r,animationPath:o="animation"})=>{let i=structuredClone(n);if(Cr({animationType:i.type,animationId:e,animationPath:o}),delete i.name,delete i.playback,i.id=e,i.targetId=t,r!==void 0){let s=Zc(r,`${o}.playback`);s!==void 0&&(i.playback=s)}return i},Jc=(e,{animationId:t="animation",animationPath:n="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return Cr({animationType:e.type,animationId:t,animationPath:n}),e.type},Xc=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},Qc=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},Zc=(e,t="animation.playback")=>{if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`[${t}] playback must be an object.`);if(e.continuity!==void 0&&e.continuity!=="render"&&e.continuity!=="persistent")throw new Error(`[${t}] playback.continuity must be "render" or "persistent".`);if(e.speed!==void 0&&(typeof e.speed!="number"||!Number.isFinite(e.speed)||e.speed<=0))throw new Error(`[${t}] playback.speed must be a finite number greater than 0.`);let n={};return e.continuity!==void 0&&(n.continuity=e.continuity),e.speed!==void 0&&e.speed!==1&&(n.speed=e.speed),Object.keys(n).length>0?n:void 0},el=e=>{let t=e?.playback?.speed;return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1},Je=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),ui=e=>e?.playback?.continuity==="persistent",gr=e=>Array.isArray(e)?e.map(gr):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((t,n)=>(t[n]=gr(e[n]),t),{}),ln=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let t=structuredClone(e);return t.playback&&(delete t.playback.continuity,t.playback.speed===1&&delete t.playback.speed,Object.keys(t.playback).length===0&&delete t.playback),JSON.stringify(gr(t))},di=(e=[])=>e.filter(t=>ui(t)).map(t=>structuredClone(t)),fi=e=>Array.isArray(e?.keyframes)?e.keyframes.reduce((t,n)=>{let r=typeof n?.duration=="number"&&Number.isFinite(n.duration)?n.duration:0;return t+r},0):0,lr=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((t,n)=>Math.max(t,fi(n)),0),pi=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max(lr(e.tween),lr(e.prev?.tween),lr(e.next?.tween),fi(e.mask?.progress))/el(e),Zo=({animationInstances:e,activePersistentAnimations:t})=>{if(!Array.isArray(e)||e.length===0||!Array.isArray(t)||t.length===0)return!1;let n=new Set(t.map(ln).filter(Boolean));return e.some(r=>{if(!ui(r))return!1;let o=ln(r);return o?n.has(o):!1})},Ee=({animationInstances:e,isLineCompleted:t,skipTransitionsAndAnimations:n,activePersistentAnimations:r,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||n?!1:i&&!t||Zo({animationInstances:e,activePersistentAnimations:r})?!0:i?!1:Zo({animationInstances:e,activePersistentAnimations:o}),tl=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),nl=(e,t)=>{if(tl(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},rl=({resources:e,animationId:t,playback:n,instanceId:r,targetId:o,animationPath:i="animation"})=>{if(!t||!o)return!1;let s=e?.animations?.[t];return s?Kc({id:r,targetId:o,animation:s,playback:n,animationPath:i}):null},ol=(e,{defaultTargetId:t,defaultId:n,animationPath:r="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return Cr({animationType:o.type,animationId:o.id??n,animationPath:r}),o.id??=n,o.targetId??=t,o},Sr=({animations:e,transitions:t,defaultTargetId:n,idPrefix:r,animationPathPrefix:o=r})=>{t.forEach((i,s)=>{e.push(ol(i,{defaultTargetId:n,defaultId:`${r}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},yr=(e,t)=>{if(e===void 0)return[];if(!Array.isArray(e)||e.some(n=>n===null||typeof n!="object"||Array.isArray(n)))throw new Error(`${t} must be an array of objects`);return e},il=({content:e,path:t,variables:n})=>yr(e,t).reduce((r,o)=>{let i=at(o.text,{variables:n});return r+`${i??""}`.length},0),ei=(e=[])=>{let t=new Map;for(let n of e)n?.id&&t.set(n.id,(t.get(n.id)??0)+1);return new Set(Array.from(t.entries()).filter(([,n])=>n>1).map(([n])=>n))},rn=(e,t=0,n=new Set)=>{if(!n.has(e?.id))return`character-container-${e.id}`;let r=e?.sprites?.map(({resourceId:o})=>o)||[];return r.length===0?`character-container-${e.id}`:`character-container-${e.id}-${t}-${r.join("-")}`},on=(e,t)=>{if(!t.transformId)throw new Error(`Visual item "${t.id}" requires transformId`);let n=e.transforms?.[t.transformId];if(!n)throw new Error(`Transform "${t.transformId}" not found for visual item "${t.id}"`);return n},sl=(e,t={})=>{if(!t?.transformId)return;let n=e.transforms?.[t.transformId];if(!n)throw new Error(`Transform "${t.transformId}" not found for background`);return n},al=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],cl=(e={})=>al.some(t=>Je(e,t)),hi=(e={},t)=>{if(t){if(e.images?.[t])return"sprite";if(e.videos?.[t])return"video";if(e.spritesheets?.[t])return"spritesheet-animation";if(e.layouts?.[t])return"container"}},cn=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},ll=(e={})=>e.textStyles||{},ul=(e={})=>e.images||{},dl=.5,fl=(e={},t,n)=>{if(t){if(!e.animations?.[t])throw new Error(`Animation '${t}' not found in spritesheet resource '${n}'`);return t}return Object.keys(e.animations??{})[0]},mi=({id:e,resourceId:t,spritesheet:n,animationName:r,animationSpeed:o,loop:i,transform:s={}}={})=>{let l=fl(n,r,t),a=l?n.animations?.[l]:void 0;if(!a){console.warn(`Spritesheet animation not found: ${t}`);return}return{id:e,type:"spritesheet-animation",...s,width:n.width,height:n.height,src:n.fileId,atlas:n.jsonData,playback:{frames:a.frames,animationSpeed:o??a.animationSpeed??dl,loop:i??a.loop??!0}}},gi=({id:e,item:t,resources:n={}}={})=>{let r=n.images?.[t.resourceId];if(r)return{type:"sprite",id:e,src:r.fileId,width:r.width,height:r.height,x:0,y:0};let o=n.spritesheets?.[t.resourceId];if(o)return mi({id:e,resourceId:t.resourceId,spritesheet:o,animationName:t.animationName,animationSpeed:t.animationSpeed,loop:t.loop,transform:{x:0,y:0}});console.warn(`Character sprite resource not found: ${t.resourceId}`)},pl=(e={})=>e.colors||{},hl=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,kt=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,ut=(e,t,n)=>{if(typeof e!="string"||e.length===0)throw new Error(`${n} at "${t}" must resolve to a non-empty string`)},ur=(e,t,n)=>{if(e===void 0)return 1;if(typeof e!="number"||!Number.isFinite(e))throw new Error(`${t} for text style "${n}" must be a number between 0 and 1`);if(e<0||e>1)throw new Error(`${t} for text style "${n}" must be a number between 0 and 1`);return e},dr=(e,t,n,r,{minimum:o}={})=>{if(e===void 0)return r;if(typeof e!="number"||!Number.isFinite(e)||o!==void 0&&e<o){let i=o===void 0?"a finite number":`a finite number >= ${o}`;throw new Error(`shadow.${t} for text style "${n}" must be ${i}`)}return e},fn=(e,t)=>{if(typeof e!="string"||!hl.test(e))throw new Error(`${t} must resolve to a hex color`);return e.length===4?`#${e.slice(1).split("").map(n=>n.repeat(2)).join("")}`:e},ti=(e,t,n)=>{let r=fn(e,n);if(t===1)return r;let o=Number.parseInt(r.slice(1,3),16),i=Number.parseInt(r.slice(3,5),16),s=Number.parseInt(r.slice(5,7),16);return`rgba(${o}, ${i}, ${s}, ${t})`},ml=(e={},t)=>{let n=ll(e)?.[t];if(!n)throw new Error(`Text style "${t}" not found`);let o=(Array.isArray(n.fontId)?n.fontId:[n.fontId]).map(a=>{let c=e.fonts?.[a];if(!c)throw new Error(`Font "${a}" not found for text style "${t}"`);return c.fileId}),i=e.colors?.[n.colorId];if(!i)throw new Error(`Color "${n.colorId}" not found for text style "${t}"`);let s=ur(n.colorAlpha,"colorAlpha",t),l={fontFamily:Array.isArray(n.fontId)?o.join(", "):o[0],fontSize:n.fontSize??16,fontWeight:n.fontWeight??"400",fontStyle:n.fontStyle??"normal",lineHeight:n.lineHeight??1.2,fill:ti(i.hex,s,`Color "${n.colorId}" for text style "${t}"`)};if(n.align!==void 0&&(l.align=n.align),n.wordWrap!==void 0&&(l.wordWrap=n.wordWrap),n.breakWords!==void 0&&(l.breakWords=n.breakWords),n.wordWrapWidth!==void 0&&(l.wordWrapWidth=n.wordWrapWidth),n.strokeColorId){let a=e.colors?.[n.strokeColorId];if(!a)throw new Error(`Stroke color "${n.strokeColorId}" not found for text style "${t}"`);let c=ur(n.strokeAlpha,"strokeAlpha",t);l.strokeColor=ti(a.hex,c,`Stroke color "${n.strokeColorId}" for text style "${t}"`)}else if(n.strokeAlpha!==void 0)throw new Error(`strokeAlpha for text style "${t}" requires strokeColorId`);if(n.strokeWidth!==void 0&&(l.strokeWidth=n.strokeWidth),n.shadow!==void 0){let a=e.colors?.[n.shadow.colorId];if(!a)throw new Error(`Shadow color "${n.shadow.colorId}" not found for text style "${t}"`);l.shadow={color:fn(a.hex,`Shadow color "${n.shadow.colorId}" for text style "${t}"`),alpha:ur(n.shadow.alpha,"shadow.alpha",t),blur:dr(n.shadow.blur,"blur",t,0,{minimum:0}),offsetX:dr(n.shadow.offsetX,"offsetX",t,2),offsetY:dr(n.shadow.offsetY,"offsetY",t,2)}}return l},br=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>br(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(Object.prototype.hasOwnProperty.call(e,"textStyle"))throw new Error(`Inline textStyle is not allowed in layout elements at "${n}". Use textStyleId instead`);let r={};for(let[o,i]of Object.entries(e))o!=="textStyleId"&&(r[o]=br(i,t,kt(n,o)));return e.textStyleId!==void 0&&(ut(e.textStyleId,n,"textStyleId"),r.textStyle=ml(t,e.textStyleId)),r},_r=(e={},t)=>{let n=pl(e)?.[t];if(!n)throw new Error(`Color "${t}" not found`);return fn(n.hex,`Color "${t}"`)},yi=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",fr=(e,t,n)=>{let r=e?.[t];if(!(!r||typeof r!="object"||Array.isArray(r))&&Object.prototype.hasOwnProperty.call(r,"fill"))throw new Error(`Inline ${t}.fill is not allowed in rect layout elements at "${n}". Use ${yi(`${t}.fill`)} instead`)},gl=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>Lt(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;let r={};for(let[o,i]of Object.entries(e))o!=="colorId"&&(r[o]=Lt(i,t,kt(n,o)));return e.colorId!==void 0&&(ut(e.colorId,n,"colorId"),r.fill=_r(t,e.colorId)),r},Lt=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>Lt(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="rect"){if(Object.prototype.hasOwnProperty.call(e,"fill"))throw new Error(`Inline fill is not allowed in rect layout elements at "${n}". Use ${yi("fill")} instead`);fr(e,"hover",n),fr(e,"click",n),fr(e,"rightClick",n)}let r={};for(let[o,i]of Object.entries(e))if(!(e.type==="rect"&&o==="colorId")){if(e.type==="rect"&&(o==="hover"||o==="click"||o==="rightClick")){r[o]=gl(i,t,kt(n,o));continue}r[o]=Lt(i,t,kt(n,o))}return e.type==="rect"&&e.colorId!==void 0&&(ut(e.colorId,n,"colorId"),r.fill=_r(t,e.colorId)),r},pr=(e={},t)=>{let n=ul(e)?.[t];return n||null},bi=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",ni=(e,t,n,r)=>{let o=e?.[t];if(!(!o||typeof o!="object"||Array.isArray(o))&&Object.prototype.hasOwnProperty.call(o,r))throw new Error(`Inline ${t}.${r} is not allowed in sprite layout elements at "${n}". Use ${bi(`${t}.${r}`)} instead`)},ri=(e,t,n)=>{let r=e[t];e[t]={...r&&typeof r=="object"&&!Array.isArray(r)?r:{},src:n}},Ir=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>Ir(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="sprite"){for(let o of["url","src","hoverUrl","hoverSrc","clickUrl","clickSrc"])if(Object.prototype.hasOwnProperty.call(e,o))throw new Error(`Inline ${o} is not allowed in sprite layout elements at "${n}". Use ${bi(o)} instead`);ni(e,"hover",n,"src"),ni(e,"click",n,"src")}let r={};for(let[o,i]of Object.entries(e))e.type==="sprite"&&(o==="imageId"||o==="hoverImageId"||o==="clickImageId")||(r[o]=Ir(i,t,kt(n,o)));if(e.type==="sprite"&&e.imageId!==void 0){ut(e.imageId,n,"imageId");let o=pr(t,e.imageId),i=o?.fileId??e.imageId;r.src=i,r.width===void 0&&o?.width!==void 0&&(r.width=o.width),r.height===void 0&&o?.height!==void 0&&(r.height=o.height)}return e.type==="sprite"&&e.hoverImageId!==void 0&&(ut(e.hoverImageId,n,"hoverImageId"),ri(r,"hover",pr(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(ut(e.clickImageId,n,"clickImageId"),ri(r,"click",pr(t,e.clickImageId)?.fileId??e.clickImageId)),r},Rr=(e,t={},n="root")=>Ir(Lt(br(e,t,n),t,n),t,n),Oe=Rr,Qe=(e=[])=>e.find(t=>t.id==="story"),yl="#000000",Ar="bg-cg-background-color",bl=({resources:e={},background:t={},screen:n})=>t?.colorId===void 0?fn(n?.backgroundColor??yl,"screen.backgroundColor"):_r(e,t.colorId),Ii=(e={})=>{if(Je(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},Il=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},oi=(e={},{includeDefaultAlpha:t=!1}={})=>{let n=Ii(e),r=Il(e),o={};return(t||n!==void 0)&&(o.alpha=n??1),r&&(o.blur=r),o},Al=(e={})=>{if(Je(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},wl=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},Ai=(e={})=>{let t=Al(e),n=wl(e),r={};return t!==void 0&&(r.alpha=t),n&&(r.blur=n),r},Rt=(e={})=>Ai(e),Ve=(e={},t={})=>{let n={x:t.x??e.x,y:t.y??e.y,anchorX:t.anchorX??e.anchorX,anchorY:t.anchorY??e.anchorY,rotation:t.rotation??e.rotation,scaleX:t.scaleX??e.scaleX,scaleY:t.scaleY??e.scaleY},r=t.originX??e.originX,o=t.originY??e.originY;return r!==void 0&&(n.originX=r),o!==void 0&&(n.originY=o),n},El=["id","type","resourceId","transformId","x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY","layer","opacity","blur","animations"],Or=(e={})=>e.text&&Je(e.text,"content")&&Je(e.text,"textStyleId"),ii=(e={})=>{if(e.resourceId)return e.resourceId;if(Or(e))return"text"},xl=e=>{if(e.text){if(e.resourceId)throw new Error(`Visual item "${e.id}" cannot define both resourceId and text`);if(!Or(e))throw new Error(`Visual item "${e.id}" text requires content and textStyleId`);for(let t of El)if(Je(e.text,t))throw new Error(`Visual item "${e.id}" text.${t} is reserved for the visual item`)}},vl=({resources:e,background:t,screen:n={width:1920,height:1080},includeOpacity:r=!1})=>{let o={id:Ar,type:"rect",x:0,y:0,width:n?.width??1920,height:n?.height??1080,fill:bl({resources:e,background:t,screen:n})};if(r){let i=Ii(t);i!==void 0&&(o.alpha=i)}return o},Cl=(e={},t)=>t?!!(e.images?.[t]||e.videos?.[t]||e.spritesheets?.[t]||e.layouts?.[t]):!1,si=({resources:e={},resourceId:t,colorId:n})=>{let r=hi(e,t);return t&&(r||n===void 0)?{resourceId:t,targetId:cn({resourceId:t,kind:r})}:n!==void 0?{resourceId:Ar,targetId:Ar}:{resourceId:void 0,targetId:void 0}},wi=100,Xe=wi,Sl="channel:bgm",_l="channel:voice",Rl="default",Ol=e=>String(e).replaceAll("%","%25").replaceAll(":","%3A"),Ot=(...e)=>e.map(Ol).join(":"),un=(e,t,n)=>{let r=new Set;e.forEach(({id:o})=>{if(r.has(o)){let i=n?` in ${n}`:"";throw new Error(`Duplicate ${t} id "${o}"${i}.`)}r.add(o)})},kl=(e,t)=>e*t/wi,Ei=(e={},t)=>e?.[t]??Ge[t],kr=(e={},t,n=Xe)=>kl(n,Ei(e,t)),Lr=({id:e,volume:t,muted:n,pan:r,children:o,runtime:i})=>({id:e,type:"audio-channel",volume:t,muted:!!i?.muteAll||(n??!1),pan:r??0,children:o}),sn=(e,t,n,r)=>e[n]!==void 0?e[n]:t[n]!==void 0?t[n]:r,Ll=["muted","pan","playbackRate","startAt","endAt"],$r=({id:e,sound:t,resource:n,defaultLoop:r=!1})=>{let o={id:e,type:"sound",src:n.fileId,loop:sn(t,n,"loop",r),volume:sn(t,n,"volume",Xe),startDelayMs:sn(t,n,"startDelayMs",0)};Ll.forEach(s=>{let l=sn(t,n,s,void 0);l!==void 0&&(o[s]=l)});let i=o.startAt??0;if(o.endAt!==void 0&&o.endAt!==null&&o.endAt<i)throw new Error(`Sound "${e}" endAt (${o.endAt}) must be greater than or equal to startAt (${i}).`);return o},xe=({variables:e,runtime:t,saveSlots:n=[],dialogueState:r,includeInactiveAdvDialogue:o=!1,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,confirmDialog:d,form:f,historyDialogue:p=[],characters:h={},dialogueUIHidden:g,skipOnlyViewedLines:b,skipTransitionsAndAnimations:A}={})=>{let w={dialogueTextSpeed:t?.dialogueTextSpeed??50,autoForwardDelay:t?.autoForwardDelay??1e3,autoForwardSpeed:t?.autoForwardSpeed??1,skipUnseenText:t?.skipUnseenText??!1,skipTransitionsAndAnimations:t?.skipTransitionsAndAnimations??!1,soundVolume:t?.soundVolume??50,musicVolume:t?.musicVolume??50,muteAll:t?.muteAll??!1,saveLoadPagination:t?.saveLoadPagination??1,menuPage:t?.menuPage??"",menuEntryPoint:t?.menuEntryPoint??"",autoMode:t?.autoMode??s??!1,skipMode:t?.skipMode??l??!1,dialogueUIHidden:t?.dialogueUIHidden??g??!1,isLineCompleted:t?.isLineCompleted??i??!1},C=Pl({dialogueState:r,includeInactiveAdvDialogue:o,characters:h,variables:e,runtime:w}),R={variables:e,runtime:w,saveSlots:n,isChoiceVisible:a,isFormVisible:c,canRollback:u,confirmDialog:d,form:f,historyDialogue:p,characters:h};return C&&(R.dialogue=C,R.dialogueLines=C.lines),R},ai=100,dn=(e,t)=>{if(Array.isArray(e))return e.map(r=>dn(r,t));if(!e||typeof e!="object")return e;let n={...e};return Object.keys(n).forEach(r=>{n[r]=dn(n[r],t)}),n.type==="text-revealing"?t(n):n},$l=e=>dn(e,t=>({...t,revealEffect:"none"})),Tl=e=>dn(e,t=>{let n=Number(t.speed??t.displaySpeed),r=Number.isFinite(n)?Math.max(n,ai):ai;return{...t,speed:r,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:r}:{}}}),je=(e,{isLineCompleted:t=!1,skipMode:n=!1,skipTransitionsAndAnimations:r=!1}={})=>t||r?$l(e):n?Tl(e):e,xi=({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:{}}}}),wr=e=>{if(Array.isArray(e))return e.map(wr);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=wr(s);let n=t.click?.payload;if(!n||typeof n!="object"||Array.isArray(n))return t;let r=n.actions,o=r&&typeof r=="object"&&!Array.isArray(r)&&Object.prototype.hasOwnProperty.call(r,"nextLine")?{...r.nextLine,bypassChoice:!0}:void 0;return{...t,click:{...t.click,payload:{...n,bypassChoice:!0,...o?{actions:{...r,nextLine:o}}:{}}}}},Dl=new Set(["click","change","submit","focusEvent","blurEvent","selectionChange","compositionStart","compositionUpdate","compositionEnd"]),ci="submit",hr=(e,t,n={})=>{let r=e?.payload&&typeof e.payload=="object"&&!Array.isArray(e.payload)?e.payload:{},o=r.actions&&typeof r.actions=="object"?r.actions:{},i=n.replaceActions===!0?t:{...o,...t};return{...e||{},payload:{...r,actions:i}}},Er=(e,t,n={})=>{if(Array.isArray(e))return e.map(c=>Er(c,t,n));if(!e||typeof e!="object")return e;let r=typeof e.type=="string",o=r&&e.formRole===ci,i=r&&n.submitRoleAncestor,s=o||i?{submitRoleAncestor:!0}:{},l={};for(let[c,u]of Object.entries(e))l[c]=Er(u,t,c==="children"?s:{});let a=l;if(a.type==="input"&&typeof a.field=="string"){let c=t?.fields?.[a.field];if(c){let u={updateFormField:{formKey:t.key,field:c.id,value:"_event.value"}};a={...a,value:c.value,placeholder:a.placeholder===void 0?c.placeholder:a.placeholder,multiline:a.multiline===void 0?c.multiline:a.multiline,...a.maxLength===void 0&&c.maxLength!==void 0?{maxLength:c.maxLength}:{},change:hr(a.change,u),submit:hr(a.submit,t.submitActions)}}}return a.formRole===ci||i?{...a,click:hr(a.click,t.submitActions,{replaceActions:!0})}:a},xr=(e,t)=>{if(Array.isArray(e))return e.map(r=>xr(r,t));if(!e||typeof e!="object")return e;let n={};for(let[r,o]of Object.entries(e))n[r]=xr(o,t);for(let r of Dl){let o=n[r]?.payload;!o||typeof o!="object"||Array.isArray(o)||(n[r]={...n[r],payload:{...o,_interactionSource:"form"}})}return n},vr=({characterId:e,character:t,characterName:n,characters:r={},variables:o={}}={})=>{let i=e?r?.[e]:void 0,s=Qt({characterId:e,character:t,characterName:n,characters:r,variables:o});return{...i||{},...t||{},name:s}},vi=(e=[],t={},n={})=>e.map(r=>{let o=vr({characterId:r.characterId,character:r.character,characterName:r.characterName,characters:t,variables:n}),i=typeof r.text=="string"?r.text:Array.isArray(r.content)?r.content.map(s=>s?.text??"").join(""):"";return{...r,text:i,character:o,characterName:o.name}}),Nl=e=>!(!e||e.mode==="adv"&&e.content===void 0),Pl=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:n={},variables:r,runtime:o}={})=>{if(!t&&!Nl(e))return;let i=e.content===void 0?[{text:""}]:yr(e.content,"dialogue.content"),s=e.content===void 0?0:il({content:e.initialRevealedContent,path:"dialogue.initialRevealedContent",variables:r}),l=o?.dialogueTextSpeed??Ge.dialogueTextSpeed,a=e.textSpeed??l,c=(e.lines||[]).map((d,f)=>{let p=yr(d.content,`dialogue.lines[${f}].content`),h=vr({characterId:d.characterId,character:d.character,characterName:d.characterName,characters:n,variables:r});return{...d,textSpeed:d.textSpeed??l,content:p.map(g=>({...g,text:at(g.text,{variables:r})})),character:h,characterName:h.name}}),u=vr({characterId:e.characterId,character:e.character,characters:n,variables:r});return{characterId:e.characterId,persistCharacter:e.persistCharacter,persistSprite:e.persistSprite,character:u,textSpeed:a,content:i.map(d=>({...d,text:at(d.text,{variables:r})})),initialRevealedCharacters:s,lines:c}},Ci=({container:e,resources:t,templateData:n,isLineCompleted:r=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=ce(e,n,{functions:Re});return Oe(je(s,{isLineCompleted:r,skipMode:o,skipTransitionsAndAnimations:i}),t)},mr=(e,t={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(t),li=({renderStateKeyboard:e,keyboard:t,phase:n})=>{!t||typeof t!="object"||Array.isArray(t)||Object.entries(t).forEach(([r,o])=>{let i=e[r]??{},s=n==="keydown"?o?.keydown:o?.keyup;if(n==="keydown"&&s&&typeof s=="object"){e[r]={...i,keydown:{payload:mr(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[r].keyup={payload:mr(o.keyup)});return}e[r]={...i,[n]:{payload:mr(o)}}})},Vl=(e={},t={})=>{let n={};return li({renderStateKeyboard:n,keyboard:e,phase:"keydown"}),li({renderStateKeyboard:n,keyboard:t,phase:"keyup"}),Object.keys(n).length>0?n:void 0},ke=({animationsDef:e,resources:t,previousResourceId:n,currentResourceId:r,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:l})=>{if(!e)return[];let a=[],c=({instanceId:A,targetId:w})=>{let C=rl({resources:t,animationId:p,playback:h,instanceId:A,targetId:w,animationPath:s});C&&a.push(C)},u=n!=null&&n!==!1,d=r!=null&&r!==!1,f=o&&i&&o===i;nl(e,s);let p=Xc(e),h=Qc(e),g=t?.animations?.[p],b=Jc(g,{animationId:p,animationPath:s});if(b==="update")return d&&i?c({instanceId:`${l}-animation-update`,targetId:i}):u&&o&&c({instanceId:`${l}-animation-update`,targetId:o}),a;if(b==="transition"){let A=`${l}-animation-transition`,w=h?.continuity==="persistent"?A:`${l}-animation-in`;if(u&&d&&f)return c({instanceId:A,targetId:i}),a;u&&c({instanceId:`${l}-animation-out`,targetId:o}),d&&c({instanceId:w,targetId:i})}return a},jl=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),Fl=(e,{presentationState:t,previousPresentationState:n,currentLineActions:r,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:l,variables:a,runtime:c,activePersistentAnimations:u,restoredPersistentAnimations:d,autoMode:f,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:b,form:A,saveSlots:w=[]})=>{let{elements:C,animations:R}=e;if(t.background){let V=r===void 0?!0:Je(r?.background??{},"animations"),j=C.find(ue=>ue.id==="story");if(!j)return e;let E=sl(o,t.background),B=E||cl(t.background),U=n?.background?.resourceId,J=n?.background?.colorId,M=t.background.resourceId??(t.background.animations?U:void 0),Y=t.background.colorId??(t.background.animations?J:void 0),G=Cl(o,M),X={...t.background,colorId:Y};if((Y!==void 0||G)&&j.children.push(vl({resources:o,background:X,screen:i,includeOpacity:!G})),M){let{images:ue={},videos:de={},spritesheets:Q={}}=o,re=hi(o,M),fe;if(re==="sprite"?fe=ue[M]:re==="video"?fe=de[M]:re==="spritesheet-animation"&&(fe=Q[M]),fe){let S=re==="video",O=re==="spritesheet-animation",F={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...E},oe={...oi(t.background,{includeDefaultAlpha:!0}),...Ve(F,t.background)},ie;O?ie=mi({id:cn({resourceId:M,kind:re}),resourceId:M,spritesheet:fe,animationName:t.background.animationName,animationSpeed:t.background.animationSpeed,loop:t.background.loop,transform:oe}):ie={id:cn({resourceId:M,kind:re}),type:S?"video":"sprite",src:fe.fileId,width:fe.width,height:fe.height,...oe},S&&(ie.loop=t.background.loop??!1,ie.volume=fe.volume??50),ie&&j.children.push(ie)}}if(M){let{layouts:ue={}}=o,de=ue[M];if(de){let Q={id:cn({resourceId:M,kind:"container"}),type:"container",children:de.elements,...oi(t.background)};B&&Object.assign(Q,Ve({x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...E},t.background));let re=ce(Q,xe({variables:a,runtime:c,saveSlots:w,dialogueState:t.dialogue,isLineCompleted:s,autoMode:f,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:b,form:A,characters:o.characters||{},skipTransitionsAndAnimations:l}),{functions:Re});j.children.push(Oe(je(re,{isLineCompleted:s,skipMode:p,skipTransitionsAndAnimations:l}),o))}}let ve=si({resources:o,resourceId:U,colorId:J}),te=si({resources:o,resourceId:M,colorId:Y}),ne=ke({animationsDef:t.background.animations,resources:o,previousResourceId:ve.resourceId,currentResourceId:te.resourceId,previousTargetId:ve.targetId,currentTargetId:te.targetId,animationPath:"background.animations",idPrefix:"bg-cg"});Ee({animationInstances:ne,isLineCompleted:s,skipTransitionsAndAnimations:l,activePersistentAnimations:u,restoredPersistentAnimations:d,isAuthoredOnCurrentLine:V})&&R.push(...ne)}return e},Ml=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:l,animations:a}=e;if(t.character&&r){let c=l.find(h=>h.id==="story");if(!c)return e;let u=t.character.items||[],d=n?.character?.items||[],f=ei(u),p=ei(d);for(let h=0;h<u.length;h++){let g=u[h],{transformId:b,sprites:A}=g,w=d.find(M=>M.id===g.id),C=d.findIndex(M=>M.id===g.id),R=w?.sprites&&w.sprites.length>0,V=A&&A.length>0,j=C>=0?rn(w,C,p):void 0,E=ke({animationsDef:g.animations,resources:r,previousResourceId:j,currentResourceId:V?rn(g,h,f):void 0,previousTargetId:j,currentTargetId:V?rn(g,h,f):void 0,animationPath:`character.items[${h}].animations`,idPrefix:"character"});if(g.animations&&!A&&!b&&R&&Ee({animationInstances:E,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){a.push(...E);continue}if(g.animations&&!A&&!b)continue;if(!A||A.length===0||!b){console.warn("Character item missing sprites or transformId:",g);continue}let B=rn(g,h,f),U=r.transforms[b];if(!U){console.warn("Transform not found:",b);continue}let J={type:"container",id:B,...Ve(U,g),...Rt(g),children:[]};for(let M of A){let Y=gi({id:`${B}-${M.id}`,item:M,resources:r});Y&&J.children.push(Y)}c.children.push(J),Ee({animationInstances:E,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...E)}}return e},Si=(e,t)=>{if(!cr.includes(e))throw new Error(`${t} must be one of: ${cr.join(", ")}.`)},Bl=(e,t)=>{let n=!!e.resourceId||Or(e),r=e.layer??(n?void 0:t?.layer)??ar;return Si(r,`Visual item "${e.id}" layer`),r},Ul=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,runtime:l,activePersistentAnimations:a,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,form:h,saveSlots:g=[],visualLayer:b})=>{let{elements:A,animations:w}=e;if(t.visual&&r){let C=A.find(E=>E.id==="story");if(!C)return e;let R=t.visual.items,V=n?.visual?.items||[],j=xe({variables:s,runtime:l,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:o,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,form:h,characters:r.characters||{},skipTransitionsAndAnimations:i});b!==void 0&&Si(b,"visualLayer");for(let E of R){let B=V.find(G=>G.id===E.id),U=Bl(E,B);if(b!==void 0&&U!==b)continue;if(xl(E),E.text){let G=on(r,E),X={...structuredClone(E.text),id:`visual-${E.id}`,type:"text",...Ve(G,E)};Object.assign(X,Rt(E)),C.children.push(Oe(ce(X,j,{functions:Re}),r))}if(E.resourceId){let{images:G={},videos:X={},spritesheets:ve={}}=r,te=ve[E.resourceId];if(te){let ne=on(r,E),ue=E.animationName;if(ue){let de=te.animations?.[ue];if(!de)throw new Error(`Animation '${ue}' not found in spritesheet resource '${E.resourceId}'`);let Q=Rt(E),re={id:`visual-${E.id}`,type:"spritesheet-animation",...Ve(ne,E),width:E.width??te.width,height:E.height??te.height,alpha:Q.alpha??E.alpha??1,src:te.fileId,atlas:te.jsonData,playback:{frames:de.frames,animationSpeed:E.animationSpeed??de.animationSpeed??.5,loop:E.loop??de.loop??!0}};Q.blur&&(re.blur=Q.blur),C.children.push(structuredClone(re))}}else{let ne=G[E.resourceId]||X[E.resourceId];if(ne){let ue=X[E.resourceId]!==void 0,de=on(r,E),Q={id:`visual-${E.id}`,type:ue?"video":"sprite",src:ne.fileId,width:ne.width,height:ne.height,...Ve(de,E)};Object.assign(Q,Rt(E)),ue&&(Q.loop=ne.loop??!1,Q.volume=ne.volume??50),C.children.push(Q)}}}if(E.resourceId){let{layouts:G={}}=r,X=G[E.resourceId];if(X){let ve=on(r,E),te={id:`visual-${E.id}`,type:"container",children:structuredClone(X.elements),...Ve(ve,E)};Object.assign(te,Rt(E));let ne=ce(te,j,{functions:Re});C.children.push(Oe(je(ne,{isLineCompleted:o,skipMode:u,skipTransitionsAndAnimations:i}),r))}}let J=ii(B),M=ii(E),Y=ke({animationsDef:E.animations,resources:r,previousResourceId:J,currentResourceId:M,previousTargetId:J?`visual-${E.id}`:void 0,currentTargetId:M?`visual-${E.id}`:void 0,animationPath:`visual.items[${E.id}].animations`,idPrefix:E.id});Ee({animationInstances:Y,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:a})&&w.push(...Y)}}return e},lt="dialogue-character-sprite",zl=(e,{presentationState:t,previousPresentationState:n,resources:r={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:l}=e,a=Qe(e.elements);if(!a)return e;let c=t.dialogue?.character?.sprite,u=n?.dialogue?.character?.sprite,d=xt(c),f=xt(u),p=ke({animationsDef:c?.animations,resources:r,previousResourceId:f?lt:void 0,currentResourceId:d?lt:void 0,previousTargetId:f?lt:void 0,currentTargetId:d?lt:void 0,animationPath:"dialogue.character.sprite.animations",idPrefix:"dialogue-character-sprite"});if(!d)return c?.animations&&f&&Ee({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...p),e;let h=r.transforms?.[c.transformId];if(!h)return console.warn("Transform not found:",c.transformId),e;let g={type:"container",id:lt,...Ve(h),children:[]};for(let b of c.items){let A=gi({id:`${lt}-${b.id}`,item:b,resources:r});A&&g.children.push(A)}return a.children.push(g),Ee({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...p),e},ql=(e,{presentationState:t,previousPresentationState:n,resources:r={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:a,canRollback:c,form:u,skipOnlyViewedLines:d,isLineCompleted:f,skipTransitionsAndAnimations:p,variables:h,runtime:g,activePersistentAnimations:b,saveSlots:A=[]})=>{let{elements:w,animations:C}=e;if(!t.dialogue||o)return e;let R=w.find(j=>j.id==="story");if(!R)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:j={}}=r,E=j[t.dialogue.ui.resourceId];if(E){let B={elements:E.elements},U=xe({variables:h,runtime:g,saveSlots:A,dialogueState:t.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:f,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:a,canRollback:c,form:u,characters:r.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:d,skipTransitionsAndAnimations:p}),J={functions:Re},M=an(B,U,J),Y=ce(M,U,J),G=Oe(je(Y?.elements,{isLineCompleted:f,skipMode:s,skipTransitionsAndAnimations:p}),r);if(Array.isArray(G))for(let X of G)R.children.push(X);else G&&R.children.push(G)}}zl(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:f,skipTransitionsAndAnimations:p,activePersistentAnimations:b});let V=ke({animationsDef:t.dialogue.ui?.animations,resources:r,previousResourceId:n?.dialogue?.ui?.resourceId,currentResourceId:t.dialogue.ui?.resourceId,previousTargetId:n?.dialogue?.ui?.resourceId?"dialogue-container":void 0,currentTargetId:t.dialogue.ui?.resourceId?"dialogue-container":void 0,animationPath:"dialogue.ui.animations",idPrefix:"dialogue-ui"});return Ee({animationInstances:V,isLineCompleted:f,skipTransitionsAndAnimations:p,activePersistentAnimations:b})&&C.push(...V),e},Hl=(e,{presentationState:t,previousPresentationState:n,resources:r,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,runtime:a,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,form:h,activePersistentAnimations:g,saveSlots:b=[]})=>{let{elements:A,animations:w}=e;if(t.choice&&r){let C=Qe(A);if(!C)return e;let R=r?.layouts[t.choice.resourceId];if(R&&R.elements){let j={elements:R.elements},E=ce(j,{...xe({variables:l,runtime:a,saveSlots:b,dialogueState:t.dialogue,isLineCompleted:i,autoMode:c,skipMode:u,isChoiceVisible:d??!!t.choice,isFormVisible:f,canRollback:p,form:h,characters:r.characters||{},skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}},{functions:Re}),B=wr(Oe(je(E?.elements,{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),r));if(Array.isArray(B))for(let U of B)C.children.push(U);else B&&C.children.push(B)}let V=ke({animationsDef:t.choice.animations,resources:r,previousResourceId:n?.choice?.resourceId,currentResourceId:t.choice.resourceId,previousTargetId:n?.choice?.resourceId?"choice-container":void 0,currentTargetId:t.choice.resourceId?"choice-container":void 0,animationPath:"choice.animations",idPrefix:"choice"});Ee({animationInstances:V,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:g})&&w.push(...V)}return e},Wl=(e,{presentationState:t,previousPresentationState:n,resources:r,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,runtime:a,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,activePersistentAnimations:h,saveSlots:g=[],form:b})=>{let{elements:A,animations:w}=e;if(!b?.resourceId||!r)return e;let C=Qe(A);if(!C)return e;let R=r?.layouts?.[b.resourceId];if(!R)return console.warn(`Form layout not found: ${b.resourceId}`),e;let V={id:"form-container",type:"container",x:0,y:0,children:R.elements||[]},j={...xe({variables:l,runtime:a,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:i,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,characters:r.characters||{},skipTransitionsAndAnimations:s,form:b}),form:b},E=ce(V,j,{functions:Re}),B=xr(Oe(je(Er(E,b),{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),r),b);B&&C.children.push(B);let U=ke({animationsDef:b.animations,resources:r,previousResourceId:n?.form?.resourceId,currentResourceId:b.resourceId,previousTargetId:n?.form?.resourceId?"form-container":void 0,currentTargetId:b.resourceId?"form-container":void 0,animationPath:"form.animations",idPrefix:"form"});return Ee({animationInstances:U,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:h})&&w.push(...U),e},Yl=(e,{presentationState:t,resources:n={},variables:r,runtime:o,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,saveSlots:f=[],skipTransitionsAndAnimations:p})=>{if(!t.control?.resourceId)return e;let h=n.controls?.[t.control.resourceId];if(!h)return e;let g=Vl(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 b=Qe(e.elements);if(!b)return e;let A={id:`control-${t.control.resourceId}`,type:"container",x:0,y:0,children:h.elements};return b.children.push(Ci({container:A,resources:n,templateData:xe({variables:r,runtime:o,saveSlots:f,dialogueState:t.dialogue,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,characters:n.characters||{},skipTransitionsAndAnimations:p}),isLineCompleted:i,skipMode:l,skipTransitionsAndAnimations:p})),e},Gl=(e,{presentationState:t,resources:n,runtime:r,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&n){if(!Qe(i))return e;let a=t.bgm,c=!Array.isArray(a.sounds),u=c?a.resourceId?[{id:"default",resourceId:a.resourceId,loop:a.loop??!0,volume:a.volume,startDelayMs:a.startDelayMs??0}]:[]:a.sounds,d=[];if(c||un(u,"BGM sound"),u.forEach(p=>{let h=n.sounds?.[p.resourceId];h&&d.push($r({id:Ot("bgm",c?"default":p.id),sound:p,resource:h,defaultLoop:!0}))}),d.length===0)return e;let f=xe({variables:o,runtime:r}).runtime;s.push(Lr({id:Sl,volume:kr(f,"musicVolume",c?Xe:a.volume??Xe),muted:a.muted,pan:a.pan,children:d,runtime:f}))}return e},Kl=(e,{presentationState:t,resources:n,runtime:r})=>{let{audio:o}=e;if(t.sfx&&n){let i=t.sfx,s=!Array.isArray(i.channels),l=s?[{id:Rl,sounds:i.items??[]}]:i.channels;s||un(l,"SFX channel"),l.forEach(a=>{let c=[];s||un(a.sounds,"SFX sound",`SFX channel "${a.id}"`),a.sounds.forEach((u,d)=>{let f=n.sounds?.[u.resourceId];f&&c.push($r({id:s?Ot("sfx","default",d,u.id):Ot("sfx",a.id,u.id),sound:u,resource:f}))}),c.length!==0&&o.push(Lr({id:Ot("channel","sfx",a.id),volume:kr(r,"soundVolume",a.volume??Xe),muted:a.muted,pan:a.pan,children:c,runtime:r}))})}return e},Jl=(e,t,n)=>{if(!(!t||!n))return e?.voices?.[t]?.[n]},Xl=(e,{presentationState:t,resources:n,currentSceneId:r,runtime:o,variables:i})=>{let{audio:s}=e;if(!t?.voice)return e;let l=t.voice,a=!Array.isArray(l.sounds),c=a?l.resourceId?[{id:"default",resourceId:l.resourceId,loop:l.loop??!1,volume:Xe,startDelayMs:l.startDelayMs??0}]:[]:l.sounds,u=[];if(a||un(c,"Voice sound"),c.forEach(f=>{let p=Jl(n,r,f.resourceId);p&&u.push($r({id:Ot("voice",r,a?"default":f.id),sound:f,resource:p}))}),u.length===0)return e;let d=xe({variables:i,runtime:o}).runtime;return s.push(Lr({id:_l,volume:a?l.volume??Ei(d,"soundVolume"):kr(d,"soundVolume",l.volume??Xe),muted:l.muted,pan:l.pan,children:u,runtime:d})),e},Ql=(e,{presentationState:t,previousPresentationState:n,resources:r={},variables:o,runtime:i,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,saveSlots:f=[],isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})=>{let{elements:b,animations:A}=e;if(t.layout){let V=Qe(b);if(!V)return e;let j=r.layouts[t.layout.resourceId];if(!j)return e;Array.isArray(j.transitions)&&!p&&!h&&Sr({animations:A,transitions:j.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let E={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:j.elements||[]};V.children.push(Ci({container:E,resources:r,templateData:xe({variables:o,runtime:i,saveSlots:f,dialogueState:t.dialogue,isLineCompleted:p,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,characters:r.characters||{},skipTransitionsAndAnimations:h}),isLineCompleted:p,skipMode:l,skipTransitionsAndAnimations:h}))}let w=n?.layout?.resourceId,C=t.layout?.resourceId,R=ke({animationsDef:t.layout?.animations,resources:r,previousResourceId:w,currentResourceId:C,previousTargetId:w?`layout-${w}`:void 0,currentTargetId:C?`layout-${C}`:void 0,animationPath:"layout.animations",idPrefix:"layout"});return Ee({animationInstances:R,isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})&&A.push(...R),e},Zl=(e,{currentLineActions:t,previousPresentationState:n,resources:r={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:l}=e,a=t?.screen?.animations;if(!a)return e;let c=n!=null,u=ke({animationsDef:a,resources:r,previousResourceId:c?"story":void 0,currentResourceId:"story",previousTargetId:c?"story":void 0,currentTargetId:"story",animationPath:"screen.animations",idPrefix:"screen"});return Ee({animationInstances:u,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...u),e},eu=(e,{presentationState:t})=>{let n=Qe(e.elements);return!n||!t?.screen||Object.assign(n,Ai(t.screen)),e},tu=(e,{presentationState:t,resources:n={},variables:r,runtime:o,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:a,canRollback:c,form:u,overlayStack:d=[],dialogueHistory:f=[],saveSlots:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:b})=>{let{elements:A,animations:w}=e;return d&&d.length>0&&d.forEach((C,R)=>{let V=n.layouts[C.resourceId];if(!V){console.warn(`Overlay layout not found: ${C.resourceId}`);return}Array.isArray(V.transitions)&&(b||Sr({animations:w,transitions:V.transitions,defaultTargetId:`overlayStack-${R}`,idPrefix:`overlayStack-${R}`,animationPathPrefix:`overlayStack[${R}]`}));let j={id:`overlayStack-${R}`,type:"container",x:0,y:0,children:[xi({id:`overlayStack-${R}-blocker`,screen:h}),...V.elements||[]]},E=vi(f,n.characters,r),B=xe({variables:r,runtime:o,saveSlots:p,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:a,canRollback:c,form:u,historyDialogue:E,characters:n.characters||{},skipTransitionsAndAnimations:b}),U=ce(j,B,{functions:Re}),[J,...M]=U.children||[],Y=Oe(je({...U,children:M},{isLineCompleted:g,skipMode:s,skipTransitionsAndAnimations:b}),n);A.push({...Y,children:J?[J,...Y.children||[]]:Y.children})}),e},nu=(e,{presentationState:t,resources:n={},variables:r,runtime:o,saveSlots:i=[],autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,confirmDialog:f,dialogueHistory:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:b})=>{let{elements:A,animations:w}=e;if(!f?.resourceId)return e;let C=n.layouts?.[f.resourceId];if(!C)return console.warn(`ConfirmDialog layout not found: ${f.resourceId}`),e;Array.isArray(C.transitions)&&!b&&Sr({animations:w,transitions:C.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let R={id:"confirmDialog",type:"container",x:0,y:0,children:[xi({id:"confirmDialog-blocker",screen:h}),...C.elements||[]]},V=vi(p,n.characters,r),j=ce(R,xe({variables:r,runtime:o,saveSlots:i,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,confirmDialog:f,historyDialogue:V,characters:n.characters||{},skipTransitionsAndAnimations:b}),{functions:Re}),[E,...B]=j.children||[],U=Oe(je({...j,children:B},{isLineCompleted:g,skipMode:l,skipTransitionsAndAnimations:b}),n);return A.push({...U,children:E?[E,...U.children||[]]:U.children}),e},$t=e=>(t,n)=>Ul(t,{...n,visualLayer:e}),ru=$t(_e.BEHIND_BACKGROUND),ou=$t(_e.BEHIND_CHARACTER),iu=$t(_e.BEHIND_DIALOGUE),su=$t(_e.BEHIND_CHOICE),au=$t(_e.FOREGROUND),_i=e=>Xt(jl,[Yl,ru,Fl,ou,Ml,iu,ql,su,Hl,Wl,Ql,au,eu,Zl,Gl,Kl,Xl,tu,nu])(e);function Ri(e,t=""){let n=[],r=e.length,o=0,i=0,s=-1,l=()=>{let a=0,c=0,u;do u=parseInt(e[o++],36),a+=(u&15)<<c,c+=4;while(u&16);return a};for(;o<r;){let a=s+1+l();s=a+l(),n.push([a,s,t?parseInt(t[i++],36):0])}return n}function Oi(e,t,n){let r=0,o=t.length-1;for(;r<=o;){let i=r+o>>>1,s=n[i];if(e<t[i])o=i-1;else if(e>s>>>5)r=i+1;else return s&31}return 0}var ki="090001000h1v5g2903000hl2v6jh16ng1s210111110o35aa10u2k1g10l6600152113h2010u1q1r5aq3890o13181214r22k3158q2n1000v100h1k20000001207030001160721k171001h1j11610332010010321210090411021c1c02100o301201412230u1130b100h1j116111420120411001100k11l10051001h1j11611142011000321210072411021d0g10r3000000132120090o200200g1j11f2012031213711271t1001o301001000001121371b1f0c101h1l2011001031212000080a1t1001m40400102101600i11t301006c7i601008b6p41r10101041h3d0004115a1j290p3q223000511010100g1501010302003172030c0010016000e0i6v50n40n5tl12ir33s12t11u11cj30100060700010a90t220000l71i20m7203010241000502rd101004k300000006101027050920g3t22bk1300616g209030207u18c1000t10003010501b2o20000102000004g37070101o921c000640602001mcv3rg20000001o16d0c0m1fg6g2h30m10q55f1vm11c0ma0p1a42nc0ne1a090q3314902021204020112030318250105bb1201110i1021i15101131502141b15120511011k1155132040202510201010603060a1f02040104210b1g3290e0e0kn11vs12j11j3040pp12t80g6v1vmo7319g21g51gh103040n11010040j51i3f01q1h1d0m27p1a0000cs13200523j200010301010100v140018a4q2501010101c08000i1f12601011g3012215110u1a0001015000pcq181000100011000iji5fvc0u91g5bhg20ie0l94lo6002115303121s12240la1tj23h44tj11t45m4ah33q700000l3ep2021a200t220301012040a0i320j2040007f00100r20c100g3208000011531000s520201036020t900207l1101n311000000321210090a12634b910201l22001051020120011020000e1i520701020000n10h5001050000010000010001re0010323010001r11i520701000001q6000000107l600000230004gg12080001lc62027111n1000411230000000000t820321030030r10090n205001380800501020n2050c0001mc00002000000nc006150000i5l1100600010001q753011160000i441111000000rl11019100000c1h201043102n10ltk1f006eoss2b0202gs94r36si2033ku101m373h50b1rqs4113sli1t22m1uh2435070726u13k92rr7m34h380e0m141egl561g1261114k60ga6nn10t33sv13uf1jf0207150qt16t66pr60n23k6bf1f0e1l29g71c1e029j1n30p11ea0k1028139m16rb2v621122i52213040tf1u3b51n17127c0232041d120819052c28220104060306l5g3l4572g130152cqdl2c3o37a5o27u11c32d9m2cu2191obo57eh9gg1tv3",Li="262122424333333393233393339333333333393393bf3b3b3b3b3f3f3bffff33b3bb33ff3f33b3b3333333bffff3b33bb33f33bffff33b3bb33ff3f33b3bbb333b3ff33b333f33b3b3b3b3333b3bf33b3bb39333b33b33b3b3b333b333333b3b33333f3b33b3ffb3f3fff3f3b33f35dc33333f3b3b3b33323333b3bb3b33b3fb3b3333b33333bff3b3f33bfb3b3ff3b3b3b3b3b333b333b3323e22442344444444444444444444444444444444444444444444444444444444444444444444444444444443333333333b3b3bb33333b353bff3b3b3b3f3ff3b3b333bfff3f33333fb3bb3fb3b3bb33232333f333fff333333333b3b3333bb3b39393f3b3fbf33bb3b393b3b3b3333b33b33b3bbb33b33ffff3b3333bb3933b3b3b333b3b3b3b3b33b3b3b33b3b3b33b3b33b33b3b3b3fffff3bb39b9b3b33b3bf3f3b33f3b3f93b33b3b3bb33b33b3b3b3333393b3b3b33b39bffb3b332333b333dd3b3333233332333333333333333333333333333444444444444a4444444444444344444444444444444444444444444444444444444444",$i="0001000000010010000000100000000000000000000000000001000000010014000100000001001000010101100101100000000000000000000100000001111000010000000110101001110111111111000100000021001000010000000100100001000000011010000100000001111000013000000100140001000000010010";var Ti=65535,Tr=40960,pn=126976,Pi=new Uint8Array(12288),Vi=new Uint8Array(3072),ji=new Uint8Array(2816),Fi,Mi;{let e=(o,i,s,l,a)=>{let c=i+o.length-1;for(let u=s<i?i:s,d=l>c?c:l;u<=d;u++)o[u-i]=a},t=new Uint32Array(320),n=new Uint32Array(320),r=0;for(let[o,i,s]of Ri(ki,Li))e(Pi,0,o,i,s),e(Vi,Tr,o,i,s),e(ji,pn,o,i,s),i>=65040&&!(o>=pn&&i<=129791)&&(t[r]=o,n[r++]=i<<5|s);Fi=t.slice(0,r),Mi=n.slice(0,r)}function Di(e){return e<12288?Pi[e]:e<Tr?e<12336?e>=12330?3:0:e<12443?e===12336||e===12349?4:e>=12441?3:0:e===12951||e===12953?4:0:e<44032?Vi[e-Tr]:e<55204?(e-44032)%28?8:7:e<57344?e<=55238?e>=55216?13:0:e>=55243&&e<=55291?12:0:e<65024?e===64286?3:0:e<65040?3:e>=pn&&e<129792?ji[e-pn]:e>=917504?e>921599?0:e>=917536&&e<917632||e>=917760&&e<918e3?3:2:Oi(e,Fi,Mi)}var Bi=Uint8Array.from($i,Number);function cu(e){return e===2381||e===2509||e===2637||e===2765||e===2893||e===3149||e===3405||e===4153||e===6098||e===6752||e===6980||e===7083||e===43456||e===43766||e===68159||e===69939||e===70608||e===71998||e===72263||e===72345||e===73538}function Ni(e,t,n){switch(t){case 3:return e&24?n===8204?e&6:(e&24)===16||cu(n)?e&6|16:e&6|8:e&6;case 4:return 2;case 10:return e&1^1;case 14:return(e&2)<<1|e&24;default:return 8}}function*Ui(e){let t=e.length;if(t===0)return;let n=e.codePointAt(0),r=n>Ti?2:1,o=Di(n),i=50200>>o&1?Ni(0,o,n):0,s=0,l=n,a=o;for(;r<t;){n=e.codePointAt(r);let c=n>Ti?2:1,u=Di(n),d=Bi[o<<4|u],f;d===0?f=!0:d===1?f=!1:d===2?f=!(i&1):d===3?f=!(i&4):f=(i&24)!==16,i=50200>>u&1&&(i!==0||u!==3)?Ni(i,u,n):0,f&&(yield{segment:e.slice(s,r),index:s,input:e,_hd:l,_catBegin:a===15?0:a,_catEnd:o===15?0:o},s=r,l=n,a=u),r+=c,o=u}yield{segment:e.slice(s),index:s,input:e,_hd:l,_catBegin:a===15?0:a,_catEnd:o===15?0:o}}function*zi(e){for(let t of Ui(e))yield t.segment}{let e=Ui("_");Bi._keep=[e,e.next()]}var qi=1e3,lu=1,uu=60,du=3,fu=.5,pu=2e4,hu=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,mu=/^\s+$/u,Hi,gu=e=>{let t=`${e??""}`.normalize("NFC"),n=globalThis.Intl?.Segmenter;return typeof n!="function"?Array.from(zi(t)):(Hi??=new n(void 0,{granularity:"grapheme"}),Array.from(Hi.segment(t),({segment:r})=>r))},yu=e=>gu(e).reduce((t,n)=>mu.test(n)?t+fu:hu.test(n)?t+du:t+1,0),Wi=({text:e="",baseDelay:t=qi,speed:n=lu}={})=>{let r=Number.isFinite(t)?Math.max(0,t):qi,o=Number.isFinite(n)&&n>0?n:1,i=yu(e)*uu/o,s=Math.max(r,pu);return Math.min(r+i,s)};var hn={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},Xi=1,Dr=1,ft="choice",Fe="form",yn=()=>({manual:{...hn.manual},auto:{...hn.auto},applyMode:hn.applyMode}),Nr=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let n=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...yn()},n&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},T=e=>{let t=se(e)?He(e):e;return structuredClone(t)},$=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Qi=(e,t)=>{if(typeof t!="string"||t.length===0)throw new Error("Achievement action requires a non-empty resourceId");let n=e.projectData.resources?.achievements?.[t];if(!n)throw new Error(`Achievement resource "${t}" not found`);if(n.type!=="boolean"&&n.type!=="number")throw new Error(`Achievement resource "${t}" has invalid type "${n.type}"`);return n},Dt=e=>String(e),Zi=()=>({sections:[],resources:[]}),bu=e=>$(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):Zi(),Iu=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",Au=({sectionId:e,lineId:t,content:n,dialogueState:r,characterName:o})=>({sectionId:e,lineId:t,content:n,text:Iu(n),characterId:r.characterId,character:{...r.character||{},name:o},characterName:o}),wu=()=>({resourceId:void 0}),Eu=e=>{if(!$(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},pt=(e,t)=>{let n=e?.story?.scenes??{};for(let[r,o]of Object.entries(n))if(o?.sections?.[t])return{sceneId:r,section:o.sections[t]};return{sceneId:void 0,section:void 0}},es=e=>{let t=e?.story?.scenes??{},n=new Map;for(let[r,o]of Object.entries(t)){let i=o?.sections??{};for(let s of Object.keys(i)){let l=n.get(s);if(l!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${l}" and "${r}". Section IDs must be globally unique.`);n.set(s,r)}}},ts=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},ns=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==Xi)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},xu=(e,t={})=>{let n;try{n=ns(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let r={...t,formatVersion:n,slotId:ts(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete r.slotKey,delete r.date,r},vu=(e={})=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,xu(t,n)])),rs=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:n})=>kf(n));return t.length>0?t:void 0},Cu=e=>{!$(e)||!Array.isArray(e.timeline)||(e.returnabilityVersion=Dr,e.timeline.forEach(t=>{if(!$(t))return;typeof t.returnable!="boolean"&&delete t.returnable;let n=rs(t.executedActions);if(n){t.executedActions=n;return}delete t.executedActions}))},Yi=(e,t,n,r="viewedRegistry")=>{let o=t==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[o]:String(e)};if(!$(e))throw new Error(`Malformed ${r}.${t}[${n}] entry.`);if(typeof e[o]!="string"||e[o].length===0)throw new Error(`Malformed ${r}.${t}[${n}] entry: missing ${o}.`);if(t==="sections"){let i={sectionId:e.sectionId};if(e.lastLineId!==void 0&&e.lastLineId!==null&&typeof e.lastLineId!="string")throw new Error(`Malformed ${r}.sections[${n}] entry: invalid lastLineId.`);return typeof e.lastLineId=="string"&&e.lastLineId.length>0&&(i.lastLineId=e.lastLineId),i}return{resourceId:e.resourceId}},Su=(e,t="viewedRegistry")=>{if(e===void 0)return Zi();if(!$(e))throw new Error(`Malformed ${t}.`);if(e.sections!==void 0&&!Array.isArray(e.sections))throw new Error(`Malformed ${t}.sections.`);if(e.resources!==void 0&&!Array.isArray(e.resources))throw new Error(`Malformed ${t}.resources.`);let n=e.sections??[],r=e.resources??[];return{sections:Object.values(Object.fromEntries(n.map((o,i)=>{let s=Yi(o,"sections",i,t);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(r.map((o,i)=>{let s=Yi(o,"resources",i,t);return[s.resourceId,s]})))}},os=(e,t,n)=>{if(!$(e))throw new Error(`Malformed save slot ${n}.`);let{sectionId:r,lineId:o}=e;if(typeof r!="string"||r.length===0)throw new Error(`Malformed save slot ${n}: missing sectionId.`);if(typeof o!="string"||o.length===0)throw new Error(`Malformed save slot ${n}: missing lineId.`);let{sceneId:i,section:s}=pt(t,r);if(!s)throw new Error(`Malformed save slot ${n}: section "${r}" does not exist in projectData.`);if(!s.lines?.some(a=>a.id===o))throw new Error(`Malformed save slot ${n}: line "${o}" does not exist in section "${r}".`);return{sceneId:i,sectionId:r,lineId:o}},is=(e,t)=>e?.sectionId===t?.sectionId&&e?.lineId===t?.lineId,_u=(e,t)=>{let{section:n}=pt(e,t?.sectionId);return n?.lines?.find(r=>r.id===t?.lineId)},Ru=(e,t)=>{let{section:n}=pt(e,t?.sectionId),r=n?.lines?.findIndex(i=>i.id===t?.lineId);if(typeof r!="number"||r<0)return null;let o=n.lines[r+1];return o?{sectionId:t.sectionId,lineId:o.id}:null},ss=(e,t,n)=>{if(typeof t?.sectionId!="string")return!1;let{section:r}=pt(e,t.sectionId);return is({sectionId:t.sectionId,lineId:r?.lines?.[0]?.id},n)},Ou=new Set(["jumpToLine","rollbackByOffset","rollbackToLine","sectionTransition","resetStoryAtSection"]),dt={always:"always",maybe:"maybe",never:"never"},ku=e=>{if(!Object.prototype.hasOwnProperty.call(e??{},"when"))return dt.always;let t=e.when,n;if(t===null||typeof t=="boolean"||typeof t=="number")n=t;else if($(t)&&Object.keys(t).length===1&&Object.prototype.hasOwnProperty.call(t,"literal"))n=t.literal;else return dt.maybe;return n?dt.always:dt.never},as=(e,t)=>{if(!Array.isArray(e?.branches))return!1;for(let n of e.branches){let r=ku(n);if(r!==dt.never){if(t(n))return!0;if(r===dt.always)return!1}}return!1},cs=e=>as(e,t=>Object.entries(t?.actions??{}).some(([n,r])=>n==="conditional"?cs(r):Ou.has(n))),ls=(e,t,n)=>as(t,r=>Object.entries(r?.actions??{}).some(([o,i])=>o==="sectionTransition"?ss(e,i,n):o==="conditional"?ls(e,i,n):!1)),Lu=(e,t,n)=>{if(!t)return!0;let r=_u(n,e)?.actions;if(!$(r))return!0;if(ss(n,r.sectionTransition,t))return!1;let o=r.conditional;return o?!(ls(n,o,t)||!(r.choice?.resourceId||r.form?.resourceId)&&!cs(o)&&is(Ru(n,e),t)):!0},$u=(e,t,n)=>{if(!$(e)||!Array.isArray(e.timeline))return Tt({pointer:t,replayStartIndex:1});let r=new WeakSet,o=e.timeline.flatMap((c,u)=>{if(!$(c))return[];try{let d=os(c,n,`rollback.timeline[${u}]`),f=gn({sectionId:d.sectionId,lineId:d.lineId,rollbackPolicy:c.rollbackPolicy,returnable:c.returnable});typeof c.returnable=="boolean"&&r.add(f);let p=rs(T(c.executedActions));return p&&(f.executedActions=p),[f]}catch{return[]}});if(o.length===0)return Tt({pointer:t,replayStartIndex:1});e.returnabilityVersion!==Dr&&o.forEach((c,u)=>{!r.has(c)&&!Lu(c,o[u+1],n)&&(c.returnable=!1)});let s=typeof e.currentIndex=="number"?Math.trunc(e.currentIndex):o.length-1;(s<0||s>=o.length)&&(s=o.length-1);let l=o[s];if(l?.sectionId!==t.sectionId||l?.lineId!==t.lineId){let c=o.findLastIndex(u=>u.sectionId===t.sectionId&&u.lineId===t.lineId);c>=0?s=c:(o.push(gn({sectionId:t.sectionId,lineId:t.lineId})),s=o.length-1)}let a=typeof e.replayStartIndex=="number"?Math.min(Math.max(Math.trunc(e.replayStartIndex),0),s):0;return{currentIndex:s,isRestoring:!1,replayStartIndex:a,timeline:o}},Tu=(e,t,n)=>{if(!$(e))throw new Error(`Malformed save slot contexts[${n}] entry.`);let r=jr(t),o=os(e.pointers?.read,t,`contexts[${n}].pointers.read`);if(e.variables!==void 0&&!$(e.variables))throw new Error(`Malformed save slot contexts[${n}].variables entry.`);if(e.runtime!==void 0&&!$(e.runtime))throw new Error(`Malformed save slot contexts[${n}].runtime entry.`);let i=e.variables?st(T(e.variables),t.resources?.variables??{}):{},s=Wu({loadedContextRuntime:$(e.runtime)?T(e.runtime):{}}),l={currentPointerMode:"read",pointers:{read:o},configuration:$(e.configuration)?T(e.configuration):{},views:Array.isArray(e.views)?T(e.views):[],bgm:$(e.bgm)?T(e.bgm):{resourceId:void 0},variables:{...r,...i},rollback:$u(e.rollback,o,t)};return s&&(l.runtime=s),l},Du=(e,t)=>{if(!$(e))throw new Error("Malformed save slot state.");if(!Array.isArray(e.contexts)||e.contexts.length===0)throw new Error("Malformed save slot state: contexts must be a non-empty array.");return{contexts:e.contexts.map((n,r)=>Tu(n,t,r))}},Nu=(e,t)=>{if(!$(e))throw new Error("Malformed save slot.");let n=ns(e.formatVersion);return{...e,formatVersion:n,state:Du(e.state,t)}},Gi=(e,t,{required:n=!1}={})=>{if(e===void 0){if(n)throw new Error(`showConfirmDialog requires ${t}`);return{hideConfirmDialog:{}}}if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`showConfirmDialog ${t} must be an action object`);let r=T(e);return Object.prototype.hasOwnProperty.call(r,"hideConfirmDialog")||(r.hideConfirmDialog={}),r},Pu=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:Gi(e.confirmActions,"confirmActions",{required:!0}),cancelActions:Gi(e.cancelActions,"cancelActions")}},ht=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},Vu=e=>($(e.global.formDrafts)||(e.global.formDrafts={}),e.global.formDrafts),mt=e=>{Object.prototype.hasOwnProperty.call(e.global,"formDrafts")&&(e.global.formDrafts={})},us=e=>{if(!(!$(e)||!e.animations))return{animations:T(e.animations)}},ju=(e,t)=>{let n=us(t);if(n){e.global.pendingScreenTransition=n;return}delete e.global.pendingScreenTransition},Fu=e=>{let t=e?.id??e?.resourceId;return typeof t=="string"&&t.length>0?t:void 0},Mu=(e,t)=>{let n=e?.sectionId,r=e?.lineId;if(!(!n||!r||!t))return`${n}:${r}:${t}`},mn=e=>String(e??""),ds=(e,t)=>{let n=mn(t);return e?.trim===!0?n.trim():n},Bu=e=>$(e?.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,t])=>$(t)).map(([t,n])=>[t,{id:t,...T(n)}])):{},Uu=(e,t)=>{if(!t||!$(e.global.formDrafts))return;let n=e.global.formDrafts[t];return $(n)?n:void 0},fs=(e,t)=>{let n=Vu(e);$(n[t])||(n[t]={values:{},touched:{},errors:{},submitted:!1});let r=n[t];return $(r.values)||(r.values={}),$(r.touched)||(r.touched={}),$(r.errors)||(r.errors={}),typeof r.submitted!="boolean"&&(r.submitted=!1),r},Pr=(e,t)=>{let n=ds(e,t);return e?.required===!0&&n.length===0?"required":null},zu=({state:e,pointer:t})=>{if(!t?.sectionId||!t?.lineId)return{};let r=le({state:e},{sectionId:t.sectionId})?.lines||[],o=r.findIndex(i=>i.id===t.lineId);return o<0?{}:Ye(r.slice(0,o+1).map(i=>i.actions||{}))},qu=({state:e,form:t,pointer:n})=>{if(!t?.resourceId)return null;let r=Fu(t),o=Mu(n,r);if(!r||!o)return null;let i=Uu(e,o),s=Bu(t),l=In({state:e}),a={},c=[],u={},d=!0;return Object.entries(s).forEach(([f,p])=>{let h=mn(l?.[p.variableId]),g=Object.prototype.hasOwnProperty.call(i?.values??{},f)?mn(i.values[f]):h,b=i?.touched?.[f]===!0,A=Pr(p,g),w=i?.submitted||b?A:null,C=typeof p.maxLength=="number"?Math.max(0,Math.round(p.maxLength)):void 0,R={id:f,variableId:p.variableId,value:g,initialValue:h,valid:!A,error:w,touched:b,required:p.required===!0,trim:p.trim===!0,placeholder:p.placeholder===void 0?"":String(p.placeholder),multiline:p.multiline===!0,...C!==void 0?{maxLength:C}:{}};A&&(d=!1),a[f]=R,c.push(R),u[f]=g}),{id:r,key:o,resourceId:t.resourceId,animations:t.animations,valid:d,submitted:i?.submitted===!0,fields:a,fieldList:c,values:u,submitActions:{submitForm:{formKey:o,actions:T(t.submitActions??{})}},cancelActions:{cancelForm:{formKey:o,actions:T(t.cancelActions??{})}}}},Ze=[],Ki="line",Vr="interaction",gn=({sectionId:e,lineId:t,rollbackPolicy:n,returnable:r})=>({sectionId:e,lineId:t,rollbackPolicy:n??"free",...typeof r=="boolean"?{returnable:r}:{}}),jr=e=>{let{contextVariableDefaultValues:t}=Zt(e??{});return T(t)},ps=()=>({...T(_t)}),hs=({loadedRuntime:e,runtimeIds:t,defaults:n={},path:r})=>{if(e===void 0)return{runtimeState:T(n),hasLoadedValues:!1};if(!$(e))throw new Error(`Malformed ${r}.`);let o=T(n),i=!1;return t.forEach(s=>{e[s]!==void 0&&(o[s]=ms(s,T(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},Hu=({loadedGlobalRuntime:e={}})=>hs({loadedRuntime:e,runtimeIds:ir,defaults:Ge,path:"global.runtime"}).runtimeState,Wu=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:n}=hs({loadedRuntime:e,runtimeIds:sr,defaults:ps(),path:"context.runtime"});return n?t:void 0},bn=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},Yu=e=>e.runtime?(sr.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=T(_t[t]))}),e.runtime):(e.runtime=ps(),e.runtime),Gu=e=>Qo(e.global),Ku=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:Gu(e)}})},Ju=e=>Xo[e],Xu=(e,t)=>{let n=Ju(e);if(n==="number"){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} requires a finite numeric value`);return}if(n==="boolean"){if(typeof t!="boolean")throw new Error(`${e} requires a boolean value`);return}if(n==="string"){if(typeof t!="string")throw new Error(`${e} requires a string value`);return}throw new Error(`Unsupported runtime field "${e}"`)},ms=(e,t)=>{if(Xu(e,t),e==="autoForwardSpeed"&&t<=0)throw new Error("autoForwardSpeed requires a value greater than 0");return e==="saveLoadPagination"?Math.max(1,Math.trunc(t)):t},gs=(e,t,n)=>{let r=ms(t,n);if(t in _t){let o=bn(e);if(!o)return r;let i=Yu(o);return i[t]=r,r}return e.global[t]=r,r},ys=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:T(e)},configuration:{},views:[],bgm:wu(),variables:jr(t),rollback:Tt({pointer:e})}),gt=e=>e?(e.currentPointerMode="read",$(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,Qu=(e,{queueRender:t=!0}={})=>{let n=e.contexts?.[e.contexts.length-1],r=n?.pointers?.read;if(!n||!r?.sectionId||!r?.lineId)return null;let o=ys({pointer:r,projectData:e.projectData});return e.contexts[e.contexts.length-1]=o,Zu(e,{queueRender:t}),o},Zu=(e,{queueRender:t=!0}={})=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,ht(e),mt(e),e.global.nextLineConfig=yn(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"}),t&&e.global.pendingEffects.push({name:"render"})},bs=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},Tt=({pointer:e,replayStartIndex:t=0})=>{let n=e?.sectionId&&e?.lineId;return{currentIndex:n?0:-1,isRestoring:!1,replayStartIndex:t,timeline:n?[gn({sectionId:e.sectionId,lineId:e.lineId})]:[]}},tt=(e,t={})=>{if(e?.rollback)return bs(e.rollback),Array.isArray(e.rollback.timeline)||(e.rollback.timeline=[]),typeof e.rollback.currentIndex!="number"&&(e.rollback.currentIndex=e.rollback.timeline.length>0?e.rollback.timeline.length-1:-1),typeof e.rollback.isRestoring!="boolean"&&(e.rollback.isRestoring=!1),typeof e.rollback.replayStartIndex!="number"&&(e.rollback.replayStartIndex=0),e.rollback;let n=e?.pointers?.read;return e.rollback=Tt({pointer:n,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},Fr=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return;let r=tt(n);r.isRestoring||(r.currentIndex<r.timeline.length-1&&(r.timeline=r.timeline.slice(0,r.currentIndex+1)),r.timeline.push(gn(t)),r.currentIndex=r.timeline.length-1)},ed=({state:e})=>{let n=e.contexts?.[e.contexts.length-1]?.rollback;return!Array.isArray(n?.timeline)||typeof n.currentIndex!="number"?null:{checkpointIndex:n.currentIndex,checkpoint:n.timeline[n.currentIndex]??null}},td=({state:e},t={})=>{let{checkpointIndex:n,checkpointIdentity:r,sectionId:o,lineId:i}=t,l=e.contexts?.[e.contexts.length-1]?.rollback;if(!Number.isInteger(n)||!Array.isArray(l?.timeline)||typeof l.currentIndex!="number")return e;let a=l.timeline[n];return(se(a)?jn(a):a)!==r||a?.sectionId!==o||a?.lineId!==i||(a.returnable=!1),e},nd=({state:e},t={})=>{let{slotId:n,saveSlotIdentity:r,checkpointIndex:o,sectionId:i,lineId:s}=t,l=Dt(n),a=e.global.saveSlots?.[l],c=se(a)?jn(a):a;if(!a||c!==r)return e;let u=a.state?.contexts,d=Array.isArray(u)?u.at(-1):null,f=d?.rollback,p=f?.timeline?.[o];return!Number.isInteger(o)||f?.currentIndex!==o||d?.pointers?.read?.sectionId!==i||d?.pointers?.read?.lineId!==s||p?.sectionId!==i||p?.lineId!==s||(p.returnable=!1,f.returnabilityVersion=Dr,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}})),e},rd=e=>{let n=e.contexts?.[e.contexts.length-1]?.rollback;if(!n||n.isRestoring||!Array.isArray(n.timeline)||typeof n.currentIndex!="number")return null;let r=Ze[Ze.length-1],o=typeof r?.checkpointIndex=="number"?r.checkpointIndex:n.currentIndex;return o<0||o>=n.timeline.length?null:(typeof r?.checkpointIndex!="number"&&o<n.timeline.length-1&&(n.timeline=n.timeline.slice(0,o+1)),n.timeline[o]??null)},od=({state:e},t={})=>{let n=t?.source===Ki?Ki:Vr,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?(Ze.push({checkpointIndex:null,source:n}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),Ze.push({checkpointIndex:o.currentIndex,source:n}),e)},id=({state:e})=>(Ze.pop(),e),Se=(e,t,n)=>{let o=Ze[Ze.length-1]?.source??Vr;if(!Lf(t,o))return;let i=rd(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:T(n)}))},Ji=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return;let r=t?.operations??[];for(let{variableId:o,op:i,value:s,roundTo:l}of r){let a=e.projectData.resources?.variables?.[o],c=a?.scope,u=a?.type;if(Ne(a))throw new Error(`Cannot update computed variable: ${o}`);if(a?.readonly===!0)throw new Error(`Cannot update readonly variable: ${o}`);en(c,o),tn(u,i,o),Zn(u,i,s,o,{roundTo:l}),c==="context"&&(n.variables[o]=nn(n.variables[o],i,s,{roundTo:l}))}},sd=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:n,payload:r})=>{$f(e,n,r)})},ad=(e,t)=>{let{sectionId:n,lineId:r}=t,s=le({state:e},{sectionId:n})?.lines?.find(l=>l.id===r)?.actions;s&&Object.entries(s).forEach(([l,a])=>{Ns(e,l,a)})},Is=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return e;let r=tt(n),o=r.timeline[t];if(!o)return e;e.global.autoMode&&Pt({state:e}),e.global.skipMode&&Me({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),r.isRestoring=!0,r.currentIndex=t;try{n.variables=jr(e.projectData),delete n.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=T(hn),e.global.overlayStack=[],ht(e),mt(e),e.global.isLineCompleted=!0;let i=r.replayStartIndex??0;for(let l=i;l<=t;l++)l>i&&Nr(e),ad(e,r.timeline[l]),sd(e,r.timeline[l]);let s=gt(n);s.read={sectionId:o.sectionId,lineId:o.lineId},e.global.pendingEffects=e.global.pendingEffects.filter(l=>l?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{r.isRestoring=!1}return e},cd=e=>{let{projectData:t}=e,n=e.global??{},{saveSlots:r={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=n;es(t);let l=t.story.initialSceneId,a=t.story.scenes[l],c=a.initialSectionId,u=a.sections[c],d={sceneId:l,sectionId:c,lineId:u.initialLineId??u.lines[0].id},{globalVariablesDefaultValues:f}=Zt(t),p={...f,...st(o,t.resources?.variables??{})};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,formDrafts:{},accountViewedRegistry:Su(s,"accountViewedRegistry"),nextLineConfig:yn(),saveSlots:vu(r),overlayStack:[],variables:p,...Hu({loadedGlobalRuntime:i})},contexts:[ys({pointer:d,projectData:t})]}},ld=({state:e})=>e.global.overlayStack||[],ud=({state:e})=>e.global.pendingEffects,As=({state:e})=>e.global.skipMode,dd=({state:e})=>e.global.autoMode,ws=({state:e})=>e.global.dialogueUIHidden,Es=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],n=t[t.length-1];if(!n)return[];let{sectionId:r,lineId:o}=n.pointers.read,i=le({state:e},{sectionId:r});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(d=>d.id===o),l=i.lines.slice(0,s+1),a=[],c={},u=Ct({variables:{...e.global?.variables??{},...bn(e)?.variables??{}},runtime:Ke(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1});for(let d of l){let f=d.actions||{};if(c=Ye([c,f]),!f.dialogue)continue;let p=c.dialogue||{},h=Qt({characterId:p.characterId,character:p.character,characters:e.projectData.resources?.characters??{},variables:u}),g=Au({sectionId:r,lineId:d.id,content:f.dialogue.append===!0?p.content:f.dialogue.content,dialogueState:p,characterName:h});if(f.dialogue.append===!0&&a.length>0){a[a.length-1]={...a[a.length-1],content:g.content,text:g.text,characterId:g.characterId,character:g.character,characterName:g.characterName};continue}a.push(g)}return a},fd=({state:e})=>e.global.confirmDialog??null,Nt=({state:e},{pointer:t}={})=>{let n=t??Ie({state:e})?.pointer,r=zu({state:e,pointer:n});return qu({state:e,form:r.form,pointer:n})},pd=({state:e},{pointer:t}={})=>!!Nt({state:e},{pointer:t}),Ae=({state:e},{pointer:t}={})=>{let n=Nt({state:e},{pointer:t});if(n)return{source:Fe,formId:n.id,formKey:n.key};let r=xs({state:e,pointer:t});return r?{source:ft,resourceId:r}:null},hd=({state:e,registry:t},n)=>{let{sectionId:r,lineId:o}=n,s=(Array.isArray(t?.sections)?t.sections:[]).find(u=>u.sectionId===r);if(!s)return!1;if(s.lastLineId===void 0||o===void 0)return!0;let l=le({state:e},{sectionId:r});if(!l||!l.lines||!Array.isArray(l.lines))return s.lastLineId===o;let a=l.lines.findIndex(u=>u.id===s.lastLineId),c=l.lines.findIndex(u=>u.id===o);return a===-1||c===-1?s.lastLineId===o:c<=a},md=({registry:e},t)=>{let{resourceId:n}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===n)},Mr=({state:e},t)=>hd({state:e,registry:e.global.accountViewedRegistry},t),gd=({state:e},t)=>md({registry:e.global.accountViewedRegistry},t),yd=({state:e})=>e.global.nextLineConfig,xs=({state:e,pointer:t}={})=>{let n=t??Ie({state:e})?.pointer;if(!n)return;let r=n?.sectionId,o=n?.lineId,s=le({state:e},{sectionId:r})?.lines||[],l=s.findIndex(c=>c.id===o);if(l<0)return;let a;for(let c of s.slice(0,l+1)){let u=c?.actions;if(u?.cleanAll&&(a=void 0),!u||!Object.prototype.hasOwnProperty.call(u,"choice")){a=void 0;continue}let d=u.choice;if(d?.resourceId){a=d.resourceId;continue}d?.animations||(a=void 0)}return a},vs=({state:e})=>!!xs({state:e}),bd=({state:e})=>structuredClone(e),Id=({state:e})=>T(e.projectData.resources?.achievements??{}),Ad=({state:e},t)=>{let n=e.projectData.resources?.achievements?.[t?.resourceId];return n===void 0?void 0:T(n)},Cs=({state:e})=>e.global.saveSlots,wd=({state:e},t)=>{let n=t?.slotId,r=Dt(n);return e.global.saveSlots[r]},Br=({state:e})=>Ke(e),Ed=({state:e},t)=>Pe(e,t?.runtimeId),In=({state:e})=>{let t={...e.global?.variables??{},...bn(e)?.variables??{}};return Ct({variables:t,runtime:Ke(e),variableConfigs:e.projectData.resources?.variables??{}})},Ie=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],n=t[t.length-1];if(n)return{currentPointerMode:"read",pointer:n.pointers?.read}},le=({state:e},t)=>{let{sectionId:n}=t;return pt(e.projectData,n).section},An=({state:e})=>{let t=Ie({state:e});if(!t?.pointer)return;let{sectionId:n,lineId:r}=t.pointer,o=le({state:e},{sectionId:n});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===r)},Ss=({state:e})=>{let{sectionId:t,lineId:n}=Ie({state:e}).pointer,o=le({state:e},{sectionId:t})?.lines||[],i=o.findIndex(c=>c.id===n),l=o.slice(0,i+1).map(c=>{let u=c.actions||{},d={};return Object.keys(u).forEach(f=>{d[f]=u[f]}),d});return Ye(l)},xd=e=>{let t=An({state:e})?.actions?.dialogue;if(t?.clear===!0||!Array.isArray(t?.content))return"";let n=In({state:e});return t.content.map(r=>`${at(r?.text,{variables:n})??""}`).join("")},wn=({state:e})=>Wi({text:xd(e),baseDelay:Pe(e,"autoForwardDelay"),speed:Pe(e,"autoForwardSpeed")}),vd=({state:e})=>{let t=_s({state:e}),r=An({state:e})?.actions??{},o=Ye([t??{},r]);return tr(t??{},o??{})},Cd=({state:e},{sectionId:t})=>{let n=le({state:e},{sectionId:t});if(!n?.lines)return[];let r=[],o={};for(let i of n.lines){let s=i.actions||{},l=Ye([o,s]),a=tr(o,l);r.push({id:i.id,changes:a,presentationState:l}),o=nr(l)}return r},Sd=({state:e},{sectionId:t,includePresentationState:n=!1})=>{let r=Cd({state:e},{sectionId:t});return n?{lines:r}:{lines:r.map(({presentationState:o,...i})=>i)}},_s=({state:e})=>{let{sectionId:t,lineId:n}=Ie({state:e}).pointer,o=le({state:e},{sectionId:t})?.lines||[],i=o.findIndex(a=>a.id===n);if(i<=0)return null;let l=o.slice(0,i).map(a=>{let c=a.actions||{},u={};return Object.keys(c).forEach(d=>{u[d]=c[d]}),u});return nr(Ye(l))},Ur=({state:e},{slotsPerPage:t=6}={})=>{let o=((Br({state:e}).saveLoadPagination??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let l=o+s,a=e.global.saveSlots&&e.global.saveSlots[Dt(l)]||{};i.push({...a,slotId:l})}return{saveSlots:i}},_d=Cs,Rd=Ur,Od=e=>{let n=e.contexts?.[e.contexts.length-1]?.rollback;return!n||!Array.isArray(n.timeline)||typeof n.currentIndex!="number"?!1:n.currentIndex>=0&&n.currentIndex<n.timeline.length-1},kd=({state:e},t={})=>{let n=Ss({state:e}),r=_s({state:e}),o=An({state:e})?.actions??{},i=e.global.pendingScreenTransition,s=i?.animations?{...o,screen:T(i)}:o,l=i?.animations&&r===null?{}:r,{sectionId:a}=Ie({state:e}).pointer,{sceneId:c}=pt(e.projectData,a),u=Br({state:e}),d=t?.activePersistentAnimations??[],f=t?.restoredPersistentAnimations??[],p=Nt({state:e}),h=vs({state:e}),g=In({state:e}),{saveSlots:b}=Ur({state:e}),A=Od(e);return _i({presentationState:n,previousPresentationState:l,currentLineActions:s,resources:e.projectData.resources,currentSceneId:c,screen:e.projectData.screen,dialogueUIHidden:u.dialogueUIHidden,autoMode:u.autoMode,skipMode:u.skipMode,isChoiceVisible:h,isFormVisible:!!p,canRollback:js({state:e}),skipOnlyViewedLines:!u.skipUnseenText,isLineCompleted:u.isLineCompleted,skipTransitionsAndAnimations:!!u.skipTransitionsAndAnimations||A,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,form:p,dialogueHistory:Es({state:e}),saveSlots:b,variables:g,runtime:u,activePersistentAnimations:d,restoredPersistentAnimations:f})},Ld=({state:e},t)=>(e.global.confirmDialog=Pu(t),e.global.pendingEffects.push({name:"render"}),e),$d=({state:e})=>(e.global.confirmDialog&&(ht(e),e.global.pendingEffects.push({name:"render"})),e),Td=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),Se(e,"pushOverlay",t),e),Dd=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),Se(e,"popOverlay",void 0),e),Nd=({state:e},t)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=t),e.global.pendingEffects.push({name:"render"}),Se(e,"replaceLastOverlay",t),e),Pd=({state:e})=>(e.global.overlayStack=[],ht(e),mt(e),e.global.pendingEffects.push({name:"render"}),Se(e,"clearOverlays",void 0),e),Vd=(e,{activeInteraction:t})=>{e.global.autoMode&&e.global.pendingEffects.push({name:"clearAutoNextTimer"}),t&&e.global.skipMode&&e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.nextLineConfig?.auto?.enabled&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},En=(e,t,{screenTransition:n}={})=>{e.global.isLineCompleted=!1,ju(e,n),mt(e);let r=Ae({state:e},{pointer:t}),o=r?.source===ft,i=r?.source===Fe;return Vd(e,{activeInteraction:r}),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:o,isFormVisible:i,activeInteraction:r}},xn=(e,t,n)=>{!(t?.source===ft||t?.source===Fe)||n||!e.global.skipMode||e.global.pendingEffects.push({name:"startSkipNextTimer"})},Rs=({state:e})=>(Ae({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:wn({state:e})}}),e.global.pendingEffects.push({name:"render"})),e),Pt=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),jd=({state:e})=>{let t=e.global.autoMode;return Ae({state:e})&&!t||(t?Pt({state:e}):Rs({state:e})),e},Os=({state:e})=>(Ae({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),Fd=({state:e})=>{let t=As({state:e});return Ae({state:e})&&!t||(t?Me({state:e}):Os({state:e})),e},vn=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),Se(e,"showDialogueUI",void 0),e),ks=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),Se(e,"hideDialogueUI",void 0),e),Md=({state:e})=>(ws({state:e})?vn({state:e}):ks({state:e}),e),Be=(e,t,n)=>(gs(e,t,n),Ku(e),e.global.pendingEffects.push({name:"render"}),e),Vt=(e,t,n,r)=>{let o=gs(e,t,n);return e.global.pendingEffects.push({name:"render"}),Se(e,r,{value:o}),e},Bd=({state:e},t)=>Be(e,"dialogueTextSpeed",t?.value),Ud=({state:e},t)=>Be(e,"autoForwardDelay",t?.value),zd=({state:e},t)=>Be(e,"autoForwardSpeed",t?.value),qd=({state:e},t)=>Be(e,"skipUnseenText",t?.value),Hd=({state:e},t)=>Be(e,"skipTransitionsAndAnimations",t?.value),Wd=({state:e},t)=>Be(e,"soundVolume",t?.value),Yd=({state:e},t)=>Be(e,"musicVolume",t?.value),Gd=({state:e},t)=>Be(e,"muteAll",t?.value),Kd=({state:e},t)=>Vt(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),Jd=({state:e})=>{let t=Pe(e,"saveLoadPagination")+1;return Vt(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},Xd=({state:e})=>{let t=Pe(e,"saveLoadPagination")-1;return Vt(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},Qd=({state:e},t)=>Vt(e,"menuPage",t?.value,"setMenuPage"),Zd=({state:e},t)=>Vt(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),ef=({state:e})=>(e.global.pendingEffects=[],e),tf=({state:e},t)=>(e.global.pendingEffects.push(t),e),nf=({state:e},t)=>{let n=t?.resourceId;return Qi(e,n),e.global.pendingEffects.push({name:"completeAchievement",payload:{resourceId:n}}),e},rf=({state:e},t)=>{let n=t?.resourceId,r=Qi(e,n);if(r.type!=="number")throw new Error(`Achievement resource "${n}" does not support numeric progress`);let o=t?.current;if(!Number.isInteger(o)||o<0)throw new Error(`Achievement progress for "${n}" must be a non-negative integer`);if(!Number.isInteger(r.target)||r.target<1)throw new Error(`Achievement resource "${n}" must have a positive integer target`);let i=Math.min(o,r.target);return e.global.pendingEffects.push({name:"setAchievementProgress",payload:{resourceId:n,current:i,target:r.target,completed:i>=r.target}}),e},Ls=(e,{sectionId:t,resetStoryState:n=!1,screen:r})=>{let o=!!us(r),i=le({state:e},{sectionId:t});if(!i)return console.warn(`Section not found: ${t}`),e;let s=i.lines?.[0];if(!s)return console.warn(`Section ${t} has no lines`),e;if(n&&!Qu(e,{queueRender:!o}))return e;let l=Ae({state:e});n&&e.global.skipMode&&Me({state:e});let a=e.contexts?.[e.contexts.length-1];if(a){let u=gt(a),d=u.read;n||et(e,{sectionId:d?.sectionId,lineId:d?.lineId}),a.rollback||tt(a,{compatibilityAnchor:!0}),u.read={sectionId:t,lineId:s.id},n?a.rollback=Tt({pointer:u.read}):Fr(e,{sectionId:t,lineId:s.id})}let{activeInteraction:c}=En(e,a?.pointers?.read,{screenTransition:r});return xn(e,l,c),e},of=({state:e},t)=>Ls(e,{sectionId:t?.sectionId,resetStoryState:!0,screen:t?.screen}),$s=e=>(e.global.accountViewedRegistry=bu(e.global.accountViewedRegistry),e.global.accountViewedRegistry),zr=(e,t)=>{!Array.isArray(t)||t.length===0||e.global.pendingEffects.push({name:"applyScopedDataUpdates",payload:{updates:t.map(n=>({scope:n.scope,path:n.path,op:n.op,value:T(n.value)}))}})},Ts=(e,t)=>{zr(e,[{scope:"account",path:"viewedRegistry",op:"markViewed",value:{sections:(Array.isArray(t?.sections)?t.sections:[]).map(n=>({sectionId:n.sectionId,...n.lastLineId===void 0?{}:{lineId:n.lastLineId}})),resources:Array.isArray(t?.resources)?t.resources:[]}}])},sf=(e,t,{sectionId:n,lineId:r})=>{if(!n||!r)return!1;let o=$(t)?t:{};Array.isArray(o.sections)||(o.sections=[]);let i=o.sections.find(s=>s.sectionId===n);if(i){if(i.lastLineId===void 0)return!1;let s=le({state:e},{sectionId:n});if(s?.lines){let l=s.lines.findIndex(c=>c.id===i.lastLineId),a=s.lines.findIndex(c=>c.id===r);if(l===-1||a>l)return i.lastLineId===r?!1:(i.lastLineId=r,!0)}else return i.lastLineId===r?!1:(i.lastLineId=r,!0);return!1}else return o.sections.push({sectionId:n,lastLineId:r}),!0},et=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;sf(e,$s(e),t)&&Ts(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},af=({state:e},t)=>(et(e,t),e.global.pendingEffects.push({name:"render"}),e),cf=({state:e},t)=>{let{resourceId:n}=t;if(e.global.accountViewedRegistry!==void 0){let r=$s(e);r.resources.find(i=>i.resourceId===n)||(r.resources.push({resourceId:n}),Ts(e,{sections:[],resources:[{resourceId:n}]}))}return e.global.pendingEffects.push({name:"render"}),e},Ds=({state:e},t)=>{let n=Eu(t.manual),{auto:r,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,l=e.contexts?.[e.contexts.length-1]?.rollback?.isRestoring===!0;n&&r?(e.global.nextLineConfig={manual:n,auto:r},o!==void 0?e.global.nextLineConfig.applyMode=o:s!==void 0&&(e.global.nextLineConfig.applyMode=s)):(n&&(e.global.nextLineConfig.manual=n),r&&(e.global.nextLineConfig.auto=r),o!==void 0&&(e.global.nextLineConfig.applyMode=o));let a=e.global.nextLineConfig.auto?.enabled,c=Ae({state:e});return!l&&!c&&a===!0&&!i?e.global.nextLineConfig.auto?.trigger==="fromStart"?e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):e.global.isLineCompleted&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):!l&&a===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),Se(e,"setNextLineConfig",t),e},lf=({state:e},t)=>{let n=t?.slotId;if(n==null||n==="")throw new Error("saveSlot requires slotId");let{thumbnailImage:r}=t,o=t?.savedAt,i=Dt(n),s=T(e.contexts);s?.forEach(c=>{gt(c),bs(c.rollback),Cu(c.rollback)});let l={contexts:s},a={formatVersion:Xi,slotId:ts(n),savedAt:typeof o=="number"?o:Date.now(),image:r,state:l};return e.global.saveSlots[i]=a,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},uf=({state:e},t)=>{let n=t?.slotId;if(n==null||n==="")throw new Error("loadSlot requires slotId");let r=Dt(n),o=e.global.saveSlots[r];if(o){let i=Nu(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=yn(),e.global.overlayStack=[],e.global.isLineCompleted=!0,ht(e),mt(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},df=({state:e},t)=>{let{projectData:n}=t;es(n),e.projectData=n;let r=n?.resources?.variables??{},{contextVariableDefaultValues:o,globalVariablesDefaultValues:i}=Zt(n??{});return Object.prototype.hasOwnProperty.call(e.global??{},"variables")&&(e.global.variables={...i,...st(e.global.variables,r)}),e.contexts?.forEach(s=>{Object.prototype.hasOwnProperty.call(s??{},"variables")&&(s.variables={...o,...st(s.variables,r)})}),ht(e),mt(e),e.global.pendingEffects.push({name:"render"}),e},ff=({state:e},t)=>{let{sectionId:n,lineId:r}=t;if(!r)return console.warn("jumpToLine requires lineId parameter"),e;let o=e.contexts[e.contexts.length-1];if(!o)return console.warn("No context available for jumpToLine"),e;let i=n||o.pointers.read?.sectionId;if(n&&!le({state:e},{sectionId:n}))return console.warn(`Section not found: ${n}`),e;let s=le({state:e},{sectionId:i});if(!s?.lines||!Array.isArray(s.lines))return console.warn(`Section ${i} has no lines`),e;if(!s.lines.find(d=>d.id===r))return console.warn(`Line not found: ${r} in section ${i}`),e;let a=Ae({state:e}),c=gt(o);c.read={sectionId:i,lineId:r};let{activeInteraction:u}=En(e,c.read);return xn(e,a,u),e},pf=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return vn({state:e}),e;let n=Ae({state:e});if(n?.source===ft&&t?.bypassChoice!==!0||n?.source===Fe&&t?._interactionSource!==Fe)return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let u=Ie({state:e})?.pointer,d=u?.sectionId,f=u?.lineId;d&&f&&et(e,{sectionId:d,lineId:f}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&!n&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:wn({state:e})}});let p=e.global.nextLineConfig;return p?.auto?.enabled&&!n&&p.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:p.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e}let r=Ie({state:e})?.pointer,o=r?.sectionId,i=le({state:e},{sectionId:o}),s=e.contexts[e.contexts.length-1],l=i?.lines||[],c=l.findIndex(u=>u.id===r?.lineId)+1;if(c<l.length){let u=l[c],d=!Pe(e,"skipUnseenText");if(e.global.skipMode&&d&&!Mr({state:e},{sectionId:o,lineId:u.id}))return Me({state:e}),e;if(s&&!s.rollback&&tt(s,{compatibilityAnchor:!0}),s){let p=gt(s),h=p.read?.lineId;h&&o&&et(e,{sectionId:o,lineId:h}),p.read={sectionId:o,lineId:u.id}}Fr(e,{sectionId:o,lineId:u.id}),Nr(e);let{activeInteraction:f}=En(e,{sectionId:o,lineId:u.id});xn(e,n,f)}else e.global.autoMode&&Pt({state:e}),e.global.skipMode&&Me({state:e});return e},hf=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=Ae({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:wn({state:e})}});let n=Ie({state:e})?.pointer,r=n?.sectionId,o=n?.lineId;r&&o&&et(e,{sectionId:r,lineId:o});let i=e.global.nextLineConfig;return i?.auto?.enabled&&!t&&i.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:i.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e},mf=({state:e},t)=>Ls(e,{sectionId:t?.sectionId,screen:t?.screen}),gf=({state:e},t)=>{let n=t?._conditionalContinuation===!0;if(e.global.dialogueUIHidden&&!n)return vn({state:e}),e;let r=Ae({state:e});if(r?.source===ft&&t?.bypassChoice!==!0||r?.source===Fe&&t?._interactionSource!==Fe||r&&r.source!==ft&&r.source!==Fe)return e;let o=Ie({state:e})?.pointer,i=o?.sectionId,s=le({state:e},{sectionId:i}),l=e.contexts[e.contexts.length-1],a=s?.lines||[],u=a.findIndex(d=>d.id===o?.lineId)+1;if(u<a.length){let d=a[u],f=!Pe(e,"skipUnseenText");if(e.global.skipMode&&f&&!Mr({state:e},{sectionId:i,lineId:d.id})&&(Me({state:e}),!n))return e;if(l&&!l.rollback&&tt(l,{compatibilityAnchor:!0}),l){let h=gt(l),g=h.read?.lineId;g&&i&&et(e,{sectionId:i,lineId:g}),h.read={sectionId:i,lineId:d.id}}Fr(e,{sectionId:i,lineId:d.id}),Nr(e);let{activeInteraction:p}=En(e,{sectionId:i,lineId:d.id});xn(e,r,p)}else e.global.autoMode&&Pt({state:e}),e.global.skipMode&&Me({state:e}),e.global.nextLineConfig.auto?.enabled&&(e.global.nextLineConfig.auto.enabled=!1,e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}));return e},qr=(e,t={})=>{let n=Nt({state:e});return!n||t.formKey&&t.formKey!==n.key||t.formId&&t.formId!==n.id?null:n},yf=(e,t)=>{if(!t.variableId)throw new Error(`form field "${t.id}" requires variableId`);let n=e.projectData.resources?.variables?.[t.variableId],r=n?.scope,o=n?.type;if(Ne(n))throw new Error(`Cannot update computed variable: ${t.variableId}`);if(n?.readonly===!0)throw new Error(`Cannot update readonly variable: ${t.variableId}`);return en(r,t.variableId),tn(o,"set",t.variableId),{variableConfig:n,scope:r}},bf=(e,t)=>({id:e.id,key:e.key,valid:!0,values:T(t),fields:T(e.fields),fieldList:T(e.fieldList)}),If=e=>{if(e.global.isLineCompleted)return;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=Ie({state:e})?.pointer,n=t?.sectionId,r=t?.lineId;n&&r&&et(e,{sectionId:n,lineId:r})},Af=({state:e},t={})=>{let n=qr(e,t),r=t.field;if(!n?.fields?.[r])return e;let o=fs(e,n.key),i=mn(t.value),s=n.fields[r],l=Pr(s,i);return o.values[r]=i,o.touched[r]=!0,l?o.errors[r]=l:delete o.errors[r],e.global.pendingEffects.push({name:"render"}),e},wf=({state:e},t={})=>{let n=qr(e,t);if(!n)return{submitted:!1,valid:!1,reason:"inactive"};let r=fs(e,n.key);r.submitted=!0;let o={},i={};if(Object.entries(n.fields).forEach(([d,f])=>{let p=Object.prototype.hasOwnProperty.call(r.values,d)?r.values[d]:f.value,h=Pr(f,p);r.touched[d]=!0,h&&(i[d]=h),o[d]=ds(f,p)}),r.errors=i,Object.keys(i).length>0)return e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!1,errors:T(i),form:{id:n.id,key:n.key,values:T(o)}};let s=e.contexts[e.contexts.length-1];if(s?.rollback?.isRestoring)return{submitted:!1,valid:!1,reason:"restoring"};let l=!1,a=[],c=[];Object.entries(n.fields).forEach(([d,f])=>{let{scope:p}=yf(e,f),h=p==="context"?s.variables:e.global.variables,g=o[d];h[f.variableId]=nn(h[f.variableId],"set",g),p==="context"&&(l=!0,c.push({variableId:f.variableId,op:"set",value:g})),(p==="device"||p==="account")&&a.push({scope:p,path:`variables.${f.variableId}`,op:"set",value:T(h[f.variableId])})}),l&&Se(e,"updateVariable",{id:"submitForm",operations:c}),zr(e,a);let u=bf(n,o);return If(e),delete e.global.formDrafts[n.key],e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!0,form:u}},Ef=({state:e},t={})=>{let n=qr(e,t);return n?(delete e.global.formDrafts?.[n.key],e.global.pendingEffects.push({name:"render"}),{cancelled:!0,form:{id:n.id,key:n.key,values:T(n.values),fields:T(n.fields),fieldList:T(n.fieldList)}}):{cancelled:!1,reason:"inactive"}},xf=({state:e},t)=>{let{id:n,operations:r=[]}=t;if(!n)throw new Error("updateVariable requires an id field");if(typeof n!="string"||!/^[a-zA-Z0-9]+$/.test(n))throw new Error(`updateVariable id must be alphanumeric, got: "${n}"`);let o=e.contexts[e.contexts.length-1];if(o?.rollback?.isRestoring)return e;let i=!1,s=[],l=[];return r.forEach(({variableId:a,op:c,value:u,roundTo:d})=>{let f=e.projectData.resources?.variables?.[a],p=f?.scope,h=f?.type;if(Ne(f))throw new Error(`Cannot update computed variable: ${a}`);if(f?.readonly===!0)throw new Error(`Cannot update readonly variable: ${a}`);en(p,a),tn(h,c,a),Zn(h,c,u,a,{roundTo:d});let g=p==="context"?o.variables:e.global.variables;if(p==="context"){i=!0;let b={variableId:a,op:c,value:u};d!==void 0&&(b.roundTo=d),l.push(b)}g[a]=nn(g[a],c,u,{roundTo:d}),(p==="device"||p==="account")&&s.push({scope:p,path:`variables.${a}`,op:"set",value:T(g[a])})}),i&&Se(e,"updateVariable",{id:n,operations:l}),zr(e,s),e.global.pendingEffects.push({name:"render"}),e},vf=e=>(t,n)=>e({state:t},n),Cf=e=>({variables:Ct({variables:{...e.global?.variables??{},...bn(e)?.variables??{}},runtime:Ke(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1}),runtime:Ke(e)}),Sf=e=>{if(!$(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")},_f=(e,t,n)=>{if(!$(e))throw new Error(`conditional branch at index ${t} must be an object`);if(!$(e.actions))throw new Error(`conditional branch at index ${t} requires actions object`);if(!Object.prototype.hasOwnProperty.call(e,"when")&&t!==n-1)throw new Error("conditional else branch must be the last branch")},Rf=(e,t)=>{Sf(t);for(let n=0;n<t.branches.length;n+=1){let r=t.branches[n];if(_f(r,n,t.branches.length),!(Object.prototype.hasOwnProperty.call(r,"when")&&!vt(r.when,Cf(e)))){Object.entries(r.actions).forEach(([i,s])=>{Ns(e,i,s)});return}}},Of={conditional:{replayLine:Rf},updateVariable:{recordSources:[Vr],replayLine:Ji,replayRecorded:Ji,persistInSaveSlot:!0},setNextLineConfig:{replayLine:vf(Ds)}},Cn=e=>Of[e]??null,kf=e=>Cn(e)?.persistInSaveSlot===!0,Lf=(e,t)=>{let n=Cn(e)?.recordSources;return Array.isArray(n)&&n.includes(t)},$f=(e,t,n)=>{Cn(t)?.replayRecorded?.(e,n)},Ns=(e,t,n)=>{Cn(t)?.replayLine?.(e,n)},Tf=e=>e?.returnable!==!1,Ps=(e,t)=>{if(t>=0)return e.currentIndex+t;let n=Math.abs(t);for(let r=e.currentIndex-1;r>=0;r-=1)if(Tf(e.timeline[r])&&(n-=1,n===0))return r;return-1},Vs=({state:e},t)=>{let{offset:n}=t;if(n===void 0||typeof n!="number")return console.warn("selectLineIdByOffset requires a numeric offset"),null;let r=e.contexts[e.contexts.length-1];if(!r)return null;let o=r.rollback;if(!Array.isArray(o?.timeline)||typeof o?.currentIndex!="number")return null;let i=Ps(o,n);if(i<0||i>=o.timeline.length)return null;let s=o.timeline[i];return{sectionId:s.sectionId,lineId:s.lineId}},js=({state:e})=>Vs({state:e},{offset:-1})!==null,Df=({state:e},t)=>{let{offset:n=-1}=t;if(n>=0)throw new Error("rollbackByOffset requires a negative offset");let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let o=tt(r,{compatibilityAnchor:!r.rollback}),i=Ps(o,n);return i<0||i>=o.timeline.length?e:Is(e,i)},Nf=({state:e},t)=>{let{sectionId:n,lineId:r}=t,o=e.contexts[e.contexts.length-1];if(!o)throw new Error("No context available for rollbackToLine");let i=tt(o,{compatibilityAnchor:!o.rollback}),l=i.timeline.slice(0,i.currentIndex+1).findLastIndex(a=>a.sectionId===n&&a.lineId===r);if(l===-1)throw new Error(`Line ${r} not found in section ${n} rollback timeline`);return l===i.currentIndex?e:Is(e,l)},Fs=e=>{let t=cd(e);return Do(t,{selectPendingEffects:ud,selectSkipMode:As,selectAutoMode:dd,selectIsChoiceVisible:vs,selectIsFormVisible:pd,selectActiveInteraction:Ae,selectActiveForm:Nt,selectDialogueUIHidden:ws,selectDialogueHistory:Es,selectConfirmDialog:fd,selectIsLineAccountViewed:Mr,selectIsResourceAccountViewed:gd,selectNextLineConfig:yd,selectSystemState:bd,selectAchievements:Id,selectAchievement:Ad,selectSaveSlotMap:Cs,selectSaveSlots:_d,selectSaveSlot:wd,selectRuntime:Br,selectRuntimeValue:Ed,selectAllVariables:In,selectCurrentPointer:Ie,selectSection:le,selectCurrentLine:An,selectPresentationState:Ss,selectAutoForwardTimerDelay:wn,selectPresentationChanges:vd,selectSectionLineChanges:Sd,selectSaveSlotPage:Ur,selectCurrentPageSlots:Rd,selectRenderState:kd,selectOverlayStack:ld,selectLineIdByOffset:Vs,selectCanRollback:js,selectRollbackCursor:ed,startAutoMode:Rs,stopAutoMode:Pt,toggleAutoMode:jd,startSkipMode:Os,stopSkipMode:Me,toggleSkipMode:Fd,showDialogueUI:vn,hideDialogueUI:ks,toggleDialogueUI:Md,setDialogueTextSpeed:Bd,setAutoForwardDelay:Ud,setAutoForwardSpeed:zd,setSkipUnseenText:qd,setSkipTransitionsAndAnimations:Hd,setSoundVolume:Wd,setMusicVolume:Yd,setMuteAll:Gd,setSaveLoadPagination:Kd,incrementSaveLoadPagination:Jd,decrementSaveLoadPagination:Xd,setMenuPage:Qd,setMenuEntryPoint:Zd,showConfirmDialog:Ld,hideConfirmDialog:$d,resetStoryAtSection:of,clearPendingEffects:ef,appendPendingEffect:tf,completeAchievement:nf,setAchievementProgress:rf,beginRollbackActionBatch:od,endRollbackActionBatch:id,markRollbackCheckpointTransient:td,markSavedRollbackCheckpointTransient:nd,addViewedLine:af,addViewedResource:cf,setNextLineConfig:Ds,saveSlot:lf,loadSlot:uf,updateProjectData:df,sectionTransition:mf,jumpToLine:ff,nextLine:pf,markLineCompleted:hf,rollbackToLine:Nf,rollbackByOffset:Df,pushOverlay:Td,popOverlay:Dd,replaceLastOverlay:Nd,clearOverlays:Pd,updateFormField:Af,submitForm:wf,cancelForm:Ef,updateVariable:xf,nextLineFromSystem:gf},{transformActionFirstArgument:r=>({state:r}),transformSelectorFirstArgument:r=>({state:r})})};var Pf="route-engine",Vf="projectPersistence";var Bs=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),ee=e=>Object.prototype.toString.call(e)==="[object Object]",Ms="variables.",jf=(e={})=>{let t=ee(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(n=>typeof n=="string"||typeof n=="number"?{sectionId:String(n)}:!ee(n)||typeof n.sectionId!="string"||n.sectionId.length===0?null:{sectionId:n.sectionId,...typeof n.lineId=="string"?{lineId:n.lineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(n=>typeof n=="string"||typeof n=="number"?{resourceId:String(n)}:!ee(n)||typeof n.resourceId!="string"||n.resourceId.length===0?null:{resourceId:n.resourceId}).filter(Boolean)}},Ff=(e={})=>{let t=ee(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(n=>typeof n=="string"||typeof n=="number"?{sectionId:String(n)}:!ee(n)||typeof n.sectionId!="string"||n.sectionId.length===0?null:{sectionId:n.sectionId,...typeof n.lastLineId=="string"?{lastLineId:n.lastLineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(n=>typeof n=="string"||typeof n=="number"?{resourceId:String(n)}:!ee(n)||typeof n.resourceId!="string"||n.resourceId.length===0?null:{resourceId:n.resourceId}).filter(Boolean)}},Mf=(e,t)=>{let n=Ff(e),r=jf(t),o=n.sections.map(s=>({...s})),i=n.resources.map(s=>({...s}));return r.sections.forEach(s=>{let l=o.find(a=>a.sectionId===s.sectionId);if(!l){o.push({sectionId:s.sectionId,...s.lineId===void 0?{}:{lastLineId:s.lineId}});return}if(l.lastLineId!==void 0){if(s.lineId===void 0){delete l.lastLineId;return}l.lastLineId=s.lineId}}),r.resources.forEach(s=>{i.find(a=>a.resourceId===s.resourceId)||i.push({...s})}),{sections:o,resources:i}},Us=(e={})=>{let t=ee(e)?e:{};return{saveSlots:ee(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:ee(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:ee(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:ee(t.globalRuntime)?t.globalRuntime:{},accountViewedRegistry:ee(t.accountViewedRegistry)?t.accountViewedRegistry:{}}},Bf=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((t,n)=>{if(!ee(t))throw new Error(`Malformed applyScopedDataUpdates.updates[${n}] entry.`);let r=t.path?.startsWith(Ms)?t.path.slice(Ms.length):null;if(r!==null){if(!["device","account"].includes(t.scope))throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${n}].`);if(r.length===0)throw new Error(`Malformed applyScopedDataUpdates path "${t.path}" at updates[${n}].`);if(t.op!=="set")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${n}].`);return{scope:t.scope,path:t.path,op:t.op,value:t.value,variableId:r}}if(t.path==="viewedRegistry"){if(t.scope!=="account")throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${n}].`);if(t.op!=="markViewed")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${n}].`);return t}throw typeof t.path!="string"?new Error(`Malformed applyScopedDataUpdates path at updates[${n}].`):new Error(`Unsupported applyScopedDataUpdates path "${t.path}" at updates[${n}].`)})},Uf=(e,t)=>{let n={};return Bf(t).forEach(r=>{if(r.path==="viewedRegistry"){n.accountViewedRegistry=Mf(n.accountViewedRegistry??e.accountViewedRegistry,r.value);return}let o=r.scope==="device"?"globalDeviceVariables":"globalAccountVariables";n[o]={...e[o],...n[o],[r.variableId]:r.value}}),n},Hr=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},zf=e=>{let t=Hr(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},qf=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},Hf=({indexedDB:e,databaseName:t,objectStoreName:n})=>new Promise((r,o)=>{let i=e.open(t,1);i.onupgradeneeded=()=>{let s=i.result;s.objectStoreNames.contains(n)||s.createObjectStore(n,{keyPath:"namespace"})},i.onsuccess=()=>{r(i.result)},i.onerror=()=>{o(i.error??new Error(`Failed to open IndexedDB database "${t}".`))}}),Wf=async({databasePromise:e,objectStoreName:t,namespace:n})=>{let r=await e;return new Promise((o,i)=>{let a=r.transaction(t,"readonly").objectStore(t).get(n);a.onsuccess=()=>{o(a.result??null)},a.onerror=()=>{i(a.error??new Error(`Failed to read persisted namespace "${n}" from IndexedDB.`))}})},jt=async({databasePromise:e,objectStoreName:t,namespace:n,patch:r})=>{let o=await e;return new Promise((i,s)=>{let l=o.transaction(t,"readwrite"),a=l.objectStore(t),c=a.get(n),u=!1,d=p=>{u||(u=!0,s(p))},f=()=>{u||(u=!0,i())};c.onerror=()=>{d(c.error??new Error(`Failed to read persisted namespace "${n}" before updating IndexedDB.`))},c.onsuccess=()=>{let p=Us(c.result),h=typeof r=="function"?r(p):r,g={namespace:n,version:1,...Bs(),...p,...h},b=a.put(g);b.onerror=()=>{d(b.error??new Error(`Failed to persist namespace "${n}" to IndexedDB.`))}},l.oncomplete=()=>{f()},l.onerror=()=>{d(l.error??new Error(`IndexedDB transaction failed while updating namespace "${n}".`))},l.onabort=()=>{d(l.error??new Error(`IndexedDB transaction aborted while updating namespace "${n}".`))}})},Yf=async({databasePromise:e,objectStoreName:t,namespace:n})=>{let r=await e;return new Promise((o,i)=>{let s=r.transaction(t,"readwrite"),a=s.objectStore(t).delete(n),c=!1,u=f=>{c||(c=!0,i(f))},d=()=>{c||(c=!0,o())};a.onerror=()=>{u(a.error??new Error(`Failed to clear persisted namespace "${n}" from IndexedDB.`))},s.oncomplete=()=>{d()},s.onerror=()=>{u(s.error??new Error(`IndexedDB transaction failed while clearing namespace "${n}".`))},s.onabort=()=>{u(s.error??new Error(`IndexedDB transaction aborted while clearing namespace "${n}".`))}})},Wr=(e={})=>{let{indexedDB:t,databaseName:n=Pf,objectStoreName:r=Vf,namespace:o}=e,i=qf(t),s=zf(o),l=Hf({indexedDB:i,databaseName:n,objectStoreName:r});return{namespace:s,load:async()=>{let a=await Wf({databasePromise:l,objectStoreName:r,namespace:s});return{...Bs(),...Us(a)}},clear:async()=>Yf({databasePromise:l,objectStoreName:r,namespace:s}),saveSlots:async a=>jt({databasePromise:l,objectStoreName:r,namespace:s,patch:{saveSlots:ee(a)?a:{}}}),saveGlobalDeviceVariables:async a=>jt({databasePromise:l,objectStoreName:r,namespace:s,patch:{globalDeviceVariables:ee(a)?a:{}}}),saveGlobalAccountVariables:async a=>jt({databasePromise:l,objectStoreName:r,namespace:s,patch:{globalAccountVariables:ee(a)?a:{}}}),saveGlobalRuntime:async a=>jt({databasePromise:l,objectStoreName:r,namespace:s,patch:{globalRuntime:ee(a)?a:{}}}),applyScopedDataUpdates:async a=>jt({databasePromise:l,objectStoreName:r,namespace:s,patch:c=>Uf(c,a)})}},Gf=Wr;var Kf=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),Jf=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),zs="conditional",Kr=Symbol("conditionalAutoContinue"),Xf=new Set(["sectionTransition","resetStoryAtSection"]),Qf=new Set(["nextLine","nextLineFromSystem","resetStoryAtSection","sectionTransition"]),Zf=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),Yr="form",ep=new Set(["submitForm","cancelForm"]),Ft=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Sn=e=>e?.type===Kr,Gr=(e,t)=>e?.sectionId===t?.sectionId&&e?.lineId===t?.lineId;function Jr(e){let t,n=0,r=null,o=0,i=!1,s=0,l=[],a=null,c=new Map,u=new Map,d=new Map,{handlePendingEffects:f}=e,p=(y=new Map,I=Date.now())=>new Map(Array.from(y.entries()).filter(([,x])=>I<x.expiresAt).map(([x,_])=>[x,{animation:structuredClone(_.animation),startedAt:_.startedAt,expiresAt:_.expiresAt}])),h=(y=new Map)=>Array.from(y.values()).map(I=>structuredClone(I.animation)),g=(y=Date.now())=>{c=new Map(Array.from(c.entries()).filter(([,I])=>y<I.expiresAt))},b=()=>{if(!(o>0||i)){i=!0;try{for(;t.selectPendingEffects().length>0;){let y=[...t.selectPendingEffects()];t.clearPendingEffects();try{f(y)}catch(I){throw t.clearPendingEffects(),y.forEach(x=>{t.appendPendingEffect(x)}),I}}}finally{i=!1}}},A=y=>{o+=1;try{return y()}finally{o-=1,b()}},w=({initialState:y,namespace:I})=>{t=Fs(y),n=0,r=Hr(I),o=0,i=!1,s=0,l=[],a=null,c=new Map,u=new Map,d=new Map,t.appendPendingEffect({name:"handleLineActions"}),b()},C=()=>r,R=()=>t.selectPresentationState(),V=()=>t.selectPresentationChanges(),j=y=>t.selectSectionLineChanges(y),E=(y={})=>{n+=1;let I=Date.now();g(I);let x=u.size>0,_=p(c,I),D=x?p(u,I):new Map,q={...t.selectRenderState({activePersistentAnimations:h(_),restoredPersistentAnimations:h(D)}),id:`render-${n}`};return d.set(q.id,{builtAt:I,persistentAnimationSessions:new Map([...D.entries(),..._.entries()]),usedRestoredPersistentAnimationSessions:x}),q},B=(y={})=>E(y),U=(y={})=>E(y),J=y=>{let I=typeof y?.id=="string"&&y.id.length>0?y.id:null,x=I?d.get(I):null;I&&d.delete(I);let _=new Map;di(y?.animations).forEach(D=>{let H=ln(D);if(!H)return;let q=x?.persistentAnimationSessions?.get(H)??c.get(H),rt=Math.max(0,pi(D)),yt=q?.startedAt??x?.builtAt??Date.now();_.set(H,{animation:structuredClone(D),startedAt:yt,expiresAt:yt+rt})}),c=_,x?.usedRestoredPersistentAnimationSessions&&(u=new Map)},M=()=>t.selectSystemState(),Y=()=>t.selectAchievements(),G=y=>t.selectAchievement(y),X=()=>t.selectSaveSlotMap(),ve=y=>t.selectSaveSlot(y),te=y=>t.selectSaveSlotPage(y),ne=()=>t.selectSkipMode(),ue=()=>t.selectAutoMode(),de=()=>t.selectRuntime(),Q=()=>t.selectIsChoiceVisible(),re=()=>t.selectIsFormVisible(),fe=()=>t.selectActiveInteraction(),S=()=>t.selectPendingEffects().some(y=>y?.name==="handleLineActions"||y?.name==="render"),O=(y,I,x={})=>!Ft(I)||y!=="nextLine"?I:x.bypassChoice===!0?{...I,bypassChoice:!0}:x.interactionSource===Yr?{...I,_interactionSource:Yr}:I,F=(y={})=>({type:Kr,payload:O("nextLine",{_conditionalContinuation:!0},y)}),oe=(y,I)=>Sn(y)?{type:Kr,payload:{...y.payload,...I.payload}}:I,ie=y=>{y.savedCheckpointOccurrences.forEach(I=>{t.markSavedRollbackCheckpointTransient(I)}),y.savedCheckpointOccurrences=[]},z=(y,I)=>{let x=a;return a=null,!x||!Gr(x.pointer,y)||x.checkpointIndex!==I?.checkpointIndex||x.checkpointIdentity!==I?.checkpoint?[]:x.savedCheckpointOccurrences},Le=y=>{y.markCurrentCheckpointTransient&&(t.markRollbackCheckpointTransient({checkpointIndex:y.rollbackCursor?.checkpointIndex,checkpointIdentity:y.rollbackCursor?.checkpoint,sectionId:y.pointer?.sectionId,lineId:y.pointer?.lineId}),ie(y))},nt=(y,I,x)=>Qf.has(y)?y==="resetStoryAtSection"?x?.checkpoint!==I?.checkpoint:x?.checkpoint!==I?.checkpoint&&x?.checkpointIndex>I?.checkpointIndex:!1,Ws=y=>{let I=l.at(-1);if(!I?.markCurrentCheckpointTransient)return;let x=t.selectSaveSlot({slotId:y?.slotId});x&&I.savedCheckpointOccurrences.push({slotId:y.slotId,saveSlotIdentity:x,checkpointIndex:I.rollbackCursor?.checkpointIndex,sectionId:I.pointer?.sectionId,lineId:I.pointer?.lineId})},Ys=(y,I,x)=>{let _=l.at(-1);if(!_)return;let D=t.selectCurrentPointer()?.pointer,H=nt(y,I,x);if(Gr(_.pointer,D)){let q=x?.checkpoint!==I?.checkpoint||x?.checkpointIndex!==I?.checkpointIndex;(H||q&&Zf.has(y))&&(Le(_),_.pointer=D,_.rollbackCursor=x,_.markCurrentCheckpointTransient=H,_.savedCheckpointOccurrences=[]);return}Le(_),_.pointer=D,_.rollbackCursor=t.selectRollbackCursor?.()??null,_.markCurrentCheckpointTransient=H,_.savedCheckpointOccurrences=[]},Mt=(y,I)=>{if(!t[y])return;Xf.has(y)&&(s+=1),Kf.has(y)&&(Jf.has(y)?u=p(c):u=new Map,c=new Map);let x=t.selectRollbackCursor?.()??null,_=t[y](I),D=t.selectRollbackCursor?.()??null;return y==="saveSlot"&&Ws(I),Ys(y,x,D),b(),_},Gs=(y,I,x)=>{let _=t.selectCurrentPointer()?.pointer;I!==_||x!==s||(t.appendPendingEffect({name:"clearAutoNextTimer"}),t.appendPendingEffect({name:"clearNextLineConfigTimer"}),Mt("nextLineFromSystem",y.payload))},Qr=(y,I={})=>A(()=>{let x,_=t.selectCurrentPointer()?.pointer??null,D=t.selectRollbackCursor?.()??null,H=s,q={pointer:_,rollbackCursor:D,markCurrentCheckpointTransient:I.rollbackSource==="line",savedCheckpointOccurrences:I.savedCheckpointOccurrences?.slice()??[]};l.push(q);try{t.beginRollbackActionBatch({source:I.rollbackSource});try{x=y()}finally{t.endRollbackActionBatch({})}Sn(x)&&Gs(x,_,H)}finally{l.pop(),(!Gr(_,q.pointer)||D?.checkpoint!==q.rollbackCursor?.checkpoint)&&q.markCurrentCheckpointTransient&&q.savedCheckpointOccurrences.length>0&&(a={pointer:q.pointer,checkpointIndex:q.rollbackCursor?.checkpointIndex,checkpointIdentity:q.rollbackCursor?.checkpoint,savedCheckpointOccurrences:q.savedCheckpointOccurrences})}}),Zr=(y,I,x,_={})=>{if(y===zs)return Qr(()=>{let D=Rn(x),H=rr({[y]:I},D);return eo(H[y],x,_)},_);Mt(y,I)},Ks=(y,I)=>{Zr(y,I)},Rn=y=>{if(!y)return{variables:t.selectAllVariables?t.selectAllVariables():void 0,runtime:t.selectRuntime?t.selectRuntime():{}};if(Object.prototype.hasOwnProperty.call(y,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:I,...x}=y,_=t.selectAllVariables?t.selectAllVariables():void 0;return{...x,_event:I,variables:_,runtime:t.selectRuntime?t.selectRuntime():{}}},Js=y=>{if(!Ft(y))throw new Error("conditional action payload must be an object");if(!Array.isArray(y.branches))throw new Error("conditional action requires branches array");if(y.branches.length===0)throw new Error("conditional action requires at least one branch")},Xs=(y,I,x)=>{if(!Ft(y))throw new Error(`conditional branch at index ${I} must be an object`);if(!Ft(y.actions))throw new Error(`conditional branch at index ${I} requires actions object`);if(!Object.prototype.hasOwnProperty.call(y,"when")&&I!==x-1)throw new Error("conditional else branch must be the last branch")},eo=(y,I,x)=>{Js(y);let _=F(x);for(let D=0;D<y.branches.length;D+=1){let H=y.branches[D];Xs(H,D,y.branches.length);let q=Rn(I);if(Object.prototype.hasOwnProperty.call(H,"when")&&!vt(H.when,q))continue;let yt=On(H.actions,I,x);return Sn(yt)?oe(_,yt):_}return _},Qs=(y,I)=>({...y??{},_form:I}),Zs=(y,I,x,_)=>{let D=Mt(y,I),H=D?.submitted===!0&&D.valid===!0,q=D?.cancelled===!0;if(!(!H&&!q)&&Ft(I.actions))return On(I.actions,Qs(x,D.form),{..._,interactionSource:Yr})},ea=(y,I,x,_)=>{let D=Rn(x),q=rr({[y]:I},D)[y];if(y===zs)return eo(q,x,_);let rt=O(y,q,_);if(ep.has(y))return Zs(y,rt,x,_);Mt(y,rt)},On=(y,I,x)=>{let _;return Object.entries(y).forEach(([D,H])=>{let q=ea(D,H,I,x);Sn(q)&&(_=oe(_,q))}),_},to=(y,I,x={})=>Qr(()=>On(y,I,x),x),ta=y=>{let I=t.selectCurrentPointer()?.pointer;if(y!==I||t.selectActiveInteraction())return;let x=t.selectNextLineConfig();x?.auto?.enabled&&x.auto.trigger==="fromStart"&&t.appendPendingEffect({name:"nextLineConfigTimer",payload:{delay:x.auto.delay}})};return{init:w,handleAction:Zr,handleInternalAction:Ks,handleActions:to,selectRenderState:B,prepareRenderState:U,commitRenderState:J,selectPresentationState:R,selectPresentationChanges:V,selectSectionLineChanges:j,selectSystemState:M,selectAchievements:Y,selectAchievement:G,selectSaveSlotMap:X,selectSaveSlot:ve,selectSaveSlotPage:te,selectSaveSlots:X,selectRuntime:de,selectIsChoiceVisible:Q,selectIsFormVisible:re,selectActiveInteraction:fe,selectHasPendingRenderWork:S,handleLineActions:()=>A(()=>{let y=t.selectCurrentPointer()?.pointer,I=t.selectRollbackCursor?.()??null,x=z(y,I),_=t.selectCurrentLine(),D=!1;return _?.actions&&(to(_.actions,void 0,{rollbackSource:"line",savedCheckpointOccurrences:x}),D=!0),ta(y),D}),getNamespace:C}}var Xr=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:n=>{e=n},addElapsed:n=>{e+=n},getCallback:()=>t,setCallback:n=>{t=n}}},tp=80,Hs=({engine:e,routeGraphics:t,trackRenderDispatch:n},r)=>{if(e.selectHasPendingRenderWork?.())return;let o=e.prepareRenderState?.(r)??e.selectRenderState(r);n?.(o),t.render(o),e.commitRenderState?.(o)},np=({engine:e,routeGraphics:t,trackRenderDispatch:n,getRenderDispatchCount:r},o)=>{let i=r?.()??0,s=e.handleLineActions();(r?.()??0)===i&&Hs({engine:e,routeGraphics:t,trackRenderDispatch:n},o)},rp=({engine:e,ticker:t,autoTimer:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let l=r.delay??1e3;n.getElapsed()>=l&&(t.remove(i),n.setCallback(null),n.setElapsed(0),_n(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},op=({ticker:e,autoTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},ip=({engine:e,ticker:t,skipTimer:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let l=r?.delay??tp;n.getElapsed()>=l&&(n.setElapsed(0),_n(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},sp=({ticker:e,skipTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},ap=({engine:e,ticker:t,nextLineConfigTimerState:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let l=r.delay??1e3;n.getElapsed()>=l&&(n.setElapsed(0),_n(e,"nextLineFromSystem",{}),t.remove(i),n.getCallback()===i&&n.setCallback(null))};n.setCallback(i),t.add(i)},cp=({ticker:e,nextLineConfigTimerState:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},lp=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveSlots(t?.saveSlots))},up=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalDeviceVariables(t?.globalDeviceVariables))},dp=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalAccountVariables(t?.globalAccountVariables))},fp=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalRuntime(t?.globalRuntime))},pp=({enqueuePersistenceWrite:e},t)=>{e(n=>{if(typeof n.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return n.applyScopedDataUpdates(t?.updates)})},qs={render:Hs,saveSlots:lp,saveGlobalDeviceVariables:up,saveGlobalAccountVariables:dp,saveGlobalRuntime:fp,applyScopedDataUpdates:pp,handleLineActions:np,startAutoNextTimer:rp,clearAutoNextTimer:op,startSkipNextTimer:ip,clearSkipNextTimer:sp,nextLineConfigTimer:ap,clearNextLineConfigTimer:cp},hp=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),_n=(e,t,n)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,n)},mp=(e=[])=>{let t=new Set,n=[];for(let r=e.length-1;r>=0;r-=1){let o=e[r];if(typeof o?.name!="string"||o.name.length===0)throw new Error("Pending effect is missing a valid name.");if(!hp.has(o.name)){n.unshift(o);continue}t.has(o.name)||(t.add(o.name),n.unshift(o))}return n},gp=({getEngine:e,routeGraphics:t,ticker:n,handleUnhandledEffect:r,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:l})=>{let a=Xr(),c=Xr(),u=Xr(),d=s??null,f=Promise.resolve(),p=null,h=null,g=!1,b=0,A=S=>{if(o){o(S);return}console.error("RouteEngine persistence write failed.",S)},w=()=>{if(d)return d;let S=e();return d=Wr({indexedDB:i,namespace:l??S?.getNamespace?.()}),d},C=S=>{f=f.catch(()=>{}).then(()=>{let O=w();return S(O)}).catch(O=>{A(O)})},R=S=>{let O=typeof S?.id=="string"&&S.id.length>0?S.id:null;b+=1,p=O,g=!1},V=()=>b,j=(S={})=>{if(S?.aborted===!0)return!1;let O=typeof S?.id=="string"&&S.id.length>0?S.id:null;return O?O!==p||O===h?!1:(h=O,!0):p!==null||g?!1:(g=!0,!0)},E=(S,O={})=>{if(S!=="renderComplete"||!j(O))return!1;let F=e();return _n(F,"markLineCompleted",{}),!0},B=new Set(["updateFormField","submitForm","cancelForm"]),U=new Set(["updateVariable"]),J=S=>typeof S?.selectActiveInteraction=="function"?S.selectActiveInteraction():typeof S?.selectIsChoiceVisible=="function"&&S.selectIsChoiceVisible()?{source:"choice"}:null,M=S=>S?._formKey??S?.formKey,Y=(S,O)=>M(S)===O?.formKey,G=(S,O)=>!S||typeof S!="object"||Array.isArray(S)?!1:S._interactionSource===O?.source,X=(S,O)=>G(S,O)?O.source==="form"?Y(S,O):!0:!1,ve=(S,O)=>!S||typeof S!="object"||Array.isArray(S)||O?.source!=="form"?!1:Y(S,O),te=(S={})=>Object.keys(S).some(O=>B.has(O)),ne=(S={},O)=>Object.entries(S).some(([F,oe])=>B.has(F)&&ve(oe,O)),ue=(S={})=>Object.keys(S).length>0&&Object.keys(S).every(O=>U.has(O)),de=(S={},O)=>{let F=S?.actions;return O?.source==="form"?!F||typeof F!="object"||Array.isArray(F)?!1:ne(F,O)?!0:te(F)?!1:ue(F):X(S,O)?!0:!F||typeof F!="object"||Array.isArray(F)?!1:Object.values(F).some(oe=>X(oe,O))},Q=(S,O={})=>{if(!O?.actions)return!1;let F=J(S);return!F||F.source==="choice"?!1:!de(O,F)},re=({preprocessPayload:S,onEvent:O}={})=>async(F,oe={})=>{let ie=e();if(Q(ie,oe))return O?.(F,oe);let z=await S?.(F,oe)??oe;if(Q(ie,z))return O?.(F,z);if(E(F,z),z?.actions){let Le=z?._event?{_event:z._event}:z?.event?{_event:z.event}:void 0,nt;z?.bypassChoice===!0?nt={bypassChoice:!0}:z?._interactionSource&&(nt={interactionSource:z._interactionSource}),nt?ie.handleActions(z.actions,Le,nt):ie.handleActions(z.actions,Le)}return O?.(F,z)},fe=S=>{let O=e(),F=mp(S),oe=F.some(z=>z.name==="handleLineActions");F.forEach(z=>{if(!qs[z.name]&&!r)throw new Error(`Unhandled pending effect "${z.name}".`)});let ie={engine:O,routeGraphics:t,ticker:n,autoTimer:a,skipTimer:c,nextLineConfigTimerState:u,trackRenderDispatch:R,getRenderDispatchCount:V,enqueuePersistenceWrite:C};for(let z of F){if(oe&&z.name==="render")continue;let Le=qs[z.name];if(Le){Le(ie,z.payload);continue}r(z,ie)}};return fe.handleRouteGraphicsEvent=E,fe.createRouteGraphicsEventHandler=re,fe},yp=gp;var bp=(e,t={})=>{let{resources:n={}}=t;return Rr(e,n)};var Jh=Jr;export{ar as DEFAULT_VISUAL_LAYER,ct as RENDER_LAYER,_e as VISUAL_LAYER,yp as createEffectsHandler,Gf as createIndexedDbPersistence,Jh as default,er as formatDate,uc as resolveComputedVariables,bp as resolveLayoutReferences};
1
+ var wa=Object.defineProperty;var Ea=(e,t)=>{for(var n in t)wa(e,n,{get:t[n],enumerable:!0})};var go=Symbol.for("immer-nothing"),uo=Symbol.for("immer-draftable"),ge=Symbol.for("immer-state");function Ie(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var ct=Object.getPrototypeOf;function ae(e){return!!e&&!!e[ge]}function We(e){return e?yo(e)||Array.isArray(e)||!!e[uo]||!!e.constructor?.[uo]||Gt(e)||Kt(e):!1}var xa=Object.prototype.constructor.toString();function yo(e){if(!e||typeof e!="object")return!1;let t=ct(e);if(t===null)return!0;let n=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return n===Object?!0:typeof n=="function"&&Function.toString.call(n)===xa}function Un(e){return ae(e)||Ie(15,e),e[ge].base_}function qt(e,t){Yt(e)===0?Reflect.ownKeys(e).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function Yt(e){let t=e[ge];return t?t.type_:Array.isArray(e)?1:Gt(e)?2:Kt(e)?3:0}function Nn(e,t){return Yt(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function bo(e,t,n){let r=Yt(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function va(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Gt(e){return e instanceof Map}function Kt(e){return e instanceof Set}function He(e){return e.copy_||e.base_}function Pn(e,t){if(Gt(e))return new Map(e);if(Kt(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let n=yo(e);if(t===!0||t==="class_only"&&!n){let r=Object.getOwnPropertyDescriptors(e);delete r[ge];let o=Reflect.ownKeys(r);for(let i=0;i<o.length;i++){let s=o[i],l=r[s];l.writable===!1&&(l.writable=!0,l.configurable=!0),(l.get||l.set)&&(r[s]={configurable:!0,writable:!0,enumerable:l.enumerable,value:e[s]})}return Object.create(ct(e),r)}else{let r=ct(e);if(r!==null&&n)return{...e};let o=Object.create(r);return Object.assign(o,e)}}function Bn(e,t=!1){return Jt(e)||ae(e)||!We(e)||(Yt(e)>1&&(e.set=e.add=e.clear=e.delete=Ca),Object.freeze(e),t&&Object.entries(e).forEach(([n,r])=>Bn(r,!0))),e}function Ca(){Ie(2)}function Jt(e){return Object.isFrozen(e)}var Sa={};function Ye(e){let t=Sa[e];return t||Ie(0,e),t}var wt;function Io(){return wt}function Ra(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function fo(e,t){t&&(Ye("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Vn(e){jn(e),e.drafts_.forEach(_a),e.drafts_=null}function jn(e){e===wt&&(wt=e.parent_)}function po(e){return wt=Ra(wt,e)}function _a(e){let t=e[ge];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function ho(e,t){t.unfinalizedDrafts_=t.drafts_.length;let n=t.drafts_[0];return e!==void 0&&e!==n?(n[ge].modified_&&(Vn(t),Ie(4)),We(e)&&(e=Ht(t,e),t.parent_||Wt(t,e)),t.patches_&&Ye("Patches").generateReplacementPatches_(n[ge].base_,e,t.patches_,t.inversePatches_)):e=Ht(t,n,[]),Vn(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==go?e:void 0}function Ht(e,t,n){if(Jt(t))return t;let r=t[ge];if(!r)return qt(t,(o,i)=>mo(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Wt(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;let o=r.copy_,i=o,s=!1;r.type_===3&&(i=new Set(o),o.clear(),s=!0),qt(i,(l,a)=>mo(e,r,o,l,a,n,s)),Wt(e,o,!1),n&&e.patches_&&Ye("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function mo(e,t,n,r,o,i,s){if(ae(o)){let l=i&&t&&t.type_!==3&&!Nn(t.assigned_,r)?i.concat(r):void 0,a=Ht(e,o,l);if(bo(n,r,a),ae(a))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if(We(o)&&!Jt(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Ht(e,o),(!t||!t.scope_.parent_)&&typeof r!="symbol"&&Object.prototype.propertyIsEnumerable.call(n,r)&&Wt(e,o)}}function Wt(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&Bn(t,n)}function Oa(e,t){let n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:Io(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=r,i=zn;n&&(o=[r],i=Et);let{revoke:s,proxy:l}=Proxy.revocable(o,i);return r.draft_=l,r.revoke_=s,l}var zn={get(e,t){if(t===ge)return e;let n=He(e);if(!Nn(n,t))return ka(e,n,t);let r=n[t];return e.finalized_||!We(r)?r:r===Tn(e.base_,t)?(Dn(e),e.copy_[t]=Mn(r,e)):r},has(e,t){return t in He(e)},ownKeys(e){return Reflect.ownKeys(He(e))},set(e,t,n){let r=Ao(He(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){let o=Tn(He(e),t),i=o?.[ge];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(va(n,o)&&(n!==void 0||Nn(e.base_,t)))return!0;Dn(e),Fn(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return Tn(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,Dn(e),Fn(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let n=He(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){Ie(11)},getPrototypeOf(e){return ct(e.base_)},setPrototypeOf(){Ie(12)}},Et={};qt(zn,(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,n){return zn.set.call(this,e[0],t,n,e[0])};function Tn(e,t){let n=e[ge];return(n?He(n):e)[t]}function ka(e,t,n){let r=Ao(t,n);return r?"value"in r?r.value:r.get?.call(e.draft_):void 0}function Ao(e,t){if(!(t in e))return;let n=ct(e);for(;n;){let r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=ct(n)}}function Fn(e){e.modified_||(e.modified_=!0,e.parent_&&Fn(e.parent_))}function Dn(e){e.copy_||(e.copy_=Pn(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var $a=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){let i=n;n=t;let s=this;return function(a=i,...c){return s.produce(a,u=>n.call(this,u,...c))}}typeof n!="function"&&Ie(6),r!==void 0&&typeof r!="function"&&Ie(7);let o;if(We(t)){let i=po(this),s=Mn(t,void 0),l=!0;try{o=n(s),l=!1}finally{l?Vn(i):jn(i)}return fo(i,r),ho(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===go&&(o=void 0),this.autoFreeze_&&Bn(o,!0),r){let i=[],s=[];Ye("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else Ie(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,a=>t(a,...l));let r,o;return[this.produce(t,n,(s,l)=>{r=s,o=l}),r,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){We(e)||Ie(8),ae(e)&&(e=Ge(e));let t=po(this),n=Mn(e,void 0);return n[ge].isManual_=!0,jn(t),n}finishDraft(e,t){let n=e&&e[ge];(!n||!n.isManual_)&&Ie(9);let{scope_:r}=n;return fo(r,t),ho(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){let o=t[n];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}n>-1&&(t=t.slice(n+1));let r=Ye("Patches").applyPatches_;return ae(e)?r(e,t):this.produce(e,o=>r(o,t))}};function Mn(e,t){let n=Gt(e)?Ye("MapSet").proxyMap_(e,t):Kt(e)?Ye("MapSet").proxySet_(e,t):Oa(e,t);return(t?t.scope_:Io()).drafts_.push(n),n}function Ge(e){return ae(e)||Ie(10,e),wo(e)}function wo(e){if(!We(e)||Jt(e))return e;let t=e[ge],n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=Pn(e,t.scope_.immer_.useStrictShallowCopy_)}else n=Pn(e,!0);return qt(n,(r,o)=>{bo(n,r,wo(o))}),t&&(t.finalized_=!1),n}var ye=new $a,qn=ye.produce,Hp=ye.produceWithPatches.bind(ye),Wp=ye.setAutoFreeze.bind(ye),Yp=ye.setUseStrictShallowCopy.bind(ye),Gp=ye.applyPatches.bind(ye),Kp=ye.createDraft.bind(ye),Jp=ye.finishDraft.bind(ye);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},k={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},lt={NOT:0};var C=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},me=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var Hn=e=>{if(!e||e.trim()==="")throw new C("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let n=e.includes("===")?"==":"!=";throw new C(`Invalid comparison operator '${e.includes("===")?"===":"!=="}' - did you mean '${n}'? (got: '${e}')`)}let t=["<",">","<=",">=","==","!="];for(let n of t)if(e.trim().endsWith(n))throw new C(`Incomplete comparison expression - missing right operand (got: '${e}')`)},Eo=e=>{if(e.trim().endsWith(" in"))throw new C(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new C(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,n]=e.split(" in ");if(!n||n.trim()==="")throw new C(`Missing iterable expression after 'in' (got: '$for ${e}')`);let r=t.includes(",")?t.split(",").map(o=>o.trim()):[t.trim()];for(let o of r){if(!o)throw new C(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new C(`Invalid loop syntax (got: '$for ${e}')`)}};var xo=(e,t,n=!1)=>{if(t===null)return new me(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new me(`Cannot iterate over undefined value at '$for ${e}'`);let r=typeof t;return n?new me(`Cannot iterate over non-array value in loop '${e}' - got ${r} instead`):new me(`Cannot iterate over non-array value (got: ${r}) at '$for ${e}'`)},vo=(e,t)=>{let n=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new me(`Unknown function '${e}' (${n})`)};var La=(e,t,n={})=>{let r={},o={};n&&typeof n=="object"&&(n.functions!==void 0||n.partials!==void 0?(r=n.functions||{},o=n.partials||{}):typeof n=="object"&&(r=n));let s=L(e,{functions:r,partials:o},t,{});return s===void 0?{}:s},L=(e,t,n,r)=>{let o=t.functions||t;if(e.var&&!e.type)return J(e.var,n,r);if(e.type===m.LITERAL)return e.value;if(e.type===m.VARIABLE)return J(e.path,n,r);if(e.type===m.INTERPOLATION)return Da(e.parts,t,n,r);switch(e.type){case m.FUNCTION:return So(e,t,n,r);case m.BINARY:return Ro(e,t,n,r);case m.UNARY:return _o(e,t,n,r);case m.CONDITIONAL:return Pa(e,t,n,r);case m.LOOP:return Ua(e,t,n,r);case m.OBJECT:return za(e,t,n,r);case m.ARRAY:return qa(e,t,n,r);case m.PARTIAL:return Ha(e,t,n,r);case m.PATH_REFERENCE:return Wa(e,t,n,r);default:throw new Error(`Unknown node type: ${e.type}`)}},Co=new Map,Ta=e=>{let t=[],n="",r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(i==="[")n&&(t.push({type:"property",value:n}),n=""),r=!0;else if(i==="]"){if(r&&n){let s=n.trim();if(/^\d+$/.test(s))t.push({type:"index",value:parseInt(s,10)});else if(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'")){let l=s.slice(1,-1);t.push({type:"property",value:l})}else t.push({type:"property",value:s});n=""}r=!1}else n+=i}return n&&t.push({type:"property",value:n}),t},J=(e,t,n)=>{if(!e)return;if(e in n)return n[e];let r=Co.get(e);if(!r){let i=[],s="",l=0;for(let a=0;a<e.length;a++){let c=e[a];c==="["?(l++,s+=c):c==="]"?(l--,s+=c):c==="."&&l===0?s&&(i.push(s),s=""):s+=c}s&&i.push(s),r=[];for(let a of i){let c=Ta(a.trim());r.push(...c)}Co.set(e,r)}let o=t;for(let i=0;i<r.length;i++){let s=r[i];if(s.type==="property"&&s.value in n){o=n[s.value];continue}if(o==null)return;(s.type==="property"||s.type==="index")&&(o=o[s.value])}return o},Da=(e,t,n,r)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=L(i,t,n,r);o.push(s!=null?String(s):"")}return o.join("")},So=(e,t,n,r)=>{let o=t.functions||t,i=o[e.name];if(!i)throw vo(e.name,o);let s=e.args.map(l=>L(l,t,n,r));return i(...s)},Pe=(e,t,n,r)=>{if(e.var&&!e.type)return J(e.var,n,r);switch(e.type){case m.VARIABLE:return J(e.path,n,r);case m.LITERAL:return e.value;case m.BINARY:return Ro(e,t,n,r);case m.UNARY:return _o(e,t,n,r);case m.FUNCTION:return So(e,t,n,r);default:return L(e,t,n,r)}},Ro=(e,t,n,r)=>{if(e.op===k.AND||e.op===k.OR){let s=Pe(e.left,t,n,r),l=Pe(e.right,t,n,r);switch(e.op){case k.AND:return s&&l;case k.OR:return s||l}}let o=L(e.left,t,n,r),i=L(e.right,t,n,r);switch(e.op){case k.EQ:return o==i;case k.NEQ:return o!=i;case k.GT:return o>i;case k.LT:return o<i;case k.GTE:return o>=i;case k.LTE:return o<=i;case k.IN:return Array.isArray(i)?i.includes(o):!1;case k.ADD:if(typeof o!="number"||typeof i!="number")throw new me(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case k.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new me(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},_o=(e,t,n,r)=>{let o=e.op===lt.NOT?Pe(e.operand,t,n,r):L(e.operand,t,n,r);if(e.op===lt.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},Na=(e,t,n,r)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===m.VARIABLE)if(J(o.path,n,r)){let s=e.bodies[0];if(s.type===m.OBJECT&&s.properties.length<=5){let l={};for(let a of s.properties){let c=a.parsedKey?L(a.parsedKey,t,n,r):a.key,u=a.value;if(u.type===m.LITERAL)l[c]=u.value;else if(u.type===m.VARIABLE)l[c]=J(u.path,n,r);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=J(f.path,n,r);d.push(p!=null?String(p):"")}else{let p=L(f,t,n,r);d.push(p!=null?String(p):"")}l[c]=d.join("")}else l[c]=L(u,t,n,r)}return l}}else{let s=e.bodies[1];if(s.type===m.OBJECT&&s.properties.length<=5){let l={};for(let a of s.properties){let c=a.parsedKey?L(a.parsedKey,t,n,r):a.key,u=a.value;if(u.type===m.LITERAL)l[c]=u.value;else if(u.type===m.VARIABLE)l[c]=J(u.path,n,r);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=J(f.path,n,r);d.push(p!=null?String(p):"")}else{let p=L(f,t,n,r);d.push(p!=null?String(p):"")}l[c]=d.join("")}else l[c]=L(u,t,n,r)}return l}}}return null},Pa=(e,t,n,r)=>{let o=Na(e,t,n,r);if(o!==null)return o;for(let i=0;i<e.conditions.length;i++){let s=e.conditions[i];if(s===null||Pe(s,t,n,r))return L(e.bodies[i],t,n,r)}return Oo},Va=(e,t)=>{let n=e.body,r=e.itemVar;if(n.type===m.CONDITIONAL&&n.conditions.length===1&&n.conditions[0].type===m.VARIABLE){let o=n.conditions[0].path,i=n.bodies[0];if(o.startsWith(r+".")){let s=o.substring(r.length+1);if(i.type===m.OBJECT&&i.properties.length<=5){for(let a of i.properties)if(a.parsedKey)return null;let l=[];for(let a=0;a<t.length;a++){let c=t[a];if(c[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===r)u[f]=c;else if(h.startsWith(r+".")){let g=h.substring(r.length+1);u[f]=c[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 I=y.path;if(I===r)h.push(c!=null?String(c):"");else if(I.startsWith(r+".")){let w=I.substring(r.length+1),E=c[w];h.push(E!=null?String(E):"")}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},ja=(e,t)=>{let n=e.body,r=e.itemVar,o=Va(e,t);if(o!==null)return o;if(n.type===m.OBJECT&&n.properties.length<=5&&!n.whenCondition){for(let l of n.properties)if(l.parsedKey)return null;let i=[],s=!0;for(let l of n.properties){let a=l.key,c=l.value;if(c.type===m.LITERAL)i.push({key:a,type:"literal",value:c.value});else if(c.type===m.VARIABLE){let u=c.path;if(u===r)i.push({key:a,type:"item"});else if(u.startsWith(r+".")){let d=u.substring(r.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:a,type:"prop",prop:d});else{s=!1;break}}else{s=!1;break}}else if(c.type===m.INTERPOLATION&&c.parts.length===1){let u=c.parts[0];if(u.type===m.VARIABLE){let d=u.path;if(d===r)i.push({key:a,type:"item_string"});else if(d.startsWith(r+".")){let f=d.substring(r.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:a,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 a=0;a<t.length;a++){let c=t[a];l[a]={id:c.id,title:c.title!=null?String(c.title):"",completed:c.completed}}else for(let a=0;a<t.length;a++){let c=t[a],u={};for(let d of i)if(d.type==="literal")u[d.key]=d.value;else if(d.type==="item")u[d.key]=c;else if(d.type==="prop")u[d.key]=c[d.prop];else if(d.type==="item_string")u[d.key]=c!=null?String(c):"";else if(d.type==="prop_string"){let f=c[d.prop];u[d.key]=f!=null?String(f):""}l[a]=u}return l}}return null},Fa=(e,t,n,r,o)=>{let i=[],s=e.body;if(s.type===m.OBJECT&&s.fast!==!1){let l=e.itemVar,a=e.indexVar;for(let c=0;c<o.length;c++){let u=o[c],d={},f={...r,[l]:u,...a&&{[a]:c}};f.__paths__||(f.__paths__=r.__paths__||{});let p=e.iterable.path||"";if(r&&r.__paths__&&p){let h=p.split("."),g=h[0];g in r.__paths__&&(p=r.__paths__[g],h.length>1&&(p+="."+h.slice(1).join(".")))}f.__paths__={...f.__paths__,[l]:`${p}[${c}]`,...a&&{[a]:c}};for(let h of s.properties){let g=h.parsedKey?L(h.parsedKey,t,n,f):h.key,y=h.value;if(y.type===m.LITERAL)d[g]=y.value;else if(y.type===m.VARIABLE){let I=y.path;if(I===l)d[g]=u;else if(I===a)d[g]=c;else if(I.startsWith(l+".")){let w=I.substring(l.length+1);!w.includes(".")&&!w.includes("[")?d[g]=u[w]:d[g]=J(I,n,{...r,[l]:u,...a&&{[a]:c}})}else d[g]=J(I,n,{...r,[l]:u,...a&&{[a]:c}})}else if(y.type===m.INTERPOLATION){let I=[];for(let w of y.parts)if(typeof w=="string")I.push(w);else if(w.type===m.VARIABLE){let E=w.path,_;if(E===l)_=u;else if(E===a)_=c;else if(E.startsWith(l+".")){let j=E.substring(l.length+1);!j.includes(".")&&!j.includes("[")?_=u[j]:_=J(E,n,{...r,[l]:u,...a&&{[a]:c}})}else _=J(E,n,{...r,[l]:u,...a&&{[a]:c}});I.push(_!=null?String(_):"")}else{let E={...r,[l]:u,...a&&{[a]:c}},_=L(w,t,n,E);I.push(_!=null?String(_):"")}d[g]=I.join("")}else{let I={...r,[l]:u,...a&&{[a]:c}};d[g]=L(y,t,n,I)}}i.push(d)}return i}return null},Ma=(e,t,n)=>{let r=e.body;if(r.type===m.OBJECT&&r.properties.length===1&&r.properties[0].key==="$if item.visible"){let i=r.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],a=s.properties[1];if(l.key==="id"&&l.value.type===m.VARIABLE&&l.value.path==="item.id"&&a.key==="$if item.highlighted"&&a.value.type===m.CONDITIONAL){let c=[];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),c.push(f)}}return c}}}}return null},Ua=(e,t,n,r)=>{let o=L(e.iterable,t,n,r);if(!Array.isArray(o)){let c,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(", ");c=`${e.iterable.name}(${f})`}else c=e.iterable.path||"undefined";let d=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${c}`;throw xo(d,o,u)}if(!e.indexVar){let c=Ma(e,o,e.itemVar);if(c!==null)return c}if(!e.indexVar){let c=ja(e,o);if(c!==null)return c}let i=Fa(e,t,n,r,o);if(i!==null)return i;let s=[],l=e.iterable.path||"";if(r&&r.__paths__&&l){let c=l.split("."),u=c[0];u in r.__paths__&&(l=r.__paths__[u],c.length>1&&(l+="."+c.slice(1).join(".")))}let a=!1;e.body.type===m.ARRAY&&(e.body.items.length<=1?a=!1:a=e.body._shouldPreserveArray??=e.body.items.some(c=>c.type===m.OBJECT&&c.properties.some(u=>u.key.startsWith("$if ")||u.key.startsWith("$when "))));for(let c=0;c<o.length;c++){let u=e.indexVar?{...r,[e.itemVar]:o[c],[e.indexVar]:c}:{...r,[e.itemVar]:o[c]};u.__paths__||(u.__paths__=r.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${l}[${c}]`},e.indexVar&&(u.__paths__[e.indexVar]=c);let d=L(e.body,t,n,u);if(Array.isArray(d)&&d.length===1&&!a){let f=d[0];s.push(f===void 0?{}:f)}else s.push(d===void 0?{}:d)}return s},Ba=(e,t,n,r)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?L(o.parsedKey,t,n,r):o.key,s=o.value;if(s.type===m.OBJECT&&s.properties.length<=10&&!s.whenCondition){let l={},a={},c=!0;for(let u of s.properties){let d=u.parsedKey?L(u.parsedKey,t,n,r):u.key,f=u.value;if(f.type===m.LITERAL)a[d]=f.value;else if(f.type===m.VARIABLE)a[d]=J(f.path,n,r);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=J(h.path,n,r);p.push(g!=null?String(g):"")}else{c=!1;break}if(!c)break;a[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]=J(y.path,n,r);else if(y.type===m.INTERPOLATION){let I=[];for(let w of y.parts)if(typeof w=="string")I.push(w);else if(w.type===m.VARIABLE){let E=J(w.path,n,r);I.push(E!=null?String(E):"")}else{c=!1;break}if(!c)break;p[g]=I.join("")}else{c=!1;break}}if(!c)break;a[d]=p}else{c=!1;break}}if(c)return l[i]=a,l}}return null},za=(e,t,n,r)=>{let o=t.functions||t;if(e.whenCondition&&!Pe(e.whenCondition,o,n,r))return;let i=Ba(e,t,n,r);if(i!==null)return i;if(e.fast){let c={};for(let u of e.properties){let d=u.parsedKey?L(u.parsedKey,t,n,r):u.key,f=u.value;if(f.type===m.LITERAL)c[d]=f.value;else if(f.type===m.VARIABLE)c[d]=J(f.path,n,r);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=J(h.path,n,r);p.push(g!=null?String(g):"")}else{let g=L(h,t,n,r);p.push(g!=null?String(g):"")}c[d]=p.join("")}else c[d]=L(f,t,n,r)}return c}let s={},l=null,a=!1;for(let c of e.properties)if(!c.key.startsWith("$if ")&&!c.key.match(/^\$if\s+\w+.*:?$/)&&!c.key.startsWith("$elif")&&!c.key.startsWith("$else")&&!c.key.startsWith("$for ")){a=!0;break}for(let c of e.properties)if(c.key.startsWith("$if ")||c.key.match(/^\$if\s+\w+.*:?$/)){let u=L(c.value,t,n,r);if(!a&&u!==null&&u!==void 0)return Array.isArray(u)&&u.length===1?u[0]:u;typeof u=="object"&&u!==null&&!Array.isArray(u)&&Object.assign(s,u)}else if(c.key.startsWith("$for ")){if(e.properties.length===1)return L(c.value,t,n,r)}else{let u=c.value;if(u&&u.type===m.OBJECT&&u.properties){let d=u.properties.find(f=>f.key.startsWith("$for "));if(d){let f=L(d.value,t,n,r);f!==void 0&&(s[c.key]=f)}else{let f=L(c.value,t,n,r);f!==void 0&&(s[c.key]=f)}}else{let d=c.parsedKey?L(c.parsedKey,t,n,r):c.key,f=L(c.value,t,n,r);f!==void 0&&(s[d]=f)}}return s},Oo={},qa=(e,t,n,r)=>{let o=[];for(let i of e.items)if(i.type===m.LOOP){let s=L(i,t,n,r);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=L(i,t,n,r);s!==Oo&&s!==void 0&&o.push(s)}return o},Ha=(e,t,n,r)=>{let{name:o,data:i,whenCondition:s}=e,l=t.partials||{},a=t.functions||t;if(s&&!Pe(s,a,n,r))return;if(!l[o])throw new me(`Partial '${o}' is not defined`);let c=r._partialStack||[];if(c.includes(o))throw new me(`Circular partial reference detected: ${o}`);let u=l[o],d=n,f={...r,_partialStack:[...c,o]};if(r){d={...n};for(let p of Object.keys(r))p.startsWith("_")||(d[p]=r[p])}if(i){let p=L(i,t,n,r);d={...d,...p}}return L(u,t,d,f)},Wa=(e,t,n,r)=>{let{path:o}=e,i=o.split("."),s=i[0],l=i.slice(1);if(!r||!(s in r))throw new me(`Path reference '#{${o}}' refers to '${s}' which is not a loop variable in the current scope`);if(r.__paths__||(r.__paths__={}),!(s in r.__paths__))throw new me(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let a=r.__paths__[s];if(typeof a=="number"){if(l.length>0)throw new me(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(a)}return l.length>0&&(a+="."+l.join(".")),a};var Wn=La;var Ya=/\$\{([^}]*)\}/g,Ga=/#\{([^}]*)\}/g,$o=(e,t={})=>{let n=e.match(/^(\w+)\((.*)\)$/);if(!n)return{isFunction:!1};let[,r,o]=n,i=Ka(o,t);return{isFunction:!0,type:m.FUNCTION,name:r,args:i}},Ka=(e,t={})=>e.trim()?Ja(e).map(r=>Xa(r.trim(),t)):[],Ja=e=>{let t=[],n="",r=0,o=!1,i="";for(let s=0;s<e.length;s++){let l=e[s],a=s>0?e[s-1]:"";!o&&(l==='"'||l==="'")?(o=!0,i=l,n+=l):o&&l===i&&a!=="\\"?(o=!1,i="",n+=l):!o&&l==="("?(r++,n+=l):!o&&l===")"?(r--,n+=l):!o&&l===","&&r===0?(t.push(n),n=""):n+=l}return n&&t.push(n),t},Xa=(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 n=$o(e,t);if(n.isFunction)return{type:n.type,name:n.name,args:n.args};let r=e.trim(),o=[{op:" + ",type:"ADD"},{op:" - ",type:"SUBTRACT"}],i=-1,s=null;for(let{op:l,type:a}of o){let c=0;for(;c<r.length;){let u=Ke(r.substring(c),l);if(u===-1)break;let d=c+u;d>i&&(i=d,s={op:l,type:a}),c=d+l.length}}if(i!==-1)try{return ee(r,t)}catch{return{type:m.VARIABLE,path:r}}return{type:m.VARIABLE,path:r}},Lo=/^\w+\(.*\)$/,Qa=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,Za=e=>{if(!(!e||e.trim()===""||Lo.test(e))&&Qa.test(e))throw e.includes("?")&&e.includes(":")?new C(`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 C(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new C(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},ko=e=>{let t=e.trim();if(Lo.test(t))throw new C(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new C(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new C(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new C(`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 C(`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}},xt=(e,t={})=>{let n=e.trim();Za(n);let r=$o(n,t);if(r.isFunction)return{type:r.type,name:r.name,args:r.args};if(n.includes("[")&&!/[\s+\-*/%|&?:]/.test(n)){let o=0;for(let i of n)i==="["?o++:i==="]"&&o--;if(o!==0)throw new Error("Invalid array index syntax")}return{type:m.VARIABLE,path:n}},Yn=(e,t={})=>{let n=e,r=[];(e.includes("\\${")||e.includes("\\#{"))&&(n=e.replace(/\\\\(\$\{[^}]*\})/g,"\\DOUBLE_ESC_VAR$1"),n=n.replace(/\\\\(#\{[^}]*\})/g,"\\DOUBLE_ESC_PATH$1"),n=n.replace(/\\(\$\{[^}]*\})/g,(c,u)=>{let d=`__ESCAPED_${r.length}__`;return r.push(u),d}),n=n.replace(/\\(#\{[^}]*\})/g,(c,u)=>{let d=`__ESCAPED_${r.length}__`;return r.push(u),d}),n=n.replace(/\\DOUBLE_ESC_VAR/g,"\\"),n=n.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...n.matchAll(Ya)],i=[...n.matchAll(Ga)],s=[...o.map(c=>({match:c,type:"variable"})),...i.map(c=>({match:c,type:"pathref"}))].sort((c,u)=>c.match.index-u.match.index);if(s.length===0){let c=n;for(let u=0;u<r.length;u++)c=c.replace(`__ESCAPED_${u}__`,r[u]);return{type:m.LITERAL,value:c}}if(s.length===1&&s[0].match[0]===n&&r.length===0){let{match:c,type:u}=s[0];try{return u==="variable"?xt(c[1],t):ko(c[1])}catch(d){if(d.message==="Invalid array index syntax")return{type:m.LITERAL,value:n};throw d}}let l=[],a=0;for(let{match:c,type:u}of s){let[d,f]=c,p=c.index;if(p>a){let h=n.substring(a,p);for(let g=0;g<r.length;g++)h=h.replace(`__ESCAPED_${g}__`,r[g]);h&&l.push(h)}try{let h;u==="variable"?h=xt(f.trim(),t):h=ko(f.trim()),l.push(h)}catch(h){if(h.message==="Invalid array index syntax")l.push(d);else throw h}a=p+d.length}if(a<n.length){let c=n.substring(a);for(let u=0;u<r.length;u++)c=c.replace(`__ESCAPED_${u}__`,r[u]);c&&l.push(c)}return{type:m.INTERPOLATION,parts:l}};var Jn=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),No=e=>Object.keys(e),ce=e=>e.join("."),Ve=(e,t,n)=>{let r=No(e).filter(o=>!t.has(o));if(r.length>0)throw new C(`Unexpected key '${r[0]}' in condition JSON at '${ce(n)}'`)},je=(e,t)=>typeof e=="string"?Yn(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?tc(e,t):nc(e,t):{type:m.LITERAL,value:e},ec=e=>{let{$each:t,...n}=e;if(typeof t!="string")throw new C("$each value must be a non-empty string");let r=t.trim();if(r==="")throw new C("$each value must be a non-empty string");if(Object.keys(n).length===0)throw new C("Empty $each body not allowed");if(n.$partial!==void 0)throw new C("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${r}`]:n}},tc=(e,t)=>{let n=[],r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(typeof i=="object"&&i!==null&&!Array.isArray(i)){if(i.$each!==void 0)try{let a=ec(i),c=Object.keys(a);if(c.length===1&&/^\$for(?::\w+)?\s/.test(c[0])){let u=Do(c[0],a[c[0]],t,!0);n.push(u),r=!0;continue}}catch(a){throw a instanceof C?a:new C(a.message)}let l=Object.keys(i);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let a=Do(l[0],i[l[0]],t);n.push(a),r=!0;continue}}let s=je(i,t);n.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)&&(r=!0)}return{type:m.ARRAY,items:n,fast:!r}},nc=(e,t)=>{let n=[],r=!1,o=null,i=Object.entries(e),s=0;if(e.$partial!==void 0){if(typeof e.$partial!="string")throw new C("$partial value must be a string");if(e.$partial.trim()==="")throw new C("$partial value cannot be an empty string");let a=["$if","$elif","$else","$for"],c=[];for(let[I]of i)for(let w of a)if(I===w||I.startsWith(w+" ")||I.startsWith(w+"#")){c.push(w);break}if(c.length>0)throw new C(`Cannot use $partial with ${c.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[I,w]of Object.entries(f)){let E=I;(I.startsWith("\\$")||I.startsWith("$$"))&&(E=I.slice(1)),p[E]=w,h=!0}let g=null;if(h&&(g=je(p,t),g.type===m.OBJECT)){let I=!1;for(let w of g.properties)if(w.value.type===m.VARIABLE||w.value.type===m.INTERPOLATION||w.value.type===m.FUNCTION||w.value.type===m.CONDITIONAL||w.value.type===m.OBJECT&&!w.value.fast||w.value.type===m.ARRAY&&!w.value.fast){I=!0;break}I&&(g.fast=!1)}let y={type:m.PARTIAL,name:u,data:g};return d!==void 0&&(y.whenCondition=To(d,t)),y}for(let[a,c]of i)if(a==="$when"){if(o!==null)throw new C("Multiple '$when' directives on the same object are not allowed");if(c==null)throw new C("Missing condition expression after '$when'");o=To(c,t),r=!0}else if(a.startsWith("$when#")||a.startsWith("$when "))throw new C("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<i.length;){let[a,c]=i[s];if(a==="$when"){s++;continue}if(a==="$each")throw new C("$each can only be used inside arrays");if(a.startsWith("$if ")||a.match(/^\$if#\w+\s/)||a.match(/^\$if\s+\w+.*:$/)){let u=rc(i,s,t);n.push({key:a,value:u.node}),r=!0,s=u.nextIndex}else if(/^\$for(?::\w+)?\s/.test(a)){let u=a.match(/^\$for(?::(\w+))?\s/)?.[1]||"",d=u?`:${u}`:"";throw new C(`$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(a.startsWith("$elif ")||a.startsWith("$else"))throw new C(`'${a.split(" ")[0]}' without matching '$if'`);if(a==="$if"||a==="$if:")throw new C("Missing condition expression after '$if'");{let u=je(c,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)&&(r=!0);let d=Yn(a,t),f={key:a,value:u};(d.type!==m.LITERAL||d.value!==a)&&(f.parsedKey=d),n.push(f),s++}}}let l={type:m.OBJECT,properties:n,fast:!r};return o&&(l.whenCondition=o),l},rc=(e,t,n={})=>{let r=[],o=[],i=t,[s,l]=e[i],a=null,c;if(s.startsWith("$if#")){let d=s.match(/^\$if#(\w+)\s+(.+)$/);if(d)a=d[1],c=d[2];else throw new C(`Invalid conditional syntax: ${s}`)}else c=s.substring(4),c.endsWith(":")&&(c=c.slice(0,-1).trim());Hn(c);let u=ee(c,n);for(r.push(u),o.push(je(l,n)),i++;i<e.length;){let[d,f]=e[i],p=!1,h;if(a?d.startsWith(`$elif#${a} `)?(h=d.substring(`$elif#${a} `.length),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(d===`$else#${a}`||d===`$else#${a}:`)&&(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)r.push(null);else{Hn(h);let g=ee(h,n);r.push(g)}if(o.push(je(f,n)),i++,h===null)break}else break}return{node:{type:m.CONDITIONAL,conditions:r,bodies:o,id:a},nextIndex:i}},Gn={eq:k.EQ,neq:k.NEQ,gt:k.GT,gte:k.GTE,lt:k.LT,lte:k.LTE,in:k.IN,add:k.ADD,sub:k.SUBTRACT},Kn={all:k.AND,any:k.OR},oc=new Set(["var","literal","call","not",...Object.keys(Gn),...Object.keys(Kn)]),ic=(e,t,n)=>{if(!Array.isArray(e))throw new C(`Condition JSON operator '${t}' at '${ce(n)}' requires an array`);if(e.length!==2)throw new C(`Condition JSON operator '${t}' at '${ce(n)}' requires exactly 2 operands`);return e},sc=(e,t,n,r,o)=>{if(!Array.isArray(e))throw new C(`Condition JSON operator '${t}' at '${ce(o)}' requires an array`);if(e.length===0)throw new C(`Condition JSON operator '${t}' at '${ce(o)}' requires at least 1 condition`);return e.map((s,l)=>be(s,r,[...o,l])).reduce((s,l)=>({type:m.BINARY,op:n,left:s,right:l}))},ac=(e,t,n)=>{let r,o;if(typeof e.call=="string")r=e.call,o=e.args??[],Ve(e,new Set(["call","args"]),n);else if(Jn(e.call))r=e.call.name,o=e.call.args??[],Ve(e,new Set(["call"]),n),Ve(e.call,new Set(["name","args"]),[...n,"call"]);else throw new C(`Condition JSON call at '${ce(n)}' requires a function name`);if(typeof r!="string"||r.trim()==="")throw new C(`Condition JSON call at '${ce(n)}' requires a non-empty function name`);if(!/^\w+$/.test(r))throw new C(`Invalid condition JSON function name '${r}' at '${ce(n)}'`);if(!Array.isArray(o))throw new C(`Condition JSON call '${r}' at '${ce(n)}' requires args to be an array`);return{type:m.FUNCTION,name:r,args:o.map((i,s)=>be(i,t,[...n,"args",s]))}},be=(e,t={},n=["$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 C(`Condition JSON array at '${ce(n)}' must be wrapped in an operator or { literal: [...] }`);if(!Jn(e))throw new C(`Invalid condition JSON value at '${ce(n)}'`);let r=No(e);if(r.length===0)throw new C(`Condition JSON object at '${ce(n)}' must contain an operator`);let o=r.filter(s=>oc.has(s));if(o.length===0)throw new C(`Unknown condition JSON operator '${r[0]}' at '${ce(n)}'`);if(o.length>1)throw new C(`Condition JSON at '${ce(n)}' must contain exactly one operator`);let i=o.includes("call")?"call":o[0];if(i==="var"){if(Ve(e,new Set(["var"]),n),typeof e.var!="string"||e.var.trim()==="")throw new C(`Condition JSON var at '${ce(n)}' requires a non-empty path`);return{type:m.VARIABLE,path:e.var}}if(i==="literal")return Ve(e,new Set(["literal"]),n),{type:m.LITERAL,value:e.literal};if(i==="call")return ac(e,t,n);if(i==="not")return Ve(e,new Set(["not"]),n),{type:m.UNARY,op:lt.NOT,operand:be(e.not,t,[...n,"not"])};if(i in Kn)return Ve(e,new Set([i]),n),sc(e[i],i,Kn[i],t,[...n,i]);if(i in Gn){Ve(e,new Set([i]),n);let s=ic(e[i],i,[...n,i]);return{type:m.BINARY,op:Gn[i],left:be(s[0],t,[...n,i,0]),right:be(s[1],t,[...n,i,1])}}throw new C(`Unknown condition JSON operator '${i}' at '${ce(n)}'`)},To=(e,t={})=>{if(e==null)throw new C("Missing condition expression after '$when'");if(typeof e=="string"){if(e.trim()==="")throw new C("Empty condition expression after '$when'");return ee(e,t)}return Jn(e)||Array.isArray(e)?be(e,t):{type:m.LITERAL,value:e}},ee=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let c=e.slice(1,-1),u=0,d=!0;for(let f=0;f<c.length;f++)if(c[f]==="("?u++:c[f]===")"&&u--,u<0){d=!1;break}if(d&&u===0)return ee(c,t)}let n=Ke(e,"||");if(n!==-1)return{type:m.BINARY,op:k.OR,left:ee(e.substring(0,n).trim(),t),right:ee(e.substring(n+2).trim(),t)};let r=Ke(e,"&&");if(r!==-1)return{type:m.BINARY,op:k.AND,left:ee(e.substring(0,r).trim(),t),right:ee(e.substring(r+2).trim(),t)};let o=[{op:">=",type:k.GTE},{op:"<=",type:k.LTE},{op:"==",type:k.EQ},{op:"!=",type:k.NEQ},{op:">",type:k.GT},{op:"<",type:k.LT},{op:" in ",type:k.IN}];for(let{op:c,type:u}of o){let d=Ke(e,c);if(d!==-1)return{type:m.BINARY,op:u,left:ee(e.substring(0,d).trim(),t),right:ee(e.substring(d+c.length).trim(),t)}}let i=-1,s=null,l=[{op:" + ",type:k.ADD},{op:" - ",type:k.SUBTRACT}];for(let{op:c,type:u}of l){let d=0;for(;d<e.length;){let f=Ke(e.substring(d),c);if(f===-1)break;let p=d+f;p>i&&(i=p,s={op:c,type:u}),d=p+c.length}}if(i!==-1&&s)return{type:m.BINARY,op:s.type,left:ee(e.substring(0,i).trim(),t),right:ee(e.substring(i+s.op.length).trim(),t)};let a=[" * "," / "," % "];for(let c of a)if(Ke(e,c)!==-1)throw new C(`Arithmetic operations are not allowed in conditionals: "${c}"`);return e.startsWith("!")?{type:m.UNARY,op:lt.NOT,operand:ee(e.substring(1).trim(),t)}:Po(e,t)},Ke=(e,t)=>{let n=0,r=0;for(;r<=e.length-t.length;){if(e[r]==="(")n++;else if(e[r]===")")n--;else if(n===0&&e.substring(r,r+t.length)===t)return r;r++}return-1},cc=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}},Po=(e,t)=>{let n=e.trim();if(n.match(/^(\w+)\((.*)\)$/))return xt(n,t);let o=cc(n);if(o.type===m.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(n))return{type:m.VARIABLE,path:n};try{return xt(n,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},lc=(e,t=!1)=>{let n=t?"$each":"$for";try{Eo(e)}catch(r){if(r instanceof C&&t){let o=r.message.replace(/\$for/g,"$each");throw new C(o.replace("Parse Error: ",""))}throw r}},Do=(e,t,n,r=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let y=r?"$each":"$for";throw new C(`Invalid loop syntax (got: '${e.replace("$for",y)}')`)}let s=i[1],l=i[2].trim();lc(l,r);let a=l.match(/^(.+?)\s+in\s+(.+)$/);if(!a){let y=r?"$each":"$for";throw new C(`Invalid loop syntax - missing 'in' keyword (got: '${y} ${l}')`)}let c=a[1].trim(),u=a[2].trim(),d,f=null;if(c.includes(",")){let y=c.split(",").map(I=>I.trim());if(y.length!==2)throw new C(`Invalid loop variables: ${c}. Expected format: "item" or "item, index"`);d=y[0],f=y[1]}else d=c;let p=["this","undefined","null","true","false"];if(p.includes(d))throw new C(`Reserved variable name: ${d}`);if(f&&p.includes(f))throw new C(`Reserved variable name: ${f}`);let h=Po(u,n),g=je(t,n);return{type:m.LOOP,itemVar:d,indexVar:f,iterable:h,body:g,flatten:s!=="nested"}};var uc=(e,t={})=>{let{functions:n={}}=t;return je(e,n)},Xt=uc;var vt={};Ea(vt,{now:()=>dc});var dc=()=>Date.now();var fc=(e,t,n={})=>{let{functions:r={},partials:o={}}=n,i={...vt,...r},s=Xt(e,{functions:i}),l={};for(let[a,c]of Object.entries(o))l[a]=Xt(c,{functions:i});return Wn(s,t,{functions:i,partials:l})},le=fc;var pc=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",hc=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,mc=(e,t)=>{if(pc(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new C("Empty condition expression");return ee(e,t)}return be(e,t)},gc=(e,t={},n={})=>{let r=hc(n),o={...vt,...r},i=mc(e,o);return!!Pe(i,{functions:o,partials:{}},t,{})},Xn=gc;var sr=Symbol("runStoreTransaction"),St=(e,t={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return Xn(e,t)},yc=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Bo=(e,t,n={})=>{let r=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=c=>c,transformActionFirstArgument:l=c=>c}=n;for(let[c,u]of Object.entries(t))c!=="createInitialState"&&(c.startsWith("select")?o[c]=(...d)=>u(s(r),...d):i[c]=(...d)=>{let f;return r=qn(r,h=>{let g=u(l(h),...d);f=g!==void 0&&!ae(g)?g:void 0}),f});let a=c=>{if(typeof c!="function")throw new Error("Store transaction requires a callback");let u=r;try{return c()}catch(d){throw r=u,d}};return{...o,...i,[sr]:a}},tn=(e,t)=>n=>{let r=e(),o=Array.isArray(n)?n:[n];return qn(r,i=>{o.forEach(s=>{t.forEach(l=>{l(i,s)})})})};var bc=(e,t)=>{if(e.default!==void 0)return e.default;let n=["number","boolean","string","object"];if(!n.includes(e.type))throw new Error(`Invalid variable type: ${e.type} for variable ${t}. Expected one of: ${n.join(", ")}`);switch(e.type){case"number":return 0;case"boolean":return!1;case"string":return"";case"object":return{}}},T=(e,t)=>Object.prototype.hasOwnProperty.call(e??{},t),tr=(e,t,n)=>{Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0})},Oe=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),zo=e=>{let t=ae(e)?Ge(e):e;return structuredClone(t)},Ic=({characterId:e,resourceCharacter:t,variables:n={}}={})=>{if(!T(t,"nameVariableId"))return;let r=t.nameVariableId,o=n?.[r];if(typeof o!="string")throw new Error(`Character "${e}" nameVariableId "${r}" must resolve to a string variable`);return o},nn=({characterId:e,character:t,characterName:n,characters:r={},variables:o={}}={})=>{let i=e?r?.[e]:void 0;if(t?.name!==void 0)return t.name;if(n!==void 0)return n;let s=Ic({characterId:e,resourceCharacter:i,variables:o});return s!==void 0?s:i?.name||""},Ce=e=>T(e,"computed"),ut=(e={},t={})=>Object.fromEntries(Object.entries(e??{}).filter(([n])=>!Ce(t[n]))),we=(e,t)=>new Error(`${t} has invalid path: ${JSON.stringify(e)}`),Ac=(e,t,n)=>{if(e[0]==='"')try{return JSON.parse(e)}catch{throw we(t,n)}let o="";for(let i=1;i<e.length-1;i+=1){let s=e[i];if(s!=="\\"){if(s.charCodeAt(0)<32)throw we(t,n);o+=s;continue}if(i+=1,i>=e.length-1)throw we(t,n);let l=e[i];if(l==="u"){let c=e.slice(i+1,i+5);if(c.length!==4||!/^[0-9a-fA-F]{4}$/.test(c))throw we(t,n);o+=String.fromCharCode(Number.parseInt(c,16)),i+=4;continue}let a={"\\":"\\",'"':'"',"'":"'","/":"/",n:`
2
+ `,r:"\r",t:" ",b:"\b",f:"\f"};if(!T(a,l))throw we(t,n);o+=a[l]}return o},qo=(e,t="Computed expression var")=>{if(typeof e!="string"||e.length===0||e.trim()!==e)throw we(e,t);let n=[],r=0,o=()=>{let s=r;for(;r<e.length&&e[r]!=="."&&e[r]!=="["&&e[r]!=="]";)r+=1;let l=e.slice(s,r);if(l.length===0||l.trim()!==l||/\s/.test(l))throw we(e,t);n.push(l)},i=()=>{for(r+=1;r<e.length&&/\s/.test(e[r]);)r+=1;let s=e[r];if(/\d/.test(s??"")){let u=r;for(;r<e.length&&/\d/.test(e[r]);)r+=1;let d=e.slice(u,r);for(;r<e.length&&/\s/.test(e[r]);)r+=1;if(e[r]!=="]"||d.length>1&&d.startsWith("0"))throw we(e,t);r+=1,n.push(d);return}if(s!=='"'&&s!=="'")throw we(e,t);let l=s,a=r;r+=1;let c=!1;for(;r<e.length;){let u=e[r];if(c)c=!1;else if(u==="\\")c=!0;else if(u===l){let d=e.slice(a,r+1);for(r+=1;r<e.length&&/\s/.test(e[r]);)r+=1;if(e[r]!=="]")throw we(e,t);r+=1,n.push(Ac(d,e,t));return}r+=1}if(c||r>=e.length)throw we(e,t)};for(o();r<e.length;){if(e[r]==="."){r+=1,o();continue}if(e[r]==="["){i();continue}throw we(e,t)}return n},Qn=(e,t)=>{let n=e;for(let r of t){if(n==null||!T(n,r))return;n=n[r]}return n},Ho=(e,t={})=>{if(typeof e!="string"||e.trim()==="")throw new Error("Computed expression var requires a non-empty string path");let n=qo(e),[r,o,...i]=n;if(r==="variables"){if(!o)return t.variables;let s=typeof t.resolveVariable=="function"?t.resolveVariable(o):t.variables?.[o];return Qn(s,i)}return r==="runtime"?Qn(t.runtime,n.slice(1)):Qn(t,n)},Wo=(e,t,n)=>{if(!Array.isArray(t))throw new Error(`Computed expression operator "${e}" requires an array`);if(n!==void 0&&t.length!==n)throw new Error(`Computed expression operator "${e}" requires ${n} operand(s)`)},nr=(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`)},wc=(e,t)=>{if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Computed expression operator "${e}" requires finite numeric operands`)},ve=(e,t,n,r)=>(Wo(e,t,r),t.map(o=>en(o,n))),Ae=(e,t,n,r)=>{let o=ve(e,t,n,r);return o.forEach(i=>wc(e,i)),o},Ec=(e,t,n)=>{switch(e){case"var":return Ho(t,n);case"add":{let[r,o]=Ae(e,t,n,2);return r+o}case"sub":{let[r,o]=Ae(e,t,n,2);return r-o}case"mul":{let[r,o]=Ae(e,t,n,2);return r*o}case"div":{let[r,o]=Ae(e,t,n,2);return r/o}case"mod":{let[r,o]=Ae(e,t,n,2);return r%o}case"neg":{let[r]=Ae(e,t,n,1);return-r}case"round":{let[r]=Ae(e,t,n,1);return Math.round(r)}case"floor":{let[r]=Ae(e,t,n,1);return Math.floor(r)}case"ceil":{let[r]=Ae(e,t,n,1);return Math.ceil(r)}case"min":{let[r,o]=Ae(e,t,n,2);return Math.min(r,o)}case"max":{let[r,o]=Ae(e,t,n,2);return Math.max(r,o)}case"clamp":{let[r,o,i]=Ae(e,t,n,3);return Math.min(i,Math.max(o,r))}case"eq":{let[r,o]=ve(e,t,n,2);return r==o}case"neq":{let[r,o]=ve(e,t,n,2);return r!=o}case"gt":{let[r,o]=ve(e,t,n,2);return r>o}case"gte":{let[r,o]=ve(e,t,n,2);return r>=o}case"lt":{let[r,o]=ve(e,t,n,2);return r<o}case"lte":{let[r,o]=ve(e,t,n,2);return r<=o}case"in":{let[r,o]=ve(e,t,n,2);return Array.isArray(o)?o.includes(r):!1}case"and":case"all":return nr(e,t),t.every(r=>!!en(r,n));case"or":case"any":return nr(e,t),t.some(r=>!!en(r,n));case"not":{let[r]=ve(e,t,n,1);return!r}case"length":{let[r]=ve(e,t,n,1);return typeof r=="string"||Array.isArray(r)?r.length:Oe(r)?Object.keys(r).length:0}case"includes":{let[r,o]=ve(e,t,n,2);return typeof r=="string"||Array.isArray(r)?r.includes(o):!1}case"literal":return zo(t);default:throw new Error(`Unknown computed expression operator: ${e}`)}},en=(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 n=Object.entries(e);if(n.length!==1)throw new Error("Computed expression objects must contain exactly one operator");let[[r,o]]=n;return Ec(r,o,t)},rr=(e,t)=>{if(e===null||typeof e!="object"||T(e,"literal"))return e;if(T(e,"var"))return{literal:Ho(e.var,t)};if(T(e,"call"))throw new Error("Function calls are not supported in computed-variable conditions");return Object.fromEntries(Object.entries(e).map(([n,r])=>[n,Array.isArray(r)?r.map(o=>rr(o,t)):rr(r,t)]))},xc=(e,t={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return be(e),St(rr(e,t))},Yo=(e,t)=>{if(!Oe(e))throw new Error(`${t} must be an object`);let n=T(e,"expr"),r=T(e,"value");if(n===r)throw new Error(`${t} must contain exactly one of expr or value`)},Zn=(e,t,n)=>(Yo(e,t),T(e,"value")?zo(e.value):en(e.expr,n)),vc=(e,t={},n="unknown")=>{if(!Oe(e))throw new Error(`Computed variable "${n}" computed must be an object`);let r=T(e,"expr"),o=T(e,"value");if(T(e,"branches")){if(r||o)throw new Error(`Computed variable "${n}" cannot combine branches with expr or value`);if(!Array.isArray(e.branches))throw new Error(`Computed variable "${n}" branches must be an array`);if(e.branches.length===0)throw new Error(`Computed variable "${n}" branches must not be empty`);if(!Oe(e.default))throw new Error(`Computed variable "${n}" requires default`);for(let s=0;s<e.branches.length;s+=1){let l=e.branches[s];if(!Oe(l))throw new Error(`Computed variable "${n}" branch ${s} must be an object`);if(!T(l,"when"))throw new Error(`Computed variable "${n}" branch ${s} requires when`);if(xc(l.when,t))return Zn(l,`Computed variable "${n}" branch ${s}`,t)}return Zn(e.default,`Computed variable "${n}" default`,t)}if(r===o)throw new Error(`Computed variable "${n}" must contain exactly one of expr, value, or branches`);return Zn(e,`Computed variable "${n}"`,t)},Go=(e,t,n)=>{switch(t){case"number":if(typeof n!="number"||!Number.isFinite(n))throw new Error(`Computed variable "${e}" expected type number, got ${Array.isArray(n)?"array":typeof n}`);return;case"boolean":if(typeof n!="boolean")throw new Error(`Computed variable "${e}" expected type boolean, got ${Array.isArray(n)?"array":typeof n}`);return;case"string":if(typeof n!="string")throw new Error(`Computed variable "${e}" expected type string, got ${Array.isArray(n)?"array":typeof n}`);return;case"object":if(n===null||typeof n!="object")throw new Error(`Computed variable "${e}" expected type object, got ${typeof n}`);return;default:throw new Error(`Invalid variable type: ${t} for computed variable ${e}`)}},Cc=Object.freeze({add:2,sub:2,mul:2,div:2,mod:2,neg:1,round:1,floor:1,ceil:1,min:2,max:2,clamp:3,eq:2,neq:2,gt:2,gte:2,lt:2,lte:2,in:2,not:1,length:1,includes:2}),Sc=new Set(["and","or","all","any"]),Rc=new Set(["add","sub","mul","div","mod","neg","round","floor","ceil","min","max","clamp","length"]),_c=new Set(["add","sub","mul","div","mod","neg","round","floor","ceil","min","max","clamp"]),Oc=new Set(["eq","neq","gt","gte","lt","lte","in","and","or","all","any","not","includes"]),kc=new Set(["all","any","eq","neq","gt","gte","lt","lte","in","add","sub"]),Ko=new WeakMap,Vo=e=>e===null?"null":Array.isArray(e)?"object":typeof e,Qt=(e,t,n)=>{for(let r of Object.keys(e))if(!t.has(r))throw new Error(`${n} contains unsupported property "${r}"`)},$c=(e,t,n,r)=>{if(n!==void 0&&n!==t)throw new Error(`Computed variable "${e}" ${r} expected type ${t}, got ${n}`)},Jo=(e,{variableId:t,variableConfigs:n,dependencies:r,path:o})=>{let i=`Computed variable "${t}" ${o} var`,[s,l,...a]=qo(e,i);if(s!=="variables"&&s!=="runtime")throw new Error(`${i} must reference variables.* or runtime.*, got ${JSON.stringify(e)}`);if(!l)throw new Error(`${i} must reference a concrete ${s} member, got ${JSON.stringify(e)}`);if(s==="runtime")return;if(!T(n,l))throw new Error(`Computed variable "${t}" ${o} references unknown variable "${l}"`);let c=n[l];return Ce(c)&&r.add(l),a.length===0?c?.type:void 0},Xo=(e,{variableId:t,variableConfigs:n,dependencies:r,path:o})=>{if(e===null||typeof e!="object"){if(typeof e=="number"&&!Number.isFinite(e))throw new Error(`Computed variable "${t}" ${o} must use finite numeric literals`);return Vo(e)}if(Array.isArray(e))throw new Error("Computed expression arrays are not valid; use value for literal arrays");let i=Object.entries(e);if(i.length!==1)throw new Error("Computed expression objects must contain exactly one operator");let[[s,l]]=i;if(s==="var"){if(typeof l!="string"||l.trim()==="")throw new Error("Computed expression var requires a non-empty string path");return Jo(l,{variableId:t,variableConfigs:n,dependencies:r,path:o})}if(s==="literal"){if(typeof l=="number"&&!Number.isFinite(l))throw new Error(`Computed variable "${t}" ${o} must use finite numeric literals`);return Vo(l)}let a=Cc[s];if(a===void 0&&!Sc.has(s))throw new Error(`Unknown computed expression operator: ${s}`);a===void 0?nr(s,l):Wo(s,l,a);let c=l.map((u,d)=>Xo(u,{variableId:t,variableConfigs:n,dependencies:r,path:`${o}.${s}[${d}]`}));if(_c.has(s)&&c.forEach(u=>{if(u!==void 0&&u!=="number")throw new Error(`Computed expression operator "${s}" requires numeric operands`)}),Rc.has(s))return"number";if(Oc.has(s))return"boolean"},Lc=(e,{variableId:t,variableConfigs:n,dependencies:r,path:o})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");try{be(e)}catch(s){throw new Error(`Computed variable "${t}" ${o} is invalid: ${s.message}`,{cause:s})}let i=(s,l)=>{if(s===null||typeof s!="object"||T(s,"literal"))return;if(T(s,"var")){Jo(s.var,{variableId:t,variableConfigs:n,dependencies:r,path:l});return}if(T(s,"call"))throw new Error(`Computed variable "${t}" ${l} function calls are not supported`);if(T(s,"not")){i(s.not,`${l}.not`);return}let a=Object.keys(s).find(c=>kc.has(c));s[a].forEach((c,u)=>{i(c,`${l}.${a}[${u}]`)})};i(e,o)},er=(e,{variableId:t,variableConfig:n,variableConfigs:r,dependencies:o,path:i,allowedKeys:s=new Set(["expr","value"])})=>{if(Yo(e,`Computed variable "${t}" ${i}`),Qt(e,s,i),T(e,"value")){Go(t,n.type,e.value);return}let l=Xo(e.expr,{variableId:t,variableConfigs:r,dependencies:o,path:`${i}.expr`});$c(t,n.type,l,`${i}.expr`)},Tc=(e,t,n)=>{let r=t.computed;if(!Oe(r))throw new Error(`Computed variable "${e}" computed must be an object`);let o=new Set,i=T(r,"expr"),s=T(r,"value");if(T(r,"branches")){if(Qt(r,new Set(["branches","default"]),`Computed variable "${e}" computed`),i||s)throw new Error(`Computed variable "${e}" cannot combine branches with expr or value`);if(!Array.isArray(r.branches))throw new Error(`Computed variable "${e}" branches must be an array`);if(r.branches.length===0)throw new Error(`Computed variable "${e}" branches must not be empty`);if(!Oe(r.default))throw new Error(`Computed variable "${e}" requires default`);return r.branches.forEach((a,c)=>{if(!Oe(a))throw new Error(`Computed variable "${e}" branch ${c} must be an object`);if(Qt(a,new Set(["when","expr","value"]),`Computed variable "${e}" branch ${c}`),!T(a,"when"))throw new Error(`Computed variable "${e}" branch ${c} requires when`);Lc(a.when,{variableId:e,variableConfigs:n,dependencies:o,path:`computed.branches[${c}].when`}),er(a,{variableId:e,variableConfig:t,variableConfigs:n,dependencies:o,path:`computed.branches[${c}]`,allowedKeys:new Set(["when","expr","value"])})}),er(r.default,{variableId:e,variableConfig:t,variableConfigs:n,dependencies:o,path:"computed.default"}),o}if(Qt(r,new Set(["expr","value"]),`Computed variable "${e}" computed`),i===s)throw new Error(`Computed variable "${e}" must contain exactly one of expr, value, or branches`);return er(r,{variableId:e,variableConfig:t,variableConfigs:n,dependencies:o,path:"computed"}),o},Je=(e={})=>{if(!Oe(e))throw new Error("Variable configs must be an object");if(T(e,"__proto__"))throw new Error('Variable id "__proto__" is reserved');if(T(e,""))throw new Error("Variable ids must not be empty");let t=new Map;Object.entries(e).forEach(([i,s])=>{if(Ce(s)){if(!Oe(s))throw new Error(`Computed variable "${i}" must be an object`);if(!T(s,"type"))throw new Error(`Computed variable "${i}" requires type`);if(!T(s,"scope"))throw new Error(`Computed variable "${i}" requires scope`);if(T(s,"default"))throw new Error(`Computed variable "${i}" must not declare a top-level default`);if(_t(s.scope,i),!["number","boolean","string","object"].includes(s.type))throw new Error(`Invalid variable type: ${s.type} for computed variable ${i}`);t.set(i,Tc(i,s,e))}});let n=new Set,r=[];t.forEach((i,s)=>{if(n.has(s))return;let l=[{variableId:s,dependencies:[...t.get(s)??[]],nextDependencyIndex:0}],a=new Map([[s,0]]);for(;l.length>0;){let c=l.at(-1);if(c.nextDependencyIndex>=c.dependencies.length){l.pop(),a.delete(c.variableId),n.add(c.variableId),r.push(c.variableId);continue}let u=c.dependencies[c.nextDependencyIndex];if(c.nextDependencyIndex+=1,n.has(u))continue;let d=a.get(u);if(d!==void 0){let f=[...l.slice(d).map(({variableId:p})=>p),u].join(" -> ");throw new Error(`Computed variable cycle detected: ${f}`)}a.set(u,l.length),l.push({variableId:u,dependencies:[...t.get(u)??[]],nextDependencyIndex:0})}});let o=Object.freeze({evaluationOrder:Object.freeze(r)});return Ko.set(e,o),o},Rt=({variables:e={},runtime:t={},variableConfigs:n={},eager:r=!0}={})=>{let{evaluationOrder:o}=Ko.get(n)??Je(n),i=ut(e,n),s=Object.entries(n).filter(([,y])=>Ce(y)).map(([y])=>y),l=Object.create(null),a=[],c=new Map(o.map((y,I)=>[y,I])),u=-1,d=!1,f=y=>{if(T(l,y))return l[y];let I=n[y];if(!Ce(I))return T(i,y)?i[y]:void 0;let w=a.indexOf(y);if(w>=0){let E=[...a.slice(w),y].join(" -> ");throw new Error(`Computed variable cycle detected: ${E}`)}a.push(y);try{let E=vc(I.computed,g,y);return Go(y,I.type,E),tr(l,y,E),E}finally{a.pop()}},p=y=>{if(T(l,y))return l[y];let I=n[y];if(!Ce(I))return T(i,y)?i[y]:void 0;let w=c.get(y);if(r&&!d&&w!==void 0&&w>u){d=!0;try{for(let E=u+1;E<=w;E+=1)f(o[E]),u=E}finally{d=!1}return l[y]}return f(y)},h=new Proxy({},{get:(y,I)=>{if(typeof I=="string")return p(I)},has:(y,I)=>typeof I=="string"&&(T(i,I)||s.includes(I)),ownKeys:()=>[...new Set([...Object.keys(i),...s])],getOwnPropertyDescriptor:(y,I)=>{if(!(typeof I!="string"||!T(i,I)&&!s.includes(I)))return{enumerable:!0,configurable:!0}}}),g={variables:h,runtime:t,resolveVariable:p};return r?(s.forEach(y=>{p(y)}),{...i,...l}):h},Dc=({variables:e={},runtime:t={},variableConfigs:n,projectData:r}={})=>{let o=n??r?.resources?.variables??{};return Je(o),Rt({variables:e,runtime:t,variableConfigs:o,eager:!0})},rn=e=>{let t={},n={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([r,o])=>{if(Ce(o))return;let i=bc(o,r);o.scope==="context"?tr(t,r,i):tr(n,r,i)}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}},_t=(e,t)=>{let n=["context","device","account"];if(!e)throw new Error(`Variable scope is required for variable: ${t}`);if(!n.includes(e))throw new Error(`Invalid variable scope: ${e} for variable ${t}. Expected one of: ${n.join(", ")}`)},on=(e,t,n)=>{let r={number:["set","increment","decrement","multiply","divide"],boolean:["set","toggle"],string:["set"],object:["set"]},o=r[e];if(!o)throw new Error(`Unknown variable type: ${e} for variable ${n}`);if(!Object.values(r).flat().includes(t))throw new Error(`Unknown operation: ${t}`);if(!o.includes(t))throw new Error(`Operation "${t}" is not valid for variable "${n}" of type "${e}". Valid operations: ${o.join(", ")}`)},Nc=2,jo=12,Qo=(e=Nc)=>{if(!Number.isInteger(e)||e<0||e>jo)throw new Error(`Operation "divide" requires roundTo to be an integer between 0 and ${jo}.`);return e},Pc=(e,t)=>{let n=10**t;return Math.round((e+Number.EPSILON)*n)/n},Zt=e=>typeof e=="number"&&Number.isFinite(e),ar=(e,t,n,r,o={})=>{if(e==="number"){if(t==="set"&&!Zt(n))throw new Error(`Operation "set" requires value to be a number for variable "${r}".`);if(t==="multiply"&&!Zt(n))throw new Error(`Operation "multiply" requires value to be a number for variable "${r}".`);if(t==="divide"&&!Zt(n))throw new Error(`Operation "divide" requires value to be a number for variable "${r}".`);if(t==="divide"){if(n===0)throw new Error(`Operation "divide" requires value to be a non-zero number for variable "${r}".`);Qo(o.roundTo)}}},sn=(e,t,n,r={})=>{let o=(s,l,a)=>{let c=s??l;if(!Zt(c))throw new Error(`Operation "${t}" requires ${a} to be a number.`);return c},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 n;case"multiply":return o(e,1,"current value")*o(n,void 0,"value");case"divide":return Pc(o(e,0,"current value")/i(n),Qo(r.roundTo));case"increment":return o(e,0,"current value")+o(n,1,"value");case"decrement":return o(e,0,"current value")-o(n,1,"value");case"toggle":return!e;default:throw new Error(`Unknown operation: ${t}`)}};var cr=(e,t="DD/MM/YYYY - HH:mm")=>{if(!e)return"";let n=new Date(e),r=s=>String(s).padStart(2,"0"),o=String(n.getFullYear()),i={DD:r(n.getDate()),MM:r(n.getMonth()+1),MMM:yc[n.getMonth()],YYYY:o,YY:o.slice(-2),HH:r(n.getHours()),mm:r(n.getMinutes()),ss:r(n.getSeconds())};return t.replace(/YYYY|MMM|YY|MM|DD|HH|mm|ss/g,s=>i[s])},Vc=(e,t)=>{let n=i=>i?.ui,r=n(e),o=n(t);return JSON.stringify(r)===JSON.stringify(o)?null:r&&!o?{changeType:"delete",data:e}:o&&!r?{changeType:"add",data:t}:o&&r?{changeType:"update",data:t}:null},Ct=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,jc=(e,t)=>{let n=e?.character?.sprite,r=t?.character?.sprite,o=Ct(n)?n:void 0,i=Ct(r)?r:void 0;return JSON.stringify(o)===JSON.stringify(i)?null:o&&!i?{changeType:"delete",data:o}:i&&!o?{changeType:"add",data:i}:i&&o?{changeType:"update",data:i}:null},Fo=e=>{if(e?.resourceId===void 0)return;let t={resourceId:e.resourceId};e.transformId!==void 0&&(t.transformId=e.transformId);for(let n of["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"])e[n]!==void 0&&(t[n]=e[n]);for(let n of["animationName","animationSpeed","loop"])e[n]!==void 0&&(t[n]=e[n]);return t},Mo=e=>{if(e?.colorId!==void 0)return{colorId:e.colorId}},Uo=(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,Fc=(e,t)=>{let n={},r=Uo(Fo(e),Fo(t)),o=Uo(Mo(e),Mo(t));return r&&(n.resource=r),o&&(n.color=o),Object.keys(n).length>0?n:null},lr=(e={},t={})=>{let n={},r=["sfx","voice"],o=a=>{let c=e[a],u=t[a];u&&!c?n[a]={changeType:"add",data:u}:c&&!u?r.includes(a)||(n[a]={changeType:"delete",data:c}):c&&u&&JSON.stringify(c)!==JSON.stringify(u)&&(n[a]={changeType:"update",data:u})},i=Fc(e.background,t.background);i&&(n.background=i),o("screen"),o("bgm"),o("voice");let s=Vc(e.dialogue,t.dialogue);s&&(n.dialogue=s);let l=jc(e.dialogue,t.dialogue);return l&&(n.dialogueSprite=l),o("choice"),o("form"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),n},ur=(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 n=o=>{t[o]&&(delete t[o].animations,Object.keys(t[o]).length===0&&delete t[o])};n("layout"),n("choice"),n("form"),n("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 r=(o,i)=>{let s=t[o]?.items;Array.isArray(s)&&(t[o].items=s.map(l=>{let a={...l};return delete a.animations,i(a)?a:null}).filter(Boolean),t[o].items.length===0&&delete t[o])};return r("character",o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId),r("visual",o=>o.resourceId||o.transformId),t},Mc=(e,t)=>{if(!e||!t)return;let n=e;for(let r of t.split(".")){if(n==null||!(r in Object(n)))return;n=n[r]}return n},Uc=(e,t)=>{if(typeof e!="string")return e;if(e==="_event"){if(t==null)throw new Error('Action template binding "_event" requires event context "_event".');return t}if(!e.startsWith("_event."))return e;if(t==null)throw new Error(`Action template binding "${e}" requires event context "_event".`);let n=e.slice(7),r=Mc(t,n);if(r===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return r},Bc={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"])},Zo=(e,t)=>{let n=e[e.length-1];return n?Bc[n]?.has(t)===!0:!1},or=(e,t,n=[])=>Array.isArray(e)?e.map(r=>or(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,Zo(n,r)?o:or(o,t,[...n,r])])):Uc(e,t),ir=(e,t,n=[])=>Array.isArray(e)?e.map(r=>ir(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,Zo(n,r)?o:ir(o,t,[...n,r])])):typeof e=="string"?le(e,t):e,dr=(e,t)=>{if(!t)return e;if(Object.prototype.hasOwnProperty.call(t,"event"))throw new Error('Action template context key "event" is no longer supported. Use "_event".');let n=or(e,t._event);return ir(n,t)};var W=e=>structuredClone(ae(e)?Ge(e):e),V=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),ei=e=>e?.animations?.playback?.continuity==="persistent",P=(e,t)=>V(e??{},t)&&e[t]!==void 0,Ot=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:W(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},zc=e=>P(e,"opacity")||P(e,"blur"),si=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],ai=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],fr=["animationName","animationSpeed","loop"],qc=e=>si.some(t=>P(e,t)),ci=e=>e?.text&&P(e.text,"content")&&P(e.text,"textStyleId"),li=e=>P(e,"text"),Hc=(e,t)=>e.resourceId?!0:ci(e)?!t?.text:!1,Wc=(e,t)=>{let n={...W(e),...t};return t.text&&e.text&&(n.text={...W(e.text),...W(t.text)}),n},Yc=(e,t)=>{if(li(e)){if(e.resourceId)throw new Error(`Visual item "${e.id}" cannot define both resourceId and text`);if(!ci(e)&&!t?.text)throw new Error(`Visual item "${e.id}" text requires content and textStyleId`)}},ti=e=>ai.some(t=>P(e,t)),ni=e=>fr.some(t=>P(e,t)),Gc=(e,t,{hasAuthoredTransformId:n=!1}={})=>{if(!t)return e;for(let r of ai)!n&&!P(e,r)&&P(t,r)&&(e[r]=t[r]),V(e,r)&&e[r]===void 0&&delete e[r];return e},ui=(e,t,n)=>{let r=e[n];return r?.id===t?.id?r:e.find(o=>o.id===t?.id)},Kc=(e,t)=>{if(!t)return e;for(let n of si)!P(e,n)&&P(t,n)&&(e[n]=t[n]),V(e,n)&&e[n]===void 0&&delete e[n];return e},Jc=(e,t)=>(t&&(!P(e,"opacity")&&P(t,"opacity")&&(e.opacity=t.opacity),!P(e,"blur")&&P(t,"blur")&&(e.blur=W(t.blur)),V(e,"opacity")&&e.opacity===void 0&&delete e.opacity,V(e,"blur")&&e.blur===void 0&&delete e.blur),e),di=(e,t,n=[],{hasPatchFn:r=()=>!1,mergeItemFn:o}={})=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let i=e.map((s,l)=>{let a=ui(n,s,l),c=t(s,a),u=zc(s),d=qc(s),f=r(s),p=V(s,"animations"),h=W(s);return!c&&(u||d||f)&&a&&(h=o?o(a,h):{...W(a),...h},p||delete h.animations),Jc(Kc(h,a),a)}).filter(s=>t(s)||s.animations);return{hasValidItems:i.length>0,processedItems:i}},Xc=e=>{if(e){if(e.character&&V(e.character,"name"))return e.character.name;if(V(e,"characterName"))return e.characterName}},fi=e=>!!e?.character&&V(e.character,"sprite"),Qc=e=>{let t={},n=!1,r=Xc(e);return r!==void 0&&(t.name=r,n=!0),fi(e)&&(t.sprite=W(e.character.sprite),n=!0),n?t:void 0},ri=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},oi=({dialogueState:e,dialogueAction:t,persistCharacter:n})=>V(t,"persistSprite")?t.persistSprite===!0:V(e,"persistSprite")?e.persistSprite===!0:n&&!V(t,"characterId"),ii=({previousCharacter:e,characterFields:t,hasCharacterId:n,persistCharacter:r,persistSprite:o,hasExplicitPersistSprite:i,isAppendingAdvDialogueContent:s})=>{let l={},a=e??{},c=t??{},u=s&&!n,d=u&&!i;return V(c,"name")?l.name=c.name:(r&&!n||u)&&V(a,"name")&&(l.name=W(a.name)),V(c,"sprite")?l.sprite=W(c.sprite):(o||d)&&V(a,"sprite")&&(l.sprite=W(a.sprite)),Object.keys(l).length>0?l:void 0},Zc=({dialogueState:e,content:t,append:n=!1})=>{if(!n||!Array.isArray(t)){e.content=t,delete e.initialRevealedContent;return}let r=Array.isArray(e.content)?e.content:[];r.length>0?e.initialRevealedContent=r.map(o=>W(o)):delete e.initialRevealedContent,e.content=[...r,...t]},el=()=>({}),tl=(e,t)=>{if(!t.screen)return;let n=P(t.screen,"opacity"),r=P(t.screen,"blur"),o=V(t.screen,"animations");if(!n&&!r){o||delete e.screen;return}let i=e.screen,s={};if(n?s.opacity=t.screen.opacity:P(i,"opacity")&&(s.opacity=i.opacity),r?s.blur=W(t.screen.blur):P(i,"blur")&&(s.blur=W(i.blur)),V(s,"opacity")&&s.opacity===void 0&&delete s.opacity,V(s,"blur")&&s.blur===void 0&&delete s.blur,Object.keys(s).length===0){delete e.screen;return}e.screen=s},nl=(e,t)=>{if(t.background){let n=P(t.background,"resourceId"),r=P(t.background,"colorId"),o=P(t.background,"opacity"),i=P(t.background,"blur"),s=P(t.background,"transformId"),l=ti(t.background),a=ni(t.background),{animationsOnly:c,state:u}=Ot(t.background,p=>P(p,"resourceId")||P(p,"colorId")||P(p,"opacity")||P(p,"blur")||P(p,"transformId")||ti(p)||ni(p));if(c){e.background=e.background?{...W(e.background),...u}:u;return}if(!n&&!r&&!o&&!i&&!s&&!l&&!a){delete e.background;return}let d=e.background,f=W(t.background);if(!n&&d?.resourceId){f.resourceId=d.resourceId,!V(f,"transformId")&&d.transformId&&(f.transformId=d.transformId);for(let p of fr)!P(f,p)&&P(d,p)&&(f[p]=d[p])}Gc(f,d,{hasAuthoredTransformId:s}),!r&&d?.colorId&&(f.colorId=d.colorId),!o&&P(d,"opacity")&&(f.opacity=d.opacity),!i&&P(d,"blur")&&(f.blur=W(d.blur)),V(f,"resourceId")&&f.resourceId===void 0&&delete f.resourceId,V(f,"colorId")&&f.colorId===void 0&&delete f.colorId,V(f,"animations")&&f.animations===void 0&&delete f.animations,V(f,"transformId")&&f.transformId===void 0&&delete f.transformId,V(f,"opacity")&&f.opacity===void 0&&delete f.opacity,V(f,"blur")&&f.blur===void 0&&delete f.blur;for(let p of fr)V(f,p)&&f[p]===void 0&&delete f[p];if(!f.resourceId&&!f.colorId){delete e.background;return}d?.resourceId===f.resourceId&&d?.transformId===f.transformId&&!V(f,"animations")&&ei(d)&&(f.animations=W(d.animations)),e.background=f}else e.background?.animations&&!ei(e.background)&&(e.background.animations={})},rl=(e,t)=>{if(!t.dialogue){if(e.dialogue&&(ri(e.dialogue),e.dialogue.mode==="adv")){e.dialogue.content=void 0,delete e.dialogue.initialRevealedContent,delete e.dialogue.textSpeed;let u=e.dialogue.persistCharacter===!0,d=oi({dialogueState:e.dialogue,dialogueAction:{},persistCharacter:u});u||delete e.dialogue.characterId,e.dialogue.character=ii({previousCharacter:e.dialogue.character,characterFields:{},hasCharacterId:!1,persistCharacter:u,persistSprite:d,hasExplicitPersistSprite:!1,isAppendingAdvDialogueContent:!1}),e.dialogue.character||delete e.dialogue.character}return}e.dialogue||(e.dialogue={});let n=e.dialogue.mode;if(t.dialogue.ui){let{animationsOnly:u,state:d}=Ot(t.dialogue.ui,f=>!!f.resourceId);u?e.dialogue.ui={...e.dialogue.ui,...d}:e.dialogue.ui={...t.dialogue.ui}}else e.dialogue?.ui?.animations&&(e.dialogue.ui.animations={});t.dialogue.mode==="adv"&&(e.dialogue.content=e.dialogue.content||void 0,e.dialogue.characterId=e.dialogue.characterId||void 0,e.dialogue.mode="adv"),t.dialogue.mode==="nvl"&&(e.dialogue?.mode!=="nvl"&&(e.dialogue.lines=[]),e.dialogue.mode="nvl");let r=t.dialogue.append===!0&&n!=="nvl"&&e.dialogue?.mode!=="nvl"&&Array.isArray(t.dialogue.content);t.dialogue.content!==void 0&&Zc({dialogueState:e.dialogue,content:t.dialogue.content,append:r}),V(t.dialogue,"textSpeed")?e.dialogue.textSpeed=t.dialogue.textSpeed:delete e.dialogue.textSpeed;let o=V(t.dialogue,"persistCharacter")?t.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;o?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let i=oi({dialogueState:e.dialogue,dialogueAction:t.dialogue,persistCharacter:o});V(t.dialogue,"persistSprite")&&(e.dialogue.persistSprite=i);let s=V(t.dialogue,"characterId"),l=Qc(t.dialogue),a=fi(t.dialogue);s?t.dialogue.characterId?e.dialogue.characterId=t.dialogue.characterId:delete e.dialogue.characterId:!o&&!r&&delete e.dialogue.characterId;let c=ii({previousCharacter:e.dialogue.character,characterFields:l,hasCharacterId:s,persistCharacter:o,persistSprite:i,hasExplicitPersistSprite:V(t.dialogue,"persistSprite"),isAppendingAdvDialogueContent:r});if(c?e.dialogue.character=c:delete e.dialogue.character,a||ri(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 u={content:t.dialogue.content,characterId:e.dialogue.characterId??null};e.dialogue.textSpeed!==void 0&&(u.textSpeed=e.dialogue.textSpeed),e.dialogue.character&&(u.character=W(e.dialogue.character)),e.dialogue.lines.push(u)}},ol=(e,t)=>{if(t.sfx){let n=Array.isArray(t.sfx.items)&&t.sfx.items.length>0,r=Array.isArray(t.sfx.channels)&&t.sfx.channels.length>0;if(!n&&!r){delete e.sfx;return}e.sfx=W(t.sfx)}else e.sfx&&delete e.sfx},il=(e,t)=>{if(t.bgm){let n=Array.isArray(t.bgm.sounds);if(!t.bgm.resourceId&&!n||n&&t.bgm.sounds.length===0){e.bgm=void 0;return}e.bgm=W(t.bgm),t.bgm.resourceId&&(e.bgm.loop=t.bgm.loop??!0)}},sl=(e,t)=>{if(t.visual){let n=e.visual?.items||[];t.visual.items?.forEach((i,s)=>{Yc(i,ui(n,i,s))});let{hasValidItems:r,processedItems:o}=di(t.visual.items,Hc,n,{hasPatchFn:li,mergeItemFn:Wc});r?e.visual={items:o}:delete e.visual}else e.visual?.items&&(e.visual.items=e.visual.items.map(n=>n.animations?{...n,animations:{}}:n))},al=(e,t)=>{if(!t.character){e.character?.items&&(e.character.items=e.character.items.map(o=>o.animations?{...o,animations:{}}:o));return}let{hasValidItems:n,processedItems:r}=di(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId,e.character?.items||[]);n?e.character={items:r}:delete e.character},cl=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},ll=(e,t)=>{if(t.layout){let{animationsOnly:n,state:r}=Ot(t.layout,o=>!!o.resourceId);if(n){e.layout=r;return}if(!t.layout.resourceId){delete e.layout;return}e.layout=t.layout}else e.layout&&delete e.layout},ul=(e,t)=>{if(t.choice){let{animationsOnly:n,state:r}=Ot(t.choice,o=>!!o.resourceId);if(n){e.choice={...e.choice,...r};return}if(!t.choice.resourceId){delete e.choice;return}e.choice=t.choice}else e.choice&&delete e.choice},dl=(e,t)=>{if(t.form){let{animationsOnly:n,state:r}=Ot(t.form,o=>!!o.resourceId);if(n){e.form={...e.form,...r};return}if(!t.form.resourceId){delete e.form;return}e.form=W(t.form)}else e.form&&delete e.form},fl=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},pl=(e,t)=>{if(t.voice){let n=Array.isArray(t.voice.sounds);if(!t.voice.resourceId&&!n||n&&t.voice.sounds.length===0){delete e.voice;return}e.voice=W(t.voice)}else e.voice&&delete e.voice},hl=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(n=>{delete e[n]})},Xe=e=>tn(el,[hl,tl,nl,ol,il,sl,rl,al,cl,ll,ul,dl,fl,pl])(e);var dt=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let n=le(e,t);return n&&typeof n=="object"?e:n};var ml=Object.freeze({dialogueTextSpeed:{source:"global.dialogueTextSpeed"},autoForwardDelay:{source:"global.autoForwardDelay"},autoForwardSpeed:{source:"global.autoForwardSpeed"},skipUnseenText:{source:"global.skipUnseenText"},skipTransitionsAndAnimations:{source:"global.skipTransitionsAndAnimations"},soundVolume:{source:"global.soundVolume"},musicVolume:{source:"global.musicVolume"},muteAll:{source:"global.muteAll"},saveLoadPagination:{source:"context.runtime.saveLoadPagination"},menuPage:{source:"context.runtime.menuPage"},menuEntryPoint:{source:"context.runtime.menuEntryPoint"},autoMode:{source:"global.autoMode"},skipMode:{source:"global.skipMode"},dialogueUIHidden:{source:"global.dialogueUIHidden"},isLineCompleted:{source:"global.isLineCompleted"}}),Qe=Object.freeze({dialogueTextSpeed:50,autoForwardDelay:1e3,autoForwardSpeed:1,skipUnseenText:!1,skipTransitionsAndAnimations:!1,soundVolume:50,musicVolume:50,muteAll:!1,autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isLineCompleted:!1}),kt=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),pi=Object.freeze({dialogueTextSpeed:"number",autoForwardDelay:"number",autoForwardSpeed:"number",skipUnseenText:"boolean",skipTransitionsAndAnimations:"boolean",soundVolume:"number",musicVolume:"number",muteAll:"boolean",saveLoadPagination:"number",menuPage:"string",menuEntryPoint:"string",autoMode:"boolean",skipMode:"boolean",dialogueUIHidden:"boolean",isLineCompleted:"boolean"}),pr=Object.freeze(["dialogueTextSpeed","autoForwardDelay","autoForwardSpeed","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),hr=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),gl=(e,t)=>{if(t.startsWith("global.")){let n=t.slice(7);return e?.global?.[n]}if(t.startsWith("context.runtime.")){let n=t.slice(16),r=Array.isArray(e?.contexts)?e.contexts:[];return r[r.length-1]?.runtime?.[n]}},Ze=e=>Object.fromEntries(Object.entries(ml).map(([t,n])=>{let r=gl(e,n.source),o=r!==void 0?r:Qe[t]??kt[t];return[t,o]})),Fe=(e,t)=>Ze(e)[t],hi=(e={})=>Object.fromEntries(pr.map(t=>[t,e[t]??Qe[t]]));var ft=Object.freeze({VISUAL_BEHIND_BACKGROUND:10,BACKGROUND:20,VISUAL_BEHIND_CHARACTER:30,CHARACTER:40,VISUAL_BEHIND_DIALOGUE:50,DIALOGUE:60,VISUAL_BEHIND_CHOICE:70,CHOICE:80,VISUAL_FOREGROUND:90}),$e=Object.freeze({BEHIND_BACKGROUND:ft.VISUAL_BEHIND_BACKGROUND,BEHIND_CHARACTER:ft.VISUAL_BEHIND_CHARACTER,BEHIND_DIALOGUE:ft.VISUAL_BEHIND_DIALOGUE,BEHIND_CHOICE:ft.VISUAL_BEHIND_CHOICE,FOREGROUND:ft.VISUAL_FOREGROUND}),mr=$e.BEHIND_DIALOGUE,gr=Object.freeze(Object.values($e).sort((e,t)=>e-t));var Le={objectValues:e=>Object.entries(e).map(([t,n])=>({id:t,...n})),formatDate:cr},yl=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,bl=(e,t)=>{let n=String(t||"").trim();if(!n)return;let r=n.match(/[A-Za-z_][A-Za-z0-9_]*|\[\d+\]/g)||[],o=e;for(let i of r){if(i.startsWith("[")){let s=Number(i.slice(1,-1));o=Array.isArray(o)?o[s]:void 0;continue}o=o?.[i]}return o},un=(e,t,n)=>{if(Array.isArray(e)){let o=[];for(let i of e){if(i&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===1){let[s]=Object.keys(i),l=yl.exec(s);if(l){let[,a,c,u]=l,d=bl(t,u);if(!Array.isArray(d))continue;let f=Array.isArray(i[s])?i[s]:[];d.forEach((p,h)=>{let g={...t,[a]:p};c&&(g[c]=h),f.forEach(y=>{let I=un(y,g,n),w=le(I,g,n);Array.isArray(w)?o.push(...w):o.push(w)})});continue}}o.push(un(i,t,n))}return o}if(!e||typeof e!="object")return e;let r={};return Object.entries(e).forEach(([o,i])=>{r[o]=un(i,t,n)}),r},Tr=({animationType:e,animationId:t,animationPath:n})=>{if(e!==void 0&&!(e==="update"||e==="transition"))throw new Error(`[${n}] Animation "${t}" has unsupported type "${e}". Use "update" or "transition".`)},Il=({id:e,targetId:t,animation:n,playback:r,animationPath:o="animation"})=>{let i=structuredClone(n);if(Tr({animationType:i.type,animationId:e,animationPath:o}),delete i.name,delete i.playback,i.id=e,i.targetId=t,r!==void 0){let s=xl(r,`${o}.playback`);s!==void 0&&(i.playback=s)}return i},Al=(e,{animationId:t="animation",animationPath:n="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return Tr({animationType:e.type,animationId:t,animationPath:n}),e.type},wl=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},El=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},xl=(e,t="animation.playback")=>{if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`[${t}] playback must be an object.`);if(e.continuity!==void 0&&e.continuity!=="render"&&e.continuity!=="persistent")throw new Error(`[${t}] playback.continuity must be "render" or "persistent".`);if(e.speed!==void 0&&(typeof e.speed!="number"||!Number.isFinite(e.speed)||e.speed<=0))throw new Error(`[${t}] playback.speed must be a finite number greater than 0.`);let n={};return e.continuity!==void 0&&(n.continuity=e.continuity),e.speed!==void 0&&e.speed!==1&&(n.speed=e.speed),Object.keys(n).length>0?n:void 0},vl=e=>{let t=e?.playback?.speed;return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1},et=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Si=e=>e?.playback?.continuity==="persistent",vr=e=>Array.isArray(e)?e.map(vr):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((t,n)=>(t[n]=vr(e[n]),t),{}),fn=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let t=structuredClone(e);return t.playback&&(delete t.playback.continuity,t.playback.speed===1&&delete t.playback.speed,Object.keys(t.playback).length===0&&delete t.playback),JSON.stringify(vr(t))},Ri=(e=[])=>e.filter(t=>Si(t)).map(t=>structuredClone(t)),_i=e=>Array.isArray(e?.keyframes)?e.keyframes.reduce((t,n)=>{let r=typeof n?.duration=="number"&&Number.isFinite(n.duration)?n.duration:0;return t+r},0):0,yr=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((t,n)=>Math.max(t,_i(n)),0),Oi=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max(yr(e.tween),yr(e.prev?.tween),yr(e.next?.tween),_i(e.mask?.progress))/vl(e),mi=({animationInstances:e,activePersistentAnimations:t})=>{if(!Array.isArray(e)||e.length===0||!Array.isArray(t)||t.length===0)return!1;let n=new Set(t.map(fn).filter(Boolean));return e.some(r=>{if(!Si(r))return!1;let o=fn(r);return o?n.has(o):!1})},Se=({animationInstances:e,isLineCompleted:t,skipTransitionsAndAnimations:n,activePersistentAnimations:r,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||n?!1:i&&!t||mi({animationInstances:e,activePersistentAnimations:r})?!0:i?!1:mi({animationInstances:e,activePersistentAnimations:o}),Cl=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),Sl=(e,t)=>{if(Cl(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},Rl=({resources:e,animationId:t,playback:n,instanceId:r,targetId:o,animationPath:i="animation"})=>{if(!t||!o)return!1;let s=e?.animations?.[t];return s?Il({id:r,targetId:o,animation:s,playback:n,animationPath:i}):null},_l=(e,{defaultTargetId:t,defaultId:n,animationPath:r="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return Tr({animationType:o.type,animationId:o.id??n,animationPath:r}),o.id??=n,o.targetId??=t,o},Dr=({animations:e,transitions:t,defaultTargetId:n,idPrefix:r,animationPathPrefix:o=r})=>{t.forEach((i,s)=>{e.push(_l(i,{defaultTargetId:n,defaultId:`${r}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},Cr=(e,t)=>{if(e===void 0)return[];if(!Array.isArray(e)||e.some(n=>n===null||typeof n!="object"||Array.isArray(n)))throw new Error(`${t} must be an array of objects`);return e},Ol=({content:e,path:t,variables:n})=>Cr(e,t).reduce((r,o)=>{let i=dt(o.text,{variables:n});return r+`${i??""}`.length},0),gi=(e=[])=>{let t=new Map;for(let n of e)n?.id&&t.set(n.id,(t.get(n.id)??0)+1);return new Set(Array.from(t.entries()).filter(([,n])=>n>1).map(([n])=>n))},an=(e,t=0,n=new Set)=>{if(!n.has(e?.id))return`character-container-${e.id}`;let r=e?.sprites?.map(({resourceId:o})=>o)||[];return r.length===0?`character-container-${e.id}`:`character-container-${e.id}-${t}-${r.join("-")}`},cn=(e,t)=>{if(!t.transformId)throw new Error(`Visual item "${t.id}" requires transformId`);let n=e.transforms?.[t.transformId];if(!n)throw new Error(`Transform "${t.transformId}" not found for visual item "${t.id}"`);return n},kl=(e,t={})=>{if(!t?.transformId)return;let n=e.transforms?.[t.transformId];if(!n)throw new Error(`Transform "${t.transformId}" not found for background`);return n},$l=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],Ll=(e={})=>$l.some(t=>et(e,t)),ki=(e={},t)=>{if(t){if(e.images?.[t])return"sprite";if(e.videos?.[t])return"video";if(e.spritesheets?.[t])return"spritesheet-animation";if(e.layouts?.[t])return"container"}},dn=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},Tl=(e={})=>e.textStyles||{},Dl=(e={})=>e.images||{},Nl=.5,Pl=(e={},t,n)=>{if(t){if(!e.animations?.[t])throw new Error(`Animation '${t}' not found in spritesheet resource '${n}'`);return t}return Object.keys(e.animations??{})[0]},$i=({id:e,resourceId:t,spritesheet:n,animationName:r,animationSpeed:o,loop:i,transform:s={}}={})=>{let l=Pl(n,r,t),a=l?n.animations?.[l]:void 0;if(!a){console.warn(`Spritesheet animation not found: ${t}`);return}return{id:e,type:"spritesheet-animation",...s,width:n.width,height:n.height,src:n.fileId,atlas:n.jsonData,playback:{frames:a.frames,animationSpeed:o??a.animationSpeed??Nl,loop:i??a.loop??!0}}},Li=({id:e,item:t,resources:n={}}={})=>{let r=n.images?.[t.resourceId];if(r)return{type:"sprite",id:e,src:r.fileId,width:r.width,height:r.height,x:0,y:0};let o=n.spritesheets?.[t.resourceId];if(o)return $i({id:e,resourceId:t.resourceId,spritesheet:o,animationName:t.animationName,animationSpeed:t.animationSpeed,loop:t.loop,transform:{x:0,y:0}});console.warn(`Character sprite resource not found: ${t.resourceId}`)},Vl=(e={})=>e.colors||{},jl=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,Tt=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,ht=(e,t,n)=>{if(typeof e!="string"||e.length===0)throw new Error(`${n} at "${t}" must resolve to a non-empty string`)},br=(e,t,n)=>{if(e===void 0)return 1;if(typeof e!="number"||!Number.isFinite(e))throw new Error(`${t} for text style "${n}" must be a number between 0 and 1`);if(e<0||e>1)throw new Error(`${t} for text style "${n}" must be a number between 0 and 1`);return e},Ir=(e,t,n,r,{minimum:o}={})=>{if(e===void 0)return r;if(typeof e!="number"||!Number.isFinite(e)||o!==void 0&&e<o){let i=o===void 0?"a finite number":`a finite number >= ${o}`;throw new Error(`shadow.${t} for text style "${n}" must be ${i}`)}return e},mn=(e,t)=>{if(typeof e!="string"||!jl.test(e))throw new Error(`${t} must resolve to a hex color`);return e.length===4?`#${e.slice(1).split("").map(n=>n.repeat(2)).join("")}`:e},yi=(e,t,n)=>{let r=mn(e,n);if(t===1)return r;let o=Number.parseInt(r.slice(1,3),16),i=Number.parseInt(r.slice(3,5),16),s=Number.parseInt(r.slice(5,7),16);return`rgba(${o}, ${i}, ${s}, ${t})`},Fl=(e={},t)=>{let n=Tl(e)?.[t];if(!n)throw new Error(`Text style "${t}" not found`);let o=(Array.isArray(n.fontId)?n.fontId:[n.fontId]).map(a=>{let c=e.fonts?.[a];if(!c)throw new Error(`Font "${a}" not found for text style "${t}"`);return c.fileId}),i=e.colors?.[n.colorId];if(!i)throw new Error(`Color "${n.colorId}" not found for text style "${t}"`);let s=br(n.colorAlpha,"colorAlpha",t),l={fontFamily:Array.isArray(n.fontId)?o.join(", "):o[0],fontSize:n.fontSize??16,fontWeight:n.fontWeight??"400",fontStyle:n.fontStyle??"normal",lineHeight:n.lineHeight??1.2,fill:yi(i.hex,s,`Color "${n.colorId}" for text style "${t}"`)};if(n.align!==void 0&&(l.align=n.align),n.wordWrap!==void 0&&(l.wordWrap=n.wordWrap),n.breakWords!==void 0&&(l.breakWords=n.breakWords),n.wordWrapWidth!==void 0&&(l.wordWrapWidth=n.wordWrapWidth),n.strokeColorId){let a=e.colors?.[n.strokeColorId];if(!a)throw new Error(`Stroke color "${n.strokeColorId}" not found for text style "${t}"`);let c=br(n.strokeAlpha,"strokeAlpha",t);l.strokeColor=yi(a.hex,c,`Stroke color "${n.strokeColorId}" for text style "${t}"`)}else if(n.strokeAlpha!==void 0)throw new Error(`strokeAlpha for text style "${t}" requires strokeColorId`);if(n.strokeWidth!==void 0&&(l.strokeWidth=n.strokeWidth),n.shadow!==void 0){let a=e.colors?.[n.shadow.colorId];if(!a)throw new Error(`Shadow color "${n.shadow.colorId}" not found for text style "${t}"`);l.shadow={color:mn(a.hex,`Shadow color "${n.shadow.colorId}" for text style "${t}"`),alpha:br(n.shadow.alpha,"shadow.alpha",t),blur:Ir(n.shadow.blur,"blur",t,0,{minimum:0}),offsetX:Ir(n.shadow.offsetX,"offsetX",t,2),offsetY:Ir(n.shadow.offsetY,"offsetY",t,2)}}return l},Sr=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>Sr(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(Object.prototype.hasOwnProperty.call(e,"textStyle"))throw new Error(`Inline textStyle is not allowed in layout elements at "${n}". Use textStyleId instead`);let r={};for(let[o,i]of Object.entries(e))o!=="textStyleId"&&(r[o]=Sr(i,t,Tt(n,o)));return e.textStyleId!==void 0&&(ht(e.textStyleId,n,"textStyleId"),r.textStyle=Fl(t,e.textStyleId)),r},Nr=(e={},t)=>{let n=Vl(e)?.[t];if(!n)throw new Error(`Color "${t}" not found`);return mn(n.hex,`Color "${t}"`)},Ti=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",Ar=(e,t,n)=>{let r=e?.[t];if(!(!r||typeof r!="object"||Array.isArray(r))&&Object.prototype.hasOwnProperty.call(r,"fill"))throw new Error(`Inline ${t}.fill is not allowed in rect layout elements at "${n}". Use ${Ti(`${t}.fill`)} instead`)},Ml=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>Dt(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;let r={};for(let[o,i]of Object.entries(e))o!=="colorId"&&(r[o]=Dt(i,t,Tt(n,o)));return e.colorId!==void 0&&(ht(e.colorId,n,"colorId"),r.fill=Nr(t,e.colorId)),r},Dt=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>Dt(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="rect"){if(Object.prototype.hasOwnProperty.call(e,"fill"))throw new Error(`Inline fill is not allowed in rect layout elements at "${n}". Use ${Ti("fill")} instead`);Ar(e,"hover",n),Ar(e,"click",n),Ar(e,"rightClick",n)}let r={};for(let[o,i]of Object.entries(e))if(!(e.type==="rect"&&o==="colorId")){if(e.type==="rect"&&(o==="hover"||o==="click"||o==="rightClick")){r[o]=Ml(i,t,Tt(n,o));continue}r[o]=Dt(i,t,Tt(n,o))}return e.type==="rect"&&e.colorId!==void 0&&(ht(e.colorId,n,"colorId"),r.fill=Nr(t,e.colorId)),r},wr=(e={},t)=>{let n=Dl(e)?.[t];return n||null},Di=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",bi=(e,t,n,r)=>{let o=e?.[t];if(!(!o||typeof o!="object"||Array.isArray(o))&&Object.prototype.hasOwnProperty.call(o,r))throw new Error(`Inline ${t}.${r} is not allowed in sprite layout elements at "${n}". Use ${Di(`${t}.${r}`)} instead`)},Ii=(e,t,n)=>{let r=e[t];e[t]={...r&&typeof r=="object"&&!Array.isArray(r)?r:{},src:n}},Rr=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>Rr(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="sprite"){for(let o of["url","src","hoverUrl","hoverSrc","clickUrl","clickSrc"])if(Object.prototype.hasOwnProperty.call(e,o))throw new Error(`Inline ${o} is not allowed in sprite layout elements at "${n}". Use ${Di(o)} instead`);bi(e,"hover",n,"src"),bi(e,"click",n,"src")}let r={};for(let[o,i]of Object.entries(e))e.type==="sprite"&&(o==="imageId"||o==="hoverImageId"||o==="clickImageId")||(r[o]=Rr(i,t,Tt(n,o)));if(e.type==="sprite"&&e.imageId!==void 0){ht(e.imageId,n,"imageId");let o=wr(t,e.imageId),i=o?.fileId??e.imageId;r.src=i,r.width===void 0&&o?.width!==void 0&&(r.width=o.width),r.height===void 0&&o?.height!==void 0&&(r.height=o.height)}return e.type==="sprite"&&e.hoverImageId!==void 0&&(ht(e.hoverImageId,n,"hoverImageId"),Ii(r,"hover",wr(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(ht(e.clickImageId,n,"clickImageId"),Ii(r,"click",wr(t,e.clickImageId)?.fileId??e.clickImageId)),r},Pr=(e,t={},n="root")=>Rr(Dt(Sr(e,t,n),t,n),t,n),Te=Pr,nt=(e=[])=>e.find(t=>t.id==="story"),Ul="#000000",_r="bg-cg-background-color",Bl=({resources:e={},background:t={},screen:n})=>t?.colorId===void 0?mn(n?.backgroundColor??Ul,"screen.backgroundColor"):Nr(e,t.colorId),Ni=(e={})=>{if(et(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},zl=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},Ai=(e={},{includeDefaultAlpha:t=!1}={})=>{let n=Ni(e),r=zl(e),o={};return(t||n!==void 0)&&(o.alpha=n??1),r&&(o.blur=r),o},ql=(e={})=>{if(et(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},Hl=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},Pi=(e={})=>{let t=ql(e),n=Hl(e),r={};return t!==void 0&&(r.alpha=t),n&&(r.blur=n),r},$t=(e={})=>Pi(e),Me=(e={},t={})=>{let n={x:t.x??e.x,y:t.y??e.y,anchorX:t.anchorX??e.anchorX,anchorY:t.anchorY??e.anchorY,rotation:t.rotation??e.rotation,scaleX:t.scaleX??e.scaleX,scaleY:t.scaleY??e.scaleY},r=t.originX??e.originX,o=t.originY??e.originY;return r!==void 0&&(n.originX=r),o!==void 0&&(n.originY=o),n},Wl=["id","type","resourceId","transformId","x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY","layer","opacity","blur","animations"],Vr=(e={})=>e.text&&et(e.text,"content")&&et(e.text,"textStyleId"),wi=(e={})=>{if(e.resourceId)return e.resourceId;if(Vr(e))return"text"},Yl=e=>{if(e.text){if(e.resourceId)throw new Error(`Visual item "${e.id}" cannot define both resourceId and text`);if(!Vr(e))throw new Error(`Visual item "${e.id}" text requires content and textStyleId`);for(let t of Wl)if(et(e.text,t))throw new Error(`Visual item "${e.id}" text.${t} is reserved for the visual item`)}},Gl=({resources:e,background:t,screen:n={width:1920,height:1080},includeOpacity:r=!1})=>{let o={id:_r,type:"rect",x:0,y:0,width:n?.width??1920,height:n?.height??1080,fill:Bl({resources:e,background:t,screen:n})};if(r){let i=Ni(t);i!==void 0&&(o.alpha=i)}return o},Kl=(e={},t)=>t?!!(e.images?.[t]||e.videos?.[t]||e.spritesheets?.[t]||e.layouts?.[t]):!1,Ei=({resources:e={},resourceId:t,colorId:n})=>{let r=ki(e,t);return t&&(r||n===void 0)?{resourceId:t,targetId:dn({resourceId:t,kind:r})}:n!==void 0?{resourceId:_r,targetId:_r}:{resourceId:void 0,targetId:void 0}},Vi=100,tt=Vi,Jl="channel:bgm",Xl="channel:voice",Ql="default",Zl=e=>String(e).replaceAll("%","%25").replaceAll(":","%3A"),Lt=(...e)=>e.map(Zl).join(":"),pn=(e,t,n)=>{let r=new Set;e.forEach(({id:o})=>{if(r.has(o)){let i=n?` in ${n}`:"";throw new Error(`Duplicate ${t} id "${o}"${i}.`)}r.add(o)})},eu=(e,t)=>e*t/Vi,ji=(e={},t)=>e?.[t]??Qe[t],jr=(e={},t,n=tt)=>eu(n,ji(e,t)),Fr=({id:e,volume:t,muted:n,pan:r,children:o,runtime:i})=>({id:e,type:"audio-channel",volume:t,muted:!!i?.muteAll||(n??!1),pan:r??0,children:o}),ln=(e,t,n,r)=>e[n]!==void 0?e[n]:t[n]!==void 0?t[n]:r,tu=["muted","pan","playbackRate","startAt","endAt"],Mr=({id:e,sound:t,resource:n,defaultLoop:r=!1})=>{let o={id:e,type:"sound",src:n.fileId,loop:ln(t,n,"loop",r),volume:ln(t,n,"volume",tt),startDelayMs:ln(t,n,"startDelayMs",0)};tu.forEach(s=>{let l=ln(t,n,s,void 0);l!==void 0&&(o[s]=l)});let i=o.startAt??0;if(o.endAt!==void 0&&o.endAt!==null&&o.endAt<i)throw new Error(`Sound "${e}" endAt (${o.endAt}) must be greater than or equal to startAt (${i}).`);return o},Re=({variables:e,runtime:t,saveSlots:n=[],dialogueState:r,includeInactiveAdvDialogue:o=!1,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,confirmDialog:d,form:f,historyDialogue:p=[],characters:h={},dialogueUIHidden:g,skipOnlyViewedLines:y,skipTransitionsAndAnimations:I}={})=>{let w={dialogueTextSpeed:t?.dialogueTextSpeed??50,autoForwardDelay:t?.autoForwardDelay??1e3,autoForwardSpeed:t?.autoForwardSpeed??1,skipUnseenText:t?.skipUnseenText??!1,skipTransitionsAndAnimations:t?.skipTransitionsAndAnimations??!1,soundVolume:t?.soundVolume??50,musicVolume:t?.musicVolume??50,muteAll:t?.muteAll??!1,saveLoadPagination:t?.saveLoadPagination??1,menuPage:t?.menuPage??"",menuEntryPoint:t?.menuEntryPoint??"",autoMode:t?.autoMode??s??!1,skipMode:t?.skipMode??l??!1,dialogueUIHidden:t?.dialogueUIHidden??g??!1,isLineCompleted:t?.isLineCompleted??i??!1},E=su({dialogueState:r,includeInactiveAdvDialogue:o,characters:h,variables:e,runtime:w}),_={variables:e,runtime:w,saveSlots:n,isChoiceVisible:a,isFormVisible:c,canRollback:u,confirmDialog:d,form:f,historyDialogue:p,characters:h};return E&&(_.dialogue=E,_.dialogueLines=E.lines),_},xi=100,hn=(e,t)=>{if(Array.isArray(e))return e.map(r=>hn(r,t));if(!e||typeof e!="object")return e;let n={...e};return Object.keys(n).forEach(r=>{n[r]=hn(n[r],t)}),n.type==="text-revealing"?t(n):n},nu=e=>hn(e,t=>({...t,revealEffect:"none"})),ru=e=>hn(e,t=>{let n=Number(t.speed??t.displaySpeed),r=Number.isFinite(n)?Math.max(n,xi):xi;return{...t,speed:r,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:r}:{}}}),Ue=(e,{isLineCompleted:t=!1,skipMode:n=!1,skipTransitionsAndAnimations:r=!1}={})=>t||r?nu(e):n?ru(e):e,Fi=({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:{}}}}),Or=e=>{if(Array.isArray(e))return e.map(Or);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=Or(s);let n=t.click?.payload;if(!n||typeof n!="object"||Array.isArray(n))return t;let r=n.actions,o=r&&typeof r=="object"&&!Array.isArray(r)&&Object.prototype.hasOwnProperty.call(r,"nextLine")?{...r.nextLine,bypassChoice:!0}:void 0;return{...t,click:{...t.click,payload:{...n,bypassChoice:!0,...o?{actions:{...r,nextLine:o}}:{}}}}},ou=new Set(["click","change","submit","focusEvent","blurEvent","selectionChange","compositionStart","compositionUpdate","compositionEnd"]),vi="submit",Er=(e,t,n={})=>{let r=e?.payload&&typeof e.payload=="object"&&!Array.isArray(e.payload)?e.payload:{},o=r.actions&&typeof r.actions=="object"?r.actions:{},i=n.replaceActions===!0?t:{...o,...t};return{...e||{},payload:{...r,actions:i}}},kr=(e,t,n={})=>{if(Array.isArray(e))return e.map(c=>kr(c,t,n));if(!e||typeof e!="object")return e;let r=typeof e.type=="string",o=r&&e.formRole===vi,i=r&&n.submitRoleAncestor,s=o||i?{submitRoleAncestor:!0}:{},l={};for(let[c,u]of Object.entries(e))l[c]=kr(u,t,c==="children"?s:{});let a=l;if(a.type==="input"&&typeof a.field=="string"){let c=t?.fields?.[a.field];if(c){let u={updateFormField:{formKey:t.key,field:c.id,value:"_event.value"}};a={...a,value:c.value,placeholder:a.placeholder===void 0?c.placeholder:a.placeholder,multiline:a.multiline===void 0?c.multiline:a.multiline,...a.maxLength===void 0&&c.maxLength!==void 0?{maxLength:c.maxLength}:{},change:Er(a.change,u),submit:Er(a.submit,t.submitActions)}}}return a.formRole===vi||i?{...a,click:Er(a.click,t.submitActions,{replaceActions:!0})}:a},$r=(e,t)=>{if(Array.isArray(e))return e.map(r=>$r(r,t));if(!e||typeof e!="object")return e;let n={};for(let[r,o]of Object.entries(e))n[r]=$r(o,t);for(let r of ou){let o=n[r]?.payload;!o||typeof o!="object"||Array.isArray(o)||(n[r]={...n[r],payload:{...o,_interactionSource:"form"}})}return n},Lr=({characterId:e,character:t,characterName:n,characters:r={},variables:o={}}={})=>{let i=e?r?.[e]:void 0,s=nn({characterId:e,character:t,characterName:n,characters:r,variables:o});return{...i||{},...t||{},name:s}},Mi=(e=[],t={},n={})=>e.map(r=>{let o=Lr({characterId:r.characterId,character:r.character,characterName:r.characterName,characters:t,variables:n}),i=typeof r.text=="string"?r.text:Array.isArray(r.content)?r.content.map(s=>s?.text??"").join(""):"";return{...r,text:i,character:o,characterName:o.name}}),iu=e=>!(!e||e.mode==="adv"&&e.content===void 0),su=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:n={},variables:r,runtime:o}={})=>{if(!t&&!iu(e))return;let i=e.content===void 0?[{text:""}]:Cr(e.content,"dialogue.content"),s=e.content===void 0?0:Ol({content:e.initialRevealedContent,path:"dialogue.initialRevealedContent",variables:r}),l=o?.dialogueTextSpeed??Qe.dialogueTextSpeed,a=e.textSpeed??l,c=(e.lines||[]).map((d,f)=>{let p=Cr(d.content,`dialogue.lines[${f}].content`),h=Lr({characterId:d.characterId,character:d.character,characterName:d.characterName,characters:n,variables:r});return{...d,textSpeed:d.textSpeed??l,content:p.map(g=>({...g,text:dt(g.text,{variables:r})})),character:h,characterName:h.name}}),u=Lr({characterId:e.characterId,character:e.character,characters:n,variables:r});return{characterId:e.characterId,persistCharacter:e.persistCharacter,persistSprite:e.persistSprite,character:u,textSpeed:a,content:i.map(d=>({...d,text:dt(d.text,{variables:r})})),initialRevealedCharacters:s,lines:c}},Ui=({container:e,resources:t,templateData:n,isLineCompleted:r=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=le(e,n,{functions:Le});return Te(Ue(s,{isLineCompleted:r,skipMode:o,skipTransitionsAndAnimations:i}),t)},xr=(e,t={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(t),Ci=({renderStateKeyboard:e,keyboard:t,phase:n})=>{!t||typeof t!="object"||Array.isArray(t)||Object.entries(t).forEach(([r,o])=>{let i=e[r]??{},s=n==="keydown"?o?.keydown:o?.keyup;if(n==="keydown"&&s&&typeof s=="object"){e[r]={...i,keydown:{payload:xr(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[r].keyup={payload:xr(o.keyup)});return}e[r]={...i,[n]:{payload:xr(o)}}})},au=(e={},t={})=>{let n={};return Ci({renderStateKeyboard:n,keyboard:e,phase:"keydown"}),Ci({renderStateKeyboard:n,keyboard:t,phase:"keyup"}),Object.keys(n).length>0?n:void 0},De=({animationsDef:e,resources:t,previousResourceId:n,currentResourceId:r,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:l})=>{if(!e)return[];let a=[],c=({instanceId:I,targetId:w})=>{let E=Rl({resources:t,animationId:p,playback:h,instanceId:I,targetId:w,animationPath:s});E&&a.push(E)},u=n!=null&&n!==!1,d=r!=null&&r!==!1,f=o&&i&&o===i;Sl(e,s);let p=wl(e),h=El(e),g=t?.animations?.[p],y=Al(g,{animationId:p,animationPath:s});if(y==="update")return d&&i?c({instanceId:`${l}-animation-update`,targetId:i}):u&&o&&c({instanceId:`${l}-animation-update`,targetId:o}),a;if(y==="transition"){let I=`${l}-animation-transition`,w=h?.continuity==="persistent"?I:`${l}-animation-in`;if(u&&d&&f)return c({instanceId:I,targetId:i}),a;u&&c({instanceId:`${l}-animation-out`,targetId:o}),d&&c({instanceId:w,targetId:i})}return a},cu=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),lu=(e,{presentationState:t,previousPresentationState:n,currentLineActions:r,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:l,variables:a,runtime:c,activePersistentAnimations:u,restoredPersistentAnimations:d,autoMode:f,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:I,saveSlots:w=[]})=>{let{elements:E,animations:_}=e;if(t.background){let j=r===void 0?!0:et(r?.background??{},"animations"),F=E.find(de=>de.id==="story");if(!F)return e;let x=kl(o,t.background),z=x||Ll(t.background),q=n?.background?.resourceId,X=n?.background?.colorId,U=t.background.resourceId??(t.background.animations?q:void 0),Y=t.background.colorId??(t.background.animations?X:void 0),K=Kl(o,U),Q={...t.background,colorId:Y};if((Y!==void 0||K)&&F.children.push(Gl({resources:o,background:Q,screen:i,includeOpacity:!K})),U){let{images:de={},videos:fe={},spritesheets:Z={}}=o,oe=ki(o,U),pe;if(oe==="sprite"?pe=de[U]:oe==="video"?pe=fe[U]:oe==="spritesheet-animation"&&(pe=Z[U]),pe){let S=oe==="video",O=oe==="spritesheet-animation",M={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...x},ie={...Ai(t.background,{includeDefaultAlpha:!0}),...Me(M,t.background)},se;O?se=$i({id:dn({resourceId:U,kind:oe}),resourceId:U,spritesheet:pe,animationName:t.background.animationName,animationSpeed:t.background.animationSpeed,loop:t.background.loop,transform:ie}):se={id:dn({resourceId:U,kind:oe}),type:S?"video":"sprite",src:pe.fileId,width:pe.width,height:pe.height,...ie},S&&(se.loop=t.background.loop??!1,se.volume=pe.volume??50),se&&F.children.push(se)}}if(U){let{layouts:de={}}=o,fe=de[U];if(fe){let Z={id:dn({resourceId:U,kind:"container"}),type:"container",children:fe.elements,...Ai(t.background)};z&&Object.assign(Z,Me({x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...x},t.background));let oe=le(Z,Re({variables:a,runtime:c,saveSlots:w,dialogueState:t.dialogue,isLineCompleted:s,autoMode:f,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:I,characters:o.characters||{},skipTransitionsAndAnimations:l}),{functions:Le});F.children.push(Te(Ue(oe,{isLineCompleted:s,skipMode:p,skipTransitionsAndAnimations:l}),o))}}let _e=Ei({resources:o,resourceId:q,colorId:X}),ne=Ei({resources:o,resourceId:U,colorId:Y}),re=De({animationsDef:t.background.animations,resources:o,previousResourceId:_e.resourceId,currentResourceId:ne.resourceId,previousTargetId:_e.targetId,currentTargetId:ne.targetId,animationPath:"background.animations",idPrefix:"bg-cg"});Se({animationInstances:re,isLineCompleted:s,skipTransitionsAndAnimations:l,activePersistentAnimations:u,restoredPersistentAnimations:d,isAuthoredOnCurrentLine:j})&&_.push(...re)}return e},uu=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:l,animations:a}=e;if(t.character&&r){let c=l.find(h=>h.id==="story");if(!c)return e;let u=t.character.items||[],d=n?.character?.items||[],f=gi(u),p=gi(d);for(let h=0;h<u.length;h++){let g=u[h],{transformId:y,sprites:I}=g,w=d.find(U=>U.id===g.id),E=d.findIndex(U=>U.id===g.id),_=w?.sprites&&w.sprites.length>0,j=I&&I.length>0,F=E>=0?an(w,E,p):void 0,x=De({animationsDef:g.animations,resources:r,previousResourceId:F,currentResourceId:j?an(g,h,f):void 0,previousTargetId:F,currentTargetId:j?an(g,h,f):void 0,animationPath:`character.items[${h}].animations`,idPrefix:"character"});if(g.animations&&!I&&!y&&_&&Se({animationInstances:x,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){a.push(...x);continue}if(g.animations&&!I&&!y)continue;if(!I||I.length===0||!y){console.warn("Character item missing sprites or transformId:",g);continue}let z=an(g,h,f),q=r.transforms[y];if(!q){console.warn("Transform not found:",y);continue}let X={type:"container",id:z,...Me(q,g),...$t(g),children:[]};for(let U of I){let Y=Li({id:`${z}-${U.id}`,item:U,resources:r});Y&&X.children.push(Y)}c.children.push(X),Se({animationInstances:x,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...x)}}return e},Bi=(e,t)=>{if(!gr.includes(e))throw new Error(`${t} must be one of: ${gr.join(", ")}.`)},du=(e,t)=>{let n=!!e.resourceId||Vr(e),r=e.layer??(n?void 0:t?.layer)??mr;return Bi(r,`Visual item "${e.id}" layer`),r},fu=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,runtime:l,activePersistentAnimations:a,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,form:h,saveSlots:g=[],visualLayer:y})=>{let{elements:I,animations:w}=e;if(t.visual&&r){let E=I.find(x=>x.id==="story");if(!E)return e;let _=t.visual.items,j=n?.visual?.items||[],F=Re({variables:s,runtime:l,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:o,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,form:h,characters:r.characters||{},skipTransitionsAndAnimations:i});y!==void 0&&Bi(y,"visualLayer");for(let x of _){let z=j.find(K=>K.id===x.id),q=du(x,z);if(y!==void 0&&q!==y)continue;if(Yl(x),x.text){let K=cn(r,x),Q={...structuredClone(x.text),id:`visual-${x.id}`,type:"text",...Me(K,x)};Object.assign(Q,$t(x)),E.children.push(Te(le(Q,F,{functions:Le}),r))}if(x.resourceId){let{images:K={},videos:Q={},spritesheets:_e={}}=r,ne=_e[x.resourceId];if(ne){let re=cn(r,x),de=x.animationName;if(de){let fe=ne.animations?.[de];if(!fe)throw new Error(`Animation '${de}' not found in spritesheet resource '${x.resourceId}'`);let Z=$t(x),oe={id:`visual-${x.id}`,type:"spritesheet-animation",...Me(re,x),width:x.width??ne.width,height:x.height??ne.height,alpha:Z.alpha??x.alpha??1,src:ne.fileId,atlas:ne.jsonData,playback:{frames:fe.frames,animationSpeed:x.animationSpeed??fe.animationSpeed??.5,loop:x.loop??fe.loop??!0}};Z.blur&&(oe.blur=Z.blur),E.children.push(structuredClone(oe))}}else{let re=K[x.resourceId]||Q[x.resourceId];if(re){let de=Q[x.resourceId]!==void 0,fe=cn(r,x),Z={id:`visual-${x.id}`,type:de?"video":"sprite",src:re.fileId,width:re.width,height:re.height,...Me(fe,x)};Object.assign(Z,$t(x)),de&&(Z.loop=re.loop??!1,Z.volume=re.volume??50),E.children.push(Z)}}}if(x.resourceId){let{layouts:K={}}=r,Q=K[x.resourceId];if(Q){let _e=cn(r,x),ne={id:`visual-${x.id}`,type:"container",children:structuredClone(Q.elements),...Me(_e,x)};Object.assign(ne,$t(x));let re=le(ne,F,{functions:Le});E.children.push(Te(Ue(re,{isLineCompleted:o,skipMode:u,skipTransitionsAndAnimations:i}),r))}}let X=wi(z),U=wi(x),Y=De({animationsDef:x.animations,resources:r,previousResourceId:X,currentResourceId:U,previousTargetId:X?`visual-${x.id}`:void 0,currentTargetId:U?`visual-${x.id}`:void 0,animationPath:`visual.items[${x.id}].animations`,idPrefix:x.id});Se({animationInstances:Y,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:a})&&w.push(...Y)}}return e},pt="dialogue-character-sprite",pu=(e,{presentationState:t,previousPresentationState:n,resources:r={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:l}=e,a=nt(e.elements);if(!a)return e;let c=t.dialogue?.character?.sprite,u=n?.dialogue?.character?.sprite,d=Ct(c),f=Ct(u),p=De({animationsDef:c?.animations,resources:r,previousResourceId:f?pt:void 0,currentResourceId:d?pt:void 0,previousTargetId:f?pt:void 0,currentTargetId:d?pt:void 0,animationPath:"dialogue.character.sprite.animations",idPrefix:"dialogue-character-sprite"});if(!d)return c?.animations&&f&&Se({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...p),e;let h=r.transforms?.[c.transformId];if(!h)return console.warn("Transform not found:",c.transformId),e;let g={type:"container",id:pt,...Me(h),children:[]};for(let y of c.items){let I=Li({id:`${pt}-${y.id}`,item:y,resources:r});I&&g.children.push(I)}return a.children.push(g),Se({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...p),e},hu=(e,{presentationState:t,previousPresentationState:n,resources:r={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:a,canRollback:c,form:u,skipOnlyViewedLines:d,isLineCompleted:f,skipTransitionsAndAnimations:p,variables:h,runtime:g,activePersistentAnimations:y,saveSlots:I=[]})=>{let{elements:w,animations:E}=e;if(!t.dialogue||o)return e;let _=w.find(F=>F.id==="story");if(!_)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:F={}}=r,x=F[t.dialogue.ui.resourceId];if(x){let z={elements:x.elements},q=Re({variables:h,runtime:g,saveSlots:I,dialogueState:t.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:f,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:a,canRollback:c,form:u,characters:r.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:d,skipTransitionsAndAnimations:p}),X={functions:Le},U=un(z,q,X),Y=le(U,q,X),K=Te(Ue(Y?.elements,{isLineCompleted:f,skipMode:s,skipTransitionsAndAnimations:p}),r);if(Array.isArray(K))for(let Q of K)_.children.push(Q);else K&&_.children.push(K)}}pu(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:f,skipTransitionsAndAnimations:p,activePersistentAnimations:y});let j=De({animationsDef:t.dialogue.ui?.animations,resources:r,previousResourceId:n?.dialogue?.ui?.resourceId,currentResourceId:t.dialogue.ui?.resourceId,previousTargetId:n?.dialogue?.ui?.resourceId?"dialogue-container":void 0,currentTargetId:t.dialogue.ui?.resourceId?"dialogue-container":void 0,animationPath:"dialogue.ui.animations",idPrefix:"dialogue-ui"});return Se({animationInstances:j,isLineCompleted:f,skipTransitionsAndAnimations:p,activePersistentAnimations:y})&&E.push(...j),e},mu=(e,{presentationState:t,previousPresentationState:n,resources:r,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,runtime:a,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,form:h,activePersistentAnimations:g,saveSlots:y=[]})=>{let{elements:I,animations:w}=e;if(t.choice&&r){let E=nt(I);if(!E)return e;let _=r?.layouts[t.choice.resourceId];if(_&&_.elements){let F={elements:_.elements},x=le(F,{...Re({variables:l,runtime:a,saveSlots:y,dialogueState:t.dialogue,isLineCompleted:i,autoMode:c,skipMode:u,isChoiceVisible:d??!!t.choice,isFormVisible:f,canRollback:p,form:h,characters:r.characters||{},skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}},{functions:Le}),z=Or(Te(Ue(x?.elements,{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),r));if(Array.isArray(z))for(let q of z)E.children.push(q);else z&&E.children.push(z)}let j=De({animationsDef:t.choice.animations,resources:r,previousResourceId:n?.choice?.resourceId,currentResourceId:t.choice.resourceId,previousTargetId:n?.choice?.resourceId?"choice-container":void 0,currentTargetId:t.choice.resourceId?"choice-container":void 0,animationPath:"choice.animations",idPrefix:"choice"});Se({animationInstances:j,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:g})&&w.push(...j)}return e},gu=(e,{presentationState:t,previousPresentationState:n,resources:r,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,runtime:a,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,activePersistentAnimations:h,saveSlots:g=[],form:y})=>{let{elements:I,animations:w}=e;if(!y?.resourceId||!r)return e;let E=nt(I);if(!E)return e;let _=r?.layouts?.[y.resourceId];if(!_)return console.warn(`Form layout not found: ${y.resourceId}`),e;let j={id:"form-container",type:"container",x:0,y:0,children:_.elements||[]},F={...Re({variables:l,runtime:a,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:i,autoMode:c,skipMode:u,isChoiceVisible:d,isFormVisible:f,canRollback:p,characters:r.characters||{},skipTransitionsAndAnimations:s,form:y}),form:y},x=le(j,F,{functions:Le}),z=$r(Te(Ue(kr(x,y),{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),r),y);z&&E.children.push(z);let q=De({animationsDef:y.animations,resources:r,previousResourceId:n?.form?.resourceId,currentResourceId:y.resourceId,previousTargetId:n?.form?.resourceId?"form-container":void 0,currentTargetId:y.resourceId?"form-container":void 0,animationPath:"form.animations",idPrefix:"form"});return Se({animationInstances:q,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:h})&&w.push(...q),e},yu=(e,{presentationState:t,resources:n={},variables:r,runtime:o,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,saveSlots:f=[],skipTransitionsAndAnimations:p})=>{if(!t.control?.resourceId)return e;let h=n.controls?.[t.control.resourceId];if(!h)return e;let g=au(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=nt(e.elements);if(!y)return e;let I={id:`control-${t.control.resourceId}`,type:"container",x:0,y:0,children:h.elements};return y.children.push(Ui({container:I,resources:n,templateData:Re({variables:r,runtime:o,saveSlots:f,dialogueState:t.dialogue,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,characters:n.characters||{},skipTransitionsAndAnimations:p}),isLineCompleted:i,skipMode:l,skipTransitionsAndAnimations:p})),e},bu=(e,{presentationState:t,resources:n,runtime:r,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&n){if(!nt(i))return e;let a=t.bgm,c=!Array.isArray(a.sounds),u=c?a.resourceId?[{id:"default",resourceId:a.resourceId,loop:a.loop??!0,volume:a.volume,startDelayMs:a.startDelayMs??0}]:[]:a.sounds,d=[];if(c||pn(u,"BGM sound"),u.forEach(p=>{let h=n.sounds?.[p.resourceId];h&&d.push(Mr({id:Lt("bgm",c?"default":p.id),sound:p,resource:h,defaultLoop:!0}))}),d.length===0)return e;let f=Re({variables:o,runtime:r}).runtime;s.push(Fr({id:Jl,volume:jr(f,"musicVolume",c?tt:a.volume??tt),muted:a.muted,pan:a.pan,children:d,runtime:f}))}return e},Iu=(e,{presentationState:t,resources:n,runtime:r})=>{let{audio:o}=e;if(t.sfx&&n){let i=t.sfx,s=!Array.isArray(i.channels),l=s?[{id:Ql,sounds:i.items??[]}]:i.channels;s||pn(l,"SFX channel"),l.forEach(a=>{let c=[];s||pn(a.sounds,"SFX sound",`SFX channel "${a.id}"`),a.sounds.forEach((u,d)=>{let f=n.sounds?.[u.resourceId];f&&c.push(Mr({id:s?Lt("sfx","default",d,u.id):Lt("sfx",a.id,u.id),sound:u,resource:f}))}),c.length!==0&&o.push(Fr({id:Lt("channel","sfx",a.id),volume:jr(r,"soundVolume",a.volume??tt),muted:a.muted,pan:a.pan,children:c,runtime:r}))})}return e},Au=(e,t,n)=>{if(!(!t||!n))return e?.voices?.[t]?.[n]},wu=(e,{presentationState:t,resources:n,currentSceneId:r,runtime:o,variables:i})=>{let{audio:s}=e;if(!t?.voice)return e;let l=t.voice,a=!Array.isArray(l.sounds),c=a?l.resourceId?[{id:"default",resourceId:l.resourceId,loop:l.loop??!1,volume:tt,startDelayMs:l.startDelayMs??0}]:[]:l.sounds,u=[];if(a||pn(c,"Voice sound"),c.forEach(f=>{let p=Au(n,r,f.resourceId);p&&u.push(Mr({id:Lt("voice",r,a?"default":f.id),sound:f,resource:p}))}),u.length===0)return e;let d=Re({variables:i,runtime:o}).runtime;return s.push(Fr({id:Xl,volume:a?l.volume??ji(d,"soundVolume"):jr(d,"soundVolume",l.volume??tt),muted:l.muted,pan:l.pan,children:u,runtime:d})),e},Eu=(e,{presentationState:t,previousPresentationState:n,resources:r={},variables:o,runtime:i,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,saveSlots:f=[],isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})=>{let{elements:y,animations:I}=e;if(t.layout){let j=nt(y);if(!j)return e;let F=r.layouts[t.layout.resourceId];if(!F)return e;Array.isArray(F.transitions)&&!p&&!h&&Dr({animations:I,transitions:F.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let x={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:F.elements||[]};j.children.push(Ui({container:x,resources:r,templateData:Re({variables:o,runtime:i,saveSlots:f,dialogueState:t.dialogue,isLineCompleted:p,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,characters:r.characters||{},skipTransitionsAndAnimations:h}),isLineCompleted:p,skipMode:l,skipTransitionsAndAnimations:h}))}let w=n?.layout?.resourceId,E=t.layout?.resourceId,_=De({animationsDef:t.layout?.animations,resources:r,previousResourceId:w,currentResourceId:E,previousTargetId:w?`layout-${w}`:void 0,currentTargetId:E?`layout-${E}`:void 0,animationPath:"layout.animations",idPrefix:"layout"});return Se({animationInstances:_,isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})&&I.push(..._),e},xu=(e,{currentLineActions:t,previousPresentationState:n,resources:r={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:l}=e,a=t?.screen?.animations;if(!a)return e;let c=n!=null,u=De({animationsDef:a,resources:r,previousResourceId:c?"story":void 0,currentResourceId:"story",previousTargetId:c?"story":void 0,currentTargetId:"story",animationPath:"screen.animations",idPrefix:"screen"});return Se({animationInstances:u,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...u),e},vu=(e,{presentationState:t})=>{let n=nt(e.elements);return!n||!t?.screen||Object.assign(n,Pi(t.screen)),e},Cu=(e,{presentationState:t,resources:n={},variables:r,runtime:o,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:a,canRollback:c,form:u,overlayStack:d=[],dialogueHistory:f=[],saveSlots:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:I,animations:w}=e;return d&&d.length>0&&d.forEach((E,_)=>{let j=n.layouts[E.resourceId];if(!j){console.warn(`Overlay layout not found: ${E.resourceId}`);return}Array.isArray(j.transitions)&&(y||Dr({animations:w,transitions:j.transitions,defaultTargetId:`overlayStack-${_}`,idPrefix:`overlayStack-${_}`,animationPathPrefix:`overlayStack[${_}]`}));let F={id:`overlayStack-${_}`,type:"container",x:0,y:0,children:[Fi({id:`overlayStack-${_}-blocker`,screen:h}),...j.elements||[]]},x=Mi(f,n.characters,r),z=Re({variables:r,runtime:o,saveSlots:p,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:a,canRollback:c,form:u,historyDialogue:x,characters:n.characters||{},skipTransitionsAndAnimations:y}),q=le(F,z,{functions:Le}),[X,...U]=q.children||[],Y=Te(Ue({...q,children:U},{isLineCompleted:g,skipMode:s,skipTransitionsAndAnimations:y}),n);I.push({...Y,children:X?[X,...Y.children||[]]:Y.children})}),e},Su=(e,{presentationState:t,resources:n={},variables:r,runtime:o,saveSlots:i=[],autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,confirmDialog:f,dialogueHistory:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:I,animations:w}=e;if(!f?.resourceId)return e;let E=n.layouts?.[f.resourceId];if(!E)return console.warn(`ConfirmDialog layout not found: ${f.resourceId}`),e;Array.isArray(E.transitions)&&!y&&Dr({animations:w,transitions:E.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let _={id:"confirmDialog",type:"container",x:0,y:0,children:[Fi({id:"confirmDialog-blocker",screen:h}),...E.elements||[]]},j=Mi(p,n.characters,r),F=le(_,Re({variables:r,runtime:o,saveSlots:i,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:s,skipMode:l,isChoiceVisible:a,isFormVisible:c,canRollback:u,form:d,confirmDialog:f,historyDialogue:j,characters:n.characters||{},skipTransitionsAndAnimations:y}),{functions:Le}),[x,...z]=F.children||[],q=Te(Ue({...F,children:z},{isLineCompleted:g,skipMode:l,skipTransitionsAndAnimations:y}),n);return I.push({...q,children:x?[x,...q.children||[]]:q.children}),e},Nt=e=>(t,n)=>fu(t,{...n,visualLayer:e}),Ru=Nt($e.BEHIND_BACKGROUND),_u=Nt($e.BEHIND_CHARACTER),Ou=Nt($e.BEHIND_DIALOGUE),ku=Nt($e.BEHIND_CHOICE),$u=Nt($e.FOREGROUND),zi=e=>tn(cu,[yu,Ru,lu,_u,uu,Ou,hu,ku,mu,gu,Eu,$u,vu,xu,bu,Iu,wu,Cu,Su])(e);function qi(e,t=""){let n=[],r=e.length,o=0,i=0,s=-1,l=()=>{let a=0,c=0,u;do u=parseInt(e[o++],36),a+=(u&15)<<c,c+=4;while(u&16);return a};for(;o<r;){let a=s+1+l();s=a+l(),n.push([a,s,t?parseInt(t[i++],36):0])}return n}function Hi(e,t,n){let r=0,o=t.length-1;for(;r<=o;){let i=r+o>>>1,s=n[i];if(e<t[i])o=i-1;else if(e>s>>>5)r=i+1;else return s&31}return 0}var Wi="090001000h1v5g2903000hl2v6jh16ng1s210111110o35aa10u2k1g10l6600152113h2010u1q1r5aq3890o13181214r22k3158q2n1000v100h1k20000001207030001160721k171001h1j11610332010010321210090411021c1c02100o301201412230u1130b100h1j116111420120411001100k11l10051001h1j11611142011000321210072411021d0g10r3000000132120090o200200g1j11f2012031213711271t1001o301001000001121371b1f0c101h1l2011001031212000080a1t1001m40400102101600i11t301006c7i601008b6p41r10101041h3d0004115a1j290p3q223000511010100g1501010302003172030c0010016000e0i6v50n40n5tl12ir33s12t11u11cj30100060700010a90t220000l71i20m7203010241000502rd101004k300000006101027050920g3t22bk1300616g209030207u18c1000t10003010501b2o20000102000004g37070101o921c000640602001mcv3rg20000001o16d0c0m1fg6g2h30m10q55f1vm11c0ma0p1a42nc0ne1a090q3314902021204020112030318250105bb1201110i1021i15101131502141b15120511011k1155132040202510201010603060a1f02040104210b1g3290e0e0kn11vs12j11j3040pp12t80g6v1vmo7319g21g51gh103040n11010040j51i3f01q1h1d0m27p1a0000cs13200523j200010301010100v140018a4q2501010101c08000i1f12601011g3012215110u1a0001015000pcq181000100011000iji5fvc0u91g5bhg20ie0l94lo6002115303121s12240la1tj23h44tj11t45m4ah33q700000l3ep2021a200t220301012040a0i320j2040007f00100r20c100g3208000011531000s520201036020t900207l1101n311000000321210090a12634b910201l22001051020120011020000e1i520701020000n10h5001050000010000010001re0010323010001r11i520701000001q6000000107l600000230004gg12080001lc62027111n1000411230000000000t820321030030r10090n205001380800501020n2050c0001mc00002000000nc006150000i5l1100600010001q753011160000i441111000000rl11019100000c1h201043102n10ltk1f006eoss2b0202gs94r36si2033ku101m373h50b1rqs4113sli1t22m1uh2435070726u13k92rr7m34h380e0m141egl561g1261114k60ga6nn10t33sv13uf1jf0207150qt16t66pr60n23k6bf1f0e1l29g71c1e029j1n30p11ea0k1028139m16rb2v621122i52213040tf1u3b51n17127c0232041d120819052c28220104060306l5g3l4572g130152cqdl2c3o37a5o27u11c32d9m2cu2191obo57eh9gg1tv3",Yi="262122424333333393233393339333333333393393bf3b3b3b3b3f3f3bffff33b3bb33ff3f33b3b3333333bffff3b33bb33f33bffff33b3bb33ff3f33b3bbb333b3ff33b333f33b3b3b3b3333b3bf33b3bb39333b33b33b3b3b333b333333b3b33333f3b33b3ffb3f3fff3f3b33f35dc33333f3b3b3b33323333b3bb3b33b3fb3b3333b33333bff3b3f33bfb3b3ff3b3b3b3b3b333b333b3323e22442344444444444444444444444444444444444444444444444444444444444444444444444444444443333333333b3b3bb33333b353bff3b3b3b3f3ff3b3b333bfff3f33333fb3bb3fb3b3bb33232333f333fff333333333b3b3333bb3b39393f3b3fbf33bb3b393b3b3b3333b33b33b3bbb33b33ffff3b3333bb3933b3b3b333b3b3b3b3b33b3b3b33b3b3b33b3b33b33b3b3b3fffff3bb39b9b3b33b3bf3f3b33f3b3f93b33b3b3bb33b33b3b3b3333393b3b3b33b39bffb3b332333b333dd3b3333233332333333333333333333333333333444444444444a4444444444444344444444444444444444444444444444444444444444",Gi="0001000000010010000000100000000000000000000000000001000000010014000100000001001000010101100101100000000000000000000100000001111000010000000110101001110111111111000100000021001000010000000100100001000000011010000100000001111000013000000100140001000000010010";var Ki=65535,Ur=40960,gn=126976,Qi=new Uint8Array(12288),Zi=new Uint8Array(3072),es=new Uint8Array(2816),ts,ns;{let e=(o,i,s,l,a)=>{let c=i+o.length-1;for(let u=s<i?i:s,d=l>c?c:l;u<=d;u++)o[u-i]=a},t=new Uint32Array(320),n=new Uint32Array(320),r=0;for(let[o,i,s]of qi(Wi,Yi))e(Qi,0,o,i,s),e(Zi,Ur,o,i,s),e(es,gn,o,i,s),i>=65040&&!(o>=gn&&i<=129791)&&(t[r]=o,n[r++]=i<<5|s);ts=t.slice(0,r),ns=n.slice(0,r)}function Ji(e){return e<12288?Qi[e]:e<Ur?e<12336?e>=12330?3:0:e<12443?e===12336||e===12349?4:e>=12441?3:0:e===12951||e===12953?4:0:e<44032?Zi[e-Ur]:e<55204?(e-44032)%28?8:7:e<57344?e<=55238?e>=55216?13:0:e>=55243&&e<=55291?12:0:e<65024?e===64286?3:0:e<65040?3:e>=gn&&e<129792?es[e-gn]:e>=917504?e>921599?0:e>=917536&&e<917632||e>=917760&&e<918e3?3:2:Hi(e,ts,ns)}var rs=Uint8Array.from(Gi,Number);function Lu(e){return e===2381||e===2509||e===2637||e===2765||e===2893||e===3149||e===3405||e===4153||e===6098||e===6752||e===6980||e===7083||e===43456||e===43766||e===68159||e===69939||e===70608||e===71998||e===72263||e===72345||e===73538}function Xi(e,t,n){switch(t){case 3:return e&24?n===8204?e&6:(e&24)===16||Lu(n)?e&6|16:e&6|8:e&6;case 4:return 2;case 10:return e&1^1;case 14:return(e&2)<<1|e&24;default:return 8}}function*os(e){let t=e.length;if(t===0)return;let n=e.codePointAt(0),r=n>Ki?2:1,o=Ji(n),i=50200>>o&1?Xi(0,o,n):0,s=0,l=n,a=o;for(;r<t;){n=e.codePointAt(r);let c=n>Ki?2:1,u=Ji(n),d=rs[o<<4|u],f;d===0?f=!0:d===1?f=!1:d===2?f=!(i&1):d===3?f=!(i&4):f=(i&24)!==16,i=50200>>u&1&&(i!==0||u!==3)?Xi(i,u,n):0,f&&(yield{segment:e.slice(s,r),index:s,input:e,_hd:l,_catBegin:a===15?0:a,_catEnd:o===15?0:o},s=r,l=n,a=u),r+=c,o=u}yield{segment:e.slice(s),index:s,input:e,_hd:l,_catBegin:a===15?0:a,_catEnd:o===15?0:o}}function*is(e){for(let t of os(e))yield t.segment}{let e=os("_");rs._keep=[e,e.next()]}var ss=1e3,Tu=1,Du=60,Nu=3,Pu=.5,Vu=2e4,ju=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,Fu=/^\s+$/u,as,Mu=e=>{let t=`${e??""}`.normalize("NFC"),n=globalThis.Intl?.Segmenter;return typeof n!="function"?Array.from(is(t)):(as??=new n(void 0,{granularity:"grapheme"}),Array.from(as.segment(t),({segment:r})=>r))},Uu=e=>Mu(e).reduce((t,n)=>Fu.test(n)?t+Pu:ju.test(n)?t+Nu:t+1,0),cs=({text:e="",baseDelay:t=ss,speed:n=Tu}={})=>{let r=Number.isFinite(t)?Math.max(0,t):ss,o=Number.isFinite(n)&&n>0?n:1,i=Uu(e)*Du/o,s=Math.max(r,Vu);return Math.min(r+i,s)};var yn={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},ps=1,Br=1,gt="choice",Be="form",An=()=>({manual:{...yn.manual},auto:{...yn.auto},applyMode:yn.applyMode}),zr=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let n=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...An()},n&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},N=e=>{let t=ae(e)?Ge(e):e;return structuredClone(t)},D=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),hs=(e,t)=>{if(typeof t!="string"||t.length===0)throw new Error("Achievement action requires a non-empty resourceId");let n=e.projectData.resources?.achievements?.[t];if(!n)throw new Error(`Achievement resource "${t}" not found`);if(n.type!=="boolean"&&n.type!=="number")throw new Error(`Achievement resource "${t}" has invalid type "${n.type}"`);return n},Vt=e=>String(e),ms=()=>({sections:[],resources:[]}),Bu=e=>D(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):ms(),zu=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",qu=({sectionId:e,lineId:t,content:n,dialogueState:r,characterName:o})=>({sectionId:e,lineId:t,content:n,text:zu(n),characterId:r.characterId,character:{...r.character||{},name:o},characterName:o}),Hu=()=>({resourceId:void 0}),Wu=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},yt=(e,t)=>{let n=e?.story?.scenes??{};for(let[r,o]of Object.entries(n))if(o?.sections?.[t])return{sceneId:r,section:o.sections[t]};return{sceneId:void 0,section:void 0}},gs=e=>{let t=e?.story?.scenes??{},n=new Map;for(let[r,o]of Object.entries(t)){let i=o?.sections??{};for(let s of Object.keys(i)){let l=n.get(s);if(l!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${l}" and "${r}". Section IDs must be globally unique.`);n.set(s,r)}}},ys=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},bs=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==ps)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},Yu=(e,t={})=>{let n;try{n=bs(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let r={...t,formatVersion:n,slotId:ys(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete r.slotKey,delete r.date,r},Gu=(e={})=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Yu(t,n)])),Is=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:n})=>ep(n));return t.length>0?t:void 0},Ku=e=>{!D(e)||!Array.isArray(e.timeline)||(e.returnabilityVersion=Br,e.timeline.forEach(t=>{if(!D(t))return;typeof t.returnable!="boolean"&&delete t.returnable;let n=Is(t.executedActions);if(n){t.executedActions=n;return}delete t.executedActions}))},ls=(e,t,n,r="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 ${r}.${t}[${n}] entry.`);if(typeof e[o]!="string"||e[o].length===0)throw new Error(`Malformed ${r}.${t}[${n}] entry: missing ${o}.`);if(t==="sections"){let i={sectionId:e.sectionId};if(e.lastLineId!==void 0&&e.lastLineId!==null&&typeof e.lastLineId!="string")throw new Error(`Malformed ${r}.sections[${n}] entry: invalid lastLineId.`);return typeof e.lastLineId=="string"&&e.lastLineId.length>0&&(i.lastLineId=e.lastLineId),i}return{resourceId:e.resourceId}},Ju=(e,t="viewedRegistry")=>{if(e===void 0)return ms();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 n=e.sections??[],r=e.resources??[];return{sections:Object.values(Object.fromEntries(n.map((o,i)=>{let s=ls(o,"sections",i,t);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(r.map((o,i)=>{let s=ls(o,"resources",i,t);return[s.resourceId,s]})))}},As=(e,t,n)=>{if(!D(e))throw new Error(`Malformed save slot ${n}.`);let{sectionId:r,lineId:o}=e;if(typeof r!="string"||r.length===0)throw new Error(`Malformed save slot ${n}: missing sectionId.`);if(typeof o!="string"||o.length===0)throw new Error(`Malformed save slot ${n}: missing lineId.`);let{sceneId:i,section:s}=yt(t,r);if(!s)throw new Error(`Malformed save slot ${n}: section "${r}" does not exist in projectData.`);if(!s.lines?.some(a=>a.id===o))throw new Error(`Malformed save slot ${n}: line "${o}" does not exist in section "${r}".`);return{sceneId:i,sectionId:r,lineId:o}},ws=(e,t)=>e?.sectionId===t?.sectionId&&e?.lineId===t?.lineId,Xu=(e,t)=>{let{section:n}=yt(e,t?.sectionId);return n?.lines?.find(r=>r.id===t?.lineId)},Qu=(e,t)=>{let{section:n}=yt(e,t?.sectionId),r=n?.lines?.findIndex(i=>i.id===t?.lineId);if(typeof r!="number"||r<0)return null;let o=n.lines[r+1];return o?{sectionId:t.sectionId,lineId:o.id}:null},Es=(e,t,n)=>{if(typeof t?.sectionId!="string")return!1;let{section:r}=yt(e,t.sectionId);return ws({sectionId:t.sectionId,lineId:r?.lines?.[0]?.id},n)},Zu=new Set(["jumpToLine","rollbackByOffset","rollbackToLine","sectionTransition","resetStoryAtSection"]),mt={always:"always",maybe:"maybe",never:"never"},ed=e=>{if(!Object.prototype.hasOwnProperty.call(e??{},"when"))return mt.always;let t=e.when,n;if(t===null||typeof t=="boolean"||typeof t=="number")n=t;else if(D(t)&&Object.keys(t).length===1&&Object.prototype.hasOwnProperty.call(t,"literal"))n=t.literal;else return mt.maybe;return n?mt.always:mt.never},xs=(e,t)=>{if(!Array.isArray(e?.branches))return!1;for(let n of e.branches){let r=ed(n);if(r!==mt.never){if(t(n))return!0;if(r===mt.always)return!1}}return!1},vs=e=>xs(e,t=>Object.entries(t?.actions??{}).some(([n,r])=>n==="conditional"?vs(r):Zu.has(n))),Cs=(e,t,n)=>xs(t,r=>Object.entries(r?.actions??{}).some(([o,i])=>o==="sectionTransition"?Es(e,i,n):o==="conditional"?Cs(e,i,n):!1)),td=(e,t,n)=>{if(!t)return!0;let r=Xu(n,e)?.actions;if(!D(r))return!0;if(Es(n,r.sectionTransition,t))return!1;let o=r.conditional;return o?!(Cs(n,o,t)||!(r.choice?.resourceId||r.form?.resourceId)&&!vs(o)&&ws(Qu(n,e),t)):!0},nd=(e,t,n)=>{if(!D(e)||!Array.isArray(e.timeline))return Pt({pointer:t,replayStartIndex:1});let r=new WeakSet,o=e.timeline.flatMap((c,u)=>{if(!D(c))return[];try{let d=As(c,n,`rollback.timeline[${u}]`),f=In({sectionId:d.sectionId,lineId:d.lineId,rollbackPolicy:c.rollbackPolicy,returnable:c.returnable});typeof c.returnable=="boolean"&&r.add(f);let p=Is(N(c.executedActions));return p&&(f.executedActions=p),[f]}catch{return[]}});if(o.length===0)return Pt({pointer:t,replayStartIndex:1});e.returnabilityVersion!==Br&&o.forEach((c,u)=>{!r.has(c)&&!td(c,o[u+1],n)&&(c.returnable=!1)});let s=typeof e.currentIndex=="number"?Math.trunc(e.currentIndex):o.length-1;(s<0||s>=o.length)&&(s=o.length-1);let l=o[s];if(l?.sectionId!==t.sectionId||l?.lineId!==t.lineId){let c=o.findLastIndex(u=>u.sectionId===t.sectionId&&u.lineId===t.lineId);c>=0?s=c:(o.push(In({sectionId:t.sectionId,lineId:t.lineId})),s=o.length-1)}let a=typeof e.replayStartIndex=="number"?Math.min(Math.max(Math.trunc(e.replayStartIndex),0),s):0;return{currentIndex:s,isRestoring:!1,replayStartIndex:a,timeline:o}},rd=(e,t,n)=>{if(!D(e))throw new Error(`Malformed save slot contexts[${n}] entry.`);let r=Wr(t),o=As(e.pointers?.read,t,`contexts[${n}].pointers.read`);if(e.variables!==void 0&&!D(e.variables))throw new Error(`Malformed save slot contexts[${n}].variables entry.`);if(e.runtime!==void 0&&!D(e.runtime))throw new Error(`Malformed save slot contexts[${n}].runtime entry.`);let i=e.variables?ut(N(e.variables),t.resources?.variables??{}):{},s=gd({loadedContextRuntime:D(e.runtime)?N(e.runtime):{}}),l={currentPointerMode:"read",pointers:{read:o},configuration:D(e.configuration)?N(e.configuration):{},views:Array.isArray(e.views)?N(e.views):[],bgm:D(e.bgm)?N(e.bgm):{resourceId:void 0},variables:{...r,...i},rollback:nd(e.rollback,o,t)};return s&&(l.runtime=s),l},od=(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((n,r)=>rd(n,t,r))}},id=(e,t)=>{if(!D(e))throw new Error("Malformed save slot.");let n=bs(e.formatVersion);return{...e,formatVersion:n,state:od(e.state,t)}},us=(e,t,{required:n=!1}={})=>{if(e===void 0){if(n)throw new Error(`showConfirmDialog requires ${t}`);return{hideConfirmDialog:{}}}if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`showConfirmDialog ${t} must be an action object`);let r=N(e);return Object.prototype.hasOwnProperty.call(r,"hideConfirmDialog")||(r.hideConfirmDialog={}),r},sd=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:us(e.confirmActions,"confirmActions",{required:!0}),cancelActions:us(e.cancelActions,"cancelActions")}},bt=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},ad=e=>(D(e.global.formDrafts)||(e.global.formDrafts={}),e.global.formDrafts),It=e=>{Object.prototype.hasOwnProperty.call(e.global,"formDrafts")&&(e.global.formDrafts={})},Ss=e=>{if(!(!D(e)||!e.animations))return{animations:N(e.animations)}},cd=(e,t)=>{let n=Ss(t);if(n){e.global.pendingScreenTransition=n;return}delete e.global.pendingScreenTransition},ld=e=>{let t=e?.id??e?.resourceId;return typeof t=="string"&&t.length>0?t:void 0},ud=(e,t)=>{let n=e?.sectionId,r=e?.lineId;if(!(!n||!r||!t))return`${n}:${r}:${t}`},bn=e=>String(e??""),Rs=(e,t)=>{let n=bn(t);return e?.trim===!0?n.trim():n},dd=e=>D(e?.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,t])=>D(t)).map(([t,n])=>[t,{id:t,...N(n)}])):{},fd=(e,t)=>{if(!t||!D(e.global.formDrafts))return;let n=e.global.formDrafts[t];return D(n)?n:void 0},_s=(e,t)=>{let n=ad(e);D(n[t])||(n[t]={values:{},touched:{},errors:{},submitted:!1});let r=n[t];return D(r.values)||(r.values={}),D(r.touched)||(r.touched={}),D(r.errors)||(r.errors={}),typeof r.submitted!="boolean"&&(r.submitted=!1),r},qr=(e,t)=>{let n=Rs(e,t);return e?.required===!0&&n.length===0?"required":null},pd=({state:e,pointer:t})=>{if(!t?.sectionId||!t?.lineId)return{};let r=ue({state:e},{sectionId:t.sectionId})?.lines||[],o=r.findIndex(i=>i.id===t.lineId);return o<0?{}:Xe(r.slice(0,o+1).map(i=>i.actions||{}))},hd=({state:e,form:t,pointer:n})=>{if(!t?.resourceId)return null;let r=ld(t),o=ud(n,r);if(!r||!o)return null;let i=fd(e,o),s=dd(t),l=En({state:e}),a={},c=[],u={},d=!0;return Object.entries(s).forEach(([f,p])=>{let h=bn(l?.[p.variableId]),g=Object.prototype.hasOwnProperty.call(i?.values??{},f)?bn(i.values[f]):h,y=i?.touched?.[f]===!0,I=qr(p,g),w=i?.submitted||y?I:null,E=typeof p.maxLength=="number"?Math.max(0,Math.round(p.maxLength)):void 0,_={id:f,variableId:p.variableId,value:g,initialValue:h,valid:!I,error:w,touched:y,required:p.required===!0,trim:p.trim===!0,placeholder:p.placeholder===void 0?"":String(p.placeholder),multiline:p.multiline===!0,...E!==void 0?{maxLength:E}:{}};I&&(d=!1),a[f]=_,c.push(_),u[f]=g}),{id:r,key:o,resourceId:t.resourceId,animations:t.animations,valid:d,submitted:i?.submitted===!0,fields:a,fieldList:c,values:u,submitActions:{submitForm:{formKey:o,actions:N(t.submitActions??{})}},cancelActions:{cancelForm:{formKey:o,actions:N(t.cancelActions??{})}}}},rt=[],ds="line",Hr="interaction",In=({sectionId:e,lineId:t,rollbackPolicy:n,returnable:r})=>({sectionId:e,lineId:t,rollbackPolicy:n??"free",...typeof r=="boolean"?{returnable:r}:{}}),Wr=e=>{let{contextVariableDefaultValues:t}=rn(e??{});return N(t)},Os=()=>({...N(kt)}),ks=({loadedRuntime:e,runtimeIds:t,defaults:n={},path:r})=>{if(e===void 0)return{runtimeState:N(n),hasLoadedValues:!1};if(!D(e))throw new Error(`Malformed ${r}.`);let o=N(n),i=!1;return t.forEach(s=>{e[s]!==void 0&&(o[s]=$s(s,N(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},md=({loadedGlobalRuntime:e={}})=>ks({loadedRuntime:e,runtimeIds:pr,defaults:Qe,path:"global.runtime"}).runtimeState,gd=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:n}=ks({loadedRuntime:e,runtimeIds:hr,defaults:Os(),path:"context.runtime"});return n?t:void 0},wn=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},yd=e=>e.runtime?(hr.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=N(kt[t]))}),e.runtime):(e.runtime=Os(),e.runtime),bd=e=>hi(e.global),Id=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:bd(e)}})},Ad=e=>pi[e],wd=(e,t)=>{let n=Ad(e);if(n==="number"){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} requires a finite numeric value`);return}if(n==="boolean"){if(typeof t!="boolean")throw new Error(`${e} requires a boolean value`);return}if(n==="string"){if(typeof t!="string")throw new Error(`${e} requires a string value`);return}throw new Error(`Unsupported runtime field "${e}"`)},$s=(e,t)=>{if(wd(e,t),e==="autoForwardSpeed"&&t<=0)throw new Error("autoForwardSpeed requires a value greater than 0");return e==="saveLoadPagination"?Math.max(1,Math.trunc(t)):t},Ls=(e,t,n)=>{let r=$s(t,n);if(t in kt){let o=wn(e);if(!o)return r;let i=yd(o);return i[t]=r,r}return e.global[t]=r,r},Ts=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:N(e)},configuration:{},views:[],bgm:Hu(),variables:Wr(t),rollback:Pt({pointer:e})}),At=e=>e?(e.currentPointerMode="read",D(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,Ed=(e,{queueRender:t=!0}={})=>{let n=e.contexts?.[e.contexts.length-1],r=n?.pointers?.read;if(!n||!r?.sectionId||!r?.lineId)return null;let o=Ts({pointer:r,projectData:e.projectData});return e.contexts[e.contexts.length-1]=o,xd(e,{queueRender:t}),o},xd=(e,{queueRender:t=!0}={})=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,bt(e),It(e),e.global.nextLineConfig=An(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"}),t&&e.global.pendingEffects.push({name:"render"})},Ds=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},Pt=({pointer:e,replayStartIndex:t=0})=>{let n=e?.sectionId&&e?.lineId;return{currentIndex:n?0:-1,isRestoring:!1,replayStartIndex:t,timeline:n?[In({sectionId:e.sectionId,lineId:e.lineId})]:[]}},it=(e,t={})=>{if(e?.rollback)return Ds(e.rollback),Array.isArray(e.rollback.timeline)||(e.rollback.timeline=[]),typeof e.rollback.currentIndex!="number"&&(e.rollback.currentIndex=e.rollback.timeline.length>0?e.rollback.timeline.length-1:-1),typeof e.rollback.isRestoring!="boolean"&&(e.rollback.isRestoring=!1),typeof e.rollback.replayStartIndex!="number"&&(e.rollback.replayStartIndex=0),e.rollback;let n=e?.pointers?.read;return e.rollback=Pt({pointer:n,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},Yr=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return;let r=it(n);r.isRestoring||(r.currentIndex<r.timeline.length-1&&(r.timeline=r.timeline.slice(0,r.currentIndex+1)),r.timeline.push(In(t)),r.currentIndex=r.timeline.length-1)},vd=({state:e})=>{let n=e.contexts?.[e.contexts.length-1]?.rollback;return!Array.isArray(n?.timeline)||typeof n.currentIndex!="number"?null:{checkpointIndex:n.currentIndex,checkpoint:n.timeline[n.currentIndex]??null}},Cd=({state:e},t={})=>{let{checkpointIndex:n,checkpointIdentity:r,sectionId:o,lineId:i}=t,l=e.contexts?.[e.contexts.length-1]?.rollback;if(!Number.isInteger(n)||!Array.isArray(l?.timeline)||typeof l.currentIndex!="number")return e;let a=l.timeline[n];return(ae(a)?Un(a):a)!==r||a?.sectionId!==o||a?.lineId!==i||(a.returnable=!1),e},Sd=({state:e},t={})=>{let{slotId:n,saveSlotIdentity:r,checkpointIndex:o,sectionId:i,lineId:s}=t,l=Vt(n),a=e.global.saveSlots?.[l],c=ae(a)?Un(a):a;if(!a||c!==r)return e;let u=a.state?.contexts,d=Array.isArray(u)?u.at(-1):null,f=d?.rollback,p=f?.timeline?.[o];return!Number.isInteger(o)||f?.currentIndex!==o||d?.pointers?.read?.sectionId!==i||d?.pointers?.read?.lineId!==s||p?.sectionId!==i||p?.lineId!==s||(p.returnable=!1,f.returnabilityVersion=Br,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}})),e},Rd=e=>{let n=e.contexts?.[e.contexts.length-1]?.rollback;if(!n||n.isRestoring||!Array.isArray(n.timeline)||typeof n.currentIndex!="number")return null;let r=rt[rt.length-1],o=typeof r?.checkpointIndex=="number"?r.checkpointIndex:n.currentIndex;return o<0||o>=n.timeline.length?null:(typeof r?.checkpointIndex!="number"&&o<n.timeline.length-1&&(n.timeline=n.timeline.slice(0,o+1)),n.timeline[o]??null)},_d=({state:e},t={})=>{let n=t?.source===ds?ds:Hr,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?(rt.push({checkpointIndex:null,source:n}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),rt.push({checkpointIndex:o.currentIndex,source:n}),e)},Od=({state:e})=>(rt.pop(),e),ke=(e,t,n)=>{let o=rt[rt.length-1]?.source??Hr;if(!tp(t,o))return;let i=Rd(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:N(n)}))},fs=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return;let r=t?.operations??[];for(let{variableId:o,op:i,value:s,roundTo:l}of r){let a=e.projectData.resources?.variables?.[o],c=a?.scope,u=a?.type;if(Ce(a))throw new Error(`Cannot update computed variable: ${o}`);if(a?.readonly===!0)throw new Error(`Cannot update readonly variable: ${o}`);_t(c,o),on(u,i,o),ar(u,i,s,o,{roundTo:l}),c==="context"&&(n.variables[o]=sn(n.variables[o],i,s,{roundTo:l}))}},kd=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:n,payload:r})=>{np(e,n,r)})},$d=(e,t)=>{let{sectionId:n,lineId:r}=t,s=ue({state:e},{sectionId:n})?.lines?.find(l=>l.id===r)?.actions;s&&Object.entries(s).forEach(([l,a])=>{Xs(e,l,a)})},Ns=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return e;let r=it(n),o=r.timeline[t];if(!o)return e;e.global.autoMode&&Ft({state:e}),e.global.skipMode&&ze({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),r.isRestoring=!0,r.currentIndex=t;try{n.variables=Wr(e.projectData),delete n.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=N(yn),e.global.overlayStack=[],bt(e),It(e),e.global.isLineCompleted=!0;let i=r.replayStartIndex??0;for(let l=i;l<=t;l++)l>i&&zr(e),$d(e,r.timeline[l]),kd(e,r.timeline[l]);let s=At(n);s.read={sectionId:o.sectionId,lineId:o.lineId},e.global.pendingEffects=e.global.pendingEffects.filter(l=>l?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{r.isRestoring=!1}return e},Ld=e=>{let{projectData:t}=e,n=e.global??{},{saveSlots:r={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=n;gs(t),Je(t?.resources?.variables??{});let l=t.story.initialSceneId,a=t.story.scenes[l],c=a.initialSectionId,u=a.sections[c],d={sceneId:l,sectionId:c,lineId:u.initialLineId??u.lines[0].id},{globalVariablesDefaultValues:f}=rn(t),p={...f,...ut(o,t.resources?.variables??{})};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,formDrafts:{},accountViewedRegistry:Ju(s,"accountViewedRegistry"),nextLineConfig:An(),saveSlots:Gu(r),overlayStack:[],variables:p,...md({loadedGlobalRuntime:i})},contexts:[Ts({pointer:d,projectData:t})]}},Td=({state:e})=>e.global.overlayStack||[],Dd=({state:e})=>e.global.pendingEffects,Ps=({state:e})=>e.global.skipMode,Nd=({state:e})=>e.global.autoMode,Vs=({state:e})=>e.global.dialogueUIHidden,js=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],n=t[t.length-1];if(!n)return[];let{sectionId:r,lineId:o}=n.pointers.read,i=ue({state:e},{sectionId:r});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(d=>d.id===o),l=i.lines.slice(0,s+1),a=[],c={},u=Rt({variables:{...e.global?.variables??{},...wn(e)?.variables??{}},runtime:Ze(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1});for(let d of l){let f=d.actions||{};if(c=Xe([c,f]),!f.dialogue)continue;let p=c.dialogue||{},h=nn({characterId:p.characterId,character:p.character,characters:e.projectData.resources?.characters??{},variables:u}),g=qu({sectionId:r,lineId:d.id,content:f.dialogue.append===!0?p.content:f.dialogue.content,dialogueState:p,characterName:h});if(f.dialogue.append===!0&&a.length>0){a[a.length-1]={...a[a.length-1],content:g.content,text:g.text,characterId:g.characterId,character:g.character,characterName:g.characterName};continue}a.push(g)}return a},Pd=({state:e})=>e.global.confirmDialog??null,jt=({state:e},{pointer:t}={})=>{let n=t??Ee({state:e})?.pointer,r=pd({state:e,pointer:n});return hd({state:e,form:r.form,pointer:n})},Vd=({state:e},{pointer:t}={})=>!!jt({state:e},{pointer:t}),xe=({state:e},{pointer:t}={})=>{let n=jt({state:e},{pointer:t});if(n)return{source:Be,formId:n.id,formKey:n.key};let r=Fs({state:e,pointer:t});return r?{source:gt,resourceId:r}:null},jd=({state:e,registry:t},n)=>{let{sectionId:r,lineId:o}=n,s=(Array.isArray(t?.sections)?t.sections:[]).find(u=>u.sectionId===r);if(!s)return!1;if(s.lastLineId===void 0||o===void 0)return!0;let l=ue({state:e},{sectionId:r});if(!l||!l.lines||!Array.isArray(l.lines))return s.lastLineId===o;let a=l.lines.findIndex(u=>u.id===s.lastLineId),c=l.lines.findIndex(u=>u.id===o);return a===-1||c===-1?s.lastLineId===o:c<=a},Fd=({registry:e},t)=>{let{resourceId:n}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===n)},Gr=({state:e},t)=>jd({state:e,registry:e.global.accountViewedRegistry},t),Md=({state:e},t)=>Fd({registry:e.global.accountViewedRegistry},t),Ud=({state:e})=>e.global.nextLineConfig,Fs=({state:e,pointer:t}={})=>{let n=t??Ee({state:e})?.pointer;if(!n)return;let r=n?.sectionId,o=n?.lineId,s=ue({state:e},{sectionId:r})?.lines||[],l=s.findIndex(c=>c.id===o);if(l<0)return;let a;for(let c of s.slice(0,l+1)){let u=c?.actions;if(u?.cleanAll&&(a=void 0),!u||!Object.prototype.hasOwnProperty.call(u,"choice")){a=void 0;continue}let d=u.choice;if(d?.resourceId){a=d.resourceId;continue}d?.animations||(a=void 0)}return a},Ms=({state:e})=>!!Fs({state:e}),Bd=({state:e})=>structuredClone(e),zd=({state:e})=>N(e.projectData.resources?.achievements??{}),qd=({state:e},t)=>{let n=e.projectData.resources?.achievements?.[t?.resourceId];return n===void 0?void 0:N(n)},Us=({state:e})=>e.global.saveSlots,Hd=({state:e},t)=>{let n=t?.slotId,r=Vt(n);return e.global.saveSlots[r]},Kr=({state:e})=>Ze(e),Wd=({state:e},t)=>Fe(e,t?.runtimeId),En=({state:e})=>{let t={...e.global?.variables??{},...wn(e)?.variables??{}};return Rt({variables:t,runtime:Ze(e),variableConfigs:e.projectData.resources?.variables??{}})},Ee=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],n=t[t.length-1];if(n)return{currentPointerMode:"read",pointer:n.pointers?.read}},ue=({state:e},t)=>{let{sectionId:n}=t;return yt(e.projectData,n).section},xn=({state:e})=>{let t=Ee({state:e});if(!t?.pointer)return;let{sectionId:n,lineId:r}=t.pointer,o=ue({state:e},{sectionId:n});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===r)},Bs=({state:e})=>{let{sectionId:t,lineId:n}=Ee({state:e}).pointer,o=ue({state:e},{sectionId:t})?.lines||[],i=o.findIndex(c=>c.id===n),l=o.slice(0,i+1).map(c=>{let u=c.actions||{},d={};return Object.keys(u).forEach(f=>{d[f]=u[f]}),d});return Xe(l)},Yd=e=>{let t=xn({state:e})?.actions?.dialogue;if(t?.clear===!0||!Array.isArray(t?.content))return"";let n=En({state:e});return t.content.map(r=>`${dt(r?.text,{variables:n})??""}`).join("")},vn=({state:e})=>cs({text:Yd(e),baseDelay:Fe(e,"autoForwardDelay"),speed:Fe(e,"autoForwardSpeed")}),Gd=({state:e})=>{let t=zs({state:e}),r=xn({state:e})?.actions??{},o=Xe([t??{},r]);return lr(t??{},o??{})},Kd=({state:e},{sectionId:t})=>{let n=ue({state:e},{sectionId:t});if(!n?.lines)return[];let r=[],o={};for(let i of n.lines){let s=i.actions||{},l=Xe([o,s]),a=lr(o,l);r.push({id:i.id,changes:a,presentationState:l}),o=ur(l)}return r},Jd=({state:e},{sectionId:t,includePresentationState:n=!1})=>{let r=Kd({state:e},{sectionId:t});return n?{lines:r}:{lines:r.map(({presentationState:o,...i})=>i)}},zs=({state:e})=>{let{sectionId:t,lineId:n}=Ee({state:e}).pointer,o=ue({state:e},{sectionId:t})?.lines||[],i=o.findIndex(a=>a.id===n);if(i<=0)return null;let l=o.slice(0,i).map(a=>{let c=a.actions||{},u={};return Object.keys(c).forEach(d=>{u[d]=c[d]}),u});return ur(Xe(l))},Jr=({state:e},{slotsPerPage:t=6}={})=>{let o=((Kr({state:e}).saveLoadPagination??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let l=o+s,a=e.global.saveSlots&&e.global.saveSlots[Vt(l)]||{};i.push({...a,slotId:l})}return{saveSlots:i}},Xd=Us,Qd=Jr,Zd=e=>{let n=e.contexts?.[e.contexts.length-1]?.rollback;return!n||!Array.isArray(n.timeline)||typeof n.currentIndex!="number"?!1:n.currentIndex>=0&&n.currentIndex<n.timeline.length-1},ef=({state:e},t={})=>{let n=Bs({state:e}),r=zs({state:e}),o=xn({state:e})?.actions??{},i=e.global.pendingScreenTransition,s=i?.animations?{...o,screen:N(i)}:o,l=i?.animations&&r===null?{}:r,{sectionId:a}=Ee({state:e}).pointer,{sceneId:c}=yt(e.projectData,a),u=Kr({state:e}),d=t?.activePersistentAnimations??[],f=t?.restoredPersistentAnimations??[],p=jt({state:e}),h=Ms({state:e}),g=En({state:e}),{saveSlots:y}=Jr({state:e}),I=Zd(e);return zi({presentationState:n,previousPresentationState:l,currentLineActions:s,resources:e.projectData.resources,currentSceneId:c,screen:e.projectData.screen,dialogueUIHidden:u.dialogueUIHidden,autoMode:u.autoMode,skipMode:u.skipMode,isChoiceVisible:h,isFormVisible:!!p,canRollback:ea({state:e}),skipOnlyViewedLines:!u.skipUnseenText,isLineCompleted:u.isLineCompleted,skipTransitionsAndAnimations:!!u.skipTransitionsAndAnimations||I,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,form:p,dialogueHistory:js({state:e}),saveSlots:y,variables:g,runtime:u,activePersistentAnimations:d,restoredPersistentAnimations:f})},tf=({state:e},t)=>(e.global.confirmDialog=sd(t),e.global.pendingEffects.push({name:"render"}),e),nf=({state:e})=>(e.global.confirmDialog&&(bt(e),e.global.pendingEffects.push({name:"render"})),e),rf=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),ke(e,"pushOverlay",t),e),of=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),ke(e,"popOverlay",void 0),e),sf=({state:e},t)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=t),e.global.pendingEffects.push({name:"render"}),ke(e,"replaceLastOverlay",t),e),af=({state:e})=>(e.global.overlayStack=[],bt(e),It(e),e.global.pendingEffects.push({name:"render"}),ke(e,"clearOverlays",void 0),e),cf=(e,{activeInteraction:t})=>{e.global.autoMode&&e.global.pendingEffects.push({name:"clearAutoNextTimer"}),t&&e.global.skipMode&&e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.nextLineConfig?.auto?.enabled&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},Cn=(e,t,{screenTransition:n}={})=>{e.global.isLineCompleted=!1,cd(e,n),It(e);let r=xe({state:e},{pointer:t}),o=r?.source===gt,i=r?.source===Be;return cf(e,{activeInteraction:r}),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:o,isFormVisible:i,activeInteraction:r}},Sn=(e,t,n)=>{!(t?.source===gt||t?.source===Be)||n||!e.global.skipMode||e.global.pendingEffects.push({name:"startSkipNextTimer"})},qs=({state:e})=>(xe({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:vn({state:e})}}),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),lf=({state:e})=>{let t=e.global.autoMode;return xe({state:e})&&!t||(t?Ft({state:e}):qs({state:e})),e},Hs=({state:e})=>(xe({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),ze=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),uf=({state:e})=>{let t=Ps({state:e});return xe({state:e})&&!t||(t?ze({state:e}):Hs({state:e})),e},Rn=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),ke(e,"showDialogueUI",void 0),e),Ws=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),ke(e,"hideDialogueUI",void 0),e),df=({state:e})=>(Vs({state:e})?Rn({state:e}):Ws({state:e}),e),qe=(e,t,n)=>(Ls(e,t,n),Id(e),e.global.pendingEffects.push({name:"render"}),e),Mt=(e,t,n,r)=>{let o=Ls(e,t,n);return e.global.pendingEffects.push({name:"render"}),ke(e,r,{value:o}),e},ff=({state:e},t)=>qe(e,"dialogueTextSpeed",t?.value),pf=({state:e},t)=>qe(e,"autoForwardDelay",t?.value),hf=({state:e},t)=>qe(e,"autoForwardSpeed",t?.value),mf=({state:e},t)=>qe(e,"skipUnseenText",t?.value),gf=({state:e},t)=>qe(e,"skipTransitionsAndAnimations",t?.value),yf=({state:e},t)=>qe(e,"soundVolume",t?.value),bf=({state:e},t)=>qe(e,"musicVolume",t?.value),If=({state:e},t)=>qe(e,"muteAll",t?.value),Af=({state:e},t)=>Mt(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),wf=({state:e})=>{let t=Fe(e,"saveLoadPagination")+1;return Mt(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},Ef=({state:e})=>{let t=Fe(e,"saveLoadPagination")-1;return Mt(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},xf=({state:e},t)=>Mt(e,"menuPage",t?.value,"setMenuPage"),vf=({state:e},t)=>Mt(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),Cf=({state:e})=>(e.global.pendingEffects=[],e),Sf=({state:e},t)=>(e.global.pendingEffects.push(t),e),Rf=({state:e},t)=>{let n=t?.resourceId;return hs(e,n),e.global.pendingEffects.push({name:"completeAchievement",payload:{resourceId:n}}),e},_f=({state:e},t)=>{let n=t?.resourceId,r=hs(e,n);if(r.type!=="number")throw new Error(`Achievement resource "${n}" does not support numeric progress`);let o=t?.current;if(!Number.isInteger(o)||o<0)throw new Error(`Achievement progress for "${n}" must be a non-negative integer`);if(!Number.isInteger(r.target)||r.target<1)throw new Error(`Achievement resource "${n}" must have a positive integer target`);let i=Math.min(o,r.target);return e.global.pendingEffects.push({name:"setAchievementProgress",payload:{resourceId:n,current:i,target:r.target,completed:i>=r.target}}),e},Ys=(e,{sectionId:t,resetStoryState:n=!1,screen:r})=>{let o=!!Ss(r),i=ue({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(n&&!Ed(e,{queueRender:!o}))return e;let l=xe({state:e});n&&e.global.skipMode&&ze({state:e});let a=e.contexts?.[e.contexts.length-1];if(a){let u=At(a),d=u.read;n||ot(e,{sectionId:d?.sectionId,lineId:d?.lineId}),a.rollback||it(a,{compatibilityAnchor:!0}),u.read={sectionId:t,lineId:s.id},n?a.rollback=Pt({pointer:u.read}):Yr(e,{sectionId:t,lineId:s.id})}let{activeInteraction:c}=Cn(e,a?.pointers?.read,{screenTransition:r});return Sn(e,l,c),e},Of=({state:e},t)=>Ys(e,{sectionId:t?.sectionId,resetStoryState:!0,screen:t?.screen}),Gs=e=>(e.global.accountViewedRegistry=Bu(e.global.accountViewedRegistry),e.global.accountViewedRegistry),Xr=(e,t)=>{!Array.isArray(t)||t.length===0||e.global.pendingEffects.push({name:"applyScopedDataUpdates",payload:{updates:t.map(n=>({scope:n.scope,path:n.path,op:n.op,value:N(n.value)}))}})},Ks=(e,t)=>{Xr(e,[{scope:"account",path:"viewedRegistry",op:"markViewed",value:{sections:(Array.isArray(t?.sections)?t.sections:[]).map(n=>({sectionId:n.sectionId,...n.lastLineId===void 0?{}:{lineId:n.lastLineId}})),resources:Array.isArray(t?.resources)?t.resources:[]}}])},kf=(e,t,{sectionId:n,lineId:r})=>{if(!n||!r)return!1;let o=D(t)?t:{};Array.isArray(o.sections)||(o.sections=[]);let i=o.sections.find(s=>s.sectionId===n);if(i){if(i.lastLineId===void 0)return!1;let s=ue({state:e},{sectionId:n});if(s?.lines){let l=s.lines.findIndex(c=>c.id===i.lastLineId),a=s.lines.findIndex(c=>c.id===r);if(l===-1||a>l)return i.lastLineId===r?!1:(i.lastLineId=r,!0)}else return i.lastLineId===r?!1:(i.lastLineId=r,!0);return!1}else return o.sections.push({sectionId:n,lastLineId:r}),!0},ot=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;kf(e,Gs(e),t)&&Ks(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},$f=({state:e},t)=>(ot(e,t),e.global.pendingEffects.push({name:"render"}),e),Lf=({state:e},t)=>{let{resourceId:n}=t;if(e.global.accountViewedRegistry!==void 0){let r=Gs(e);r.resources.find(i=>i.resourceId===n)||(r.resources.push({resourceId:n}),Ks(e,{sections:[],resources:[{resourceId:n}]}))}return e.global.pendingEffects.push({name:"render"}),e},Js=({state:e},t)=>{let n=Wu(t.manual),{auto:r,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,l=e.contexts?.[e.contexts.length-1]?.rollback?.isRestoring===!0;n&&r?(e.global.nextLineConfig={manual:n,auto:r},o!==void 0?e.global.nextLineConfig.applyMode=o:s!==void 0&&(e.global.nextLineConfig.applyMode=s)):(n&&(e.global.nextLineConfig.manual=n),r&&(e.global.nextLineConfig.auto=r),o!==void 0&&(e.global.nextLineConfig.applyMode=o));let a=e.global.nextLineConfig.auto?.enabled,c=xe({state:e});return!l&&!c&&a===!0&&!i?e.global.nextLineConfig.auto?.trigger==="fromStart"?e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):e.global.isLineCompleted&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):!l&&a===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),ke(e,"setNextLineConfig",t),e},Tf=({state:e},t)=>{let n=t?.slotId;if(n==null||n==="")throw new Error("saveSlot requires slotId");let{thumbnailImage:r}=t,o=t?.savedAt,i=Vt(n),s=N(e.contexts);s?.forEach(c=>{At(c),Ds(c.rollback),Ku(c.rollback)});let l={contexts:s},a={formatVersion:ps,slotId:ys(n),savedAt:typeof o=="number"?o:Date.now(),image:r,state:l};return e.global.saveSlots[i]=a,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},Df=({state:e},t)=>{let n=t?.slotId;if(n==null||n==="")throw new Error("loadSlot requires slotId");let r=Vt(n),o=e.global.saveSlots[r];if(o){let i=id(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=An(),e.global.overlayStack=[],e.global.isLineCompleted=!0,bt(e),It(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},Nf=({state:e},t)=>{let{projectData:n}=t;gs(n),Je(n?.resources?.variables??{}),e.projectData=n;let r=n?.resources?.variables??{},{contextVariableDefaultValues:o,globalVariablesDefaultValues:i}=rn(n??{});return Object.prototype.hasOwnProperty.call(e.global??{},"variables")&&(e.global.variables={...i,...ut(e.global.variables,r)}),e.contexts?.forEach(s=>{Object.prototype.hasOwnProperty.call(s??{},"variables")&&(s.variables={...o,...ut(s.variables,r)})}),bt(e),It(e),e.global.pendingEffects.push({name:"render"}),e},Pf=({state:e},t)=>{let{sectionId:n,lineId:r}=t;if(!r)return console.warn("jumpToLine requires lineId parameter"),e;let o=e.contexts[e.contexts.length-1];if(!o)return console.warn("No context available for jumpToLine"),e;let i=n||o.pointers.read?.sectionId;if(n&&!ue({state:e},{sectionId:n}))return console.warn(`Section not found: ${n}`),e;let s=ue({state:e},{sectionId:i});if(!s?.lines||!Array.isArray(s.lines))return console.warn(`Section ${i} has no lines`),e;if(!s.lines.find(d=>d.id===r))return console.warn(`Line not found: ${r} in section ${i}`),e;let a=xe({state:e}),c=At(o);c.read={sectionId:i,lineId:r};let{activeInteraction:u}=Cn(e,c.read);return Sn(e,a,u),e},Vf=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return Rn({state:e}),e;let n=xe({state:e});if(n?.source===gt&&t?.bypassChoice!==!0||n?.source===Be&&t?._interactionSource!==Be)return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let u=Ee({state:e})?.pointer,d=u?.sectionId,f=u?.lineId;d&&f&&ot(e,{sectionId:d,lineId:f}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&!n&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:vn({state:e})}});let p=e.global.nextLineConfig;return p?.auto?.enabled&&!n&&p.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:p.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e}let r=Ee({state:e})?.pointer,o=r?.sectionId,i=ue({state:e},{sectionId:o}),s=e.contexts[e.contexts.length-1],l=i?.lines||[],c=l.findIndex(u=>u.id===r?.lineId)+1;if(c<l.length){let u=l[c],d=!Fe(e,"skipUnseenText");if(e.global.skipMode&&d&&!Gr({state:e},{sectionId:o,lineId:u.id}))return ze({state:e}),e;if(s&&!s.rollback&&it(s,{compatibilityAnchor:!0}),s){let p=At(s),h=p.read?.lineId;h&&o&&ot(e,{sectionId:o,lineId:h}),p.read={sectionId:o,lineId:u.id}}Yr(e,{sectionId:o,lineId:u.id}),zr(e);let{activeInteraction:f}=Cn(e,{sectionId:o,lineId:u.id});Sn(e,n,f)}else e.global.autoMode&&Ft({state:e}),e.global.skipMode&&ze({state:e});return e},jf=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=xe({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:vn({state:e})}});let n=Ee({state:e})?.pointer,r=n?.sectionId,o=n?.lineId;r&&o&&ot(e,{sectionId:r,lineId:o});let i=e.global.nextLineConfig;return i?.auto?.enabled&&!t&&i.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:i.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e},Ff=({state:e},t)=>Ys(e,{sectionId:t?.sectionId,screen:t?.screen}),Mf=({state:e},t)=>{let n=t?._conditionalContinuation===!0;if(e.global.dialogueUIHidden&&!n)return Rn({state:e}),e;let r=xe({state:e});if(r?.source===gt&&t?.bypassChoice!==!0||r?.source===Be&&t?._interactionSource!==Be||r&&r.source!==gt&&r.source!==Be)return e;let o=Ee({state:e})?.pointer,i=o?.sectionId,s=ue({state:e},{sectionId:i}),l=e.contexts[e.contexts.length-1],a=s?.lines||[],u=a.findIndex(d=>d.id===o?.lineId)+1;if(u<a.length){let d=a[u],f=!Fe(e,"skipUnseenText");if(e.global.skipMode&&f&&!Gr({state:e},{sectionId:i,lineId:d.id})&&(ze({state:e}),!n))return e;if(l&&!l.rollback&&it(l,{compatibilityAnchor:!0}),l){let h=At(l),g=h.read?.lineId;g&&i&&ot(e,{sectionId:i,lineId:g}),h.read={sectionId:i,lineId:d.id}}Yr(e,{sectionId:i,lineId:d.id}),zr(e);let{activeInteraction:p}=Cn(e,{sectionId:i,lineId:d.id});Sn(e,r,p)}else e.global.autoMode&&Ft({state:e}),e.global.skipMode&&ze({state:e}),e.global.nextLineConfig.auto?.enabled&&(e.global.nextLineConfig.auto.enabled=!1,e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}));return e},Qr=(e,t={})=>{let n=jt({state:e});return!n||t.formKey&&t.formKey!==n.key||t.formId&&t.formId!==n.id?null:n},Uf=(e,t)=>{if(!t.variableId)throw new Error(`form field "${t.id}" requires variableId`);let n=e.projectData.resources?.variables?.[t.variableId],r=n?.scope,o=n?.type;if(Ce(n))throw new Error(`Cannot update computed variable: ${t.variableId}`);if(n?.readonly===!0)throw new Error(`Cannot update readonly variable: ${t.variableId}`);return _t(r,t.variableId),on(o,"set",t.variableId),{variableConfig:n,scope:r}},Bf=(e,t)=>({id:e.id,key:e.key,valid:!0,values:N(t),fields:N(e.fields),fieldList:N(e.fieldList)}),zf=e=>{if(e.global.isLineCompleted)return;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=Ee({state:e})?.pointer,n=t?.sectionId,r=t?.lineId;n&&r&&ot(e,{sectionId:n,lineId:r})},qf=({state:e},t={})=>{let n=Qr(e,t),r=t.field;if(!n?.fields?.[r])return e;let o=_s(e,n.key),i=bn(t.value),s=n.fields[r],l=qr(s,i);return o.values[r]=i,o.touched[r]=!0,l?o.errors[r]=l:delete o.errors[r],e.global.pendingEffects.push({name:"render"}),e},Hf=({state:e},t={})=>{let n=Qr(e,t);if(!n)return{submitted:!1,valid:!1,reason:"inactive"};let r=_s(e,n.key);r.submitted=!0;let o={},i={};if(Object.entries(n.fields).forEach(([d,f])=>{let p=Object.prototype.hasOwnProperty.call(r.values,d)?r.values[d]:f.value,h=qr(f,p);r.touched[d]=!0,h&&(i[d]=h),o[d]=Rs(f,p)}),r.errors=i,Object.keys(i).length>0)return e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!1,errors:N(i),form:{id:n.id,key:n.key,values:N(o)}};let s=e.contexts[e.contexts.length-1];if(s?.rollback?.isRestoring)return{submitted:!1,valid:!1,reason:"restoring"};let l=!1,a=[],c=[];Object.entries(n.fields).forEach(([d,f])=>{let{scope:p}=Uf(e,f),h=p==="context"?s.variables:e.global.variables,g=o[d];h[f.variableId]=sn(h[f.variableId],"set",g),p==="context"&&(l=!0,c.push({variableId:f.variableId,op:"set",value:g})),(p==="device"||p==="account")&&a.push({scope:p,path:`variables.${f.variableId}`,op:"set",value:N(h[f.variableId])})}),l&&ke(e,"updateVariable",{id:"submitForm",operations:c}),Xr(e,a);let u=Bf(n,o);return zf(e),delete e.global.formDrafts[n.key],e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!0,form:u}},Wf=({state:e},t={})=>{let n=Qr(e,t);return n?(delete e.global.formDrafts?.[n.key],e.global.pendingEffects.push({name:"render"}),{cancelled:!0,form:{id:n.id,key:n.key,values:N(n.values),fields:N(n.fields),fieldList:N(n.fieldList)}}):{cancelled:!1,reason:"inactive"}},Yf=({state:e},t)=>{let{id:n,operations:r=[]}=t;if(!n)throw new Error("updateVariable requires an id field");if(typeof n!="string"||!/^[a-zA-Z0-9]+$/.test(n))throw new Error(`updateVariable id must be alphanumeric, got: "${n}"`);let o=e.contexts[e.contexts.length-1];if(o?.rollback?.isRestoring)return e;let i=!1,s=[],l=[];return r.forEach(({variableId:a,op:c,value:u,roundTo:d})=>{let f=e.projectData.resources?.variables?.[a],p=f?.scope,h=f?.type;if(Ce(f))throw new Error(`Cannot update computed variable: ${a}`);if(f?.readonly===!0)throw new Error(`Cannot update readonly variable: ${a}`);_t(p,a),on(h,c,a),ar(h,c,u,a,{roundTo:d});let g=p==="context"?o.variables:e.global.variables;if(p==="context"){i=!0;let y={variableId:a,op:c,value:u};d!==void 0&&(y.roundTo=d),l.push(y)}g[a]=sn(g[a],c,u,{roundTo:d}),(p==="device"||p==="account")&&s.push({scope:p,path:`variables.${a}`,op:"set",value:N(g[a])})}),i&&ke(e,"updateVariable",{id:n,operations:l}),Xr(e,s),e.global.pendingEffects.push({name:"render"}),e},Gf=e=>(t,n)=>e({state:t},n),Kf=e=>({variables:Rt({variables:{...e.global?.variables??{},...wn(e)?.variables??{}},runtime:Ze(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1}),runtime:Ze(e)}),Jf=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")},Xf=(e,t,n)=>{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!==n-1)throw new Error("conditional else branch must be the last branch")},Qf=(e,t)=>{Jf(t);for(let n=0;n<t.branches.length;n+=1){let r=t.branches[n];if(Xf(r,n,t.branches.length),!(Object.prototype.hasOwnProperty.call(r,"when")&&!St(r.when,Kf(e)))){Object.entries(r.actions).forEach(([i,s])=>{Xs(e,i,s)});return}}},Zf={conditional:{replayLine:Qf},updateVariable:{recordSources:[Hr],replayLine:fs,replayRecorded:fs,persistInSaveSlot:!0},setNextLineConfig:{replayLine:Gf(Js)}},_n=e=>Zf[e]??null,ep=e=>_n(e)?.persistInSaveSlot===!0,tp=(e,t)=>{let n=_n(e)?.recordSources;return Array.isArray(n)&&n.includes(t)},np=(e,t,n)=>{_n(t)?.replayRecorded?.(e,n)},Xs=(e,t,n)=>{_n(t)?.replayLine?.(e,n)},rp=e=>e?.returnable!==!1,Qs=(e,t)=>{if(t>=0)return e.currentIndex+t;let n=Math.abs(t);for(let r=e.currentIndex-1;r>=0;r-=1)if(rp(e.timeline[r])&&(n-=1,n===0))return r;return-1},Zs=({state:e},t)=>{let{offset:n}=t;if(n===void 0||typeof n!="number")return console.warn("selectLineIdByOffset requires a numeric offset"),null;let r=e.contexts[e.contexts.length-1];if(!r)return null;let o=r.rollback;if(!Array.isArray(o?.timeline)||typeof o?.currentIndex!="number")return null;let i=Qs(o,n);if(i<0||i>=o.timeline.length)return null;let s=o.timeline[i];return{sectionId:s.sectionId,lineId:s.lineId}},ea=({state:e})=>Zs({state:e},{offset:-1})!==null,op=({state:e},t)=>{let{offset:n=-1}=t;if(n>=0)throw new Error("rollbackByOffset requires a negative offset");let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let o=it(r,{compatibilityAnchor:!r.rollback}),i=Qs(o,n);return i<0||i>=o.timeline.length?e:Ns(e,i)},ip=({state:e},t)=>{let{sectionId:n,lineId:r}=t,o=e.contexts[e.contexts.length-1];if(!o)throw new Error("No context available for rollbackToLine");let i=it(o,{compatibilityAnchor:!o.rollback}),l=i.timeline.slice(0,i.currentIndex+1).findLastIndex(a=>a.sectionId===n&&a.lineId===r);if(l===-1)throw new Error(`Line ${r} not found in section ${n} rollback timeline`);return l===i.currentIndex?e:Ns(e,l)},ta=e=>{let t=Ld(e);return Bo(t,{selectPendingEffects:Dd,selectSkipMode:Ps,selectAutoMode:Nd,selectIsChoiceVisible:Ms,selectIsFormVisible:Vd,selectActiveInteraction:xe,selectActiveForm:jt,selectDialogueUIHidden:Vs,selectDialogueHistory:js,selectConfirmDialog:Pd,selectIsLineAccountViewed:Gr,selectIsResourceAccountViewed:Md,selectNextLineConfig:Ud,selectSystemState:Bd,selectAchievements:zd,selectAchievement:qd,selectSaveSlotMap:Us,selectSaveSlots:Xd,selectSaveSlot:Hd,selectRuntime:Kr,selectRuntimeValue:Wd,selectAllVariables:En,selectCurrentPointer:Ee,selectSection:ue,selectCurrentLine:xn,selectPresentationState:Bs,selectAutoForwardTimerDelay:vn,selectPresentationChanges:Gd,selectSectionLineChanges:Jd,selectSaveSlotPage:Jr,selectCurrentPageSlots:Qd,selectRenderState:ef,selectOverlayStack:Td,selectLineIdByOffset:Zs,selectCanRollback:ea,selectRollbackCursor:vd,startAutoMode:qs,stopAutoMode:Ft,toggleAutoMode:lf,startSkipMode:Hs,stopSkipMode:ze,toggleSkipMode:uf,showDialogueUI:Rn,hideDialogueUI:Ws,toggleDialogueUI:df,setDialogueTextSpeed:ff,setAutoForwardDelay:pf,setAutoForwardSpeed:hf,setSkipUnseenText:mf,setSkipTransitionsAndAnimations:gf,setSoundVolume:yf,setMusicVolume:bf,setMuteAll:If,setSaveLoadPagination:Af,incrementSaveLoadPagination:wf,decrementSaveLoadPagination:Ef,setMenuPage:xf,setMenuEntryPoint:vf,showConfirmDialog:tf,hideConfirmDialog:nf,resetStoryAtSection:Of,clearPendingEffects:Cf,appendPendingEffect:Sf,completeAchievement:Rf,setAchievementProgress:_f,beginRollbackActionBatch:_d,endRollbackActionBatch:Od,markRollbackCheckpointTransient:Cd,markSavedRollbackCheckpointTransient:Sd,addViewedLine:$f,addViewedResource:Lf,setNextLineConfig:Js,saveSlot:Tf,loadSlot:Df,updateProjectData:Nf,sectionTransition:Ff,jumpToLine:Pf,nextLine:Vf,markLineCompleted:jf,rollbackToLine:ip,rollbackByOffset:op,pushOverlay:rf,popOverlay:of,replaceLastOverlay:sf,clearOverlays:af,updateFormField:qf,submitForm:Hf,cancelForm:Wf,updateVariable:Yf,nextLineFromSystem:Mf},{transformActionFirstArgument:r=>({state:r}),transformSelectorFirstArgument:r=>({state:r})})};var sp="route-engine",ap="projectPersistence";var ra=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),te=e=>Object.prototype.toString.call(e)==="[object Object]",na="variables.",cp=(e={})=>{let t=te(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(n=>typeof n=="string"||typeof n=="number"?{sectionId:String(n)}:!te(n)||typeof n.sectionId!="string"||n.sectionId.length===0?null:{sectionId:n.sectionId,...typeof n.lineId=="string"?{lineId:n.lineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(n=>typeof n=="string"||typeof n=="number"?{resourceId:String(n)}:!te(n)||typeof n.resourceId!="string"||n.resourceId.length===0?null:{resourceId:n.resourceId}).filter(Boolean)}},lp=(e={})=>{let t=te(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(n=>typeof n=="string"||typeof n=="number"?{sectionId:String(n)}:!te(n)||typeof n.sectionId!="string"||n.sectionId.length===0?null:{sectionId:n.sectionId,...typeof n.lastLineId=="string"?{lastLineId:n.lastLineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(n=>typeof n=="string"||typeof n=="number"?{resourceId:String(n)}:!te(n)||typeof n.resourceId!="string"||n.resourceId.length===0?null:{resourceId:n.resourceId}).filter(Boolean)}},up=(e,t)=>{let n=lp(e),r=cp(t),o=n.sections.map(s=>({...s})),i=n.resources.map(s=>({...s}));return r.sections.forEach(s=>{let l=o.find(a=>a.sectionId===s.sectionId);if(!l){o.push({sectionId:s.sectionId,...s.lineId===void 0?{}:{lastLineId:s.lineId}});return}if(l.lastLineId!==void 0){if(s.lineId===void 0){delete l.lastLineId;return}l.lastLineId=s.lineId}}),r.resources.forEach(s=>{i.find(a=>a.resourceId===s.resourceId)||i.push({...s})}),{sections:o,resources:i}},oa=(e={})=>{let t=te(e)?e:{};return{saveSlots:te(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:te(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:te(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:te(t.globalRuntime)?t.globalRuntime:{},accountViewedRegistry:te(t.accountViewedRegistry)?t.accountViewedRegistry:{}}},dp=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((t,n)=>{if(!te(t))throw new Error(`Malformed applyScopedDataUpdates.updates[${n}] entry.`);let r=t.path?.startsWith(na)?t.path.slice(na.length):null;if(r!==null){if(!["device","account"].includes(t.scope))throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${n}].`);if(r.length===0)throw new Error(`Malformed applyScopedDataUpdates path "${t.path}" at updates[${n}].`);if(t.op!=="set")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${n}].`);return{scope:t.scope,path:t.path,op:t.op,value:t.value,variableId:r}}if(t.path==="viewedRegistry"){if(t.scope!=="account")throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${n}].`);if(t.op!=="markViewed")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${n}].`);return t}throw typeof t.path!="string"?new Error(`Malformed applyScopedDataUpdates path at updates[${n}].`):new Error(`Unsupported applyScopedDataUpdates path "${t.path}" at updates[${n}].`)})},fp=(e,t)=>{let n={};return dp(t).forEach(r=>{if(r.path==="viewedRegistry"){n.accountViewedRegistry=up(n.accountViewedRegistry??e.accountViewedRegistry,r.value);return}let o=r.scope==="device"?"globalDeviceVariables":"globalAccountVariables";n[o]={...e[o],...n[o],[r.variableId]:r.value}}),n},Zr=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},pp=e=>{let t=Zr(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},hp=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},mp=({indexedDB:e,databaseName:t,objectStoreName:n})=>new Promise((r,o)=>{let i=e.open(t,1);i.onupgradeneeded=()=>{let s=i.result;s.objectStoreNames.contains(n)||s.createObjectStore(n,{keyPath:"namespace"})},i.onsuccess=()=>{r(i.result)},i.onerror=()=>{o(i.error??new Error(`Failed to open IndexedDB database "${t}".`))}}),gp=async({databasePromise:e,objectStoreName:t,namespace:n})=>{let r=await e;return new Promise((o,i)=>{let a=r.transaction(t,"readonly").objectStore(t).get(n);a.onsuccess=()=>{o(a.result??null)},a.onerror=()=>{i(a.error??new Error(`Failed to read persisted namespace "${n}" from IndexedDB.`))}})},Ut=async({databasePromise:e,objectStoreName:t,namespace:n,patch:r})=>{let o=await e;return new Promise((i,s)=>{let l=o.transaction(t,"readwrite"),a=l.objectStore(t),c=a.get(n),u=!1,d=p=>{u||(u=!0,s(p))},f=()=>{u||(u=!0,i())};c.onerror=()=>{d(c.error??new Error(`Failed to read persisted namespace "${n}" before updating IndexedDB.`))},c.onsuccess=()=>{let p=oa(c.result),h=typeof r=="function"?r(p):r,g={namespace:n,version:1,...ra(),...p,...h},y=a.put(g);y.onerror=()=>{d(y.error??new Error(`Failed to persist namespace "${n}" to IndexedDB.`))}},l.oncomplete=()=>{f()},l.onerror=()=>{d(l.error??new Error(`IndexedDB transaction failed while updating namespace "${n}".`))},l.onabort=()=>{d(l.error??new Error(`IndexedDB transaction aborted while updating namespace "${n}".`))}})},yp=async({databasePromise:e,objectStoreName:t,namespace:n})=>{let r=await e;return new Promise((o,i)=>{let s=r.transaction(t,"readwrite"),a=s.objectStore(t).delete(n),c=!1,u=f=>{c||(c=!0,i(f))},d=()=>{c||(c=!0,o())};a.onerror=()=>{u(a.error??new Error(`Failed to clear persisted namespace "${n}" from IndexedDB.`))},s.oncomplete=()=>{d()},s.onerror=()=>{u(s.error??new Error(`IndexedDB transaction failed while clearing namespace "${n}".`))},s.onabort=()=>{u(s.error??new Error(`IndexedDB transaction aborted while clearing namespace "${n}".`))}})},eo=(e={})=>{let{indexedDB:t,databaseName:n=sp,objectStoreName:r=ap,namespace:o}=e,i=hp(t),s=pp(o),l=mp({indexedDB:i,databaseName:n,objectStoreName:r});return{namespace:s,load:async()=>{let a=await gp({databasePromise:l,objectStoreName:r,namespace:s});return{...ra(),...oa(a)}},clear:async()=>yp({databasePromise:l,objectStoreName:r,namespace:s}),saveSlots:async a=>Ut({databasePromise:l,objectStoreName:r,namespace:s,patch:{saveSlots:te(a)?a:{}}}),saveGlobalDeviceVariables:async a=>Ut({databasePromise:l,objectStoreName:r,namespace:s,patch:{globalDeviceVariables:te(a)?a:{}}}),saveGlobalAccountVariables:async a=>Ut({databasePromise:l,objectStoreName:r,namespace:s,patch:{globalAccountVariables:te(a)?a:{}}}),saveGlobalRuntime:async a=>Ut({databasePromise:l,objectStoreName:r,namespace:s,patch:{globalRuntime:te(a)?a:{}}}),applyScopedDataUpdates:async a=>Ut({databasePromise:l,objectStoreName:r,namespace:s,patch:c=>fp(c,a)})}},bp=eo;var Ip=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),Ap=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),ia="conditional",ro=Symbol("conditionalAutoContinue"),wp=new Set(["sectionTransition","resetStoryAtSection"]),Ep=new Set(["nextLine","nextLineFromSystem","resetStoryAtSection","sectionTransition"]),xp=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),to="form",vp=new Set(["submitForm","cancelForm"]),Bt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),On=e=>e?.type===ro,no=(e,t)=>e?.sectionId===t?.sectionId&&e?.lineId===t?.lineId;function oo(e){let t,n=0,r=null,o=0,i=!1,s=0,l=[],a=null,c=new Map,u=new Map,d=new Map,{handlePendingEffects:f}=e,p=(b=new Map,A=Date.now())=>new Map(Array.from(b.entries()).filter(([,v])=>A<v.expiresAt).map(([v,R])=>[v,{animation:structuredClone(R.animation),startedAt:R.startedAt,expiresAt:R.expiresAt}])),h=(b=new Map)=>Array.from(b.values()).map(A=>structuredClone(A.animation)),g=(b=Date.now())=>{c=new Map(Array.from(c.entries()).filter(([,A])=>b<A.expiresAt))},y=()=>{if(!(o>0||i)){i=!0;try{for(;t.selectPendingEffects().length>0;){let b=[...t.selectPendingEffects()];t.clearPendingEffects();try{f(b)}catch(A){throw t.clearPendingEffects(),b.forEach(v=>{t.appendPendingEffect(v)}),A}}}finally{i=!1}}},I=b=>{o+=1;let A=!1;try{let v=b();return A=!0,v}finally{o-=1,A&&y()}},w=({initialState:b,namespace:A})=>{t=ta(b),n=0,r=Zr(A),o=0,i=!1,s=0,l=[],a=null,c=new Map,u=new Map,d=new Map,t.appendPendingEffect({name:"handleLineActions"}),y()},E=()=>r,_=()=>t.selectPresentationState(),j=()=>t.selectPresentationChanges(),F=b=>t.selectSectionLineChanges(b),x=(b={})=>{n+=1;let A=Date.now();g(A);let v=u.size>0,R=p(c,A),$=v?p(u,A):new Map,G={...t.selectRenderState({activePersistentAnimations:h(R),restoredPersistentAnimations:h($)}),id:`render-${n}`};return d.set(G.id,{builtAt:A,persistentAnimationSessions:new Map([...$.entries(),...R.entries()]),usedRestoredPersistentAnimationSessions:v}),G},z=(b={})=>x(b),q=(b={})=>x(b),X=b=>{let A=typeof b?.id=="string"&&b.id.length>0?b.id:null,v=A?d.get(A):null;A&&d.delete(A);let R=new Map;Ri(b?.animations).forEach($=>{let B=fn($);if(!B)return;let G=v?.persistentAnimationSessions?.get(B)??c.get(B),he=Math.max(0,Oi($)),at=G?.startedAt??v?.builtAt??Date.now();R.set(B,{animation:structuredClone($),startedAt:at,expiresAt:at+he})}),c=R,v?.usedRestoredPersistentAnimationSessions&&(u=new Map)},U=()=>t.selectSystemState(),Y=()=>t.selectAchievements(),K=b=>t.selectAchievement(b),Q=()=>t.selectSaveSlotMap(),_e=b=>t.selectSaveSlot(b),ne=b=>t.selectSaveSlotPage(b),re=()=>t.selectSkipMode(),de=()=>t.selectAutoMode(),fe=()=>t.selectRuntime(),Z=()=>t.selectIsChoiceVisible(),oe=()=>t.selectIsFormVisible(),pe=()=>t.selectActiveInteraction(),S=()=>t.selectPendingEffects().some(b=>b?.name==="handleLineActions"||b?.name==="render"),O=(b,A,v={})=>!Bt(A)||b!=="nextLine"?A:v.bypassChoice===!0?{...A,bypassChoice:!0}:v.interactionSource===to?{...A,_interactionSource:to}:A,M=(b={})=>({type:ro,payload:O("nextLine",{_conditionalContinuation:!0},b)}),ie=(b,A)=>On(b)?{type:ro,payload:{...b.payload,...A.payload}}:A,se=b=>{b.savedCheckpointOccurrences.forEach(A=>{t.markSavedRollbackCheckpointTransient(A)}),b.savedCheckpointOccurrences=[]},H=(b,A)=>{let v=a;return a=null,!v||!no(v.pointer,b)||v.checkpointIndex!==A?.checkpointIndex||v.checkpointIdentity!==A?.checkpoint?[]:v.savedCheckpointOccurrences},Ne=b=>{b.markCurrentCheckpointTransient&&(t.markRollbackCheckpointTransient({checkpointIndex:b.rollbackCursor?.checkpointIndex,checkpointIdentity:b.rollbackCursor?.checkpoint,sectionId:b.pointer?.sectionId,lineId:b.pointer?.lineId}),se(b))},st=(b,A,v)=>Ep.has(b)?b==="resetStoryAtSection"?v?.checkpoint!==A?.checkpoint:v?.checkpoint!==A?.checkpoint&&v?.checkpointIndex>A?.checkpointIndex:!1,ca=b=>{let A=l.at(-1);if(!A?.markCurrentCheckpointTransient)return;let v=t.selectSaveSlot({slotId:b?.slotId});v&&A.savedCheckpointOccurrences.push({slotId:b.slotId,saveSlotIdentity:v,checkpointIndex:A.rollbackCursor?.checkpointIndex,sectionId:A.pointer?.sectionId,lineId:A.pointer?.lineId})},la=(b,A,v)=>{let R=l.at(-1);if(!R)return;let $=t.selectCurrentPointer()?.pointer,B=st(b,A,v);if(no(R.pointer,$)){let G=v?.checkpoint!==A?.checkpoint||v?.checkpointIndex!==A?.checkpointIndex;(B||G&&xp.has(b))&&(Ne(R),R.pointer=$,R.rollbackCursor=v,R.markCurrentCheckpointTransient=B,R.savedCheckpointOccurrences=[]);return}Ne(R),R.pointer=$,R.rollbackCursor=t.selectRollbackCursor?.()??null,R.markCurrentCheckpointTransient=B,R.savedCheckpointOccurrences=[]},zt=(b,A)=>{if(!t[b])return;b==="updateProjectData"&&ua(A),wp.has(b)&&(s+=1),Ip.has(b)&&(Ap.has(b)?u=p(c):u=new Map,c=new Map);let v=t.selectRollbackCursor?.()??null,R=t[b](A),$=t.selectRollbackCursor?.()??null;return b==="saveSlot"&&ca(A),la(b,v,$),y(),R},ua=b=>{if(!Object.prototype.hasOwnProperty.call(b??{},"projectData"))throw new Error("updateProjectData requires projectData");Je(b?.projectData?.resources?.variables??{})},da=(b,A,v)=>{let R=t.selectCurrentPointer()?.pointer;A!==R||v!==s||(t.appendPendingEffect({name:"clearAutoNextTimer"}),t.appendPendingEffect({name:"clearNextLineConfigTimer"}),zt("nextLineFromSystem",b.payload))},fa=()=>({renderSequence:n,conditionalRoutingSequence:s,rollbackNavigationContexts:l.slice(),pendingRollbackLineEntrySaveHandoff:a,persistentAnimationSessions:new Map(c),restoredPersistentAnimationSessions:new Map(u),renderPersistentAnimationMetadata:new Map(d)}),pa=b=>{n=b.renderSequence,s=b.conditionalRoutingSequence,l=b.rollbackNavigationContexts.slice(),a=b.pendingRollbackLineEntrySaveHandoff,c=new Map(b.persistentAnimationSessions),u=new Map(b.restoredPersistentAnimationSessions),d=new Map(b.renderPersistentAnimationMetadata)},so=(b,A={})=>I(()=>{let v=fa();try{return t[sr](()=>{let R,$=t.selectCurrentPointer()?.pointer??null,B=t.selectRollbackCursor?.()??null,G=s,he={pointer:$,rollbackCursor:B,markCurrentCheckpointTransient:A.rollbackSource==="line",savedCheckpointOccurrences:A.savedCheckpointOccurrences?.slice()??[]};l.push(he);try{t.beginRollbackActionBatch({source:A.rollbackSource});try{R=b()}finally{t.endRollbackActionBatch({})}On(R)&&da(R,$,G)}finally{l.pop(),(!no($,he.pointer)||B?.checkpoint!==he.rollbackCursor?.checkpoint)&&he.markCurrentCheckpointTransient&&he.savedCheckpointOccurrences.length>0&&(a={pointer:he.pointer,checkpointIndex:he.rollbackCursor?.checkpointIndex,checkpointIdentity:he.rollbackCursor?.checkpoint,savedCheckpointOccurrences:he.savedCheckpointOccurrences})}})}catch(R){throw pa(v),R}}),ao=(b,A,v,R={})=>{if(b===ia)return so(()=>{let $=$n(v),B=dr({[b]:A},$);return co(B[b],v,R)},R);zt(b,A)},ha=(b,A)=>{ao(b,A)},$n=b=>{if(!b)return{variables:t.selectAllVariables?t.selectAllVariables():void 0,runtime:t.selectRuntime?t.selectRuntime():{}};if(Object.prototype.hasOwnProperty.call(b,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:A,...v}=b,R=t.selectAllVariables?t.selectAllVariables():void 0;return{...v,_event:A,variables:R,runtime:t.selectRuntime?t.selectRuntime():{}}},ma=b=>{if(!Bt(b))throw new Error("conditional action payload must be an object");if(!Array.isArray(b.branches))throw new Error("conditional action requires branches array");if(b.branches.length===0)throw new Error("conditional action requires at least one branch")},ga=(b,A,v)=>{if(!Bt(b))throw new Error(`conditional branch at index ${A} must be an object`);if(!Bt(b.actions))throw new Error(`conditional branch at index ${A} requires actions object`);if(!Object.prototype.hasOwnProperty.call(b,"when")&&A!==v-1)throw new Error("conditional else branch must be the last branch")},co=(b,A,v)=>{ma(b);let R=M(v);for(let $=0;$<b.branches.length;$+=1){let B=b.branches[$];ga(B,$,b.branches.length);let G=$n(A);if(Object.prototype.hasOwnProperty.call(B,"when")&&!St(B.when,G))continue;let at=Ln(B.actions,A,v);return On(at)?ie(R,at):R}return R},ya=(b,A)=>({...b??{},_form:A}),ba=(b,A,v,R)=>{let $=zt(b,A),B=$?.submitted===!0&&$.valid===!0,G=$?.cancelled===!0;if(!(!B&&!G)&&Bt(A.actions))return Ln(A.actions,ya(v,$.form),{...R,interactionSource:to})},Ia=(b,A,v,R)=>{let $=$n(v),G=dr({[b]:A},$)[b];if(b===ia)return co(G,v,R);let he=O(b,G,R);if(vp.has(b))return ba(b,he,v,R);zt(b,he)},Ln=(b,A,v)=>{let R;return Object.entries(b).forEach(([$,B])=>{let G=Ia($,B,A,v);On(G)&&(R=ie(R,G))}),R},lo=(b,A,v={})=>so(()=>Ln(b,A,v),v),Aa=b=>{let A=t.selectCurrentPointer()?.pointer;if(b!==A||t.selectActiveInteraction())return;let v=t.selectNextLineConfig();v?.auto?.enabled&&v.auto.trigger==="fromStart"&&t.appendPendingEffect({name:"nextLineConfigTimer",payload:{delay:v.auto.delay}})};return{init:w,handleAction:ao,handleInternalAction:ha,handleActions:lo,selectRenderState:z,prepareRenderState:q,commitRenderState:X,selectPresentationState:_,selectPresentationChanges:j,selectSectionLineChanges:F,selectSystemState:U,selectAchievements:Y,selectAchievement:K,selectSaveSlotMap:Q,selectSaveSlot:_e,selectSaveSlotPage:ne,selectSaveSlots:Q,selectRuntime:fe,selectIsChoiceVisible:Z,selectIsFormVisible:oe,selectActiveInteraction:pe,selectHasPendingRenderWork:S,handleLineActions:()=>I(()=>{let b=t.selectCurrentPointer()?.pointer,A=t.selectRollbackCursor?.()??null,v=a,R=H(b,A),$=t.selectCurrentLine(),B=!1;if($?.actions){try{lo($.actions,void 0,{rollbackSource:"line",savedCheckpointOccurrences:R})}catch(G){throw a=v,G}B=!0}return Aa(b),B}),getNamespace:E}}var io=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:n=>{e=n},addElapsed:n=>{e+=n},getCallback:()=>t,setCallback:n=>{t=n}}},Cp=80,aa=({engine:e,routeGraphics:t,trackRenderDispatch:n},r)=>{if(e.selectHasPendingRenderWork?.())return;let o=e.prepareRenderState?.(r)??e.selectRenderState(r);n?.(o),t.render(o),e.commitRenderState?.(o)},Sp=({engine:e,routeGraphics:t,trackRenderDispatch:n,getRenderDispatchCount:r},o)=>{let i=r?.()??0,s=e.handleLineActions();(r?.()??0)===i&&aa({engine:e,routeGraphics:t,trackRenderDispatch:n},o)},Rp=({engine:e,ticker:t,autoTimer:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let l=r.delay??1e3;n.getElapsed()>=l&&(t.remove(i),n.setCallback(null),n.setElapsed(0),kn(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},_p=({ticker:e,autoTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Op=({engine:e,ticker:t,skipTimer:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let l=r?.delay??Cp;n.getElapsed()>=l&&(n.setElapsed(0),kn(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},kp=({ticker:e,skipTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},$p=({engine:e,ticker:t,nextLineConfigTimerState:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let l=r.delay??1e3;n.getElapsed()>=l&&(n.setElapsed(0),kn(e,"nextLineFromSystem",{}),t.remove(i),n.getCallback()===i&&n.setCallback(null))};n.setCallback(i),t.add(i)},Lp=({ticker:e,nextLineConfigTimerState:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Tp=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveSlots(t?.saveSlots))},Dp=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalDeviceVariables(t?.globalDeviceVariables))},Np=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalAccountVariables(t?.globalAccountVariables))},Pp=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalRuntime(t?.globalRuntime))},Vp=({enqueuePersistenceWrite:e},t)=>{e(n=>{if(typeof n.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return n.applyScopedDataUpdates(t?.updates)})},sa={render:aa,saveSlots:Tp,saveGlobalDeviceVariables:Dp,saveGlobalAccountVariables:Np,saveGlobalRuntime:Pp,applyScopedDataUpdates:Vp,handleLineActions:Sp,startAutoNextTimer:Rp,clearAutoNextTimer:_p,startSkipNextTimer:Op,clearSkipNextTimer:kp,nextLineConfigTimer:$p,clearNextLineConfigTimer:Lp},jp=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),kn=(e,t,n)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,n)},Fp=(e=[])=>{let t=new Set,n=[];for(let r=e.length-1;r>=0;r-=1){let o=e[r];if(typeof o?.name!="string"||o.name.length===0)throw new Error("Pending effect is missing a valid name.");if(!jp.has(o.name)){n.unshift(o);continue}t.has(o.name)||(t.add(o.name),n.unshift(o))}return n},Mp=({getEngine:e,routeGraphics:t,ticker:n,handleUnhandledEffect:r,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:l})=>{let a=io(),c=io(),u=io(),d=s??null,f=Promise.resolve(),p=null,h=null,g=!1,y=0,I=S=>{if(o){o(S);return}console.error("RouteEngine persistence write failed.",S)},w=()=>{if(d)return d;let S=e();return d=eo({indexedDB:i,namespace:l??S?.getNamespace?.()}),d},E=S=>{f=f.catch(()=>{}).then(()=>{let O=w();return S(O)}).catch(O=>{I(O)})},_=S=>{let O=typeof S?.id=="string"&&S.id.length>0?S.id:null;y+=1,p=O,g=!1},j=()=>y,F=(S={})=>{if(S?.aborted===!0)return!1;let O=typeof S?.id=="string"&&S.id.length>0?S.id:null;return O?O!==p||O===h?!1:(h=O,!0):p!==null||g?!1:(g=!0,!0)},x=(S,O={})=>{if(S!=="renderComplete"||!F(O))return!1;let M=e();return kn(M,"markLineCompleted",{}),!0},z=new Set(["updateFormField","submitForm","cancelForm"]),q=new Set(["updateVariable"]),X=S=>typeof S?.selectActiveInteraction=="function"?S.selectActiveInteraction():typeof S?.selectIsChoiceVisible=="function"&&S.selectIsChoiceVisible()?{source:"choice"}:null,U=S=>S?._formKey??S?.formKey,Y=(S,O)=>U(S)===O?.formKey,K=(S,O)=>!S||typeof S!="object"||Array.isArray(S)?!1:S._interactionSource===O?.source,Q=(S,O)=>K(S,O)?O.source==="form"?Y(S,O):!0:!1,_e=(S,O)=>!S||typeof S!="object"||Array.isArray(S)||O?.source!=="form"?!1:Y(S,O),ne=(S={})=>Object.keys(S).some(O=>z.has(O)),re=(S={},O)=>Object.entries(S).some(([M,ie])=>z.has(M)&&_e(ie,O)),de=(S={})=>Object.keys(S).length>0&&Object.keys(S).every(O=>q.has(O)),fe=(S={},O)=>{let M=S?.actions;return O?.source==="form"?!M||typeof M!="object"||Array.isArray(M)?!1:re(M,O)?!0:ne(M)?!1:de(M):Q(S,O)?!0:!M||typeof M!="object"||Array.isArray(M)?!1:Object.values(M).some(ie=>Q(ie,O))},Z=(S,O={})=>{if(!O?.actions)return!1;let M=X(S);return!M||M.source==="choice"?!1:!fe(O,M)},oe=({preprocessPayload:S,onEvent:O}={})=>async(M,ie={})=>{let se=e();if(Z(se,ie))return O?.(M,ie);let H=await S?.(M,ie)??ie;if(Z(se,H))return O?.(M,H);if(x(M,H),H?.actions){let Ne=H?._event?{_event:H._event}:H?.event?{_event:H.event}:void 0,st;H?.bypassChoice===!0?st={bypassChoice:!0}:H?._interactionSource&&(st={interactionSource:H._interactionSource}),st?se.handleActions(H.actions,Ne,st):se.handleActions(H.actions,Ne)}return O?.(M,H)},pe=S=>{let O=e(),M=Fp(S),ie=M.some(H=>H.name==="handleLineActions");M.forEach(H=>{if(!sa[H.name]&&!r)throw new Error(`Unhandled pending effect "${H.name}".`)});let se={engine:O,routeGraphics:t,ticker:n,autoTimer:a,skipTimer:c,nextLineConfigTimerState:u,trackRenderDispatch:_,getRenderDispatchCount:j,enqueuePersistenceWrite:E};for(let H of M){if(ie&&H.name==="render")continue;let Ne=sa[H.name];if(Ne){Ne(se,H.payload);continue}r(H,se)}};return pe.handleRouteGraphicsEvent=x,pe.createRouteGraphicsEventHandler=oe,pe},Up=Mp;var Bp=(e,t={})=>{let{resources:n={}}=t;return Pr(e,n)};var Am=oo;export{mr as DEFAULT_VISUAL_LAYER,ft as RENDER_LAYER,$e as VISUAL_LAYER,Up as createEffectsHandler,bp as createIndexedDbPersistence,Am as default,cr as formatDate,Dc as resolveComputedVariables,Bp as resolveLayoutReferences};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "route-engine-js",
3
- "version": "1.31.2",
3
+ "version": "1.31.3",
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",