route-engine-js 1.20.1 → 1.20.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.
- package/dist/RouteEngine.js +1 -1
- package/package.json +1 -1
package/dist/RouteEngine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var $i=Object.defineProperty;var ki=(e,t)=>{for(var r in t)$i(e,r,{get:t[r],enumerable:!0})};var xn=Symbol.for("immer-nothing"),In=Symbol.for("immer-draftable"),ne=Symbol.for("immer-state");function ce(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var We=Object.getPrototypeOf;function oe(e){return!!e&&!!e[ne]}function $e(e){return e?Cn(e)||Array.isArray(e)||!!e[In]||!!e.constructor?.[In]||Et(e)||vt(e):!1}var Ti=Object.prototype.constructor.toString();function Cn(e){if(!e||typeof e!="object")return!1;let t=We(e);if(t===null)return!0;let r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return r===Object?!0:typeof r=="function"&&Function.toString.call(r)===Ti}function bt(e,t){wt(e)===0?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,n)=>t(n,r,e))}function wt(e){let t=e[ne];return t?t.type_:Array.isArray(e)?1:Et(e)?2:vt(e)?3:0}function Zt(e,t){return wt(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Sn(e,t,r){let n=wt(e);n===2?e.set(t,r):n===3?e.add(r):e[t]=r}function Di(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Et(e){return e instanceof Map}function vt(e){return e instanceof Set}function Le(e){return e.copy_||e.base_}function er(e,t){if(Et(e))return new Map(e);if(vt(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=Cn(e);if(t===!0||t==="class_only"&&!r){let n=Object.getOwnPropertyDescriptors(e);delete n[ne];let o=Reflect.ownKeys(n);for(let i=0;i<o.length;i++){let s=o[i],l=n[s];l.writable===!1&&(l.writable=!0,l.configurable=!0),(l.get||l.set)&&(n[s]={configurable:!0,writable:!0,enumerable:l.enumerable,value:e[s]})}return Object.create(We(e),n)}else{let n=We(e);if(n!==null&&r)return{...e};let o=Object.create(n);return Object.assign(o,e)}}function ir(e,t=!1){return xt(e)||oe(e)||!$e(e)||(wt(e)>1&&(e.set=e.add=e.clear=e.delete=Pi),Object.freeze(e),t&&Object.entries(e).forEach(([r,n])=>ir(n,!0))),e}function Pi(){ce(2)}function xt(e){return Object.isFrozen(e)}var Ni={};function ke(e){let t=Ni[e];return t||ce(0,e),t}var et;function _n(){return et}function Vi(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function An(e,t){t&&(ke("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function tr(e){rr(e),e.drafts_.forEach(ji),e.drafts_=null}function rr(e){e===et&&(et=e.parent_)}function wn(e){return et=Vi(et,e)}function ji(e){let t=e[ne];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function En(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[ne].modified_&&(tr(t),ce(4)),$e(e)&&(e=It(t,e),t.parent_||At(t,e)),t.patches_&&ke("Patches").generateReplacementPatches_(r[ne].base_,e,t.patches_,t.inversePatches_)):e=It(t,r,[]),tr(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==xn?e:void 0}function It(e,t,r){if(xt(t))return t;let n=t[ne];if(!n)return bt(t,(o,i)=>vn(e,n,t,o,i,r)),t;if(n.scope_!==e)return t;if(!n.modified_)return At(e,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;let o=n.copy_,i=o,s=!1;n.type_===3&&(i=new Set(o),o.clear(),s=!0),bt(i,(l,c)=>vn(e,n,o,l,c,r,s)),At(e,o,!1),r&&e.patches_&&ke("Patches").generatePatches_(n,r,e.patches_,e.inversePatches_)}return n.copy_}function vn(e,t,r,n,o,i,s){if(oe(o)){let l=i&&t&&t.type_!==3&&!Zt(t.assigned_,n)?i.concat(n):void 0,c=It(e,o,l);if(Sn(r,n,c),oe(c))e.canAutoFreeze_=!1;else return}else s&&r.add(o);if($e(o)&&!xt(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;It(e,o),(!t||!t.scope_.parent_)&&typeof n!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,n)&&At(e,o)}}function At(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&ir(t,r)}function Mi(e,t){let r=Array.isArray(e),n={type_:r?1:0,scope_:t?t.scope_:_n(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=n,i=sr;r&&(o=[n],i=tt);let{revoke:s,proxy:l}=Proxy.revocable(o,i);return n.draft_=l,n.revoke_=s,l}var sr={get(e,t){if(t===ne)return e;let r=Le(e);if(!Zt(r,t))return Fi(e,r,t);let n=r[t];return e.finalized_||!$e(n)?n:n===Xt(e.base_,t)?(Qt(e),e.copy_[t]=or(n,e)):n},has(e,t){return t in Le(e)},ownKeys(e){return Reflect.ownKeys(Le(e))},set(e,t,r){let n=Rn(Le(e),t);if(n?.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){let o=Xt(Le(e),t),i=o?.[ne];if(i&&i.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(Di(r,o)&&(r!==void 0||Zt(e.base_,t)))return!0;Qt(e),nr(e)}return e.copy_[t]===r&&(r!==void 0||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_[t]=!0),!0},deleteProperty(e,t){return Xt(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,Qt(e),nr(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=Le(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:n.enumerable,value:r[t]}},defineProperty(){ce(11)},getPrototypeOf(e){return We(e.base_)},setPrototypeOf(){ce(12)}},tt={};bt(sr,(e,t)=>{tt[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});tt.deleteProperty=function(e,t){return tt.set.call(this,e,t,void 0)};tt.set=function(e,t,r){return sr.set.call(this,e[0],t,r,e[0])};function Xt(e,t){let r=e[ne];return(r?Le(r):e)[t]}function Fi(e,t,r){let n=Rn(t,r);return n?"value"in n?n.value:n.get?.call(e.draft_):void 0}function Rn(e,t){if(!(t in e))return;let r=We(e);for(;r;){let n=Object.getOwnPropertyDescriptor(r,t);if(n)return n;r=We(r)}}function nr(e){e.modified_||(e.modified_=!0,e.parent_&&nr(e.parent_))}function Qt(e){e.copy_||(e.copy_=er(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Ui=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,r,n)=>{if(typeof t=="function"&&typeof r!="function"){let i=r;r=t;let s=this;return function(c=i,...a){return s.produce(c,u=>r.call(this,u,...a))}}typeof r!="function"&&ce(6),n!==void 0&&typeof n!="function"&&ce(7);let o;if($e(t)){let i=wn(this),s=or(t,void 0),l=!0;try{o=r(s),l=!1}finally{l?tr(i):rr(i)}return An(i,n),En(o,i)}else if(!t||typeof t!="object"){if(o=r(t),o===void 0&&(o=t),o===xn&&(o=void 0),this.autoFreeze_&&ir(o,!0),n){let i=[],s=[];ke("Patches").generateReplacementPatches_(t,o,i,s),n(i,s)}return o}else ce(1,t)},this.produceWithPatches=(t,r)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,c=>t(c,...l));let n,o;return[this.produce(t,r,(s,l)=>{n=s,o=l}),n,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){$e(e)||ce(8),oe(e)&&(e=Te(e));let t=wn(this),r=or(e,void 0);return r[ne].isManual_=!0,rr(t),r}finishDraft(e,t){let r=e&&e[ne];(!r||!r.isManual_)&&ce(9);let{scope_:n}=r;return An(n,t),En(void 0,n)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){let o=t[r];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}r>-1&&(t=t.slice(r+1));let n=ke("Patches").applyPatches_;return oe(e)?n(e,t):this.produce(e,o=>n(o,t))}};function or(e,t){let r=Et(e)?ke("MapSet").proxyMap_(e,t):vt(e)?ke("MapSet").proxySet_(e,t):Mi(e,t);return(t?t.scope_:_n()).drafts_.push(r),r}function Te(e){return oe(e)||ce(10,e),On(e)}function On(e){if(!$e(e)||xt(e))return e;let t=e[ne],r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=er(e,t.scope_.immer_.useStrictShallowCopy_)}else r=er(e,!0);return bt(r,(n,o)=>{Sn(r,n,On(o))}),t&&(t.finalized_=!1),r}var ie=new Ui,ar=ie.produce,of=ie.produceWithPatches.bind(ie),sf=ie.setAutoFreeze.bind(ie),af=ie.setUseStrictShallowCopy.bind(ie),cf=ie.applyPatches.bind(ie),lf=ie.createDraft.bind(ie),uf=ie.finishDraft.bind(ie);var m={LITERAL:0,VARIABLE:1,INTERPOLATION:2,FUNCTION:3,BINARY:4,UNARY:5,CONDITIONAL:6,LOOP:7,OBJECT:8,ARRAY:9,PARTIAL:10,PATH_REFERENCE:11},O={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},qe={NOT:0};var E=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},ee=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var cr=e=>{if(!e||e.trim()==="")throw new E("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let r=e.includes("===")?"==":"!=";throw new E(`Invalid comparison operator '${e.includes("===")?"===":"!=="}' - did you mean '${r}'? (got: '${e}')`)}let t=["<",">","<=",">=","==","!="];for(let r of t)if(e.trim().endsWith(r))throw new E(`Incomplete comparison expression - missing right operand (got: '${e}')`)},Ln=e=>{if(e.trim().endsWith(" in"))throw new E(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new E(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,r]=e.split(" in ");if(!r||r.trim()==="")throw new E(`Missing iterable expression after 'in' (got: '$for ${e}')`);let n=t.includes(",")?t.split(",").map(o=>o.trim()):[t.trim()];for(let o of n){if(!o)throw new E(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new E(`Invalid loop syntax (got: '$for ${e}')`)}};var $n=(e,t,r=!1)=>{if(t===null)return new ee(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new ee(`Cannot iterate over undefined value at '$for ${e}'`);let n=typeof t;return r?new ee(`Cannot iterate over non-array value in loop '${e}' - got ${n} instead`):new ee(`Cannot iterate over non-array value (got: ${n}) at '$for ${e}'`)},kn=(e,t)=>{let r=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new ee(`Unknown function '${e}' (${r})`)};var Bi=(e,t,r={})=>{let n={},o={};r&&typeof r=="object"&&(r.functions!==void 0||r.partials!==void 0?(n=r.functions||{},o=r.partials||{}):typeof r=="object"&&(n=r));let s=L(e,{functions:n,partials:o},t,{});return s===void 0?{}:s},L=(e,t,r,n)=>{let o=t.functions||t;if(e.var&&!e.type)return G(e.var,r,n);if(e.type===m.LITERAL)return e.value;if(e.type===m.VARIABLE)return G(e.path,r,n);if(e.type===m.INTERPOLATION)return Wi(e.parts,t,r,n);switch(e.type){case m.FUNCTION:return Dn(e,t,r,n);case m.BINARY:return Pn(e,t,r,n);case m.UNARY:return Nn(e,t,r,n);case m.CONDITIONAL:return Hi(e,t,r,n);case m.LOOP:return Xi(e,t,r,n);case m.OBJECT:return Zi(e,t,r,n);case m.ARRAY:return es(e,t,r,n);case m.PARTIAL:return ts(e,t,r,n);case m.PATH_REFERENCE:return rs(e,t,r,n);default:throw new Error(`Unknown node type: ${e.type}`)}},Tn=new Map,zi=e=>{let t=[],r="",n=!1;for(let o=0;o<e.length;o++){let i=e[o];if(i==="[")r&&(t.push({type:"property",value:r}),r=""),n=!0;else if(i==="]"){if(n&&r){let s=r.trim();if(/^\d+$/.test(s))t.push({type:"index",value:parseInt(s,10)});else if(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'")){let l=s.slice(1,-1);t.push({type:"property",value:l})}else t.push({type:"property",value:s});r=""}n=!1}else r+=i}return r&&t.push({type:"property",value:r}),t},G=(e,t,r)=>{if(!e)return;if(e in r)return r[e];let n=Tn.get(e);if(!n){let i=[],s="",l=0;for(let c=0;c<e.length;c++){let a=e[c];a==="["?(l++,s+=a):a==="]"?(l--,s+=a):a==="."&&l===0?s&&(i.push(s),s=""):s+=a}s&&i.push(s),n=[];for(let c of i){let a=zi(c.trim());n.push(...a)}Tn.set(e,n)}let o=t;for(let i=0;i<n.length;i++){let s=n[i];if(s.type==="property"&&s.value in r){o=r[s.value];continue}if(o==null)return;(s.type==="property"||s.type==="index")&&(o=o[s.value])}return o},Wi=(e,t,r,n)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=L(i,t,r,n);o.push(s!=null?String(s):"")}return o.join("")},Dn=(e,t,r,n)=>{let o=t.functions||t,i=o[e.name];if(!i)throw kn(e.name,o);let s=e.args.map(l=>L(l,t,r,n));return i(...s)},Ee=(e,t,r,n)=>{if(e.var&&!e.type)return G(e.var,r,n);switch(e.type){case m.VARIABLE:return G(e.path,r,n);case m.LITERAL:return e.value;case m.BINARY:return Pn(e,t,r,n);case m.UNARY:return Nn(e,t,r,n);case m.FUNCTION:return Dn(e,t,r,n);default:return L(e,t,r,n)}},Pn=(e,t,r,n)=>{if(e.op===O.AND||e.op===O.OR){let s=Ee(e.left,t,r,n),l=Ee(e.right,t,r,n);switch(e.op){case O.AND:return s&&l;case O.OR:return s||l}}let o=L(e.left,t,r,n),i=L(e.right,t,r,n);switch(e.op){case O.EQ:return o==i;case O.NEQ:return o!=i;case O.GT:return o>i;case O.LT:return o<i;case O.GTE:return o>=i;case O.LTE:return o<=i;case O.IN:return Array.isArray(i)?i.includes(o):!1;case O.ADD:if(typeof o!="number"||typeof i!="number")throw new ee(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case O.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new ee(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},Nn=(e,t,r,n)=>{let o=e.op===qe.NOT?Ee(e.operand,t,r,n):L(e.operand,t,r,n);if(e.op===qe.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},qi=(e,t,r,n)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===m.VARIABLE)if(G(o.path,r,n)){let s=e.bodies[0];if(s.type===m.OBJECT&&s.properties.length<=5){let l={};for(let c of s.properties){let a=c.parsedKey?L(c.parsedKey,t,r,n):c.key,u=c.value;if(u.type===m.LITERAL)l[a]=u.value;else if(u.type===m.VARIABLE)l[a]=G(u.path,r,n);else if(u.type===m.INTERPOLATION){let f=[];for(let d of u.parts)if(typeof d=="string")f.push(d);else if(d.type===m.VARIABLE){let p=G(d.path,r,n);f.push(p!=null?String(p):"")}else{let p=L(d,t,r,n);f.push(p!=null?String(p):"")}l[a]=f.join("")}else l[a]=L(u,t,r,n)}return l}}else{let s=e.bodies[1];if(s.type===m.OBJECT&&s.properties.length<=5){let l={};for(let c of s.properties){let a=c.parsedKey?L(c.parsedKey,t,r,n):c.key,u=c.value;if(u.type===m.LITERAL)l[a]=u.value;else if(u.type===m.VARIABLE)l[a]=G(u.path,r,n);else if(u.type===m.INTERPOLATION){let f=[];for(let d of u.parts)if(typeof d=="string")f.push(d);else if(d.type===m.VARIABLE){let p=G(d.path,r,n);f.push(p!=null?String(p):"")}else{let p=L(d,t,r,n);f.push(p!=null?String(p):"")}l[a]=f.join("")}else l[a]=L(u,t,r,n)}return l}}}return null},Hi=(e,t,r,n)=>{let o=qi(e,t,r,n);if(o!==null)return o;for(let i=0;i<e.conditions.length;i++){let s=e.conditions[i];if(s===null||Ee(s,t,r,n))return L(e.bodies[i],t,r,n)}return Vn},Yi=(e,t)=>{let r=e.body,n=e.itemVar;if(r.type===m.CONDITIONAL&&r.conditions.length===1&&r.conditions[0].type===m.VARIABLE){let o=r.conditions[0].path,i=r.bodies[0];if(o.startsWith(n+".")){let s=o.substring(n.length+1);if(i.type===m.OBJECT&&i.properties.length<=5){for(let c of i.properties)if(c.parsedKey)return null;let l=[];for(let c=0;c<t.length;c++){let a=t[c];if(a[s]){let u={};for(let f of i.properties){let d=f.key,p=f.value;if(p.type===m.LITERAL)u[d]=p.value;else if(p.type===m.VARIABLE){let h=p.path;if(h===n)u[d]=a;else if(h.startsWith(n+".")){let g=h.substring(n.length+1);u[d]=a[g]}else return null}else if(p.type===m.INTERPOLATION){let h=[],g=!0;for(let y of p.parts)if(typeof y=="string")h.push(y);else if(y.type===m.VARIABLE){let b=y.path;if(b===n)h.push(a!=null?String(a):"");else if(b.startsWith(n+".")){let A=b.substring(n.length+1),v=a[A];h.push(v!=null?String(v):"")}else{g=!1;break}}else{g=!1;break}if(!g)return null;u[d]=h.join("")}else return null}l.push(u)}}return l}}}return null},Ki=(e,t)=>{let r=e.body,n=e.itemVar,o=Yi(e,t);if(o!==null)return o;if(r.type===m.OBJECT&&r.properties.length<=5&&!r.whenCondition){for(let l of r.properties)if(l.parsedKey)return null;let i=[],s=!0;for(let l of r.properties){let c=l.key,a=l.value;if(a.type===m.LITERAL)i.push({key:c,type:"literal",value:a.value});else if(a.type===m.VARIABLE){let u=a.path;if(u===n)i.push({key:c,type:"item"});else if(u.startsWith(n+".")){let f=u.substring(n.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:c,type:"prop",prop:f});else{s=!1;break}}else{s=!1;break}}else if(a.type===m.INTERPOLATION&&a.parts.length===1){let u=a.parts[0];if(u.type===m.VARIABLE){let f=u.path;if(f===n)i.push({key:c,type:"item_string"});else if(f.startsWith(n+".")){let d=f.substring(n.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:c,type:"prop_string",prop:d});else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}if(s){let l=new Array(t.length);if(i.length===3&&i[0].type==="prop"&&i[0].key==="id"&&i[1].type==="prop_string"&&i[1].key==="title"&&i[2].type==="prop"&&i[2].key==="completed")for(let c=0;c<t.length;c++){let a=t[c];l[c]={id:a.id,title:a.title!=null?String(a.title):"",completed:a.completed}}else for(let c=0;c<t.length;c++){let a=t[c],u={};for(let f of i)if(f.type==="literal")u[f.key]=f.value;else if(f.type==="item")u[f.key]=a;else if(f.type==="prop")u[f.key]=a[f.prop];else if(f.type==="item_string")u[f.key]=a!=null?String(a):"";else if(f.type==="prop_string"){let d=a[f.prop];u[f.key]=d!=null?String(d):""}l[c]=u}return l}}return null},Gi=(e,t,r,n,o)=>{let i=[],s=e.body;if(s.type===m.OBJECT&&s.fast!==!1){let l=e.itemVar,c=e.indexVar;for(let a=0;a<o.length;a++){let u=o[a],f={},d={...n,[l]:u,...c&&{[c]:a}};d.__paths__||(d.__paths__=n.__paths__||{});let p=e.iterable.path||"";if(n&&n.__paths__&&p){let h=p.split("."),g=h[0];g in n.__paths__&&(p=n.__paths__[g],h.length>1&&(p+="."+h.slice(1).join(".")))}d.__paths__={...d.__paths__,[l]:`${p}[${a}]`,...c&&{[c]:a}};for(let h of s.properties){let g=h.parsedKey?L(h.parsedKey,t,r,d):h.key,y=h.value;if(y.type===m.LITERAL)f[g]=y.value;else if(y.type===m.VARIABLE){let b=y.path;if(b===l)f[g]=u;else if(b===c)f[g]=a;else if(b.startsWith(l+".")){let A=b.substring(l.length+1);!A.includes(".")&&!A.includes("[")?f[g]=u[A]:f[g]=G(b,r,{...n,[l]:u,...c&&{[c]:a}})}else f[g]=G(b,r,{...n,[l]:u,...c&&{[c]:a}})}else if(y.type===m.INTERPOLATION){let b=[];for(let A of y.parts)if(typeof A=="string")b.push(A);else if(A.type===m.VARIABLE){let v=A.path,S;if(v===l)S=u;else if(v===c)S=a;else if(v.startsWith(l+".")){let D=v.substring(l.length+1);!D.includes(".")&&!D.includes("[")?S=u[D]:S=G(v,r,{...n,[l]:u,...c&&{[c]:a}})}else S=G(v,r,{...n,[l]:u,...c&&{[c]:a}});b.push(S!=null?String(S):"")}else{let v={...n,[l]:u,...c&&{[c]:a}},S=L(A,t,r,v);b.push(S!=null?String(S):"")}f[g]=b.join("")}else{let b={...n,[l]:u,...c&&{[c]:a}};f[g]=L(y,t,r,b)}}i.push(f)}return i}return null},Ji=(e,t,r)=>{let n=e.body;if(n.type===m.OBJECT&&n.properties.length===1&&n.properties[0].key==="$if item.visible"){let i=n.properties[0].value;if(i.type===m.CONDITIONAL&&i.conditions.length===1&&i.conditions[0].type===m.VARIABLE&&i.conditions[0].path==="item.visible"){let s=i.bodies[0];if(s.type===m.OBJECT&&s.properties.length===2){let l=s.properties[0],c=s.properties[1];if(l.key==="id"&&l.value.type===m.VARIABLE&&l.value.path==="item.id"&&c.key==="$if item.highlighted"&&c.value.type===m.CONDITIONAL){let a=[];for(let u=0;u<t.length;u++){let f=t[u];if(f.visible){let d={id:f.id};f.highlighted?(d.highlight=!0,d.message=`This item is highlighted: ${f.name}`):(d.highlight=!1,d.message=f.name),a.push(d)}}return a}}}}return null},Xi=(e,t,r,n)=>{let o=L(e.iterable,t,r,n);if(!Array.isArray(o)){let a,u=!1;if(e.iterable.type===m.FUNCTION){u=!0;let d=e.iterable.args.map(p=>p.type===m.LITERAL?typeof p.value=="string"?`'${p.value}'`:String(p.value):p.type===m.VARIABLE?p.path:p.type===m.FUNCTION?`${p.name}(...)`:"?").join(", ");a=`${e.iterable.name}(${d})`}else a=e.iterable.path||"undefined";let f=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${a}`;throw $n(f,o,u)}if(!e.indexVar){let a=Ji(e,o,e.itemVar);if(a!==null)return a}if(!e.indexVar){let a=Ki(e,o);if(a!==null)return a}let i=Gi(e,t,r,n,o);if(i!==null)return i;let s=[],l=e.iterable.path||"";if(n&&n.__paths__&&l){let a=l.split("."),u=a[0];u in n.__paths__&&(l=n.__paths__[u],a.length>1&&(l+="."+a.slice(1).join(".")))}let c=!1;e.body.type===m.ARRAY&&(e.body.items.length<=1?c=!1:c=e.body._shouldPreserveArray??=e.body.items.some(a=>a.type===m.OBJECT&&a.properties.some(u=>u.key.startsWith("$if ")||u.key.startsWith("$when "))));for(let a=0;a<o.length;a++){let u=e.indexVar?{...n,[e.itemVar]:o[a],[e.indexVar]:a}:{...n,[e.itemVar]:o[a]};u.__paths__||(u.__paths__=n.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${l}[${a}]`},e.indexVar&&(u.__paths__[e.indexVar]=a);let f=L(e.body,t,r,u);if(Array.isArray(f)&&f.length===1&&!c){let d=f[0];s.push(d===void 0?{}:d)}else s.push(f===void 0?{}:f)}return s},Qi=(e,t,r,n)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?L(o.parsedKey,t,r,n):o.key,s=o.value;if(s.type===m.OBJECT&&s.properties.length<=10&&!s.whenCondition){let l={},c={},a=!0;for(let u of s.properties){let f=u.parsedKey?L(u.parsedKey,t,r,n):u.key,d=u.value;if(d.type===m.LITERAL)c[f]=d.value;else if(d.type===m.VARIABLE)c[f]=G(d.path,r,n);else if(d.type===m.INTERPOLATION){let p=[];for(let h of d.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let g=G(h.path,r,n);p.push(g!=null?String(g):"")}else{a=!1;break}if(!a)break;c[f]=p.join("")}else if(d.type===m.OBJECT&&d.properties.length<=5){let p={};for(let h of d.properties){let g=h.key,y=h.value;if(y.type===m.LITERAL)p[g]=y.value;else if(y.type===m.VARIABLE)p[g]=G(y.path,r,n);else if(y.type===m.INTERPOLATION){let b=[];for(let A of y.parts)if(typeof A=="string")b.push(A);else if(A.type===m.VARIABLE){let v=G(A.path,r,n);b.push(v!=null?String(v):"")}else{a=!1;break}if(!a)break;p[g]=b.join("")}else{a=!1;break}}if(!a)break;c[f]=p}else{a=!1;break}}if(a)return l[i]=c,l}}return null},Zi=(e,t,r,n)=>{let o=t.functions||t;if(e.whenCondition&&!Ee(e.whenCondition,o,r,n))return;let i=Qi(e,t,r,n);if(i!==null)return i;if(e.fast){let a={};for(let u of e.properties){let f=u.parsedKey?L(u.parsedKey,t,r,n):u.key,d=u.value;if(d.type===m.LITERAL)a[f]=d.value;else if(d.type===m.VARIABLE)a[f]=G(d.path,r,n);else if(d.type===m.INTERPOLATION){let p=[];for(let h of d.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let g=G(h.path,r,n);p.push(g!=null?String(g):"")}else{let g=L(h,t,r,n);p.push(g!=null?String(g):"")}a[f]=p.join("")}else a[f]=L(d,t,r,n)}return a}let s={},l=null,c=!1;for(let a of e.properties)if(!a.key.startsWith("$if ")&&!a.key.match(/^\$if\s+\w+.*:?$/)&&!a.key.startsWith("$elif")&&!a.key.startsWith("$else")&&!a.key.startsWith("$for ")){c=!0;break}for(let a of e.properties)if(a.key.startsWith("$if ")||a.key.match(/^\$if\s+\w+.*:?$/)){let u=L(a.value,t,r,n);if(!c&&u!==null&&u!==void 0)return Array.isArray(u)&&u.length===1?u[0]:u;typeof u=="object"&&u!==null&&!Array.isArray(u)&&Object.assign(s,u)}else if(a.key.startsWith("$for ")){if(e.properties.length===1)return L(a.value,t,r,n)}else{let u=a.value;if(u&&u.type===m.OBJECT&&u.properties){let f=u.properties.find(d=>d.key.startsWith("$for "));if(f){let d=L(f.value,t,r,n);d!==void 0&&(s[a.key]=d)}else{let d=L(a.value,t,r,n);d!==void 0&&(s[a.key]=d)}}else{let f=a.parsedKey?L(a.parsedKey,t,r,n):a.key,d=L(a.value,t,r,n);d!==void 0&&(s[f]=d)}}return s},Vn={},es=(e,t,r,n)=>{let o=[];for(let i of e.items)if(i.type===m.LOOP){let s=L(i,t,r,n);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=L(i,t,r,n);s!==Vn&&s!==void 0&&o.push(s)}return o},ts=(e,t,r,n)=>{let{name:o,data:i,whenCondition:s}=e,l=t.partials||{},c=t.functions||t;if(s&&!Ee(s,c,r,n))return;if(!l[o])throw new ee(`Partial '${o}' is not defined`);let a=n._partialStack||[];if(a.includes(o))throw new ee(`Circular partial reference detected: ${o}`);let u=l[o],f=r,d={...n,_partialStack:[...a,o]};if(n){f={...r};for(let p of Object.keys(n))p.startsWith("_")||(f[p]=n[p])}if(i){let p=L(i,t,r,n);f={...f,...p}}return L(u,t,f,d)},rs=(e,t,r,n)=>{let{path:o}=e,i=o.split("."),s=i[0],l=i.slice(1);if(!n||!(s in n))throw new ee(`Path reference '#{${o}}' refers to '${s}' which is not a loop variable in the current scope`);if(n.__paths__||(n.__paths__={}),!(s in n.__paths__))throw new ee(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let c=n.__paths__[s];if(typeof c=="number"){if(l.length>0)throw new ee(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(c)}return l.length>0&&(c+="."+l.join(".")),c};var lr=Bi;var ns=/\$\{([^}]*)\}/g,os=/#\{([^}]*)\}/g,Mn=(e,t={})=>{let r=e.match(/^(\w+)\((.*)\)$/);if(!r)return{isFunction:!1};let[,n,o]=r,i=is(o,t);return{isFunction:!0,type:m.FUNCTION,name:n,args:i}},is=(e,t={})=>e.trim()?ss(e).map(n=>as(n.trim(),t)):[],ss=e=>{let t=[],r="",n=0,o=!1,i="";for(let s=0;s<e.length;s++){let l=e[s],c=s>0?e[s-1]:"";!o&&(l==='"'||l==="'")?(o=!0,i=l,r+=l):o&&l===i&&c!=="\\"?(o=!1,i="",r+=l):!o&&l==="("?(n++,r+=l):!o&&l===")"?(n--,r+=l):!o&&l===","&&n===0?(t.push(r),r=""):r+=l}return r&&t.push(r),t},as=(e,t={})=>{if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:m.LITERAL,value:e.slice(1,-1)};if(/^-?\d+(\.\d+)?$/.test(e))return{type:m.LITERAL,value:parseFloat(e)};if(e==="true")return{type:m.LITERAL,value:!0};if(e==="false")return{type:m.LITERAL,value:!1};if(e==="null")return{type:m.LITERAL,value:null};let r=Mn(e,t);if(r.isFunction)return{type:r.type,name:r.name,args:r.args};let n=e.trim(),o=[{op:" + ",type:"ADD"},{op:" - ",type:"SUBTRACT"}],i=-1,s=null;for(let{op:l,type:c}of o){let a=0;for(;a<n.length;){let u=De(n.substring(a),l);if(u===-1)break;let f=a+u;f>i&&(i=f,s={op:l,type:c}),a=f+l.length}}if(i!==-1)try{return J(n,t)}catch{return{type:m.VARIABLE,path:n}}return{type:m.VARIABLE,path:n}},Fn=/^\w+\(.*\)$/,cs=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,ls=e=>{if(!(!e||e.trim()===""||Fn.test(e))&&cs.test(e))throw e.includes("?")&&e.includes(":")?new E(`Complex expressions not supported in variable replacements - consider calculating the value in your data instead. Offending expression: "${e}"`):e.includes("||")||e.includes("&&")||e.includes("??")?new E(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new E(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},jn=e=>{let t=e.trim();if(Fn.test(t))throw new E(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new E(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new E(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new E(`Logical operators not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("?")&&t.includes(":"))throw new E(`Complex expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);return{type:m.PATH_REFERENCE,path:t}},rt=(e,t={})=>{let r=e.trim();ls(r);let n=Mn(r,t);if(n.isFunction)return{type:n.type,name:n.name,args:n.args};if(r.includes("[")&&!/[\s+\-*/%|&?:]/.test(r)){let o=0;for(let i of r)i==="["?o++:i==="]"&&o--;if(o!==0)throw new Error("Invalid array index syntax")}return{type:m.VARIABLE,path:r}},ur=(e,t={})=>{let r=e,n=[];(e.includes("\\${")||e.includes("\\#{"))&&(r=e.replace(/\\\\(\$\{[^}]*\})/g,"\\DOUBLE_ESC_VAR$1"),r=r.replace(/\\\\(#\{[^}]*\})/g,"\\DOUBLE_ESC_PATH$1"),r=r.replace(/\\(\$\{[^}]*\})/g,(a,u)=>{let f=`__ESCAPED_${n.length}__`;return n.push(u),f}),r=r.replace(/\\(#\{[^}]*\})/g,(a,u)=>{let f=`__ESCAPED_${n.length}__`;return n.push(u),f}),r=r.replace(/\\DOUBLE_ESC_VAR/g,"\\"),r=r.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...r.matchAll(ns)],i=[...r.matchAll(os)],s=[...o.map(a=>({match:a,type:"variable"})),...i.map(a=>({match:a,type:"pathref"}))].sort((a,u)=>a.match.index-u.match.index);if(s.length===0){let a=r;for(let u=0;u<n.length;u++)a=a.replace(`__ESCAPED_${u}__`,n[u]);return{type:m.LITERAL,value:a}}if(s.length===1&&s[0].match[0]===r&&n.length===0){let{match:a,type:u}=s[0];try{return u==="variable"?rt(a[1],t):jn(a[1])}catch(f){if(f.message==="Invalid array index syntax")return{type:m.LITERAL,value:r};throw f}}let l=[],c=0;for(let{match:a,type:u}of s){let[f,d]=a,p=a.index;if(p>c){let h=r.substring(c,p);for(let g=0;g<n.length;g++)h=h.replace(`__ESCAPED_${g}__`,n[g]);h&&l.push(h)}try{let h;u==="variable"?h=rt(d.trim(),t):h=jn(d.trim()),l.push(h)}catch(h){if(h.message==="Invalid array index syntax")l.push(f);else throw h}c=p+f.length}if(c<r.length){let a=r.substring(c);for(let u=0;u<n.length;u++)a=a.replace(`__ESCAPED_${u}__`,n[u]);a&&l.push(a)}return{type:m.INTERPOLATION,parts:l}};var pr=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),zn=e=>Object.keys(e),Q=e=>e.join("."),ve=(e,t,r)=>{let n=zn(e).filter(o=>!t.has(o));if(n.length>0)throw new E(`Unexpected key '${n[0]}' in condition JSON at '${Q(r)}'`)},xe=(e,t)=>typeof e=="string"?ur(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?fs(e,t):ds(e,t):{type:m.LITERAL,value:e},us=e=>{let{$each:t,...r}=e;if(typeof t!="string")throw new E("$each value must be a non-empty string");let n=t.trim();if(n==="")throw new E("$each value must be a non-empty string");if(Object.keys(r).length===0)throw new E("Empty $each body not allowed");if(r.$partial!==void 0)throw new E("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${n}`]:r}},fs=(e,t)=>{let r=[],n=!1;for(let o=0;o<e.length;o++){let i=e[o];if(typeof i=="object"&&i!==null&&!Array.isArray(i)){if(i.$each!==void 0)try{let c=us(i),a=Object.keys(c);if(a.length===1&&/^\$for(?::\w+)?\s/.test(a[0])){let u=Bn(a[0],c[a[0]],t,!0);r.push(u),n=!0;continue}}catch(c){throw c instanceof E?c:new E(c.message)}let l=Object.keys(i);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let c=Bn(l[0],i[l[0]],t);r.push(c),n=!0;continue}}let s=xe(i,t);r.push(s),(s.type===m.FUNCTION||s.type===m.CONDITIONAL||s.type===m.LOOP||s.type===m.PARTIAL||s.type===m.OBJECT&&!s.fast||s.type===m.ARRAY&&!s.fast)&&(n=!0)}return{type:m.ARRAY,items:r,fast:!n}},ds=(e,t)=>{let r=[],n=!1,o=null,i=Object.entries(e),s=0;if(e.$partial!==void 0){if(typeof e.$partial!="string")throw new E("$partial value must be a string");if(e.$partial.trim()==="")throw new E("$partial value cannot be an empty string");let c=["$if","$elif","$else","$for"],a=[];for(let[b]of i)for(let A of c)if(b===A||b.startsWith(A+" ")||b.startsWith(A+"#")){a.push(A);break}if(a.length>0)throw new E(`Cannot use $partial with ${a.join(", ")} at the same level. Wrap $partial in a parent object if you need conditionals.`);let{$partial:u,$when:f,...d}=e,p={},h=!1;for(let[b,A]of Object.entries(d)){let v=b;(b.startsWith("\\$")||b.startsWith("$$"))&&(v=b.slice(1)),p[v]=A,h=!0}let g=null;if(h&&(g=xe(p,t),g.type===m.OBJECT)){let b=!1;for(let A of g.properties)if(A.value.type===m.VARIABLE||A.value.type===m.INTERPOLATION||A.value.type===m.FUNCTION||A.value.type===m.CONDITIONAL||A.value.type===m.OBJECT&&!A.value.fast||A.value.type===m.ARRAY&&!A.value.fast){b=!0;break}b&&(g.fast=!1)}let y={type:m.PARTIAL,name:u,data:g};return f!==void 0&&(y.whenCondition=Un(f,t)),y}for(let[c,a]of i)if(c==="$when"){if(o!==null)throw new E("Multiple '$when' directives on the same object are not allowed");if(a==null)throw new E("Missing condition expression after '$when'");o=Un(a,t),n=!0}else if(c.startsWith("$when#")||c.startsWith("$when "))throw new E("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<i.length;){let[c,a]=i[s];if(c==="$when"){s++;continue}if(c==="$each")throw new E("$each can only be used inside arrays");if(c.startsWith("$if ")||c.match(/^\$if#\w+\s/)||c.match(/^\$if\s+\w+.*:$/)){let u=ps(i,s,t);r.push({key:c,value:u.node}),n=!0,s=u.nextIndex}else if(/^\$for(?::\w+)?\s/.test(c)){let u=c.match(/^\$for(?::(\w+))?\s/)?.[1]||"",f=u?`:${u}`:"";throw new E(`$for loops must be inside arrays - use '- $for${f} item in items:' instead of '$for${f} item in items:'. For cleaner object generation syntax, consider using $each.`)}else{if(c.startsWith("$elif ")||c.startsWith("$else"))throw new E(`'${c.split(" ")[0]}' without matching '$if'`);if(c==="$if"||c==="$if:")throw new E("Missing condition expression after '$if'");{let u=xe(a,t);(u.type===m.FUNCTION||u.type===m.CONDITIONAL||u.type===m.PARTIAL||u.type===m.OBJECT&&!u.fast||u.type===m.ARRAY&&!u.fast)&&(n=!0);let f=ur(c,t),d={key:c,value:u};(f.type!==m.LITERAL||f.value!==c)&&(d.parsedKey=f),r.push(d),s++}}}let l={type:m.OBJECT,properties:r,fast:!n};return o&&(l.whenCondition=o),l},ps=(e,t,r={})=>{let n=[],o=[],i=t,[s,l]=e[i],c=null,a;if(s.startsWith("$if#")){let f=s.match(/^\$if#(\w+)\s+(.+)$/);if(f)c=f[1],a=f[2];else throw new E(`Invalid conditional syntax: ${s}`)}else a=s.substring(4),a.endsWith(":")&&(a=a.slice(0,-1).trim());cr(a);let u=J(a,r);for(n.push(u),o.push(xe(l,r)),i++;i<e.length;){let[f,d]=e[i],p=!1,h;if(c?f.startsWith(`$elif#${c} `)?(h=f.substring(`$elif#${c} `.length),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(f===`$else#${c}`||f===`$else#${c}:`)&&(p=!0,h=null):f.startsWith("$elif ")?(h=f.substring(6),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(f==="$else"||f==="$else:")&&(p=!0,h=null),p){if(h===null)n.push(null);else{cr(h);let g=J(h,r);n.push(g)}if(o.push(xe(d,r)),i++,h===null)break}else break}return{node:{type:m.CONDITIONAL,conditions:n,bodies:o,id:c},nextIndex:i}},fr={eq:O.EQ,neq:O.NEQ,gt:O.GT,gte:O.GTE,lt:O.LT,lte:O.LTE,in:O.IN,add:O.ADD,sub:O.SUBTRACT},dr={all:O.AND,any:O.OR},hs=new Set(["var","literal","call","not",...Object.keys(fr),...Object.keys(dr)]),ms=(e,t,r)=>{if(!Array.isArray(e))throw new E(`Condition JSON operator '${t}' at '${Q(r)}' requires an array`);if(e.length!==2)throw new E(`Condition JSON operator '${t}' at '${Q(r)}' requires exactly 2 operands`);return e},gs=(e,t,r,n,o)=>{if(!Array.isArray(e))throw new E(`Condition JSON operator '${t}' at '${Q(o)}' requires an array`);if(e.length===0)throw new E(`Condition JSON operator '${t}' at '${Q(o)}' requires at least 1 condition`);return e.map((s,l)=>ge(s,n,[...o,l])).reduce((s,l)=>({type:m.BINARY,op:r,left:s,right:l}))},ys=(e,t,r)=>{let n,o;if(typeof e.call=="string")n=e.call,o=e.args??[],ve(e,new Set(["call","args"]),r);else if(pr(e.call))n=e.call.name,o=e.call.args??[],ve(e,new Set(["call"]),r),ve(e.call,new Set(["name","args"]),[...r,"call"]);else throw new E(`Condition JSON call at '${Q(r)}' requires a function name`);if(typeof n!="string"||n.trim()==="")throw new E(`Condition JSON call at '${Q(r)}' requires a non-empty function name`);if(!/^\w+$/.test(n))throw new E(`Invalid condition JSON function name '${n}' at '${Q(r)}'`);if(!Array.isArray(o))throw new E(`Condition JSON call '${n}' at '${Q(r)}' requires args to be an array`);return{type:m.FUNCTION,name:n,args:o.map((i,s)=>ge(i,t,[...r,"args",s]))}},ge=(e,t={},r=["$when"])=>{if(typeof e=="string"||typeof e=="number"||typeof e=="boolean"||e===null)return{type:m.LITERAL,value:e};if(Array.isArray(e))throw new E(`Condition JSON array at '${Q(r)}' must be wrapped in an operator or { literal: [...] }`);if(!pr(e))throw new E(`Invalid condition JSON value at '${Q(r)}'`);let n=zn(e);if(n.length===0)throw new E(`Condition JSON object at '${Q(r)}' must contain an operator`);let o=n.filter(s=>hs.has(s));if(o.length===0)throw new E(`Unknown condition JSON operator '${n[0]}' at '${Q(r)}'`);if(o.length>1)throw new E(`Condition JSON at '${Q(r)}' must contain exactly one operator`);let i=o.includes("call")?"call":o[0];if(i==="var"){if(ve(e,new Set(["var"]),r),typeof e.var!="string"||e.var.trim()==="")throw new E(`Condition JSON var at '${Q(r)}' requires a non-empty path`);return{type:m.VARIABLE,path:e.var}}if(i==="literal")return ve(e,new Set(["literal"]),r),{type:m.LITERAL,value:e.literal};if(i==="call")return ys(e,t,r);if(i==="not")return ve(e,new Set(["not"]),r),{type:m.UNARY,op:qe.NOT,operand:ge(e.not,t,[...r,"not"])};if(i in dr)return ve(e,new Set([i]),r),gs(e[i],i,dr[i],t,[...r,i]);if(i in fr){ve(e,new Set([i]),r);let s=ms(e[i],i,[...r,i]);return{type:m.BINARY,op:fr[i],left:ge(s[0],t,[...r,i,0]),right:ge(s[1],t,[...r,i,1])}}throw new E(`Unknown condition JSON operator '${i}' at '${Q(r)}'`)},Un=(e,t={})=>{if(e==null)throw new E("Missing condition expression after '$when'");if(typeof e=="string"){if(e.trim()==="")throw new E("Empty condition expression after '$when'");return J(e,t)}return pr(e)||Array.isArray(e)?ge(e,t):{type:m.LITERAL,value:e}},J=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let a=e.slice(1,-1),u=0,f=!0;for(let d=0;d<a.length;d++)if(a[d]==="("?u++:a[d]===")"&&u--,u<0){f=!1;break}if(f&&u===0)return J(a,t)}let r=De(e,"||");if(r!==-1)return{type:m.BINARY,op:O.OR,left:J(e.substring(0,r).trim(),t),right:J(e.substring(r+2).trim(),t)};let n=De(e,"&&");if(n!==-1)return{type:m.BINARY,op:O.AND,left:J(e.substring(0,n).trim(),t),right:J(e.substring(n+2).trim(),t)};let o=[{op:">=",type:O.GTE},{op:"<=",type:O.LTE},{op:"==",type:O.EQ},{op:"!=",type:O.NEQ},{op:">",type:O.GT},{op:"<",type:O.LT},{op:" in ",type:O.IN}];for(let{op:a,type:u}of o){let f=De(e,a);if(f!==-1)return{type:m.BINARY,op:u,left:J(e.substring(0,f).trim(),t),right:J(e.substring(f+a.length).trim(),t)}}let i=-1,s=null,l=[{op:" + ",type:O.ADD},{op:" - ",type:O.SUBTRACT}];for(let{op:a,type:u}of l){let f=0;for(;f<e.length;){let d=De(e.substring(f),a);if(d===-1)break;let p=f+d;p>i&&(i=p,s={op:a,type:u}),f=p+a.length}}if(i!==-1&&s)return{type:m.BINARY,op:s.type,left:J(e.substring(0,i).trim(),t),right:J(e.substring(i+s.op.length).trim(),t)};let c=[" * "," / "," % "];for(let a of c)if(De(e,a)!==-1)throw new E(`Arithmetic operations are not allowed in conditionals: "${a}"`);return e.startsWith("!")?{type:m.UNARY,op:qe.NOT,operand:J(e.substring(1).trim(),t)}:Wn(e,t)},De=(e,t)=>{let r=0,n=0;for(;n<=e.length-t.length;){if(e[n]==="(")r++;else if(e[n]===")")r--;else if(r===0&&e.substring(n,n+t.length)===t)return n;n++}return-1},bs=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}},Wn=(e,t)=>{let r=e.trim();if(r.match(/^(\w+)\((.*)\)$/))return rt(r,t);let o=bs(r);if(o.type===m.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(r))return{type:m.VARIABLE,path:r};try{return rt(r,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},Is=(e,t=!1)=>{let r=t?"$each":"$for";try{Ln(e)}catch(n){if(n instanceof E&&t){let o=n.message.replace(/\$for/g,"$each");throw new E(o.replace("Parse Error: ",""))}throw n}},Bn=(e,t,r,n=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let y=n?"$each":"$for";throw new E(`Invalid loop syntax (got: '${e.replace("$for",y)}')`)}let s=i[1],l=i[2].trim();Is(l,n);let c=l.match(/^(.+?)\s+in\s+(.+)$/);if(!c){let y=n?"$each":"$for";throw new E(`Invalid loop syntax - missing 'in' keyword (got: '${y} ${l}')`)}let a=c[1].trim(),u=c[2].trim(),f,d=null;if(a.includes(",")){let y=a.split(",").map(b=>b.trim());if(y.length!==2)throw new E(`Invalid loop variables: ${a}. Expected format: "item" or "item, index"`);f=y[0],d=y[1]}else f=a;let p=["this","undefined","null","true","false"];if(p.includes(f))throw new E(`Reserved variable name: ${f}`);if(d&&p.includes(d))throw new E(`Reserved variable name: ${d}`);let h=Wn(u,r),g=xe(t,r);return{type:m.LOOP,itemVar:f,indexVar:d,iterable:h,body:g,flatten:s!=="nested"}};var As=(e,t={})=>{let{functions:r={}}=t;return xe(e,r)},Ct=As;var nt={};ki(nt,{now:()=>ws});var ws=()=>Date.now();var Es=(e,t,r={})=>{let{functions:n={},partials:o={}}=r,i={...nt,...n},s=Ct(e,{functions:i}),l={};for(let[c,a]of Object.entries(o))l[c]=Ct(a,{functions:i});return lr(s,t,{functions:i,partials:l})},re=Es;var vs=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",xs=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,Cs=(e,t)=>{if(vs(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new E("Empty condition expression");return J(e,t)}return ge(e,t)},Ss=(e,t={},r={})=>{let n=xs(r),o={...nt,...n},i=Cs(e,o);return!!Ee(i,{functions:o,partials:{}},t,{})},hr=Ss;var it=(e,t={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return hr(e,t)},Jn=(e,t,r={})=>{let n=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=c=>c,transformActionFirstArgument:l=c=>c}=r;for(let[c,a]of Object.entries(t))c!=="createInitialState"&&(c.startsWith("select")?o[c]=(...u)=>a(s(n),...u):i[c]=(...u)=>{let f;return n=ar(n,p=>{let h=a(l(p),...u);f=h!==void 0&&!oe(h)?h:void 0}),f});return{...o,...i}},Rt=(e,t)=>r=>{let n=e(),o=Array.isArray(r)?r:[r];return ar(n,i=>{o.forEach(s=>{t.forEach(l=>{l(i,s)})})})};var _s=(e,t)=>{if(e.default!==void 0)return e.default;let r=["number","boolean","string","object"];if(!r.includes(e.type))throw new Error(`Invalid variable type: ${e.type} for variable ${t}. Expected one of: ${r.join(", ")}`);switch(e.type){case"number":return 0;case"boolean":return!1;case"string":return"";case"object":return{}}},ue=(e,t)=>Object.prototype.hasOwnProperty.call(e??{},t),ot=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Xn=e=>{let t=oe(e)?Te(e):e;return structuredClone(t)},Ce=e=>ue(e,"computed"),He=(e={},t={})=>Object.fromEntries(Object.entries(e??{}).filter(([r])=>!Ce(t[r]))),Rs=e=>String(e).replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean),mr=(e,t)=>{let r=e;for(let n of t){if(r==null)return;r=r[n]}return r},Os=(e,t={})=>{if(typeof e!="string"||e.trim()==="")throw new Error("Computed expression var requires a non-empty string path");let r=Rs(e),[n,o,...i]=r;if(n==="variables"){if(!o)return t.variables;let s=typeof t.resolveVariable=="function"?t.resolveVariable(o):t.variables?.[o];return mr(s,i)}return n==="runtime"?mr(t.runtime,r.slice(1)):mr(t,r)},Ls=(e,t,r)=>{if(!Array.isArray(t))throw new Error(`Computed expression operator "${e}" requires an array`);if(r!==void 0&&t.length!==r)throw new Error(`Computed expression operator "${e}" requires ${r} operand(s)`)},qn=(e,t)=>{if(!Array.isArray(t))throw new Error(`Computed expression operator "${e}" requires an array`);if(t.length===0)throw new Error(`Computed expression operator "${e}" requires at least one operand`)},$s=(e,t)=>{if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Computed expression operator "${e}" requires finite numeric operands`)},le=(e,t,r,n)=>(Ls(e,t,n),t.map(o=>_t(o,r))),ae=(e,t,r,n)=>{let o=le(e,t,r,n);return o.forEach(i=>$s(e,i)),o},ks=(e,t,r)=>{switch(e){case"var":return Os(t,r);case"add":{let[n,o]=ae(e,t,r,2);return n+o}case"sub":{let[n,o]=ae(e,t,r,2);return n-o}case"mul":{let[n,o]=ae(e,t,r,2);return n*o}case"div":{let[n,o]=ae(e,t,r,2);return n/o}case"mod":{let[n,o]=ae(e,t,r,2);return n%o}case"neg":{let[n]=ae(e,t,r,1);return-n}case"round":{let[n]=ae(e,t,r,1);return Math.round(n)}case"floor":{let[n]=ae(e,t,r,1);return Math.floor(n)}case"ceil":{let[n]=ae(e,t,r,1);return Math.ceil(n)}case"min":{let[n,o]=ae(e,t,r,2);return Math.min(n,o)}case"max":{let[n,o]=ae(e,t,r,2);return Math.max(n,o)}case"clamp":{let[n,o,i]=ae(e,t,r,3);return Math.min(i,Math.max(o,n))}case"eq":{let[n,o]=le(e,t,r,2);return n==o}case"neq":{let[n,o]=le(e,t,r,2);return n!=o}case"gt":{let[n,o]=le(e,t,r,2);return n>o}case"gte":{let[n,o]=le(e,t,r,2);return n>=o}case"lt":{let[n,o]=le(e,t,r,2);return n<o}case"lte":{let[n,o]=le(e,t,r,2);return n<=o}case"in":{let[n,o]=le(e,t,r,2);return Array.isArray(o)?o.includes(n):!1}case"and":case"all":return qn(e,t),t.every(n=>!!_t(n,r));case"or":case"any":return qn(e,t),t.some(n=>!!_t(n,r));case"not":{let[n]=le(e,t,r,1);return!n}case"length":{let[n]=le(e,t,r,1);return typeof n=="string"||Array.isArray(n)?n.length:ot(n)?Object.keys(n).length:0}case"includes":{let[n,o]=le(e,t,r,2);return typeof n=="string"||Array.isArray(n)?n.includes(o):!1}case"literal":return Xn(t);default:throw new Error(`Unknown computed expression operator: ${e}`)}},_t=(e,t={})=>{if(e===null||typeof e!="object")return e;if(Array.isArray(e))throw new Error("Computed expression arrays are not valid; use value for literal arrays");let r=Object.entries(e);if(r.length!==1)throw new Error("Computed expression objects must contain exactly one operator");let[[n,o]]=r;return ks(n,o,t)},Ts=(e,t={})=>it(e,{variables:t.variables,runtime:t.runtime}),Ds=(e,t)=>{if(!ot(e))throw new Error(`${t} must be an object`);let r=ue(e,"expr"),n=ue(e,"value");if(r===n)throw new Error(`${t} must contain exactly one of expr or value`)},gr=(e,t,r)=>(Ds(e,t),ue(e,"value")?Xn(e.value):_t(e.expr,r)),Ps=(e,t={},r="unknown")=>{if(!ot(e))throw new Error(`Computed variable "${r}" computed must be an object`);let n=ue(e,"expr"),o=ue(e,"value");if(ue(e,"branches")){if(n||o)throw new Error(`Computed variable "${r}" cannot combine branches with expr or value`);if(!Array.isArray(e.branches))throw new Error(`Computed variable "${r}" branches must be an array`);if(e.branches.length===0)throw new Error(`Computed variable "${r}" branches must not be empty`);if(!ot(e.default))throw new Error(`Computed variable "${r}" requires default`);for(let s=0;s<e.branches.length;s+=1){let l=e.branches[s];if(!ot(l))throw new Error(`Computed variable "${r}" branch ${s} must be an object`);if(!ue(l,"when"))throw new Error(`Computed variable "${r}" branch ${s} requires when`);if(Ts(l.when,t))return gr(l,`Computed variable "${r}" branch ${s}`,t)}return gr(e.default,`Computed variable "${r}" default`,t)}if(n===o)throw new Error(`Computed variable "${r}" must contain exactly one of expr, value, or branches`);return gr(e,`Computed variable "${r}"`,t)},Ns=(e,t,r)=>{switch(t){case"number":if(typeof r!="number"||!Number.isFinite(r))throw new Error(`Computed variable "${e}" expected type number, got ${Array.isArray(r)?"array":typeof r}`);return;case"boolean":if(typeof r!="boolean")throw new Error(`Computed variable "${e}" expected type boolean, got ${Array.isArray(r)?"array":typeof r}`);return;case"string":if(typeof r!="string")throw new Error(`Computed variable "${e}" expected type string, got ${Array.isArray(r)?"array":typeof r}`);return;case"object":if(r===null||typeof r!="object")throw new Error(`Computed variable "${e}" expected type object, got ${typeof r}`);return;default:throw new Error(`Invalid variable type: ${t} for computed variable ${e}`)}},Ot=({variables:e={},runtime:t={},variableConfigs:r={},eager:n=!0}={})=>{let o=He(e,r),i=Object.entries(r).filter(([,f])=>Ce(f)).map(([f])=>f),s={},l=[],c=f=>{if(ue(s,f))return s[f];let d=r[f];if(!Ce(d))return o[f];let p=l.indexOf(f);if(p>=0){let h=[...l.slice(p),f].join(" -> ");throw new Error(`Computed variable cycle detected: ${h}`)}l.push(f);try{let h=Ps(d.computed,u,f);return Ns(f,d.type,h),s[f]=h,h}finally{l.pop()}},a=new Proxy({},{get:(f,d)=>{if(typeof d=="string")return c(d)},has:(f,d)=>typeof d=="string"&&(ue(o,d)||i.includes(d)),ownKeys:()=>[...new Set([...Object.keys(o),...i])],getOwnPropertyDescriptor:(f,d)=>{if(!(typeof d!="string"||!ue(o,d)&&!i.includes(d)))return{enumerable:!0,configurable:!0}}}),u={variables:a,runtime:t,resolveVariable:c};return n?(i.forEach(f=>{c(f)}),{...o,...s}):a},Vs=({variables:e={},runtime:t={},variableConfigs:r,projectData:n}={})=>Ot({variables:e,runtime:t,variableConfigs:r??n?.resources?.variables??{},eager:!0}),Ir=e=>{let t={},r={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([n,o])=>{if(Ce(o))return;let i=_s(o,n);o.scope==="context"?t[n]=i:r[n]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}},Lt=(e,t)=>{let r=["context","device","account"];if(!e)throw new Error(`Variable scope is required for variable: ${t}`);if(!r.includes(e))throw new Error(`Invalid variable scope: ${e} for variable ${t}. Expected one of: ${r.join(", ")}`)},$t=(e,t,r)=>{let n={number:["set","increment","decrement","multiply","divide"],boolean:["set","toggle"],string:["set"],object:["set"]},o=n[e];if(!o)throw new Error(`Unknown variable type: ${e} for variable ${r}`);if(!Object.values(n).flat().includes(t))throw new Error(`Unknown operation: ${t}`);if(!o.includes(t))throw new Error(`Operation "${t}" is not valid for variable "${r}" of type "${e}". Valid operations: ${o.join(", ")}`)},js=2,Hn=12,Qn=(e=js)=>{if(!Number.isInteger(e)||e<0||e>Hn)throw new Error(`Operation "divide" requires roundTo to be an integer between 0 and ${Hn}.`);return e},Ms=(e,t)=>{let r=10**t;return Math.round((e+Number.EPSILON)*r)/r},St=e=>typeof e=="number"&&Number.isFinite(e),Ar=(e,t,r,n,o={})=>{if(e==="number"){if(t==="set"&&!St(r))throw new Error(`Operation "set" requires value to be a number for variable "${n}".`);if(t==="multiply"&&!St(r))throw new Error(`Operation "multiply" requires value to be a number for variable "${n}".`);if(t==="divide"&&!St(r))throw new Error(`Operation "divide" requires value to be a number for variable "${n}".`);if(t==="divide"){if(r===0)throw new Error(`Operation "divide" requires value to be a non-zero number for variable "${n}".`);Qn(o.roundTo)}}},kt=(e,t,r,n={})=>{let o=(s,l,c)=>{let a=s??l;if(!St(a))throw new Error(`Operation "${t}" requires ${c} to be a number.`);return a},i=s=>{let l=o(s,void 0,"value");if(l===0)throw new Error(`Operation "${t}" requires value to be a non-zero number.`);return l};switch(t){case"set":return r;case"multiply":return o(e,1,"current value")*o(r,void 0,"value");case"divide":return Ms(o(e,0,"current value")/i(r),Qn(n.roundTo));case"increment":return o(e,0,"current value")+o(r,1,"value");case"decrement":return o(e,0,"current value")-o(r,1,"value");case"toggle":return!e;default:throw new Error(`Unknown operation: ${t}`)}};var Zn=(e,t="DD/MM/YYYY - HH:mm")=>{if(!e)return"";let r=new Date(e),n=o=>String(o).padStart(2,"0");return t.replace("DD",n(r.getDate())).replace("MM",n(r.getMonth()+1)).replace("YYYY",r.getFullYear()).replace("YY",String(r.getFullYear()).slice(-2)).replace("HH",n(r.getHours())).replace("mm",n(r.getMinutes())).replace("ss",n(r.getSeconds()))},Fs=(e,t)=>{let r=i=>{if(!i)return;let s={};i.ui&&(s.ui=i.ui);let l=i.character?.sprite;return l&&Object.keys(l).length>0&&(s.sprite=l),Object.keys(s).length>0?s:void 0},n=r(e),o=r(t);return JSON.stringify(n)===JSON.stringify(o)?null:n&&!o?{changeType:"delete",data:e}:o&&!n?{changeType:"add",data:t}:o&&n?{changeType:"update",data:t}:null},Yn=e=>{if(e?.resourceId===void 0)return;let t={resourceId:e.resourceId};return e.transformId!==void 0&&(t.transformId=e.transformId),e.loop!==void 0&&(t.loop=e.loop),t},Kn=e=>{if(e?.colorId!==void 0)return{colorId:e.colorId}},Gn=(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,Us=(e,t)=>{let r={},n=Gn(Yn(e),Yn(t)),o=Gn(Kn(e),Kn(t));return n&&(r.resource=n),o&&(r.color=o),Object.keys(r).length>0?r:null},wr=(e={},t={})=>{let r={},n=["sfx","voice"],o=l=>{let c=e[l],a=t[l];a&&!c?r[l]={changeType:"add",data:a}:c&&!a?n.includes(l)||(r[l]={changeType:"delete",data:c}):c&&a&&JSON.stringify(c)!==JSON.stringify(a)&&(r[l]={changeType:"update",data:a})},i=Us(e.background,t.background);i&&(r.background=i),o("screen"),o("bgm"),o("voice");let s=Fs(e.dialogue,t.dialogue);return s&&(r.dialogue=s),o("choice"),o("form"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),r},Er=(e={})=>{let t=structuredClone(e);t.background&&(t.background.animations?.playback?.continuity!=="persistent"&&delete t.background.animations,!t.background.resourceId&&!t.background.colorId&&delete t.background);let r=o=>{t[o]&&(delete t[o].animations,Object.keys(t[o]).length===0&&delete t[o])};r("layout"),r("choice"),r("form"),r("screen"),t.dialogue?.ui&&(delete t.dialogue.ui.animations,Object.keys(t.dialogue.ui).length===0&&delete t.dialogue.ui,Object.keys(t.dialogue).length===0&&delete t.dialogue),t.dialogue?.character?.sprite&&(delete t.dialogue.character.sprite.animations,Object.keys(t.dialogue.character.sprite).length===0&&delete t.dialogue.character.sprite,Object.keys(t.dialogue.character).length===0&&delete t.dialogue.character,Object.keys(t.dialogue).length===0&&delete t.dialogue);let n=(o,i)=>{let s=t[o]?.items;Array.isArray(s)&&(t[o].items=s.map(l=>{let c={...l};return delete c.animations,i(c)?c:null}).filter(Boolean),t[o].items.length===0&&delete t[o])};return n("character",o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId),n("visual",o=>o.resourceId||o.transformId),t},Bs=(e,t)=>{if(!e||!t)return;let r=e;for(let n of t.split(".")){if(r==null||!(n in Object(r)))return;r=r[n]}return r},zs=(e,t)=>{if(typeof e!="string")return e;if(e==="_event"){if(t==null)throw new Error('Action template binding "_event" requires event context "_event".');return t}if(!e.startsWith("_event."))return e;if(t==null)throw new Error(`Action template binding "${e}" requires event context "_event".`);let r=e.slice(7),n=Bs(t,r);if(n===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return n},Ws={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"])},eo=(e,t)=>{let r=e[e.length-1];return r?Ws[r]?.has(t)===!0:!1},yr=(e,t,r=[])=>Array.isArray(e)?e.map(n=>yr(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,eo(r,n)?o:yr(o,t,[...r,n])])):zs(e,t),br=(e,t,r=[])=>Array.isArray(e)?e.map(n=>br(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,eo(r,n)?o:br(o,t,[...r,n])])):typeof e=="string"?re(e,t):e,vr=(e,t)=>{if(!t)return e;if(Object.prototype.hasOwnProperty.call(t,"event"))throw new Error('Action template context key "event" is no longer supported. Use "_event".');let r=yr(e,t._event);return br(r,t)};var te=e=>structuredClone(oe(e)?Te(e):e),K=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),to=e=>e?.animations?.playback?.continuity==="persistent",z=(e,t)=>K(e??{},t)&&e[t]!==void 0,st=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:te(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},qs=e=>z(e,"opacity")||z(e,"blur"),no=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],Hs=e=>no.some(t=>z(e,t)),Ys=(e,t,r)=>{let n=e[r];return n?.id===t?.id?n:e.find(o=>o.id===t?.id)},Ks=(e,t)=>{if(!t)return e;for(let r of no)!z(e,r)&&z(t,r)&&(e[r]=t[r]),K(e,r)&&e[r]===void 0&&delete e[r];return e},Gs=(e,t)=>(t&&(!z(e,"opacity")&&z(t,"opacity")&&(e.opacity=t.opacity),!z(e,"blur")&&z(t,"blur")&&(e.blur=te(t.blur)),K(e,"opacity")&&e.opacity===void 0&&delete e.opacity,K(e,"blur")&&e.blur===void 0&&delete e.blur),e),oo=(e,t,r=[])=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let n=e.map((o,i)=>{let s=Ys(r,o,i),l=t(o),c=qs(o),a=Hs(o),u=K(o,"animations"),f=te(o);return!l&&(c||a)&&s&&(f={...te(s),...f},u||delete f.animations),Gs(Ks(f,s),s)}).filter(o=>t(o)||o.animations);return{hasValidItems:n.length>0,processedItems:n}},Js=e=>{if(e){if(e.character&&K(e.character,"name"))return e.character.name;if(K(e,"characterName"))return e.characterName}},io=e=>!!e?.character&&K(e.character,"sprite"),Xs=e=>{let t={},r=!1,n=Js(e);return n!==void 0&&(t.name=n,r=!0),io(e)&&(t.sprite=te(e.character.sprite),r=!0),r?t:void 0},ro=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},Qs=({dialogueState:e,content:t,append:r=!1})=>{if(!r||!Array.isArray(t)){e.content=t,delete e.initialRevealedContent;return}let n=Array.isArray(e.content)?e.content:[];n.length>0?e.initialRevealedContent=n.map(o=>te(o)):delete e.initialRevealedContent,e.content=[...n,...t]},Zs=()=>({}),ea=(e,t)=>{if(!t.screen)return;let r=z(t.screen,"opacity"),n=z(t.screen,"blur"),o=K(t.screen,"animations");if(!r&&!n){o||delete e.screen;return}let i=e.screen,s={};if(r?s.opacity=t.screen.opacity:z(i,"opacity")&&(s.opacity=i.opacity),n?s.blur=te(t.screen.blur):z(i,"blur")&&(s.blur=te(i.blur)),K(s,"opacity")&&s.opacity===void 0&&delete s.opacity,K(s,"blur")&&s.blur===void 0&&delete s.blur,Object.keys(s).length===0){delete e.screen;return}e.screen=s},ta=(e,t)=>{if(t.background){let r=z(t.background,"resourceId"),n=z(t.background,"colorId"),o=z(t.background,"opacity"),i=z(t.background,"blur"),{animationsOnly:s,state:l}=st(t.background,u=>z(u,"resourceId")||z(u,"colorId")||z(u,"opacity")||z(u,"blur"));if(s){e.background=e.background?{...te(e.background),...l}:l;return}if(!r&&!n&&!o&&!i){delete e.background;return}let c=e.background,a=te(t.background);if(!r&&c?.resourceId&&(a.resourceId=c.resourceId,!K(a,"transformId")&&c.transformId&&(a.transformId=c.transformId)),!n&&c?.colorId&&(a.colorId=c.colorId),!o&&z(c,"opacity")&&(a.opacity=c.opacity),!i&&z(c,"blur")&&(a.blur=te(c.blur)),K(a,"resourceId")&&a.resourceId===void 0&&delete a.resourceId,K(a,"colorId")&&a.colorId===void 0&&delete a.colorId,K(a,"animations")&&a.animations===void 0&&delete a.animations,K(a,"opacity")&&a.opacity===void 0&&delete a.opacity,K(a,"blur")&&a.blur===void 0&&delete a.blur,!a.resourceId&&!a.colorId){delete e.background;return}c?.resourceId===a.resourceId&&c?.transformId===a.transformId&&!K(a,"animations")&&to(c)&&(a.animations=te(c.animations)),e.background=a}else e.background?.animations&&!to(e.background)&&(e.background.animations={})},ra=(e,t)=>{if(!t.dialogue){e.dialogue&&(ro(e.dialogue),e.dialogue.mode==="adv"&&(e.dialogue.content=void 0,delete e.dialogue.initialRevealedContent,e.dialogue.persistCharacter!==!0&&(delete e.dialogue.characterId,delete e.dialogue.character)));return}e.dialogue||(e.dialogue={});let r=e.dialogue.mode;if(t.dialogue.ui){let{animationsOnly:a,state:u}=st(t.dialogue.ui,f=>!!f.resourceId);a?e.dialogue.ui={...e.dialogue.ui,...u}:e.dialogue.ui={...t.dialogue.ui}}else e.dialogue?.ui?.animations&&(e.dialogue.ui.animations={});t.dialogue.mode==="adv"&&(e.dialogue.content=e.dialogue.content||void 0,e.dialogue.characterId=e.dialogue.characterId||void 0,e.dialogue.mode="adv"),t.dialogue.mode==="nvl"&&(e.dialogue?.mode!=="nvl"&&(e.dialogue.lines=[]),e.dialogue.mode="nvl");let n=t.dialogue.append===!0&&r!=="nvl"&&e.dialogue?.mode!=="nvl"&&Array.isArray(t.dialogue.content);t.dialogue.content!==void 0&&Qs({dialogueState:e.dialogue,content:t.dialogue.content,append:n});let o=K(t.dialogue,"persistCharacter")?t.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;o?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let i=K(t.dialogue,"characterId"),s=Xs(t.dialogue),l=s!==void 0,c=io(t.dialogue);if(i?t.dialogue.characterId?e.dialogue.characterId=t.dialogue.characterId:delete e.dialogue.characterId:!o&&!n&&delete e.dialogue.characterId,l?e.dialogue.character=!i&&o&&e.dialogue.character?{...te(e.dialogue.character),...s}:s:(i||!o&&!n)&&delete e.dialogue.character,c||ro(e.dialogue),t.dialogue.clear){delete e.dialogue;return}if(t.dialogue?.clearPage&&e.dialogue?.mode==="nvl"&&(e.dialogue.lines=[]),e.dialogue?.mode==="nvl"&&t.dialogue.content!==void 0){let a={content:t.dialogue.content,characterId:e.dialogue.characterId??null};e.dialogue.character&&(a.character=te(e.dialogue.character)),e.dialogue.lines.push(a)}},na=(e,t)=>{if(t.sfx){if(!t.sfx.items||t.sfx.items.length===0){delete e.sfx;return}e.sfx=t.sfx}else e.sfx&&delete e.sfx},oa=(e,t)=>{if(t.bgm){if(!t.bgm.resourceId){e.bgm=void 0;return}e.bgm={...t.bgm,loop:t.bgm.loop||t.bgm.loop===void 0}}},ia=(e,t)=>{if(t.visual){let{hasValidItems:r,processedItems:n}=oo(t.visual.items,o=>!!o.resourceId,e.visual?.items||[]);r?e.visual={items:n}:delete e.visual}else e.visual?.items&&(e.visual.items=e.visual.items.map(r=>r.animations?{...r,animations:{}}:r))},sa=(e,t)=>{if(!t.character){e.character?.items&&(e.character.items=e.character.items.map(o=>o.animations?{...o,animations:{}}:o));return}let{hasValidItems:r,processedItems:n}=oo(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId,e.character?.items||[]);r?e.character={items:n}:delete e.character},aa=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},ca=(e,t)=>{if(t.layout){let{animationsOnly:r,state:n}=st(t.layout,o=>!!o.resourceId);if(r){e.layout=n;return}if(!t.layout.resourceId){delete e.layout;return}e.layout=t.layout}else e.layout&&delete e.layout},la=(e,t)=>{if(t.choice){let{animationsOnly:r,state:n}=st(t.choice,o=>!!o.resourceId);if(r){e.choice={...e.choice,...n};return}if(!t.choice.resourceId){delete e.choice;return}e.choice=t.choice}else e.choice&&delete e.choice},ua=(e,t)=>{if(t.form){let{animationsOnly:r,state:n}=st(t.form,o=>!!o.resourceId);if(r){e.form={...e.form,...n};return}if(!t.form.resourceId){delete e.form;return}e.form=te(t.form)}else e.form&&delete e.form},fa=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},da=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},pa=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(r=>{delete e[r]})},Pe=e=>Rt(Zs,[pa,ea,ta,na,oa,ia,ra,sa,aa,ca,la,ua,fa,da])(e);var ha=Object.freeze({dialogueTextSpeed:{source:"global.dialogueTextSpeed"},autoForwardDelay:{source:"global.autoForwardDelay"},skipUnseenText:{source:"global.skipUnseenText"},skipTransitionsAndAnimations:{source:"global.skipTransitionsAndAnimations"},soundVolume:{source:"global.soundVolume"},musicVolume:{source:"global.musicVolume"},muteAll:{source:"global.muteAll"},saveLoadPagination:{source:"context.runtime.saveLoadPagination"},menuPage:{source:"context.runtime.menuPage"},menuEntryPoint:{source:"context.runtime.menuEntryPoint"},autoMode:{source:"global.autoMode"},skipMode:{source:"global.skipMode"},dialogueUIHidden:{source:"global.dialogueUIHidden"},isLineCompleted:{source:"global.isLineCompleted"}}),Ne=Object.freeze({dialogueTextSpeed:50,autoForwardDelay:1e3,skipUnseenText:!1,skipTransitionsAndAnimations:!1,soundVolume:50,musicVolume:50,muteAll:!1,autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isLineCompleted:!1}),at=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),so=Object.freeze({dialogueTextSpeed:"number",autoForwardDelay:"number",skipUnseenText:"boolean",skipTransitionsAndAnimations:"boolean",soundVolume:"number",musicVolume:"number",muteAll:"boolean",saveLoadPagination:"number",menuPage:"string",menuEntryPoint:"string",autoMode:"boolean",skipMode:"boolean",dialogueUIHidden:"boolean",isLineCompleted:"boolean"}),xr=Object.freeze(["dialogueTextSpeed","autoForwardDelay","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),Cr=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),ma=(e,t)=>{if(t.startsWith("global.")){let r=t.slice(7);return e?.global?.[r]}if(t.startsWith("context.runtime.")){let r=t.slice(16),n=Array.isArray(e?.contexts)?e.contexts:[];return n[n.length-1]?.runtime?.[r]}},Ye=e=>Object.fromEntries(Object.entries(ha).map(([t,r])=>{let n=ma(e,r.source),o=n!==void 0?n:Ne[t]??at[t];return[t,o]})),Ie=(e,t)=>Ye(e)[t],ao=(e={})=>Object.fromEntries(xr.map(t=>[t,e[t]??Ne[t]]));var ct=Object.freeze({VISUAL_BEHIND_BACKGROUND:10,BACKGROUND:20,VISUAL_BEHIND_CHARACTER:30,CHARACTER:40,VISUAL_BEHIND_DIALOGUE:50,DIALOGUE:60,CHOICE:70,VISUAL_FOREGROUND:80}),Se=Object.freeze({BEHIND_BACKGROUND:ct.VISUAL_BEHIND_BACKGROUND,BEHIND_CHARACTER:ct.VISUAL_BEHIND_CHARACTER,BEHIND_DIALOGUE:ct.VISUAL_BEHIND_DIALOGUE,FOREGROUND:ct.VISUAL_FOREGROUND}),Sr=Se.BEHIND_DIALOGUE,_r=Object.freeze(Object.values(Se).sort((e,t)=>e-t));var _e={objectValues:e=>Object.entries(e).map(([t,r])=>({id:t,...r})),formatDate:Zn},ga=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,ya=(e,t)=>{let r=String(t||"").trim();if(!r)return;let n=r.match(/[A-Za-z_][A-Za-z0-9_]*|\[\d+\]/g)||[],o=e;for(let i of n){if(i.startsWith("[")){let s=Number(i.slice(1,-1));o=Array.isArray(o)?o[s]:void 0;continue}o=o?.[i]}return o},Dt=(e,t,r)=>{if(Array.isArray(e)){let o=[];for(let i of e){if(i&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===1){let[s]=Object.keys(i),l=ga.exec(s);if(l){let[,c,a,u]=l,f=ya(t,u);if(!Array.isArray(f))continue;let d=Array.isArray(i[s])?i[s]:[];f.forEach((p,h)=>{let g={...t,[c]:p};a&&(g[a]=h),d.forEach(y=>{let b=Dt(y,g,r),A=re(b,g,r);Array.isArray(A)?o.push(...A):o.push(A)})});continue}}o.push(Dt(i,t,r))}return o}if(!e||typeof e!="object")return e;let n={};return Object.entries(e).forEach(([o,i])=>{n[o]=Dt(i,t,r)}),n},Wr=({animationType:e,animationId:t,animationPath:r})=>{if(e!==void 0&&!(e==="update"||e==="transition"))throw new Error(`[${r}] Animation "${t}" has unsupported type "${e}". Use "update" or "transition".`)},ba=({id:e,targetId:t,animation:r,playback:n,animationPath:o="animation"})=>{let i=structuredClone(r);return Wr({animationType:i.type,animationId:e,animationPath:o}),delete i.name,delete i.playback,i.id=e,i.targetId=t,n&&(i.playback=structuredClone(n)),i},Ia=(e,{animationId:t="animation",animationPath:r="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return Wr({animationType:e.type,animationId:t,animationPath:r}),e.type},Aa=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},wa=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},qr=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),wo=e=>e?.playback?.continuity==="persistent",Tr=e=>Array.isArray(e)?e.map(Tr):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((t,r)=>(t[r]=Tr(e[r]),t),{}),Nt=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let t=structuredClone(e);return delete t.playback,JSON.stringify(Tr(t))},Eo=(e=[])=>e.filter(t=>wo(t)).map(t=>structuredClone(t)),vo=e=>Array.isArray(e?.keyframes)?e.keyframes.reduce((t,r)=>{let n=typeof r?.duration=="number"&&Number.isFinite(r.duration)?r.duration:0;return t+n},0):0,Rr=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((t,r)=>Math.max(t,vo(r)),0),xo=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max(Rr(e.tween),Rr(e.prev?.tween),Rr(e.next?.tween),vo(e.mask?.progress)),co=({animationInstances:e,activePersistentAnimations:t})=>{if(!Array.isArray(e)||e.length===0||!Array.isArray(t)||t.length===0)return!1;let r=new Set(t.map(Nt).filter(Boolean));return e.some(n=>{if(!wo(n))return!1;let o=Nt(n);return o?r.has(o):!1})},fe=({animationInstances:e,isLineCompleted:t,skipTransitionsAndAnimations:r,activePersistentAnimations:n,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||r?!1:i&&!t||co({animationInstances:e,activePersistentAnimations:n})?!0:i?!1:co({animationInstances:e,activePersistentAnimations:o}),Ea=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),va=(e,t)=>{if(Ea(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},xa=({resources:e,animationId:t,playback:r,instanceId:n,targetId:o,animationPath:i="animation"})=>{if(!t||!o)return!1;let s=e?.animations?.[t];return s?ba({id:n,targetId:o,animation:s,playback:r,animationPath:i}):null},Ca=(e,{defaultTargetId:t,defaultId:r,animationPath:n="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return Wr({animationType:o.type,animationId:o.id??r,animationPath:n}),o.id??=r,o.targetId??=t,o},Hr=({animations:e,transitions:t,defaultTargetId:r,idPrefix:n,animationPathPrefix:o=n})=>{t.forEach((i,s)=>{e.push(Ca(i,{defaultTargetId:r,defaultId:`${n}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},Dr=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let r=re(e,t);return r&&typeof r=="object"?e:r},Pr=(e,t)=>{if(e===void 0)return[];if(!Array.isArray(e)||e.some(r=>r===null||typeof r!="object"||Array.isArray(r)))throw new Error(`${t} must be an array of objects`);return e},Sa=({content:e,path:t,variables:r})=>Pr(e,t).reduce((n,o)=>{let i=Dr(o.text,{variables:r});return n+`${i??""}`.length},0),lo=(e=[])=>{let t=new Map;for(let r of e)r?.id&&t.set(r.id,(t.get(r.id)??0)+1);return new Set(Array.from(t.entries()).filter(([,r])=>r>1).map(([r])=>r))},Tt=(e,t=0,r=new Set)=>{if(!r.has(e?.id))return`character-container-${e.id}`;let n=e?.sprites?.map(({resourceId:o})=>o)||[];return n.length===0?`character-container-${e.id}`:`character-container-${e.id}-${t}-${n.join("-")}`},Or=(e,t)=>{if(!t.transformId)throw new Error(`Visual item "${t.id}" requires transformId`);let r=e.transforms?.[t.transformId];if(!r)throw new Error(`Transform "${t.transformId}" not found for visual item "${t.id}"`);return r},_a=(e,t={})=>{if(!t?.transformId)return;let r=e.transforms?.[t.transformId];if(!r)throw new Error(`Transform "${t.transformId}" not found for background`);return r},Ra=(e={},t)=>{if(t){if(e.images?.[t])return"sprite";if(e.videos?.[t])return"video";if(e.layouts?.[t])return"container"}},Nr=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},Oa=(e={})=>e.textStyles||{},La=(e={})=>e.images||{},$a=(e={})=>e.colors||{},ka=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,lt=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,Ge=(e,t,r)=>{if(typeof e!="string"||e.length===0)throw new Error(`${r} at "${t}" must resolve to a non-empty string`)},uo=(e,t,r)=>{if(e===void 0)return 1;if(typeof e!="number"||!Number.isFinite(e))throw new Error(`${t} for text style "${r}" must be a number between 0 and 1`);if(e<0||e>1)throw new Error(`${t} for text style "${r}" must be a number between 0 and 1`);return e},Yr=(e,t)=>{if(typeof e!="string"||!ka.test(e))throw new Error(`${t} must resolve to a hex color`);return e.length===4?`#${e.slice(1).split("").map(r=>r.repeat(2)).join("")}`:e},fo=(e,t,r)=>{let n=Yr(e,r);if(t===1)return n;let o=Number.parseInt(n.slice(1,3),16),i=Number.parseInt(n.slice(3,5),16),s=Number.parseInt(n.slice(5,7),16);return`rgba(${o}, ${i}, ${s}, ${t})`},Ta=(e={},t)=>{let r=Oa(e)?.[t];if(!r)throw new Error(`Text style "${t}" not found`);let n=e.fonts?.[r.fontId];if(!n)throw new Error(`Font "${r.fontId}" not found for text style "${t}"`);let o=e.colors?.[r.colorId];if(!o)throw new Error(`Color "${r.colorId}" not found for text style "${t}"`);let i=uo(r.colorAlpha,"colorAlpha",t),s={fontFamily:n.fileId,fontSize:r.fontSize??16,fontWeight:r.fontWeight??"400",fontStyle:r.fontStyle??"normal",lineHeight:r.lineHeight??1.2,fill:fo(o.hex,i,`Color "${r.colorId}" for text style "${t}"`)};if(r.align!==void 0&&(s.align=r.align),r.wordWrap!==void 0&&(s.wordWrap=r.wordWrap),r.breakWords!==void 0&&(s.breakWords=r.breakWords),r.wordWrapWidth!==void 0&&(s.wordWrapWidth=r.wordWrapWidth),r.strokeColorId){let l=e.colors?.[r.strokeColorId];if(!l)throw new Error(`Stroke color "${r.strokeColorId}" not found for text style "${t}"`);let c=uo(r.strokeAlpha,"strokeAlpha",t);s.strokeColor=fo(l.hex,c,`Stroke color "${r.strokeColorId}" for text style "${t}"`)}else if(r.strokeAlpha!==void 0)throw new Error(`strokeAlpha for text style "${t}" requires strokeColorId`);return r.strokeWidth!==void 0&&(s.strokeWidth=r.strokeWidth),s},Vr=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>Vr(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;if(Object.prototype.hasOwnProperty.call(e,"textStyle"))throw new Error(`Inline textStyle is not allowed in layout elements at "${r}". Use textStyleId instead`);let n={};for(let[o,i]of Object.entries(e))o!=="textStyleId"&&(n[o]=Vr(i,t,lt(r,o)));return e.textStyleId!==void 0&&(Ge(e.textStyleId,r,"textStyleId"),n.textStyle=Ta(t,e.textStyleId)),n},Kr=(e={},t)=>{let r=$a(e)?.[t];if(!r)throw new Error(`Color "${t}" not found`);return Yr(r.hex,`Color "${t}"`)},Co=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",Lr=(e,t,r)=>{let n=e?.[t];if(!(!n||typeof n!="object"||Array.isArray(n))&&Object.prototype.hasOwnProperty.call(n,"fill"))throw new Error(`Inline ${t}.fill is not allowed in rect layout elements at "${r}". Use ${Co(`${t}.fill`)} instead`)},Da=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>ut(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;let n={};for(let[o,i]of Object.entries(e))o!=="colorId"&&(n[o]=ut(i,t,lt(r,o)));return e.colorId!==void 0&&(Ge(e.colorId,r,"colorId"),n.fill=Kr(t,e.colorId)),n},ut=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>ut(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="rect"){if(Object.prototype.hasOwnProperty.call(e,"fill"))throw new Error(`Inline fill is not allowed in rect layout elements at "${r}". Use ${Co("fill")} instead`);Lr(e,"hover",r),Lr(e,"click",r),Lr(e,"rightClick",r)}let n={};for(let[o,i]of Object.entries(e))if(!(e.type==="rect"&&o==="colorId")){if(e.type==="rect"&&(o==="hover"||o==="click"||o==="rightClick")){n[o]=Da(i,t,lt(r,o));continue}n[o]=ut(i,t,lt(r,o))}return e.type==="rect"&&e.colorId!==void 0&&(Ge(e.colorId,r,"colorId"),n.fill=Kr(t,e.colorId)),n},$r=(e={},t)=>{let r=La(e)?.[t];return r||null},So=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",po=(e,t,r,n)=>{let o=e?.[t];if(!(!o||typeof o!="object"||Array.isArray(o))&&Object.prototype.hasOwnProperty.call(o,n))throw new Error(`Inline ${t}.${n} is not allowed in sprite layout elements at "${r}". Use ${So(`${t}.${n}`)} instead`)},ho=(e,t,r)=>{let n=e[t];e[t]={...n&&typeof n=="object"&&!Array.isArray(n)?n:{},src:r}},jr=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>jr(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="sprite"){for(let o of["url","src","hoverUrl","hoverSrc","clickUrl","clickSrc"])if(Object.prototype.hasOwnProperty.call(e,o))throw new Error(`Inline ${o} is not allowed in sprite layout elements at "${r}". Use ${So(o)} instead`);po(e,"hover",r,"src"),po(e,"click",r,"src")}let n={};for(let[o,i]of Object.entries(e))e.type==="sprite"&&(o==="imageId"||o==="hoverImageId"||o==="clickImageId")||(n[o]=jr(i,t,lt(r,o)));if(e.type==="sprite"&&e.imageId!==void 0){Ge(e.imageId,r,"imageId");let o=$r(t,e.imageId),i=o?.fileId??e.imageId;n.src=i,n.width===void 0&&o?.width!==void 0&&(n.width=o.width),n.height===void 0&&o?.height!==void 0&&(n.height=o.height)}return e.type==="sprite"&&e.hoverImageId!==void 0&&(Ge(e.hoverImageId,r,"hoverImageId"),ho(n,"hover",$r(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(Ge(e.clickImageId,r,"clickImageId"),ho(n,"click",$r(t,e.clickImageId)?.fileId??e.clickImageId)),n},Gr=(e,t={},r="root")=>jr(ut(Vr(e,t,r),t,r),t,r),Re=Gr,je=(e=[])=>e.find(t=>t.id==="story"),Pa="#000000",Mr="bg-cg-background-color",Na=({resources:e={},background:t={},screen:r})=>t?.colorId===void 0?Yr(r?.backgroundColor??Pa,"screen.backgroundColor"):Kr(e,t.colorId),_o=(e={})=>{if(qr(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},Va=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},mo=(e={},{includeDefaultAlpha:t=!1}={})=>{let r=_o(e),n=Va(e),o={};return(t||r!==void 0)&&(o.alpha=r??1),n&&(o.blur=n),o},ja=(e={})=>{if(qr(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},Ma=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},Ro=(e={})=>{let t=ja(e),r=Ma(e),n={};return t!==void 0&&(n.alpha=t),r&&(n.blur=r),n},Pt=(e={})=>Ro(e),Ve=(e={},t={})=>{let r={x:t.x??e.x,y:t.y??e.y,anchorX:t.anchorX??e.anchorX,anchorY:t.anchorY??e.anchorY,rotation:t.rotation??e.rotation,scaleX:t.scaleX??e.scaleX,scaleY:t.scaleY??e.scaleY},n=t.originX??e.originX,o=t.originY??e.originY;return n!==void 0&&(r.originX=n),o!==void 0&&(r.originY=o),r},Fa=({resources:e,background:t,screen:r={width:1920,height:1080},includeOpacity:n=!1})=>{let o={id:Mr,type:"rect",x:0,y:0,width:r?.width??1920,height:r?.height??1080,fill:Na({resources:e,background:t,screen:r})};if(n){let i=_o(t);i!==void 0&&(o.alpha=i)}return o},Ua=(e={},t)=>t?!!(e.images?.[t]||e.videos?.[t]||e.layouts?.[t]):!1,go=({resources:e={},resourceId:t,colorId:r})=>{let n=Ra(e,t);return t&&(n||r===void 0)?{resourceId:t,targetId:Nr({resourceId:t,kind:n})}:r!==void 0?{resourceId:Mr,targetId:Mr}:{resourceId:void 0,targetId:void 0}},Oo=100,jt=Oo,Lo=(e,t)=>e*t/Oo,Ba=(e={},t=jt)=>e?.muteAll?0:Lo(t,e?.soundVolume??Ne.soundVolume),za=(e={},t=jt)=>e?.muteAll?0:Lo(t,e?.musicVolume??Ne.musicVolume),Wa=({item:e,index:t}={})=>`sfx:${t}:${e?.resourceId}`,de=({variables:e,runtime:t,saveSlots:r=[],dialogueState:n,includeInactiveAdvDialogue:o=!1,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,confirmDialog:f,form:d,historyDialogue:p=[],characters:h={},dialogueUIHidden:g,skipOnlyViewedLines:y,skipTransitionsAndAnimations:b}={})=>{let A={dialogueTextSpeed:t?.dialogueTextSpeed??50,autoForwardDelay:t?.autoForwardDelay??1e3,skipUnseenText:t?.skipUnseenText??!1,skipTransitionsAndAnimations:t?.skipTransitionsAndAnimations??!1,soundVolume:t?.soundVolume??50,musicVolume:t?.musicVolume??50,muteAll:t?.muteAll??!1,saveLoadPagination:t?.saveLoadPagination??1,menuPage:t?.menuPage??"",menuEntryPoint:t?.menuEntryPoint??"",autoMode:t?.autoMode??s??!1,skipMode:t?.skipMode??l??!1,dialogueUIHidden:t?.dialogueUIHidden??g??!1,isLineCompleted:t?.isLineCompleted??i??!1},v=Ga({dialogueState:n,includeInactiveAdvDialogue:o,characters:h,variables:e}),S={variables:e,runtime:A,saveSlots:r,isChoiceVisible:c,isFormVisible:a,canRollback:u,confirmDialog:f,form:d,historyDialogue:p,characters:h};return v&&(S.dialogue=v,S.dialogueLines=v.lines),S},yo=100,Vt=(e,t)=>{if(Array.isArray(e))return e.map(n=>Vt(n,t));if(!e||typeof e!="object")return e;let r={...e};return Object.keys(r).forEach(n=>{r[n]=Vt(r[n],t)}),r.type==="text-revealing"?t(r):r},qa=e=>Vt(e,t=>({...t,revealEffect:"none"})),Ha=e=>Vt(e,t=>{let r=Number(t.speed??t.displaySpeed),n=Number.isFinite(r)?Math.max(r,yo):yo;return{...t,speed:n,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:n}:{}}}),Oe=(e,{isLineCompleted:t=!1,skipMode:r=!1,skipTransitionsAndAnimations:n=!1}={})=>t||n?qa(e):r?Ha(e):e,$o=({id:e,screen:t={width:1920,height:1080}})=>({id:e,type:"rect",fill:"transparent",width:t.width,height:t.height,x:0,y:0,click:{payload:{actions:{}}}}),Fr=e=>{if(Array.isArray(e))return e.map(Fr);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=Fr(s);let r=t.click?.payload;if(!r||typeof r!="object"||Array.isArray(r))return t;let n=r.actions,o=n&&typeof n=="object"&&!Array.isArray(n)&&Object.prototype.hasOwnProperty.call(n,"nextLine")?{...n.nextLine,bypassChoice:!0}:void 0;return{...t,click:{...t.click,payload:{...r,bypassChoice:!0,...o?{actions:{...n,nextLine:o}}:{}}}}},Ya=new Set(["click","change","submit","focusEvent","blurEvent","selectionChange","compositionStart","compositionUpdate","compositionEnd"]),bo=(e,t)=>{let r=e?.payload&&typeof e.payload=="object"&&!Array.isArray(e.payload)?e.payload:{},n=r.actions&&typeof r.actions=="object"?r.actions:{};return{...e||{},payload:{...r,actions:{...n,...t}}}},Ur=(e,t)=>{if(Array.isArray(e))return e.map(i=>Ur(i,t));if(!e||typeof e!="object")return e;let r={};for(let[i,s]of Object.entries(e))r[i]=Ur(s,t);if(r.type!=="input"||typeof r.field!="string")return r;let n=t?.fields?.[r.field];if(!n)return r;let o={updateFormField:{formId:t.id,formKey:t.key,field:n.id,value:"_event.value",_interactionSource:"form"}};return{...r,value:n.value,placeholder:r.placeholder===void 0?n.placeholder:r.placeholder,multiline:r.multiline===void 0?n.multiline:r.multiline,...r.maxLength===void 0&&n.maxLength!==void 0?{maxLength:n.maxLength}:{},change:bo(r.change,o),submit:bo(r.submit,t.submitActions)}},Br=(e,t)=>{if(Array.isArray(e))return e.map(n=>Br(n,t));if(!e||typeof e!="object")return e;let r={};for(let[n,o]of Object.entries(e))r[n]=Br(o,t);for(let n of Ya){let o=r[n]?.payload;!o||typeof o!="object"||Array.isArray(o)||(r[n]={...r[n],payload:{...o,_interactionSource:"form",_formId:t.id,_formKey:t.key}})}return r},zr=({characterId:e,character:t,characterName:r,characters:n={}}={})=>{let o=e?n?.[e]:void 0,i=t?.name!==void 0?t.name:r!==void 0?r:o?.name||"";return{...o||{},...t||{},name:i}},ko=(e=[],t={})=>e.map(r=>{let n=zr({characterId:r.characterId,character:r.character,characterName:r.characterName,characters:t}),o=typeof r.text=="string"?r.text:Array.isArray(r.content)?r.content.map(i=>i?.text??"").join(""):"";return{...r,text:o,character:n,characterName:n.name}}),Ka=e=>!(!e||e.mode==="adv"&&e.content===void 0),Ga=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:r={},variables:n}={})=>{if(!t&&!Ka(e))return;let o=e.content===void 0?[{text:""}]:Pr(e.content,"dialogue.content"),i=e.content===void 0?0:Sa({content:e.initialRevealedContent,path:"dialogue.initialRevealedContent",variables:n}),s=(e.lines||[]).map((c,a)=>{let u=Pr(c.content,`dialogue.lines[${a}].content`),f=zr({characterId:c.characterId,character:c.character,characterName:c.characterName,characters:r});return{...c,content:u.map(d=>({...d,text:Dr(d.text,{variables:n})})),character:f,characterName:f.name}}),l=zr({characterId:e.characterId,character:e.character,characters:r});return{characterId:e.characterId,persistCharacter:e.persistCharacter,character:l,content:o.map(c=>({...c,text:Dr(c.text,{variables:n})})),initialRevealedCharacters:i,lines:s}},To=({container:e,resources:t,templateData:r,isLineCompleted:n=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=re(e,r,{functions:_e});return Re(Oe(s,{isLineCompleted:n,skipMode:o,skipTransitionsAndAnimations:i}),t)},kr=(e,t={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(t),Io=({renderStateKeyboard:e,keyboard:t,phase:r})=>{!t||typeof t!="object"||Array.isArray(t)||Object.entries(t).forEach(([n,o])=>{let i=e[n]??{},s=r==="keydown"?o?.keydown:o?.keyup;if(r==="keydown"&&s&&typeof s=="object"){e[n]={...i,keydown:{payload:kr(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[n].keyup={payload:kr(o.keyup)});return}e[n]={...i,[r]:{payload:kr(o)}}})},Ja=(e={},t={})=>{let r={};return Io({renderStateKeyboard:r,keyboard:e,phase:"keydown"}),Io({renderStateKeyboard:r,keyboard:t,phase:"keyup"}),Object.keys(r).length>0?r:void 0},Ae=({animationsDef:e,resources:t,previousResourceId:r,currentResourceId:n,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:l})=>{if(!e)return[];let c=[],a=({instanceId:b,targetId:A})=>{let v=xa({resources:t,animationId:p,playback:h,instanceId:b,targetId:A,animationPath:s});v&&c.push(v)},u=r!=null&&r!==!1,f=n!=null&&n!==!1,d=o&&i&&o===i;va(e,s);let p=Aa(e),h=wa(e),g=t?.animations?.[p],y=Ia(g,{animationId:p,animationPath:s});if(y==="update")return f&&i?a({instanceId:`${l}-animation-update`,targetId:i}):u&&o&&a({instanceId:`${l}-animation-update`,targetId:o}),c;if(y==="transition"){let b=`${l}-animation-transition`,A=h?.continuity==="persistent"?b:`${l}-animation-in`;if(u&&f&&d)return a({instanceId:b,targetId:i}),c;u&&a({instanceId:`${l}-animation-out`,targetId:o}),f&&a({instanceId:A,targetId:i})}return c},Xa=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),Qa=(e,{presentationState:t,previousPresentationState:r,currentLineActions:n,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:l,variables:c,runtime:a,activePersistentAnimations:u,restoredPersistentAnimations:f,autoMode:d,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:b,saveSlots:A=[]})=>{let{elements:v,animations:S}=e;if(t.background){let D=n===void 0?!0:qr(n?.background??{},"animations"),w=v.find(M=>M.id==="story");if(!w)return e;let P=_a(o,t.background),B=r?.background?.resourceId,j=r?.background?.colorId,V=t.background.resourceId??(t.background.animations?B:void 0),F=t.background.colorId??(t.background.animations?j:void 0),Y=Ua(o,V),W={...t.background,colorId:F};if((F!==void 0||Y)&&w.children.push(Fa({resources:o,background:W,screen:i,includeOpacity:!Y})),V){let{images:M={},videos:q={}}=o,N=M[V]||q[V];if(N){let he=q[V]!==void 0,we={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...P},ze={id:Nr({resourceId:V,kind:he?"video":"sprite"}),type:he?"video":"sprite",src:N.fileId,width:N.width,height:N.height,...mo(t.background,{includeDefaultAlpha:!0}),...Ve(we)};he&&(ze.loop=t.background.loop??!1,ze.volume=N.volume??50),w.children.push(ze)}}if(V){let{layouts:M={}}=o,q=M[V];if(q){let N={id:Nr({resourceId:V,kind:"container"}),type:"container",children:q.elements,...mo(t.background)};P&&Object.assign(N,Ve({x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...P}));let he=re(N,de({variables:c,runtime:a,saveSlots:A,dialogueState:t.dialogue,isLineCompleted:s,autoMode:d,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:b,characters:o.characters||{},skipTransitionsAndAnimations:l}),{functions:_e});w.children.push(Re(Oe(he,{isLineCompleted:s,skipMode:p,skipTransitionsAndAnimations:l}),o))}}let x=go({resources:o,resourceId:B,colorId:j}),_=go({resources:o,resourceId:V,colorId:F}),$=Ae({animationsDef:t.background.animations,resources:o,previousResourceId:x.resourceId,currentResourceId:_.resourceId,previousTargetId:x.targetId,currentTargetId:_.targetId,animationPath:"background.animations",idPrefix:"bg-cg"});fe({animationInstances:$,isLineCompleted:s,skipTransitionsAndAnimations:l,activePersistentAnimations:u,restoredPersistentAnimations:f,isAuthoredOnCurrentLine:D})&&S.push(...$)}return e},Za=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:l,animations:c}=e;if(t.character&&n){let a=l.find(h=>h.id==="story");if(!a)return e;let u=t.character.items||[],f=r?.character?.items||[],d=lo(u),p=lo(f);for(let h=0;h<u.length;h++){let g=u[h],{transformId:y,sprites:b}=g,A=f.find(F=>F.id===g.id),v=f.findIndex(F=>F.id===g.id),S=A?.sprites&&A.sprites.length>0,D=b&&b.length>0,w=v>=0?Tt(A,v,p):void 0,P=Ae({animationsDef:g.animations,resources:n,previousResourceId:w,currentResourceId:D?Tt(g,h,d):void 0,previousTargetId:w,currentTargetId:D?Tt(g,h,d):void 0,animationPath:`character.items[${h}].animations`,idPrefix:"character"});if(g.animations&&!b&&!y&&S&&fe({animationInstances:P,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){c.push(...P);continue}if(g.animations&&!b&&!y)continue;if(!b||b.length===0||!y){console.warn("Character item missing sprites or transformId:",g);continue}let B=Tt(g,h,d),j=n.transforms[y];if(!j){console.warn("Transform not found:",y);continue}let V={type:"container",id:B,...Ve(j,g),...Pt(g),children:[]};for(let F of b){let Y=n.images[F.resourceId];if(!Y){console.warn(`Image resource not found: ${F.resourceId}`);continue}V.children.push({type:"sprite",id:`${B}-${F.id}`,src:Y.fileId,width:Y.width,height:Y.height,x:0,y:0})}a.children.push(V),fe({animationInstances:P,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...P)}}return e},Do=(e,t)=>{if(!_r.includes(e))throw new Error(`${t} must be one of: ${_r.join(", ")}.`)},ec=(e,t)=>{let r=e.layer??(e.resourceId?void 0:t?.layer)??Sr;return Do(r,`Visual item "${e.id}" layer`),r},tc=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,runtime:l,activePersistentAnimations:c,autoMode:a,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,form:h,saveSlots:g=[],visualLayer:y})=>{let{elements:b,animations:A}=e;if(t.visual&&n){let v=b.find(w=>w.id==="story");if(!v)return e;let S=t.visual.items,D=r?.visual?.items||[];y!==void 0&&Do(y,"visualLayer");for(let w of S){let P=D.find(V=>V.id===w.id),B=ec(w,P);if(y!==void 0&&B!==y)continue;if(w.resourceId){let{images:V={},videos:F={},spritesheets:Y={}}=n,W=Y[w.resourceId];if(W){let x=Or(n,w),_=w.animationName;if(_){let $=W.animations?.[_];if(!$)throw new Error(`Animation '${_}' not found in spritesheet resource '${w.resourceId}'`);let M=Pt(w),q={id:`visual-${w.id}`,type:"animated-sprite",...Ve(x,w),width:w.width??W.width,height:w.height??W.height,alpha:M.alpha??w.alpha??1,spritesheetSrc:W.fileId,spritesheetData:W.jsonData,animation:{frames:$.frames,animationSpeed:w.animationSpeed??$.animationSpeed??.5,loop:w.loop??$.loop??!0}};M.blur&&(q.blur=M.blur),v.children.push(structuredClone(q))}}else{let x=V[w.resourceId]||F[w.resourceId];if(x){let _=F[w.resourceId]!==void 0,$=Or(n,w),M={id:`visual-${w.id}`,type:_?"video":"sprite",src:x.fileId,width:x.width,height:x.height,...Ve($,w)};Object.assign(M,Pt(w)),_&&(M.loop=x.loop??!1,M.volume=x.volume??50),v.children.push(M)}}}if(w.resourceId){let{layouts:V={}}=n,F=V[w.resourceId];if(F){let Y=Or(n,w),W={id:`visual-${w.id}`,type:"container",children:structuredClone(F.elements),...Ve(Y,w)};Object.assign(W,Pt(w));let x=re(W,de({variables:s,runtime:l,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:o,autoMode:a,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:i}),{functions:_e});v.children.push(Re(Oe(x,{isLineCompleted:o,skipMode:u,skipTransitionsAndAnimations:i}),n))}}let j=Ae({animationsDef:w.animations,resources:n,previousResourceId:P?.resourceId,currentResourceId:w.resourceId,previousTargetId:P?.resourceId?`visual-${w.id}`:void 0,currentTargetId:w.resourceId?`visual-${w.id}`:void 0,animationPath:`visual.items[${w.id}].animations`,idPrefix:w.id});fe({animationInstances:j,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:c})&&A.push(...j)}}return e},Ke="dialogue-character-sprite",Ao=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,rc=(e,{presentationState:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:l}=e,c=je(e.elements);if(!c)return e;let a=t.dialogue?.character?.sprite,u=r?.dialogue?.character?.sprite,f=Ao(a),d=Ao(u),p=Ae({animationsDef:a?.animations,resources:n,previousResourceId:d?Ke:void 0,currentResourceId:f?Ke:void 0,previousTargetId:d?Ke:void 0,currentTargetId:f?Ke:void 0,animationPath:"dialogue.character.sprite.animations",idPrefix:"dialogue-character-sprite"});if(!f)return a?.animations&&d&&fe({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...p),e;let h=n.transforms?.[a.transformId];if(!h)return console.warn("Transform not found:",a.transformId),e;let g={type:"container",id:Ke,...Ve(h),children:[]};for(let y of a.items){let b=n.images?.[y.resourceId];if(!b){console.warn(`Image resource not found: ${y.resourceId}`);continue}g.children.push({type:"sprite",id:`${Ke}-${y.id}`,src:b.fileId,width:b.width,height:b.height,x:0,y:0})}return c.children.push(g),fe({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...p),e},nc=(e,{presentationState:t,previousPresentationState:r,resources:n={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:c,canRollback:a,form:u,skipOnlyViewedLines:f,isLineCompleted:d,skipTransitionsAndAnimations:p,variables:h,runtime:g,activePersistentAnimations:y,saveSlots:b=[]})=>{let{elements:A,animations:v}=e;if(!t.dialogue||o)return e;let S=A.find(w=>w.id==="story");if(!S)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:w={}}=n,P=w[t.dialogue.ui.resourceId];if(P){let B={elements:P.elements},j=de({variables:h,runtime:g,saveSlots:b,dialogueState:t.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:d,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:c,canRollback:a,form:u,characters:n.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:f,skipTransitionsAndAnimations:p}),V={functions:_e},F=Dt(B,j,V),Y=re(F,j,V),W=Re(Oe(Y?.elements,{isLineCompleted:d,skipMode:s,skipTransitionsAndAnimations:p}),n);if(Array.isArray(W))for(let x of W)S.children.push(x);else W&&S.children.push(W)}}rc(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:d,skipTransitionsAndAnimations:p,activePersistentAnimations:y});let D=Ae({animationsDef:t.dialogue.ui?.animations,resources:n,previousResourceId:r?.dialogue?.ui?.resourceId,currentResourceId:t.dialogue.ui?.resourceId,previousTargetId:r?.dialogue?.ui?.resourceId?"dialogue-container":void 0,currentTargetId:t.dialogue.ui?.resourceId?"dialogue-container":void 0,animationPath:"dialogue.ui.animations",idPrefix:"dialogue-ui"});return fe({animationInstances:D,isLineCompleted:d,skipTransitionsAndAnimations:p,activePersistentAnimations:y})&&v.push(...D),e},oc=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,runtime:c,autoMode:a,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,form:h,activePersistentAnimations:g,saveSlots:y=[]})=>{let{elements:b,animations:A}=e;if(t.choice&&n){let v=je(b);if(!v)return e;let S=n?.layouts[t.choice.resourceId];if(S&&S.elements){let w={elements:S.elements},P=re(w,{...de({variables:l,runtime:c,saveSlots:y,dialogueState:t.dialogue,isLineCompleted:i,autoMode:a,skipMode:u,isChoiceVisible:f??!!t.choice,isFormVisible:d,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}},{functions:_e}),B=Fr(Re(Oe(P?.elements,{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),n));if(Array.isArray(B))for(let j of B)v.children.push(j);else B&&v.children.push(B)}let D=Ae({animationsDef:t.choice.animations,resources:n,previousResourceId:r?.choice?.resourceId,currentResourceId:t.choice.resourceId,previousTargetId:r?.choice?.resourceId?"choice-container":void 0,currentTargetId:t.choice.resourceId?"choice-container":void 0,animationPath:"choice.animations",idPrefix:"choice"});fe({animationInstances:D,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:g})&&A.push(...D)}return e},ic=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,runtime:c,autoMode:a,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,activePersistentAnimations:h,saveSlots:g=[],form:y})=>{let{elements:b,animations:A}=e;if(!y?.resourceId||!n)return e;let v=je(b);if(!v)return e;let S=n?.layouts?.[y.resourceId];if(!S)return console.warn(`Form layout not found: ${y.resourceId}`),e;let D={id:"form-container",type:"container",x:0,y:0,children:S.elements||[]},w={...de({variables:l,runtime:c,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:i,autoMode:a,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,characters:n.characters||{},skipTransitionsAndAnimations:s,form:y}),form:y},P=re(D,w,{functions:_e}),B=Br(Re(Oe(Ur(P,y),{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),n),y);B&&v.children.push(B);let j=Ae({animationsDef:y.animations,resources:n,previousResourceId:r?.form?.resourceId,currentResourceId:y.resourceId,previousTargetId:r?.form?.resourceId?"form-container":void 0,currentTargetId:y.resourceId?"form-container":void 0,animationPath:"form.animations",idPrefix:"form"});return fe({animationInstances:j,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:h})&&A.push(...j),e},sc=(e,{presentationState:t,resources:r={},variables:n,runtime:o,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,form:f,saveSlots:d=[],skipTransitionsAndAnimations:p})=>{if(!t.control?.resourceId)return e;let h=r.controls?.[t.control.resourceId];if(!h)return e;let g=Ja(h.keyboard,h.keyup);if(g&&Object.keys(g).length>0&&(e.global.keyboard=g),!Array.isArray(h.elements)||h.elements.length===0)return e;let y=je(e.elements);if(!y)return e;let b={id:`control-${t.control.resourceId}`,type:"container",x:0,y:0,children:h.elements};return y.children.push(To({container:b,resources:r,templateData:de({variables:n,runtime:o,saveSlots:d,dialogueState:t.dialogue,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,form:f,characters:r.characters||{},skipTransitionsAndAnimations:p}),isLineCompleted:i,skipMode:l,skipTransitionsAndAnimations:p})),e},ac=(e,{presentationState:t,resources:r,runtime:n,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&r){if(!je(i))return e;let c=r.sounds[t.bgm.resourceId];if(!c)return e;let a=de({variables:o,runtime:n}).runtime;s.push({id:"bgm",type:"sound",src:c.fileId,loop:t.bgm.loop??!0,volume:za(a,t.bgm.volume??c.volume??jt),startDelayMs:t.bgm.startDelayMs??null})}return e},cc=(e,{presentationState:t,resources:r,runtime:n})=>{let{audio:o}=e;if(t.sfx&&r){let i=t.sfx.items;for(let[s,l]of i.entries()){let c=r.sounds?.[l.resourceId];c&&o.push({id:Wa({item:l,index:s}),type:"sound",src:c.fileId,loop:l.loop??c.loop??!1,volume:Ba(n,l.volume??c.volume??jt),startDelayMs:l.startDelayMs??c.startDelayMs??null})}}return e},lc=(e,t,r)=>{if(!(!t||!r))return e?.voices?.[t]?.[r]},uc=(e={},t={})=>t.muteAll?0:e.volume??t.soundVolume??50,fc=(e,{presentationState:t,resources:r,currentSceneId:n,runtime:o,variables:i})=>{let{audio:s}=e;if(!t?.voice)return e;let l=t.voice,{resourceId:c,loop:a,startDelayMs:u}=l,f=lc(r,n,c);if(!f)return e;let d=de({variables:i,runtime:o}).runtime;return s.push({id:`voice-${n}-${c}`,type:"sound",src:f.fileId,volume:uc(l,d),loop:a??!1,startDelayMs:u??null}),e},dc=(e,{presentationState:t,previousPresentationState:r,resources:n={},variables:o,runtime:i,autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,form:f,saveSlots:d=[],isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})=>{let{elements:y,animations:b}=e;if(t.layout){let D=je(y);if(!D)return e;let w=n.layouts[t.layout.resourceId];if(!w)return e;Array.isArray(w.transitions)&&!p&&!h&&Hr({animations:b,transitions:w.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let P={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:w.elements||[]};D.children.push(To({container:P,resources:n,templateData:de({variables:o,runtime:i,saveSlots:d,dialogueState:t.dialogue,isLineCompleted:p,autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,form:f,characters:n.characters||{},skipTransitionsAndAnimations:h}),isLineCompleted:p,skipMode:l,skipTransitionsAndAnimations:h}))}let A=r?.layout?.resourceId,v=t.layout?.resourceId,S=Ae({animationsDef:t.layout?.animations,resources:n,previousResourceId:A,currentResourceId:v,previousTargetId:A?`layout-${A}`:void 0,currentTargetId:v?`layout-${v}`:void 0,animationPath:"layout.animations",idPrefix:"layout"});return fe({animationInstances:S,isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})&&b.push(...S),e},pc=(e,{currentLineActions:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:l}=e,c=t?.screen?.animations;if(!c)return e;let a=r!=null,u=Ae({animationsDef:c,resources:n,previousResourceId:a?"story":void 0,currentResourceId:"story",previousTargetId:a?"story":void 0,currentTargetId:"story",animationPath:"screen.animations",idPrefix:"screen"});return fe({animationInstances:u,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...u),e},hc=(e,{presentationState:t})=>{let r=je(e.elements);return!r||!t?.screen||Object.assign(r,Ro(t.screen)),e},mc=(e,{presentationState:t,resources:r={},variables:n,runtime:o,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:c,canRollback:a,form:u,overlayStack:f=[],dialogueHistory:d=[],saveSlots:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:b,animations:A}=e;return f&&f.length>0&&f.forEach((v,S)=>{let D=r.layouts[v.resourceId];if(!D){console.warn(`Overlay layout not found: ${v.resourceId}`);return}Array.isArray(D.transitions)&&(y||Hr({animations:A,transitions:D.transitions,defaultTargetId:`overlayStack-${S}`,idPrefix:`overlayStack-${S}`,animationPathPrefix:`overlayStack[${S}]`}));let w={id:`overlayStack-${S}`,type:"container",x:0,y:0,children:[$o({id:`overlayStack-${S}-blocker`,screen:h}),...D.elements||[]]},P=ko(d,r.characters),B=de({variables:n,runtime:o,saveSlots:p,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:c,canRollback:a,form:u,historyDialogue:P,characters:r.characters||{},skipTransitionsAndAnimations:y}),j=re(w,B,{functions:_e}),[V,...F]=j.children||[],Y=Re(Oe({...j,children:F},{isLineCompleted:g,skipMode:s,skipTransitionsAndAnimations:y}),r);b.push({...Y,children:V?[V,...Y.children||[]]:Y.children})}),e},gc=(e,{presentationState:t,resources:r={},variables:n,runtime:o,saveSlots:i=[],autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,form:f,confirmDialog:d,dialogueHistory:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:b,animations:A}=e;if(!d?.resourceId)return e;let v=r.layouts?.[d.resourceId];if(!v)return console.warn(`ConfirmDialog layout not found: ${d.resourceId}`),e;Array.isArray(v.transitions)&&!y&&Hr({animations:A,transitions:v.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let S={id:"confirmDialog",type:"container",x:0,y:0,children:[$o({id:"confirmDialog-blocker",screen:h}),...v.elements||[]]},D=ko(p,r.characters),w=re(S,de({variables:n,runtime:o,saveSlots:i,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,form:f,confirmDialog:d,historyDialogue:D,characters:r.characters||{},skipTransitionsAndAnimations:y}),{functions:_e}),[P,...B]=w.children||[],j=Re(Oe({...w,children:B},{isLineCompleted:g,skipMode:l,skipTransitionsAndAnimations:y}),r);return b.push({...j,children:P?[P,...j.children||[]]:j.children}),e},Mt=e=>(t,r)=>tc(t,{...r,visualLayer:e}),yc=Mt(Se.BEHIND_BACKGROUND),bc=Mt(Se.BEHIND_CHARACTER),Ic=Mt(Se.BEHIND_DIALOGUE),Ac=Mt(Se.FOREGROUND),Po=e=>Rt(Xa,[sc,yc,Qa,bc,Za,Ic,nc,oc,ic,dc,Ac,hc,pc,ac,cc,fc,mc,gc])(e);var Ft={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},Fo=1,Jr="choice",Ut="form",Wt=()=>({manual:{...Ft.manual},auto:{...Ft.auto},applyMode:Ft.applyMode}),Xr=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let r=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...Wt()},r&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},T=e=>{let t=oe(e)?Te(e):e;return structuredClone(t)},k=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),qt=e=>String(e),Uo=()=>({sections:[],resources:[]}),wc=e=>k(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):Uo(),Ec=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",vc=({sectionId:e,lineId:t,content:r,dialogueState:n,characterName:o})=>({sectionId:e,lineId:t,content:r,text:Ec(r),characterId:n.characterId,character:{...n.character||{},name:o},characterName:o}),xc=()=>({resourceId:void 0}),Cc=e=>{if(!k(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},Qr=(e,t)=>{let r=e?.story?.scenes??{};for(let[n,o]of Object.entries(r))if(o?.sections?.[t])return{sceneId:n,section:o.sections[t]};return{sceneId:void 0,section:void 0}},Bo=e=>{let t=e?.story?.scenes??{},r=new Map;for(let[n,o]of Object.entries(t)){let i=o?.sections??{};for(let s of Object.keys(i)){let l=r.get(s);if(l!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${l}" and "${n}". Section IDs must be globally unique.`);r.set(s,n)}}},zo=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},Wo=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==Fo)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},Sc=(e,t={})=>{let r;try{r=Wo(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let n={...t,formatVersion:r,slotId:zo(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete n.slotKey,delete n.date,n},_c=(e={})=>Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Sc(t,r)])),qo=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:r})=>yu(r));return t.length>0?t:void 0},Rc=e=>{!k(e)||!Array.isArray(e.timeline)||e.timeline.forEach(t=>{if(!k(t))return;let r=qo(t.executedActions);if(r){t.executedActions=r;return}delete t.executedActions})},No=(e,t,r,n="viewedRegistry")=>{let o=t==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[o]:String(e)};if(!k(e))throw new Error(`Malformed ${n}.${t}[${r}] entry.`);if(typeof e[o]!="string"||e[o].length===0)throw new Error(`Malformed ${n}.${t}[${r}] entry: missing ${o}.`);if(t==="sections"){let i={sectionId:e.sectionId};if(e.lastLineId!==void 0&&e.lastLineId!==null&&typeof e.lastLineId!="string")throw new Error(`Malformed ${n}.sections[${r}] entry: invalid lastLineId.`);return typeof e.lastLineId=="string"&&e.lastLineId.length>0&&(i.lastLineId=e.lastLineId),i}return{resourceId:e.resourceId}},Oc=(e,t="viewedRegistry")=>{if(e===void 0)return Uo();if(!k(e))throw new Error(`Malformed ${t}.`);if(e.sections!==void 0&&!Array.isArray(e.sections))throw new Error(`Malformed ${t}.sections.`);if(e.resources!==void 0&&!Array.isArray(e.resources))throw new Error(`Malformed ${t}.resources.`);let r=e.sections??[],n=e.resources??[];return{sections:Object.values(Object.fromEntries(r.map((o,i)=>{let s=No(o,"sections",i,t);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(n.map((o,i)=>{let s=No(o,"resources",i,t);return[s.resourceId,s]})))}},Ho=(e,t,r)=>{if(!k(e))throw new Error(`Malformed save slot ${r}.`);let{sectionId:n,lineId:o}=e;if(typeof n!="string"||n.length===0)throw new Error(`Malformed save slot ${r}: missing sectionId.`);if(typeof o!="string"||o.length===0)throw new Error(`Malformed save slot ${r}: missing lineId.`);let{sceneId:i,section:s}=Qr(t,n);if(!s)throw new Error(`Malformed save slot ${r}: section "${n}" does not exist in projectData.`);if(!s.lines?.some(c=>c.id===o))throw new Error(`Malformed save slot ${r}: line "${o}" does not exist in section "${n}".`);return{sceneId:i,sectionId:n,lineId:o}},Lc=(e,t,r)=>{if(!k(e)||!Array.isArray(e.timeline))return ft({pointer:t,replayStartIndex:1});let n=e.timeline.flatMap((l,c)=>{if(!k(l))return[];try{let a=Ho(l,r,`rollback.timeline[${c}]`),u=zt({sectionId:a.sectionId,lineId:a.lineId,rollbackPolicy:l.rollbackPolicy}),f=qo(T(l.executedActions));return f&&(u.executedActions=f),[u]}catch{return[]}});if(n.length===0)return ft({pointer:t,replayStartIndex:1});let o=typeof e.currentIndex=="number"?Math.trunc(e.currentIndex):n.length-1;(o<0||o>=n.length)&&(o=n.length-1);let i=n[o];if(i?.sectionId!==t.sectionId||i?.lineId!==t.lineId){let l=n.findLastIndex(c=>c.sectionId===t.sectionId&&c.lineId===t.lineId);l>=0?o=l:(n.push(zt({sectionId:t.sectionId,lineId:t.lineId})),o=n.length-1)}let s=typeof e.replayStartIndex=="number"?Math.min(Math.max(Math.trunc(e.replayStartIndex),0),o):0;return{currentIndex:o,isRestoring:!1,replayStartIndex:s,timeline:n}},$c=(e,t,r)=>{if(!k(e))throw new Error(`Malformed save slot contexts[${r}] entry.`);let n=tn(t),o=Ho(e.pointers?.read,t,`contexts[${r}].pointers.read`);if(e.variables!==void 0&&!k(e.variables))throw new Error(`Malformed save slot contexts[${r}].variables entry.`);if(e.runtime!==void 0&&!k(e.runtime))throw new Error(`Malformed save slot contexts[${r}].runtime entry.`);let i=e.variables?He(T(e.variables),t.resources?.variables??{}):{},s=Wc({loadedContextRuntime:k(e.runtime)?T(e.runtime):{}}),l={currentPointerMode:"read",pointers:{read:o},configuration:k(e.configuration)?T(e.configuration):{},views:Array.isArray(e.views)?T(e.views):[],bgm:k(e.bgm)?T(e.bgm):{resourceId:void 0},variables:{...n,...i},rollback:Lc(e.rollback,o,t)};return s&&(l.runtime=s),l},kc=(e,t)=>{if(!k(e))throw new Error("Malformed save slot state.");if(!Array.isArray(e.contexts)||e.contexts.length===0)throw new Error("Malformed save slot state: contexts must be a non-empty array.");return{contexts:e.contexts.map((r,n)=>$c(r,t,n))}},Tc=(e,t)=>{if(!k(e))throw new Error("Malformed save slot.");let r=Wo(e.formatVersion);return{...e,formatVersion:r,state:kc(e.state,t)}},Vo=(e,t,{required:r=!1}={})=>{if(e===void 0){if(r)throw new Error(`showConfirmDialog requires ${t}`);return{hideConfirmDialog:{}}}if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`showConfirmDialog ${t} must be an action object`);let n=T(e);return Object.prototype.hasOwnProperty.call(n,"hideConfirmDialog")||(n.hideConfirmDialog={}),n},Dc=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:Vo(e.confirmActions,"confirmActions",{required:!0}),cancelActions:Vo(e.cancelActions,"cancelActions")}},Xe=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},Pc=e=>(k(e.global.formDrafts)||(e.global.formDrafts={}),e.global.formDrafts),Qe=e=>{Object.prototype.hasOwnProperty.call(e.global,"formDrafts")&&(e.global.formDrafts={})},Yo=e=>{if(!(!k(e)||!e.animations))return{animations:T(e.animations)}},Nc=(e,t)=>{let r=Yo(t);if(r){e.global.pendingScreenTransition=r;return}delete e.global.pendingScreenTransition},Vc=e=>{let t=e?.id??e?.resourceId;return typeof t=="string"&&t.length>0?t:void 0},jc=(e,t)=>{let r=e?.sectionId,n=e?.lineId;if(!(!r||!n||!t))return`${r}:${n}:${t}`},Bt=e=>String(e??""),Ko=(e,t)=>{let r=Bt(t);return e?.trim===!0?r.trim():r},Mc=e=>k(e?.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,t])=>k(t)).map(([t,r])=>[t,{id:t,...T(r)}])):{},Fc=(e,t)=>{if(!t||!k(e.global.formDrafts))return;let r=e.global.formDrafts[t];return k(r)?r:void 0},Go=(e,t)=>{let r=Pc(e);k(r[t])||(r[t]={values:{},touched:{},errors:{},submitted:!1});let n=r[t];return k(n.values)||(n.values={}),k(n.touched)||(n.touched={}),k(n.errors)||(n.errors={}),typeof n.submitted!="boolean"&&(n.submitted=!1),n},Zr=(e,t)=>{let r=Ko(e,t);return e?.required===!0&&r.length===0?"required":null},Uc=({state:e,pointer:t})=>{if(!t?.sectionId||!t?.lineId)return{};let n=Z({state:e},{sectionId:t.sectionId})?.lines||[],o=n.findIndex(i=>i.id===t.lineId);return o<0?{}:Pe(n.slice(0,o+1).map(i=>i.actions||{}))},Bc=({state:e,form:t,pointer:r})=>{if(!t?.resourceId)return null;let n=Vc(t),o=jc(r,n);if(!n||!o)return null;let i=Fc(e,o),s=Mc(t),l=an({state:e}),c={},a=[],u={},f=!0;return Object.entries(s).forEach(([d,p])=>{let h=Bt(l?.[p.variableId]),g=Object.prototype.hasOwnProperty.call(i?.values??{},d)?Bt(i.values[d]):h,y=i?.touched?.[d]===!0,b=Zr(p,g),A=i?.submitted||y?b:null,v=typeof p.maxLength=="number"?Math.max(0,Math.round(p.maxLength)):void 0,S={id:d,variableId:p.variableId,value:g,initialValue:h,valid:!b,error:A,touched:y,required:p.required===!0,trim:p.trim===!0,placeholder:p.placeholder===void 0?"":String(p.placeholder),multiline:p.multiline===!0,...v!==void 0?{maxLength:v}:{}};b&&(f=!1),c[d]=S,a.push(S),u[d]=g}),{id:n,key:o,resourceId:t.resourceId,animations:t.animations,valid:f,submitted:i?.submitted===!0,fields:c,fieldList:a,values:u,submitActions:{submitForm:{formId:n,formKey:o,actions:T(t.submitActions??{})}},cancelActions:{cancelForm:{formId:n,formKey:o,actions:T(t.cancelActions??{})}}}},Me=[],jo="line",en="interaction",zt=({sectionId:e,lineId:t,rollbackPolicy:r})=>({sectionId:e,lineId:t,rollbackPolicy:r??"free"}),tn=e=>{let{contextVariableDefaultValues:t}=Ir(e??{});return T(t)},Jo=()=>({...T(at)}),Xo=({loadedRuntime:e,runtimeIds:t,defaults:r={},path:n})=>{if(e===void 0)return{runtimeState:T(r),hasLoadedValues:!1};if(!k(e))throw new Error(`Malformed ${n}.`);let o=T(r),i=!1;return t.forEach(s=>{e[s]!==void 0&&(o[s]=Qo(s,T(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},zc=({loadedGlobalRuntime:e={}})=>Xo({loadedRuntime:e,runtimeIds:xr,defaults:Ne,path:"global.runtime"}).runtimeState,Wc=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:r}=Xo({loadedRuntime:e,runtimeIds:Cr,defaults:Jo(),path:"context.runtime"});return r?t:void 0},rn=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},qc=e=>e.runtime?(Cr.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=T(at[t]))}),e.runtime):(e.runtime=Jo(),e.runtime),Hc=e=>ao(e.global),Yc=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:Hc(e)}})},Kc=e=>so[e],Gc=(e,t)=>{let r=Kc(e);if(r==="number"){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} requires a finite numeric value`);return}if(r==="boolean"){if(typeof t!="boolean")throw new Error(`${e} requires a boolean value`);return}if(r==="string"){if(typeof t!="string")throw new Error(`${e} requires a string value`);return}throw new Error(`Unsupported runtime field "${e}"`)},Qo=(e,t)=>(Gc(e,t),e==="saveLoadPagination"?Math.max(1,Math.trunc(t)):t),Zo=(e,t,r)=>{let n=Qo(t,r);if(t in at){let o=rn(e);if(!o)return n;let i=qc(o);return i[t]=n,n}return e.global[t]=n,n},ei=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:T(e)},configuration:{},views:[],bgm:xc(),variables:tn(t),rollback:ft({pointer:e})}),Ze=e=>e?(e.currentPointerMode="read",k(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,Jc=(e,{queueRender:t=!0}={})=>{let r=e.contexts?.[e.contexts.length-1],n=r?.pointers?.read;if(!r||!n?.sectionId||!n?.lineId)return null;let o=ei({pointer:n,projectData:e.projectData});return e.contexts[e.contexts.length-1]=o,Xc(e,{queueRender:t}),o},Xc=(e,{queueRender:t=!0}={})=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,Xe(e),Qe(e),e.global.nextLineConfig=Wt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"}),t&&e.global.pendingEffects.push({name:"render"})},ti=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},ft=({pointer:e,replayStartIndex:t=0})=>{let r=e?.sectionId&&e?.lineId;return{currentIndex:r?0:-1,isRestoring:!1,replayStartIndex:t,timeline:r?[zt({sectionId:e.sectionId,lineId:e.lineId})]:[]}},Ue=(e,t={})=>{if(e?.rollback)return ti(e.rollback),Array.isArray(e.rollback.timeline)||(e.rollback.timeline=[]),typeof e.rollback.currentIndex!="number"&&(e.rollback.currentIndex=e.rollback.timeline.length>0?e.rollback.timeline.length-1:-1),typeof e.rollback.isRestoring!="boolean"&&(e.rollback.isRestoring=!1),typeof e.rollback.replayStartIndex!="number"&&(e.rollback.replayStartIndex=0),e.rollback;let r=e?.pointers?.read;return e.rollback=ft({pointer:r,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},nn=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return;let n=Ue(r);if(n.isRestoring)return;n.currentIndex<n.timeline.length-1&&(n.timeline=n.timeline.slice(0,n.currentIndex+1));let o=n.timeline[n.timeline.length-1];if(o?.sectionId===t.sectionId&&o?.lineId===t.lineId&&(o?.rollbackPolicy??"free")===(t.rollbackPolicy??"free")){n.currentIndex=n.timeline.length-1;return}n.timeline.push(zt(t)),n.currentIndex=n.timeline.length-1},Qc=e=>{let r=e.contexts?.[e.contexts.length-1]?.rollback;if(!r||r.isRestoring||!Array.isArray(r.timeline)||typeof r.currentIndex!="number")return null;let n=Me[Me.length-1],o=typeof n?.checkpointIndex=="number"?n.checkpointIndex:r.currentIndex;return o<0||o>=r.timeline.length?null:(typeof n?.checkpointIndex!="number"&&o<r.timeline.length-1&&(r.timeline=r.timeline.slice(0,o+1)),r.timeline[o]??null)},Zc=({state:e},t={})=>{let r=t?.source===jo?jo:en,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?(Me.push({checkpointIndex:null,source:r}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),Me.push({checkpointIndex:o.currentIndex,source:r}),e)},el=({state:e})=>(Me.pop(),e),ye=(e,t,r)=>{let o=Me[Me.length-1]?.source??en;if(!bu(t,o))return;let i=Qc(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:T(r)}))},Mo=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return;let n=t?.operations??[];for(let{variableId:o,op:i,value:s,roundTo:l}of n){let c=e.projectData.resources?.variables?.[o],a=c?.scope,u=c?.type;if(Ce(c))throw new Error(`Cannot update computed variable: ${o}`);if(c?.readonly===!0)throw new Error(`Cannot update readonly variable: ${o}`);Lt(a,o),$t(u,i,o),Ar(u,i,s,o,{roundTo:l}),a==="context"&&(r.variables[o]=kt(r.variables[o],i,s,{roundTo:l}))}},tl=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:r,payload:n})=>{Iu(e,r,n)})},rl=(e,t)=>{let{sectionId:r,lineId:n}=t,s=Z({state:e},{sectionId:r})?.lines?.find(l=>l.id===n)?.actions;s&&Object.entries(s).forEach(([l,c])=>{bi(e,l,c)})},ri=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let n=Ue(r),o=n.timeline[t];if(!o)return e;e.global.autoMode&&pt({state:e}),e.global.skipMode&&Fe({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),n.isRestoring=!0,n.currentIndex=t;try{r.variables=tn(e.projectData),delete r.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=T(Ft),e.global.overlayStack=[],Xe(e),Qe(e),e.global.isLineCompleted=!0;let i=n.replayStartIndex??0;for(let l=i;l<=t;l++)l>i&&Xr(e),rl(e,n.timeline[l]),tl(e,n.timeline[l]);let s=Ze(r);s.read={sectionId:o.sectionId,lineId:o.lineId},e.global.pendingEffects=e.global.pendingEffects.filter(l=>l?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{n.isRestoring=!1}return e},nl=e=>{let{projectData:t}=e,r=e.global??{},{saveSlots:n={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=r;Bo(t);let l=t.story.initialSceneId,c=t.story.scenes[l],a=c.initialSectionId,u=c.sections[a],f={sceneId:l,sectionId:a,lineId:u.initialLineId??u.lines[0].id},{globalVariablesDefaultValues:d}=Ir(t),p={...d,...He(o,t.resources?.variables??{})};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,formDrafts:{},accountViewedRegistry:Oc(s,"accountViewedRegistry"),nextLineConfig:Wt(),saveSlots:_c(n),overlayStack:[],variables:p,...zc({loadedGlobalRuntime:i})},contexts:[ei({pointer:f,projectData:t})]}},ol=({state:e})=>e.global.overlayStack||[],il=({state:e})=>e.global.pendingEffects,ni=({state:e})=>e.global.skipMode,sl=({state:e})=>e.global.autoMode,oi=({state:e})=>e.global.dialogueUIHidden,ii=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],r=t[t.length-1];if(!r)return[];let{sectionId:n,lineId:o}=r.pointers.read,i=Z({state:e},{sectionId:n});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(u=>u.id===o),l=i.lines.slice(0,s+1),c=[],a={};for(let u of l){let f=u.actions||{};if(a=Pe([a,f]),!f.dialogue)continue;let d=a.dialogue||{},p="";d.character?.name!==void 0?p=d.character.name:d.characterId&&(p=e.projectData.resources?.characters?.[d.characterId]?.name||"");let h=vc({sectionId:n,lineId:u.id,content:f.dialogue.append===!0?d.content:f.dialogue.content,dialogueState:d,characterName:p});if(f.dialogue.append===!0&&c.length>0){c[c.length-1]={...c[c.length-1],content:h.content,text:h.text,characterId:h.characterId,character:h.character,characterName:h.characterName};continue}c.push(h)}return c},al=({state:e})=>e.global.confirmDialog??null,dt=({state:e},{pointer:t}={})=>{let r=t??pe({state:e})?.pointer,n=Uc({state:e,pointer:r});return Bc({state:e,form:n.form,pointer:r})},cl=({state:e},{pointer:t}={})=>!!dt({state:e},{pointer:t}),be=({state:e},{pointer:t}={})=>{let r=dt({state:e},{pointer:t});if(r)return{source:Ut,formId:r.id,formKey:r.key};let n=si({state:e,pointer:t});return n?{source:Jr,resourceId:n}:null},ll=({state:e,registry:t},r)=>{let{sectionId:n,lineId:o}=r,s=(Array.isArray(t?.sections)?t.sections:[]).find(u=>u.sectionId===n);if(!s)return!1;if(s.lastLineId===void 0||o===void 0)return!0;let l=Z({state:e},{sectionId:n});if(!l||!l.lines||!Array.isArray(l.lines))return s.lastLineId===o;let c=l.lines.findIndex(u=>u.id===s.lastLineId),a=l.lines.findIndex(u=>u.id===o);return c===-1||a===-1?s.lastLineId===o:a<=c},ul=({registry:e},t)=>{let{resourceId:r}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===r)},on=({state:e},t)=>ll({state:e,registry:e.global.accountViewedRegistry},t),fl=({state:e},t)=>ul({registry:e.global.accountViewedRegistry},t),dl=({state:e})=>e.global.nextLineConfig,si=({state:e,pointer:t}={})=>{let r=t??pe({state:e})?.pointer;if(!r)return;let n=r?.sectionId,o=r?.lineId,s=Z({state:e},{sectionId:n})?.lines||[],l=s.findIndex(a=>a.id===o);if(l<0)return;let c;for(let a of s.slice(0,l+1)){let u=a?.actions;if(u?.cleanAll&&(c=void 0),!u||!Object.prototype.hasOwnProperty.call(u,"choice")){c=void 0;continue}let f=u.choice;if(f?.resourceId){c=f.resourceId;continue}f?.animations||(c=void 0)}return c},ai=({state:e})=>!!si({state:e}),pl=({state:e})=>structuredClone(e),ci=({state:e})=>e.global.saveSlots,hl=({state:e},t)=>{let r=t?.slotId,n=qt(r);return e.global.saveSlots[n]},sn=({state:e})=>Ye(e),ml=({state:e},t)=>Ie(e,t?.runtimeId),an=({state:e})=>{let t={...e.global?.variables??{},...rn(e)?.variables??{}};return Ot({variables:t,runtime:Ye(e),variableConfigs:e.projectData.resources?.variables??{}})},pe=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],r=t[t.length-1];if(r)return{currentPointerMode:"read",pointer:r.pointers?.read}},Z=({state:e},t)=>{let{sectionId:r}=t;return Qr(e.projectData,r).section},cn=({state:e})=>{let t=pe({state:e});if(!t?.pointer)return;let{sectionId:r,lineId:n}=t.pointer,o=Z({state:e},{sectionId:r});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===n)},li=({state:e})=>{let{sectionId:t,lineId:r}=pe({state:e}).pointer,o=Z({state:e},{sectionId:t})?.lines||[],i=o.findIndex(a=>a.id===r),l=o.slice(0,i+1).map(a=>{let u=a.actions||{},f={};return Object.keys(u).forEach(d=>{f[d]=u[d]}),f});return Pe(l)},gl=({state:e})=>{let t=ui({state:e}),n=cn({state:e})?.actions??{},o=Pe([t??{},n]);return wr(t??{},o??{})},yl=({state:e},{sectionId:t})=>{let r=Z({state:e},{sectionId:t});if(!r?.lines)return[];let n=[],o={};for(let i of r.lines){let s=i.actions||{},l=Pe([o,s]),c=wr(o,l);n.push({id:i.id,changes:c,presentationState:l}),o=Er(l)}return n},bl=({state:e},{sectionId:t,includePresentationState:r=!1})=>{let n=yl({state:e},{sectionId:t});return r?{lines:n}:{lines:n.map(({presentationState:o,...i})=>i)}},ui=({state:e})=>{let{sectionId:t,lineId:r}=pe({state:e}).pointer,o=Z({state:e},{sectionId:t})?.lines||[],i=o.findIndex(c=>c.id===r);if(i<=0)return null;let l=o.slice(0,i).map(c=>{let a=c.actions||{},u={};return Object.keys(a).forEach(f=>{u[f]=a[f]}),u});return Er(Pe(l))},ln=({state:e},{slotsPerPage:t=6}={})=>{let o=((sn({state:e}).saveLoadPagination??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let l=o+s,c=e.global.saveSlots&&e.global.saveSlots[qt(l)]||{};i.push({...c,slotId:l})}return{saveSlots:i}},Il=ci,Al=ln,wl=e=>{let r=e.contexts?.[e.contexts.length-1]?.rollback;return!r||!Array.isArray(r.timeline)||typeof r.currentIndex!="number"?!1:r.currentIndex>=0&&r.currentIndex<r.timeline.length-1},El=({state:e},t={})=>{let r=li({state:e}),n=ui({state:e}),o=cn({state:e})?.actions??{},i=e.global.pendingScreenTransition,s=i?.animations?{...o,screen:T(i)}:o,l=i?.animations&&n===null?{}:n,{sectionId:c}=pe({state:e}).pointer,{sceneId:a}=Qr(e.projectData,c),u=sn({state:e}),f=t?.activePersistentAnimations??[],d=t?.restoredPersistentAnimations??[],p=dt({state:e}),h=ai({state:e}),g=an({state:e}),{saveSlots:y}=ln({state:e}),b=wl(e);return Po({presentationState:r,previousPresentationState:l,currentLineActions:s,resources:e.projectData.resources,currentSceneId:a,screen:e.projectData.screen,dialogueUIHidden:u.dialogueUIHidden,autoMode:u.autoMode,skipMode:u.skipMode,isChoiceVisible:h,isFormVisible:!!p,canRollback:Ai({state:e}),skipOnlyViewedLines:!u.skipUnseenText,isLineCompleted:u.isLineCompleted,skipTransitionsAndAnimations:!!u.skipTransitionsAndAnimations||b,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,form:p,dialogueHistory:ii({state:e}),saveSlots:y,variables:g,runtime:u,activePersistentAnimations:f,restoredPersistentAnimations:d})},vl=({state:e},t)=>(e.global.confirmDialog=Dc(t),e.global.pendingEffects.push({name:"render"}),e),xl=({state:e})=>(e.global.confirmDialog&&(Xe(e),e.global.pendingEffects.push({name:"render"})),e),Cl=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),ye(e,"pushOverlay",t),e),Sl=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),ye(e,"popOverlay",void 0),e),_l=({state:e},t)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=t),e.global.pendingEffects.push({name:"render"}),ye(e,"replaceLastOverlay",t),e),Rl=({state:e})=>(e.global.overlayStack=[],Xe(e),Qe(e),e.global.pendingEffects.push({name:"render"}),ye(e,"clearOverlays",void 0),e),Ol=e=>{e.global.autoMode&&(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"})),e.global.skipMode&&(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"})),e.global.nextLineConfig?.auto?.enabled&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},Ht=(e,t,{screenTransition:r}={})=>{e.global.isLineCompleted=!1,Nc(e,r),Qe(e);let n=be({state:e},{pointer:t}),o=n?.source===Jr,i=n?.source===Ut;return n&&Ol(e),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:o,isFormVisible:i,activeInteraction:n}},fi=({state:e})=>(be({state:e})||(e.global.skipMode&&(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"})),e.global.autoMode=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.isLineCompleted&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:Ie(e,"autoForwardDelay")}}),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),Ll=({state:e})=>{let t=e.global.autoMode;return be({state:e})&&!t||(t?pt({state:e}):fi({state:e})),e},di=({state:e})=>(be({state:e})||(e.global.autoMode&&(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"})),e.global.skipMode=!0,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"startSkipNextTimer"}),e.global.pendingEffects.push({name:"render"})),e),Fe=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),$l=({state:e})=>{let t=ni({state:e});return be({state:e})&&!t||(t?Fe({state:e}):di({state:e})),e},Yt=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),ye(e,"showDialogueUI",void 0),e),pi=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),ye(e,"hideDialogueUI",void 0),e),kl=({state:e})=>(oi({state:e})?Yt({state:e}):pi({state:e}),e),Be=(e,t,r)=>(Zo(e,t,r),Yc(e),e.global.pendingEffects.push({name:"render"}),e),ht=(e,t,r,n)=>{let o=Zo(e,t,r);return e.global.pendingEffects.push({name:"render"}),ye(e,n,{value:o}),e},Tl=({state:e},t)=>Be(e,"dialogueTextSpeed",t?.value),Dl=({state:e},t)=>Be(e,"autoForwardDelay",t?.value),Pl=({state:e},t)=>Be(e,"skipUnseenText",t?.value),Nl=({state:e},t)=>Be(e,"skipTransitionsAndAnimations",t?.value),Vl=({state:e},t)=>Be(e,"soundVolume",t?.value),jl=({state:e},t)=>Be(e,"musicVolume",t?.value),Ml=({state:e},t)=>Be(e,"muteAll",t?.value),Fl=({state:e},t)=>ht(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),Ul=({state:e})=>{let t=Ie(e,"saveLoadPagination")+1;return ht(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},Bl=({state:e})=>{let t=Ie(e,"saveLoadPagination")-1;return ht(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},zl=({state:e},t)=>ht(e,"menuPage",t?.value,"setMenuPage"),Wl=({state:e},t)=>ht(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),ql=({state:e})=>(e.global.pendingEffects=[],e),Hl=({state:e},t)=>(e.global.pendingEffects.push(t),e),hi=(e,{sectionId:t,resetStoryState:r=!1,screen:n})=>{let o=!!Yo(n),i=Z({state:e},{sectionId:t});if(!i)return console.warn(`Section not found: ${t}`),e;let s=i.lines?.[0];if(!s)return console.warn(`Section ${t} has no lines`),e;if(r&&!Jc(e,{queueRender:!o}))return e;e.global.autoMode&&pt({state:e}),r&&e.global.skipMode&&Fe({state:e});let l=e.contexts?.[e.contexts.length-1];if(l){let c=Ze(l),a=c.read;r||Je(e,{sectionId:a?.sectionId,lineId:a?.lineId}),l.rollback||Ue(l,{compatibilityAnchor:!0}),c.read={sectionId:t,lineId:s.id},r?l.rollback=ft({pointer:c.read}):nn(e,{sectionId:t,lineId:s.id})}return Ht(e,l?.pointers?.read,{screenTransition:n}),e},Yl=({state:e},t)=>hi(e,{sectionId:t?.sectionId,resetStoryState:!0,screen:t?.screen}),mi=e=>(e.global.accountViewedRegistry=wc(e.global.accountViewedRegistry),e.global.accountViewedRegistry),un=(e,t)=>{!Array.isArray(t)||t.length===0||e.global.pendingEffects.push({name:"applyScopedDataUpdates",payload:{updates:t.map(r=>({scope:r.scope,path:r.path,op:r.op,value:T(r.value)}))}})},gi=(e,t)=>{un(e,[{scope:"account",path:"viewedRegistry",op:"markViewed",value:{sections:(Array.isArray(t?.sections)?t.sections:[]).map(r=>({sectionId:r.sectionId,...r.lastLineId===void 0?{}:{lineId:r.lastLineId}})),resources:Array.isArray(t?.resources)?t.resources:[]}}])},Kl=(e,t,{sectionId:r,lineId:n})=>{if(!r||!n)return!1;let o=k(t)?t:{};Array.isArray(o.sections)||(o.sections=[]);let i=o.sections.find(s=>s.sectionId===r);if(i){if(i.lastLineId===void 0)return!1;let s=Z({state:e},{sectionId:r});if(s?.lines){let l=s.lines.findIndex(a=>a.id===i.lastLineId),c=s.lines.findIndex(a=>a.id===n);if(l===-1||c>l)return i.lastLineId===n?!1:(i.lastLineId=n,!0)}else return i.lastLineId===n?!1:(i.lastLineId=n,!0);return!1}else return o.sections.push({sectionId:r,lastLineId:n}),!0},Je=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;Kl(e,mi(e),t)&&gi(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},Gl=({state:e},t)=>(Je(e,t),e.global.pendingEffects.push({name:"render"}),e),Jl=({state:e},t)=>{let{resourceId:r}=t;if(e.global.accountViewedRegistry!==void 0){let n=mi(e);n.resources.find(i=>i.resourceId===r)||(n.resources.push({resourceId:r}),gi(e,{sections:[],resources:[{resourceId:r}]}))}return e.global.pendingEffects.push({name:"render"}),e},yi=({state:e},t)=>{let r=Cc(t.manual),{auto:n,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,l=e.contexts?.[e.contexts.length-1]?.rollback?.isRestoring===!0;r&&n?(e.global.nextLineConfig={manual:r,auto:n},o!==void 0?e.global.nextLineConfig.applyMode=o:s!==void 0&&(e.global.nextLineConfig.applyMode=s)):(r&&(e.global.nextLineConfig.manual=r),n&&(e.global.nextLineConfig.auto=n),o!==void 0&&(e.global.nextLineConfig.applyMode=o));let c=e.global.nextLineConfig.auto?.enabled,a=be({state:e});return!l&&!a&&c===!0&&!i?e.global.nextLineConfig.auto?.trigger==="fromStart"?e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):e.global.isLineCompleted&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):!l&&c===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),ye(e,"setNextLineConfig",t),e},Xl=({state:e},t)=>{let r=t?.slotId;if(r==null||r==="")throw new Error("saveSlot requires slotId");let{thumbnailImage:n}=t,o=t?.savedAt,i=qt(r),s=T(e.contexts);s?.forEach(a=>{Ze(a),ti(a.rollback),Rc(a.rollback)});let l={contexts:s},c={formatVersion:Fo,slotId:zo(r),savedAt:typeof o=="number"?o:Date.now(),image:n,state:l};return e.global.saveSlots[i]=c,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},Ql=({state:e},t)=>{let r=t?.slotId;if(r==null||r==="")throw new Error("loadSlot requires slotId");let n=qt(r),o=e.global.saveSlots[n];if(o){let i=Tc(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=Wt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,Xe(e),Qe(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},Zl=({state:e},t)=>{let{projectData:r}=t;Bo(r),e.projectData=r;let n=r?.resources?.variables??{};return Object.prototype.hasOwnProperty.call(e.global??{},"variables")&&(e.global.variables=He(e.global.variables,n)),e.contexts?.forEach(o=>{Object.prototype.hasOwnProperty.call(o??{},"variables")&&(o.variables=He(o.variables,n))}),Xe(e),Qe(e),e.global.pendingEffects.push({name:"render"}),e},eu=({state:e},t)=>{let{sectionId:r,lineId:n}=t;if(!n)return console.warn("jumpToLine requires lineId parameter"),e;let o=e.contexts[e.contexts.length-1];if(!o)return console.warn("No context available for jumpToLine"),e;let i=r||o.pointers.read?.sectionId;if(r&&!Z({state:e},{sectionId:r}))return console.warn(`Section not found: ${r}`),e;let s=Z({state:e},{sectionId:i});if(!s?.lines||!Array.isArray(s.lines))return console.warn(`Section ${i} has no lines`),e;if(!s.lines.find(a=>a.id===n))return console.warn(`Line not found: ${n} in section ${i}`),e;let c=Ze(o);return c.read={sectionId:i,lineId:n},Ht(e,c.read),e},tu=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return Yt({state:e}),e;let r=be({state:e});if(r?.source===Jr&&t?.bypassChoice!==!0||r?.source===Ut&&t?._interactionSource!==Ut)return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let u=pe({state:e})?.pointer,f=u?.sectionId,d=u?.lineId;f&&d&&Je(e,{sectionId:f,lineId:d}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:Ie(e,"autoForwardDelay")}});let p=e.global.nextLineConfig;return p?.auto?.enabled&&p.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:p.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e}let n=pe({state:e})?.pointer,o=n?.sectionId,i=Z({state:e},{sectionId:o}),s=e.contexts[e.contexts.length-1],l=i?.lines||[],a=l.findIndex(u=>u.id===n?.lineId)+1;if(a<l.length){let u=l[a],f=!Ie(e,"skipUnseenText");if(e.global.skipMode&&f&&!on({state:e},{sectionId:o,lineId:u.id}))return Fe({state:e}),e;if(s&&!s.rollback&&Ue(s,{compatibilityAnchor:!0}),s){let h=Ze(s),g=h.read?.lineId;g&&o&&Je(e,{sectionId:o,lineId:g}),h.read={sectionId:o,lineId:u.id}}nn(e,{sectionId:o,lineId:u.id}),Xr(e);let{activeInteraction:d}=Ht(e,{sectionId:o,lineId:u.id}),p=e.global.nextLineConfig;p?.auto?.enabled&&!d&&p.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:p.auto.delay}})}else e.global.autoMode&&pt({state:e}),e.global.skipMode&&Fe({state:e});return e},ru=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=be({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:Ie(e,"autoForwardDelay")}});let r=pe({state:e})?.pointer,n=r?.sectionId,o=r?.lineId;n&&o&&Je(e,{sectionId:n,lineId:o});let i=e.global.nextLineConfig;return i?.auto?.enabled&&!t&&i.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:i.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e},nu=({state:e},t)=>hi(e,{sectionId:t?.sectionId,screen:t?.screen}),ou=({state:e})=>{if(e.global.dialogueUIHidden)return Yt({state:e}),e;if(be({state:e}))return e;let t=pe({state:e})?.pointer,r=t?.sectionId,n=Z({state:e},{sectionId:r}),o=e.contexts[e.contexts.length-1],i=n?.lines||[],l=i.findIndex(c=>c.id===t?.lineId)+1;if(l<i.length){let c=i[l],a=!Ie(e,"skipUnseenText");if(e.global.skipMode&&a&&!on({state:e},{sectionId:r,lineId:c.id}))return Fe({state:e}),e;if(o&&!o.rollback&&Ue(o,{compatibilityAnchor:!0}),o){let f=Ze(o),d=f.read?.lineId;d&&r&&Je(e,{sectionId:r,lineId:d}),f.read={sectionId:r,lineId:c.id}}nn(e,{sectionId:r,lineId:c.id}),Xr(e);let{activeInteraction:u}=Ht(e,{sectionId:r,lineId:c.id});e.global.nextLineConfig.auto?.enabled&&!u&&e.global.nextLineConfig.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}})}else e.global.nextLineConfig.auto?.enabled&&(e.global.nextLineConfig.auto.enabled=!1,e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}));return e},fn=(e,t={})=>{let r=dt({state:e});return!r||t.formKey&&t.formKey!==r.key||t.formId&&t.formId!==r.id?null:r},iu=(e,t)=>{if(!t.variableId)throw new Error(`form field "${t.id}" requires variableId`);let r=e.projectData.resources?.variables?.[t.variableId],n=r?.scope,o=r?.type;if(Ce(r))throw new Error(`Cannot update computed variable: ${t.variableId}`);if(r?.readonly===!0)throw new Error(`Cannot update readonly variable: ${t.variableId}`);return Lt(n,t.variableId),$t(o,"set",t.variableId),{variableConfig:r,scope:n}},su=(e,t)=>({id:e.id,key:e.key,valid:!0,values:T(t),fields:T(e.fields),fieldList:T(e.fieldList)}),au=({state:e},t={})=>{let r=fn(e,t),n=t.field;if(!r?.fields?.[n])return e;let o=Go(e,r.key),i=Bt(t.value),s=r.fields[n],l=Zr(s,i);return o.values[n]=i,o.touched[n]=!0,l?o.errors[n]=l:delete o.errors[n],e.global.pendingEffects.push({name:"render"}),e},cu=({state:e},t={})=>{let r=fn(e,t);if(!r)return{submitted:!1,valid:!1,reason:"inactive"};let n=Go(e,r.key);n.submitted=!0;let o={},i={};if(Object.entries(r.fields).forEach(([f,d])=>{let p=Object.prototype.hasOwnProperty.call(n.values,f)?n.values[f]:d.value,h=Zr(d,p);n.touched[f]=!0,h&&(i[f]=h),o[f]=Ko(d,p)}),n.errors=i,Object.keys(i).length>0)return e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!1,errors:T(i),form:{id:r.id,key:r.key,values:T(o)}};let s=e.contexts[e.contexts.length-1];if(s?.rollback?.isRestoring)return{submitted:!1,valid:!1,reason:"restoring"};let l=!1,c=[],a=[];Object.entries(r.fields).forEach(([f,d])=>{let{scope:p}=iu(e,d),h=p==="context"?s.variables:e.global.variables,g=o[f];h[d.variableId]=kt(h[d.variableId],"set",g),p==="context"&&(l=!0,a.push({variableId:d.variableId,op:"set",value:g})),(p==="device"||p==="account")&&c.push({scope:p,path:`variables.${d.variableId}`,op:"set",value:T(h[d.variableId])})}),l&&ye(e,"updateVariable",{id:"submitForm",operations:a}),un(e,c);let u=su(r,o);return delete e.global.formDrafts[r.key],e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!0,form:u}},lu=({state:e},t={})=>{let r=fn(e,t);return r?(delete e.global.formDrafts?.[r.key],e.global.pendingEffects.push({name:"render"}),{cancelled:!0,form:{id:r.id,key:r.key,values:T(r.values),fields:T(r.fields),fieldList:T(r.fieldList)}}):{cancelled:!1,reason:"inactive"}},uu=({state:e},t)=>{let{id:r,operations:n=[]}=t;if(!r)throw new Error("updateVariable requires an id field");if(typeof r!="string"||!/^[a-zA-Z0-9]+$/.test(r))throw new Error(`updateVariable id must be alphanumeric, got: "${r}"`);let o=e.contexts[e.contexts.length-1];if(o?.rollback?.isRestoring)return e;let i=!1,s=[],l=[];return n.forEach(({variableId:c,op:a,value:u,roundTo:f})=>{let d=e.projectData.resources?.variables?.[c],p=d?.scope,h=d?.type;if(Ce(d))throw new Error(`Cannot update computed variable: ${c}`);if(d?.readonly===!0)throw new Error(`Cannot update readonly variable: ${c}`);Lt(p,c),$t(h,a,c),Ar(h,a,u,c,{roundTo:f});let g=p==="context"?o.variables:e.global.variables;if(p==="context"){i=!0;let y={variableId:c,op:a,value:u};f!==void 0&&(y.roundTo=f),l.push(y)}g[c]=kt(g[c],a,u,{roundTo:f}),(p==="device"||p==="account")&&s.push({scope:p,path:`variables.${c}`,op:"set",value:T(g[c])})}),i&&ye(e,"updateVariable",{id:r,operations:l}),un(e,s),e.global.pendingEffects.push({name:"render"}),e},fu=e=>(t,r)=>e({state:t},r),du=e=>({variables:Ot({variables:{...e.global?.variables??{},...rn(e)?.variables??{}},runtime:Ye(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1}),runtime:Ye(e)}),pu=e=>{if(!k(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")},hu=(e,t,r)=>{if(!k(e))throw new Error(`conditional branch at index ${t} must be an object`);if(!k(e.actions))throw new Error(`conditional branch at index ${t} requires actions object`);if(!Object.prototype.hasOwnProperty.call(e,"when")&&t!==r-1)throw new Error("conditional else branch must be the last branch")},mu=(e,t)=>{pu(t);for(let r=0;r<t.branches.length;r+=1){let n=t.branches[r];if(hu(n,r,t.branches.length),!(Object.prototype.hasOwnProperty.call(n,"when")&&!it(n.when,du(e)))){Object.entries(n.actions).forEach(([i,s])=>{bi(e,i,s)});return}}},gu={conditional:{replayLine:mu},updateVariable:{recordSources:[en],replayLine:Mo,replayRecorded:Mo,persistInSaveSlot:!0},setNextLineConfig:{replayLine:fu(yi)}},Kt=e=>gu[e]??null,yu=e=>Kt(e)?.persistInSaveSlot===!0,bu=(e,t)=>{let r=Kt(e)?.recordSources;return Array.isArray(r)&&r.includes(t)},Iu=(e,t,r)=>{Kt(t)?.replayRecorded?.(e,r)},bi=(e,t,r)=>{Kt(t)?.replayLine?.(e,r)},Ii=({state:e},t)=>{let{offset:r}=t;if(r===void 0||typeof r!="number")return console.warn("selectLineIdByOffset requires a numeric offset"),null;let n=e.contexts[e.contexts.length-1];if(!n)return null;let o=n.rollback;if(!Array.isArray(o?.timeline)||typeof o?.currentIndex!="number")return null;let i=o.currentIndex+r;if(i<0||i>=o.timeline.length)return null;let s=o.timeline[i];return{sectionId:s.sectionId,lineId:s.lineId}},Ai=({state:e})=>Ii({state:e},{offset:-1})!==null,Au=({state:e},t)=>{let{offset:r=-1}=t;if(r>=0)throw new Error("rollbackByOffset requires a negative offset");let n=e.contexts?.[e.contexts.length-1];if(!n)return e;let o=Ue(n,{compatibilityAnchor:!n.rollback}),i=o.currentIndex+r;return i<0||i>=o.timeline.length?e:ri(e,i)},wu=({state:e},t)=>{let{sectionId:r,lineId:n}=t,o=e.contexts[e.contexts.length-1];if(!o)throw new Error("No context available for rollbackToLine");let i=Ue(o,{compatibilityAnchor:!o.rollback}),l=i.timeline.slice(0,i.currentIndex+1).findLastIndex(c=>c.sectionId===r&&c.lineId===n);if(l===-1)throw new Error(`Line ${n} not found in section ${r} rollback timeline`);return l===i.currentIndex?e:ri(e,l)},wi=e=>{let t=nl(e);return Jn(t,{selectPendingEffects:il,selectSkipMode:ni,selectAutoMode:sl,selectIsChoiceVisible:ai,selectIsFormVisible:cl,selectActiveInteraction:be,selectActiveForm:dt,selectDialogueUIHidden:oi,selectDialogueHistory:ii,selectConfirmDialog:al,selectIsLineAccountViewed:on,selectIsResourceAccountViewed:fl,selectNextLineConfig:dl,selectSystemState:pl,selectSaveSlotMap:ci,selectSaveSlots:Il,selectSaveSlot:hl,selectRuntime:sn,selectRuntimeValue:ml,selectAllVariables:an,selectCurrentPointer:pe,selectSection:Z,selectCurrentLine:cn,selectPresentationState:li,selectPresentationChanges:gl,selectSectionLineChanges:bl,selectSaveSlotPage:ln,selectCurrentPageSlots:Al,selectRenderState:El,selectOverlayStack:ol,selectLineIdByOffset:Ii,selectCanRollback:Ai,startAutoMode:fi,stopAutoMode:pt,toggleAutoMode:Ll,startSkipMode:di,stopSkipMode:Fe,toggleSkipMode:$l,showDialogueUI:Yt,hideDialogueUI:pi,toggleDialogueUI:kl,setDialogueTextSpeed:Tl,setAutoForwardDelay:Dl,setSkipUnseenText:Pl,setSkipTransitionsAndAnimations:Nl,setSoundVolume:Vl,setMusicVolume:jl,setMuteAll:Ml,setSaveLoadPagination:Fl,incrementSaveLoadPagination:Ul,decrementSaveLoadPagination:Bl,setMenuPage:zl,setMenuEntryPoint:Wl,showConfirmDialog:vl,hideConfirmDialog:xl,resetStoryAtSection:Yl,clearPendingEffects:ql,appendPendingEffect:Hl,beginRollbackActionBatch:Zc,endRollbackActionBatch:el,addViewedLine:Gl,addViewedResource:Jl,setNextLineConfig:yi,saveSlot:Xl,loadSlot:Ql,updateProjectData:Zl,sectionTransition:nu,jumpToLine:eu,nextLine:tu,markLineCompleted:ru,rollbackToLine:wu,rollbackByOffset:Au,pushOverlay:Cl,popOverlay:Sl,replaceLastOverlay:_l,clearOverlays:Rl,updateFormField:au,submitForm:cu,cancelForm:lu,updateVariable:uu,nextLineFromSystem:ou},{transformActionFirstArgument:n=>({state:n}),transformSelectorFirstArgument:n=>({state:n})})};var Eu="route-engine",vu="projectPersistence";var vi=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),X=e=>Object.prototype.toString.call(e)==="[object Object]",Ei="variables.",xu=(e={})=>{let t=X(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!X(r)||typeof r.sectionId!="string"||r.sectionId.length===0?null:{sectionId:r.sectionId,...typeof r.lineId=="string"?{lineId:r.lineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(r=>typeof r=="string"||typeof r=="number"?{resourceId:String(r)}:!X(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},Cu=(e={})=>{let t=X(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!X(r)||typeof r.sectionId!="string"||r.sectionId.length===0?null:{sectionId:r.sectionId,...typeof r.lastLineId=="string"?{lastLineId:r.lastLineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(r=>typeof r=="string"||typeof r=="number"?{resourceId:String(r)}:!X(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},Su=(e,t)=>{let r=Cu(e),n=xu(t),o=r.sections.map(s=>({...s})),i=r.resources.map(s=>({...s}));return n.sections.forEach(s=>{let l=o.find(c=>c.sectionId===s.sectionId);if(!l){o.push({sectionId:s.sectionId,...s.lineId===void 0?{}:{lastLineId:s.lineId}});return}if(l.lastLineId!==void 0){if(s.lineId===void 0){delete l.lastLineId;return}l.lastLineId=s.lineId}}),n.resources.forEach(s=>{i.find(c=>c.resourceId===s.resourceId)||i.push({...s})}),{sections:o,resources:i}},xi=(e={})=>{let t=X(e)?e:{};return{saveSlots:X(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:X(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:X(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:X(t.globalRuntime)?t.globalRuntime:{},accountViewedRegistry:X(t.accountViewedRegistry)?t.accountViewedRegistry:{}}},_u=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((t,r)=>{if(!X(t))throw new Error(`Malformed applyScopedDataUpdates.updates[${r}] entry.`);let n=t.path?.startsWith(Ei)?t.path.slice(Ei.length):null;if(n!==null){if(!["device","account"].includes(t.scope))throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${r}].`);if(n.length===0)throw new Error(`Malformed applyScopedDataUpdates path "${t.path}" at updates[${r}].`);if(t.op!=="set")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${r}].`);return{scope:t.scope,path:t.path,op:t.op,value:t.value,variableId:n}}if(t.path==="viewedRegistry"){if(t.scope!=="account")throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${r}].`);if(t.op!=="markViewed")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${r}].`);return t}throw typeof t.path!="string"?new Error(`Malformed applyScopedDataUpdates path at updates[${r}].`):new Error(`Unsupported applyScopedDataUpdates path "${t.path}" at updates[${r}].`)})},Ru=(e,t)=>{let r={};return _u(t).forEach(n=>{if(n.path==="viewedRegistry"){r.accountViewedRegistry=Su(r.accountViewedRegistry??e.accountViewedRegistry,n.value);return}let o=n.scope==="device"?"globalDeviceVariables":"globalAccountVariables";r[o]={...e[o],...r[o],[n.variableId]:n.value}}),r},dn=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},Ou=e=>{let t=dn(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},Lu=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},$u=({indexedDB:e,databaseName:t,objectStoreName:r})=>new Promise((n,o)=>{let i=e.open(t,1);i.onupgradeneeded=()=>{let s=i.result;s.objectStoreNames.contains(r)||s.createObjectStore(r,{keyPath:"namespace"})},i.onsuccess=()=>{n(i.result)},i.onerror=()=>{o(i.error??new Error(`Failed to open IndexedDB database "${t}".`))}}),ku=async({databasePromise:e,objectStoreName:t,namespace:r})=>{let n=await e;return new Promise((o,i)=>{let c=n.transaction(t,"readonly").objectStore(t).get(r);c.onsuccess=()=>{o(c.result??null)},c.onerror=()=>{i(c.error??new Error(`Failed to read persisted namespace "${r}" from IndexedDB.`))}})},mt=async({databasePromise:e,objectStoreName:t,namespace:r,patch:n})=>{let o=await e;return new Promise((i,s)=>{let l=o.transaction(t,"readwrite"),c=l.objectStore(t),a=c.get(r),u=!1,f=p=>{u||(u=!0,s(p))},d=()=>{u||(u=!0,i())};a.onerror=()=>{f(a.error??new Error(`Failed to read persisted namespace "${r}" before updating IndexedDB.`))},a.onsuccess=()=>{let p=xi(a.result),h=typeof n=="function"?n(p):n,g={namespace:r,version:1,...vi(),...p,...h},y=c.put(g);y.onerror=()=>{f(y.error??new Error(`Failed to persist namespace "${r}" to IndexedDB.`))}},l.oncomplete=()=>{d()},l.onerror=()=>{f(l.error??new Error(`IndexedDB transaction failed while updating namespace "${r}".`))},l.onabort=()=>{f(l.error??new Error(`IndexedDB transaction aborted while updating namespace "${r}".`))}})},Tu=async({databasePromise:e,objectStoreName:t,namespace:r})=>{let n=await e;return new Promise((o,i)=>{let s=n.transaction(t,"readwrite"),c=s.objectStore(t).delete(r),a=!1,u=d=>{a||(a=!0,i(d))},f=()=>{a||(a=!0,o())};c.onerror=()=>{u(c.error??new Error(`Failed to clear persisted namespace "${r}" from IndexedDB.`))},s.oncomplete=()=>{f()},s.onerror=()=>{u(s.error??new Error(`IndexedDB transaction failed while clearing namespace "${r}".`))},s.onabort=()=>{u(s.error??new Error(`IndexedDB transaction aborted while clearing namespace "${r}".`))}})},pn=(e={})=>{let{indexedDB:t,databaseName:r=Eu,objectStoreName:n=vu,namespace:o}=e,i=Lu(t),s=Ou(o),l=$u({indexedDB:i,databaseName:r,objectStoreName:n});return{namespace:s,load:async()=>{let c=await ku({databasePromise:l,objectStoreName:n,namespace:s});return{...vi(),...xi(c)}},clear:async()=>Tu({databasePromise:l,objectStoreName:n,namespace:s}),saveSlots:async c=>mt({databasePromise:l,objectStoreName:n,namespace:s,patch:{saveSlots:X(c)?c:{}}}),saveGlobalDeviceVariables:async c=>mt({databasePromise:l,objectStoreName:n,namespace:s,patch:{globalDeviceVariables:X(c)?c:{}}}),saveGlobalAccountVariables:async c=>mt({databasePromise:l,objectStoreName:n,namespace:s,patch:{globalAccountVariables:X(c)?c:{}}}),saveGlobalRuntime:async c=>mt({databasePromise:l,objectStoreName:n,namespace:s,patch:{globalRuntime:X(c)?c:{}}}),applyScopedDataUpdates:async c=>mt({databasePromise:l,objectStoreName:n,namespace:s,patch:a=>Ru(a,c)})}},Du=pn;var Pu=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),Nu=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),Ci="conditional",hn="form",Vu=new Set(["submitForm","cancelForm"]),gt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function mn(e){let t,r=0,n=null,o=new Map,i=new Map,s=new Map,{handlePendingEffects:l}=e,c=(I=new Map,C=Date.now())=>new Map(Array.from(I.entries()).filter(([,R])=>C<R.expiresAt).map(([R,U])=>[R,{animation:structuredClone(U.animation),startedAt:U.startedAt,expiresAt:U.expiresAt}])),a=(I=new Map)=>Array.from(I.values()).map(C=>structuredClone(C.animation)),u=(I=Date.now())=>{o=new Map(Array.from(o.entries()).filter(([,C])=>I<C.expiresAt))},f=()=>{for(;t.selectPendingEffects().length>0;){let I=[...t.selectPendingEffects()];t.clearPendingEffects();try{l(I)}catch(C){throw t.clearPendingEffects(),I.forEach(R=>{t.appendPendingEffect(R)}),C}}},d=({initialState:I,namespace:C})=>{t=wi(I),r=0,n=dn(C),o=new Map,i=new Map,s=new Map,t.appendPendingEffect({name:"handleLineActions"}),f()},p=()=>n,h=()=>t.selectPresentationState(),g=()=>t.selectPresentationChanges(),y=I=>t.selectSectionLineChanges(I),b=(I={})=>{r+=1;let C=Date.now();u(C);let R=i.size>0,U=c(o,C),H=R?c(i,C):new Map,me={...t.selectRenderState({activePersistentAnimations:a(U),restoredPersistentAnimations:a(H)}),id:`render-${r}`};return s.set(me.id,{builtAt:C,persistentAnimationSessions:new Map([...H.entries(),...U.entries()]),usedRestoredPersistentAnimationSessions:R}),me},A=(I={})=>b(I),v=(I={})=>b(I),S=I=>{let C=typeof I?.id=="string"&&I.id.length>0?I.id:null,R=C?s.get(C):null;C&&s.delete(C);let U=new Map;Eo(I?.animations).forEach(H=>{let se=Nt(H);if(!se)return;let me=R?.persistentAnimationSessions?.get(se)??o.get(se),yt=Math.max(0,xo(H)),bn=me?.startedAt??R?.builtAt??Date.now();U.set(se,{animation:structuredClone(H),startedAt:bn,expiresAt:bn+yt})}),o=U,R?.usedRestoredPersistentAnimationSessions&&(i=new Map)},D=()=>t.selectSystemState(),w=()=>t.selectSaveSlotMap(),P=I=>t.selectSaveSlot(I),B=I=>t.selectSaveSlotPage(I),j=()=>t.selectSkipMode(),V=()=>t.selectAutoMode(),F=()=>t.selectRuntime(),Y=()=>t.selectIsChoiceVisible(),W=()=>t.selectIsFormVisible(),x=()=>t.selectActiveInteraction(),_=(I,C,R={})=>I!=="nextLine"||!gt(C)?C:R.bypassChoice===!0?{...C,bypassChoice:!0}:R.interactionSource===hn?{...C,_interactionSource:hn}:C,$=(I,C)=>{if(!t[I])return;Pu.has(I)&&(Nu.has(I)?i=c(o):i=new Map,o=new Map);let R=t[I](C);return f(),R},M=(I,C,R,U={})=>{if(I===Ci){let H=N(R),se=vr({[I]:C},H);ze(se[I],R,U);return}$(I,C)},q=(I,C)=>{M(I,C)},N=I=>{if(!I)return{variables:t.selectAllVariables?t.selectAllVariables():void 0,runtime:t.selectRuntime?t.selectRuntime():{}};if(Object.prototype.hasOwnProperty.call(I,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:C,...R}=I,U=t.selectAllVariables?t.selectAllVariables():void 0;return{...R,_event:C,variables:U,runtime:t.selectRuntime?t.selectRuntime():{}}},he=I=>{if(!gt(I))throw new Error("conditional action payload must be an object");if(!Array.isArray(I.branches))throw new Error("conditional action requires branches array");if(I.branches.length===0)throw new Error("conditional action requires at least one branch")},we=(I,C,R)=>{if(!gt(I))throw new Error(`conditional branch at index ${C} must be an object`);if(!gt(I.actions))throw new Error(`conditional branch at index ${C} requires actions object`);if(!Object.prototype.hasOwnProperty.call(I,"when")&&C!==R-1)throw new Error("conditional else branch must be the last branch")},ze=(I,C,R)=>{he(I);for(let U=0;U<I.branches.length;U+=1){let H=I.branches[U];we(H,U,I.branches.length);let se=N(C);if(!(Object.prototype.hasOwnProperty.call(H,"when")&&!it(H.when,se))){Jt(H.actions,C,R);return}}},Ri=(I,C)=>({...I??{},_form:C}),Oi=(I,C,R,U)=>{let H=$(I,C),se=H?.submitted===!0&&H.valid===!0,me=H?.cancelled===!0;!se&&!me||gt(C.actions)&&Jt(C.actions,Ri(R,H.form),{...U,interactionSource:hn})},Li=(I,C,R,U)=>{let H=N(R),me=vr({[I]:C},H)[I];if(I===Ci){ze(me,R,U);return}let yt=_(I,me,U);if(Vu.has(I)){Oi(I,yt,R,U);return}$(I,yt)},Jt=(I,C,R)=>{Object.entries(I).forEach(([U,H])=>{Li(U,H,C,R)})},yn=(I,C,R={})=>{t.beginRollbackActionBatch({source:R.rollbackSource});try{Jt(I,C,R)}finally{t.endRollbackActionBatch({})}};return{init:d,handleAction:M,handleInternalAction:q,handleActions:yn,selectRenderState:A,prepareRenderState:v,commitRenderState:S,selectPresentationState:h,selectPresentationChanges:g,selectSectionLineChanges:y,selectSystemState:D,selectSaveSlotMap:w,selectSaveSlot:P,selectSaveSlotPage:B,selectSaveSlots:w,selectRuntime:F,selectIsChoiceVisible:Y,selectIsFormVisible:W,selectActiveInteraction:x,handleLineActions:()=>{let I=t.selectCurrentLine();return I?.actions?(yn(I.actions,void 0,{rollbackSource:"line"}),!0):!1},getNamespace:p}}var gn=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:r=>{e=r},addElapsed:r=>{e+=r},getCallback:()=>t,setCallback:r=>{t=r}}},ju=80,_i=({engine:e,routeGraphics:t,trackRenderDispatch:r},n)=>{let o=e.prepareRenderState?.(n)??e.selectRenderState(n);r?.(o),t.render(o),e.commitRenderState?.(o)},Mu=({engine:e,routeGraphics:t,trackRenderDispatch:r,getRenderDispatchCount:n},o)=>{let i=n?.()??0,s=e.handleLineActions();(n?.()??0)===i&&_i({engine:e,routeGraphics:t,trackRenderDispatch:r},o)},Fu=({engine:e,ticker:t,autoTimer:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let l=n.delay??1e3;r.getElapsed()>=l&&(t.remove(i),r.setCallback(null),r.setElapsed(0),Gt(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},Uu=({ticker:e,autoTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},Bu=({engine:e,ticker:t,skipTimer:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let l=n?.delay??ju;r.getElapsed()>=l&&(r.setElapsed(0),Gt(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},zu=({ticker:e,skipTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},Wu=({engine:e,ticker:t,nextLineConfigTimerState:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let l=n.delay??1e3;r.getElapsed()>=l&&(r.setElapsed(0),Gt(e,"nextLineFromSystem",{}),t.remove(i),r.setCallback(null))};r.setCallback(i),t.add(i)},qu=({ticker:e,nextLineConfigTimerState:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},Hu=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveSlots(t?.saveSlots))},Yu=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalDeviceVariables(t?.globalDeviceVariables))},Ku=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalAccountVariables(t?.globalAccountVariables))},Gu=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalRuntime(t?.globalRuntime))},Ju=({enqueuePersistenceWrite:e},t)=>{e(r=>{if(typeof r.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return r.applyScopedDataUpdates(t?.updates)})},Si={render:_i,saveSlots:Hu,saveGlobalDeviceVariables:Yu,saveGlobalAccountVariables:Ku,saveGlobalRuntime:Gu,applyScopedDataUpdates:Ju,handleLineActions:Mu,startAutoNextTimer:Fu,clearAutoNextTimer:Uu,startSkipNextTimer:Bu,clearSkipNextTimer:zu,nextLineConfigTimer:Wu,clearNextLineConfigTimer:qu},Xu=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),Gt=(e,t,r)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,r)},Qu=(e=[])=>{let t=new Set,r=[];for(let n=e.length-1;n>=0;n-=1){let o=e[n];if(typeof o?.name!="string"||o.name.length===0)throw new Error("Pending effect is missing a valid name.");if(!Xu.has(o.name)){r.unshift(o);continue}t.has(o.name)||(t.add(o.name),r.unshift(o))}return r},Zu=({getEngine:e,routeGraphics:t,ticker:r,handleUnhandledEffect:n,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:l})=>{let c=gn(),a=gn(),u=gn(),f=s??null,d=Promise.resolve(),p=null,h=null,g=!1,y=0,b=x=>{if(o){o(x);return}console.error("RouteEngine persistence write failed.",x)},A=()=>{if(f)return f;let x=e();return f=pn({indexedDB:i,namespace:l??x?.getNamespace?.()}),f},v=x=>{d=d.catch(()=>{}).then(()=>{let _=A();return x(_)}).catch(_=>{b(_)})},S=x=>{let _=typeof x?.id=="string"&&x.id.length>0?x.id:null;y+=1,p=_,g=!1},D=()=>y,w=(x={})=>{if(x?.aborted===!0)return!1;let _=typeof x?.id=="string"&&x.id.length>0?x.id:null;return _?_!==p||_===h?!1:(h=_,!0):p!==null||g?!1:(g=!0,!0)},P=(x,_={})=>{if(x!=="renderComplete"||!w(_))return!1;let $=e();return Gt($,"markLineCompleted",{}),!0},B=x=>typeof x?.selectActiveInteraction=="function"?x.selectActiveInteraction():typeof x?.selectIsChoiceVisible=="function"&&x.selectIsChoiceVisible()?{source:"choice"}:null,j=(x,_)=>!(!x||typeof x!="object"||Array.isArray(x)||x._interactionSource!==_?.source||_.source==="form"&&x._formKey&&x._formKey!==_.formKey||_.source==="form"&&x.formKey&&x.formKey!==_.formKey),V=(x={},_)=>{if(j(x,_))return!0;let $=x?.actions;return!$||typeof $!="object"||Array.isArray($)?!1:Object.values($).some(M=>j(M,_))},F=(x,_={})=>{if(!_?.actions)return!1;let $=B(x);return!$||$.source==="choice"?!1:!V(_,$)},Y=({preprocessPayload:x,onEvent:_}={})=>async($,M={})=>{let q=e();if(F(q,M))return _?.($,M);let N=await x?.($,M)??M;if(F(q,N))return _?.($,N);if(P($,N),N?.actions){let he=N?._event?{_event:N._event}:N?.event?{_event:N.event}:void 0,we;N?.bypassChoice===!0?we={bypassChoice:!0}:N?._interactionSource&&(we={interactionSource:N._interactionSource}),we?q.handleActions(N.actions,he,we):q.handleActions(N.actions,he)}return _?.($,N)},W=x=>{let _=e(),$=Qu(x);$.forEach(q=>{if(!Si[q.name]&&!n)throw new Error(`Unhandled pending effect "${q.name}".`)});let M={engine:_,routeGraphics:t,ticker:r,autoTimer:c,skipTimer:a,nextLineConfigTimerState:u,trackRenderDispatch:S,getRenderDispatchCount:D,enqueuePersistenceWrite:v};for(let q of $){let N=Si[q.name];if(N){N(M,q.payload);continue}n(q,M)}};return W.handleRouteGraphicsEvent=P,W.createRouteGraphicsEventHandler=Y,W},ef=Zu;var tf=(e,t={})=>{let{resources:r={}}=t;return Gr(e,r)};var wd=mn;export{Sr as DEFAULT_VISUAL_LAYER,ct as RENDER_LAYER,Se as VISUAL_LAYER,ef as createEffectsHandler,Du as createIndexedDbPersistence,wd as default,Vs as resolveComputedVariables,tf as resolveLayoutReferences};
|
|
1
|
+
var $i=Object.defineProperty;var ki=(e,t)=>{for(var r in t)$i(e,r,{get:t[r],enumerable:!0})};var Rn=Symbol.for("immer-nothing"),vn=Symbol.for("immer-draftable"),ae=Symbol.for("immer-state");function de(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var He=Object.getPrototypeOf;function ce(e){return!!e&&!!e[ae]}function Te(e){return e?On(e)||Array.isArray(e)||!!e[vn]||!!e.constructor?.[vn]||St(e)||_t(e):!1}var Ti=Object.prototype.constructor.toString();function On(e){if(!e||typeof e!="object")return!1;let t=He(e);if(t===null)return!0;let r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return r===Object?!0:typeof r=="function"&&Function.toString.call(r)===Ti}function Et(e,t){Ct(e)===0?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,n)=>t(n,r,e))}function Ct(e){let t=e[ae];return t?t.type_:Array.isArray(e)?1:St(e)?2:_t(e)?3:0}function rr(e,t){return Ct(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Ln(e,t,r){let n=Ct(e);n===2?e.set(t,r):n===3?e.add(r):e[t]=r}function Di(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function St(e){return e instanceof Map}function _t(e){return e instanceof Set}function ke(e){return e.copy_||e.base_}function nr(e,t){if(St(e))return new Map(e);if(_t(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=On(e);if(t===!0||t==="class_only"&&!r){let n=Object.getOwnPropertyDescriptors(e);delete n[ae];let o=Reflect.ownKeys(n);for(let i=0;i<o.length;i++){let s=o[i],l=n[s];l.writable===!1&&(l.writable=!0,l.configurable=!0),(l.get||l.set)&&(n[s]={configurable:!0,writable:!0,enumerable:l.enumerable,value:e[s]})}return Object.create(He(e),n)}else{let n=He(e);if(n!==null&&r)return{...e};let o=Object.create(n);return Object.assign(o,e)}}function cr(e,t=!1){return Rt(e)||ce(e)||!Te(e)||(Ct(e)>1&&(e.set=e.add=e.clear=e.delete=Pi),Object.freeze(e),t&&Object.entries(e).forEach(([r,n])=>cr(n,!0))),e}function Pi(){de(2)}function Rt(e){return Object.isFrozen(e)}var Ni={};function De(e){let t=Ni[e];return t||de(0,e),t}var nt;function $n(){return nt}function Vi(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function xn(e,t){t&&(De("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function or(e){ir(e),e.drafts_.forEach(ji),e.drafts_=null}function ir(e){e===nt&&(nt=e.parent_)}function Cn(e){return nt=Vi(nt,e)}function ji(e){let t=e[ae];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function Sn(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[ae].modified_&&(or(t),de(4)),Te(e)&&(e=vt(t,e),t.parent_||xt(t,e)),t.patches_&&De("Patches").generateReplacementPatches_(r[ae].base_,e,t.patches_,t.inversePatches_)):e=vt(t,r,[]),or(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Rn?e:void 0}function vt(e,t,r){if(Rt(t))return t;let n=t[ae];if(!n)return Et(t,(o,i)=>_n(e,n,t,o,i,r)),t;if(n.scope_!==e)return t;if(!n.modified_)return xt(e,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;let o=n.copy_,i=o,s=!1;n.type_===3&&(i=new Set(o),o.clear(),s=!0),Et(i,(l,c)=>_n(e,n,o,l,c,r,s)),xt(e,o,!1),r&&e.patches_&&De("Patches").generatePatches_(n,r,e.patches_,e.inversePatches_)}return n.copy_}function _n(e,t,r,n,o,i,s){if(ce(o)){let l=i&&t&&t.type_!==3&&!rr(t.assigned_,n)?i.concat(n):void 0,c=vt(e,o,l);if(Ln(r,n,c),ce(c))e.canAutoFreeze_=!1;else return}else s&&r.add(o);if(Te(o)&&!Rt(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;vt(e,o),(!t||!t.scope_.parent_)&&typeof n!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,n)&&xt(e,o)}}function xt(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&cr(t,r)}function Mi(e,t){let r=Array.isArray(e),n={type_:r?1:0,scope_:t?t.scope_:$n(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=n,i=lr;r&&(o=[n],i=ot);let{revoke:s,proxy:l}=Proxy.revocable(o,i);return n.draft_=l,n.revoke_=s,l}var lr={get(e,t){if(t===ae)return e;let r=ke(e);if(!rr(r,t))return Fi(e,r,t);let n=r[t];return e.finalized_||!Te(n)?n:n===er(e.base_,t)?(tr(e),e.copy_[t]=ar(n,e)):n},has(e,t){return t in ke(e)},ownKeys(e){return Reflect.ownKeys(ke(e))},set(e,t,r){let n=kn(ke(e),t);if(n?.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){let o=er(ke(e),t),i=o?.[ae];if(i&&i.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(Di(r,o)&&(r!==void 0||rr(e.base_,t)))return!0;tr(e),sr(e)}return e.copy_[t]===r&&(r!==void 0||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_[t]=!0),!0},deleteProperty(e,t){return er(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,tr(e),sr(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=ke(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:n.enumerable,value:r[t]}},defineProperty(){de(11)},getPrototypeOf(e){return He(e.base_)},setPrototypeOf(){de(12)}},ot={};Et(lr,(e,t)=>{ot[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});ot.deleteProperty=function(e,t){return ot.set.call(this,e,t,void 0)};ot.set=function(e,t,r){return lr.set.call(this,e[0],t,r,e[0])};function er(e,t){let r=e[ae];return(r?ke(r):e)[t]}function Fi(e,t,r){let n=kn(t,r);return n?"value"in n?n.value:n.get?.call(e.draft_):void 0}function kn(e,t){if(!(t in e))return;let r=He(e);for(;r;){let n=Object.getOwnPropertyDescriptor(r,t);if(n)return n;r=He(r)}}function sr(e){e.modified_||(e.modified_=!0,e.parent_&&sr(e.parent_))}function tr(e){e.copy_||(e.copy_=nr(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Ui=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,r,n)=>{if(typeof t=="function"&&typeof r!="function"){let i=r;r=t;let s=this;return function(c=i,...a){return s.produce(c,u=>r.call(this,u,...a))}}typeof r!="function"&&de(6),n!==void 0&&typeof n!="function"&&de(7);let o;if(Te(t)){let i=Cn(this),s=ar(t,void 0),l=!0;try{o=r(s),l=!1}finally{l?or(i):ir(i)}return xn(i,n),Sn(o,i)}else if(!t||typeof t!="object"){if(o=r(t),o===void 0&&(o=t),o===Rn&&(o=void 0),this.autoFreeze_&&cr(o,!0),n){let i=[],s=[];De("Patches").generateReplacementPatches_(t,o,i,s),n(i,s)}return o}else de(1,t)},this.produceWithPatches=(t,r)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,c=>t(c,...l));let n,o;return[this.produce(t,r,(s,l)=>{n=s,o=l}),n,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){Te(e)||de(8),ce(e)&&(e=Pe(e));let t=Cn(this),r=ar(e,void 0);return r[ae].isManual_=!0,ir(t),r}finishDraft(e,t){let r=e&&e[ae];(!r||!r.isManual_)&&de(9);let{scope_:n}=r;return xn(n,t),Sn(void 0,n)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){let o=t[r];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}r>-1&&(t=t.slice(r+1));let n=De("Patches").applyPatches_;return ce(e)?n(e,t):this.produce(e,o=>n(o,t))}};function ar(e,t){let r=St(e)?De("MapSet").proxyMap_(e,t):_t(e)?De("MapSet").proxySet_(e,t):Mi(e,t);return(t?t.scope_:$n()).drafts_.push(r),r}function Pe(e){return ce(e)||de(10,e),Tn(e)}function Tn(e){if(!Te(e)||Rt(e))return e;let t=e[ae],r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=nr(e,t.scope_.immer_.useStrictShallowCopy_)}else r=nr(e,!0);return Et(r,(n,o)=>{Ln(r,n,Tn(o))}),t&&(t.finalized_=!1),r}var le=new Ui,ur=le.produce,af=le.produceWithPatches.bind(le),cf=le.setAutoFreeze.bind(le),lf=le.setUseStrictShallowCopy.bind(le),uf=le.applyPatches.bind(le),ff=le.createDraft.bind(le),df=le.finishDraft.bind(le);var m={LITERAL:0,VARIABLE:1,INTERPOLATION:2,FUNCTION:3,BINARY:4,UNARY:5,CONDITIONAL:6,LOOP:7,OBJECT:8,ARRAY:9,PARTIAL:10,PATH_REFERENCE:11},O={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},Ye={NOT:0};var E=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},ne=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var fr=e=>{if(!e||e.trim()==="")throw new E("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let r=e.includes("===")?"==":"!=";throw new E(`Invalid comparison operator '${e.includes("===")?"===":"!=="}' - did you mean '${r}'? (got: '${e}')`)}let t=["<",">","<=",">=","==","!="];for(let r of t)if(e.trim().endsWith(r))throw new E(`Incomplete comparison expression - missing right operand (got: '${e}')`)},Dn=e=>{if(e.trim().endsWith(" in"))throw new E(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new E(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,r]=e.split(" in ");if(!r||r.trim()==="")throw new E(`Missing iterable expression after 'in' (got: '$for ${e}')`);let n=t.includes(",")?t.split(",").map(o=>o.trim()):[t.trim()];for(let o of n){if(!o)throw new E(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new E(`Invalid loop syntax (got: '$for ${e}')`)}};var Pn=(e,t,r=!1)=>{if(t===null)return new ne(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new ne(`Cannot iterate over undefined value at '$for ${e}'`);let n=typeof t;return r?new ne(`Cannot iterate over non-array value in loop '${e}' - got ${n} instead`):new ne(`Cannot iterate over non-array value (got: ${n}) at '$for ${e}'`)},Nn=(e,t)=>{let r=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new ne(`Unknown function '${e}' (${r})`)};var Bi=(e,t,r={})=>{let n={},o={};r&&typeof r=="object"&&(r.functions!==void 0||r.partials!==void 0?(n=r.functions||{},o=r.partials||{}):typeof r=="object"&&(n=r));let s=L(e,{functions:n,partials:o},t,{});return s===void 0?{}:s},L=(e,t,r,n)=>{let o=t.functions||t;if(e.var&&!e.type)return J(e.var,r,n);if(e.type===m.LITERAL)return e.value;if(e.type===m.VARIABLE)return J(e.path,r,n);if(e.type===m.INTERPOLATION)return Wi(e.parts,t,r,n);switch(e.type){case m.FUNCTION:return jn(e,t,r,n);case m.BINARY:return Mn(e,t,r,n);case m.UNARY:return Fn(e,t,r,n);case m.CONDITIONAL:return Hi(e,t,r,n);case m.LOOP:return Xi(e,t,r,n);case m.OBJECT:return Zi(e,t,r,n);case m.ARRAY:return es(e,t,r,n);case m.PARTIAL:return ts(e,t,r,n);case m.PATH_REFERENCE:return rs(e,t,r,n);default:throw new Error(`Unknown node type: ${e.type}`)}},Vn=new Map,zi=e=>{let t=[],r="",n=!1;for(let o=0;o<e.length;o++){let i=e[o];if(i==="[")r&&(t.push({type:"property",value:r}),r=""),n=!0;else if(i==="]"){if(n&&r){let s=r.trim();if(/^\d+$/.test(s))t.push({type:"index",value:parseInt(s,10)});else if(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'")){let l=s.slice(1,-1);t.push({type:"property",value:l})}else t.push({type:"property",value:s});r=""}n=!1}else r+=i}return r&&t.push({type:"property",value:r}),t},J=(e,t,r)=>{if(!e)return;if(e in r)return r[e];let n=Vn.get(e);if(!n){let i=[],s="",l=0;for(let c=0;c<e.length;c++){let a=e[c];a==="["?(l++,s+=a):a==="]"?(l--,s+=a):a==="."&&l===0?s&&(i.push(s),s=""):s+=a}s&&i.push(s),n=[];for(let c of i){let a=zi(c.trim());n.push(...a)}Vn.set(e,n)}let o=t;for(let i=0;i<n.length;i++){let s=n[i];if(s.type==="property"&&s.value in r){o=r[s.value];continue}if(o==null)return;(s.type==="property"||s.type==="index")&&(o=o[s.value])}return o},Wi=(e,t,r,n)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=L(i,t,r,n);o.push(s!=null?String(s):"")}return o.join("")},jn=(e,t,r,n)=>{let o=t.functions||t,i=o[e.name];if(!i)throw Nn(e.name,o);let s=e.args.map(l=>L(l,t,r,n));return i(...s)},Ce=(e,t,r,n)=>{if(e.var&&!e.type)return J(e.var,r,n);switch(e.type){case m.VARIABLE:return J(e.path,r,n);case m.LITERAL:return e.value;case m.BINARY:return Mn(e,t,r,n);case m.UNARY:return Fn(e,t,r,n);case m.FUNCTION:return jn(e,t,r,n);default:return L(e,t,r,n)}},Mn=(e,t,r,n)=>{if(e.op===O.AND||e.op===O.OR){let s=Ce(e.left,t,r,n),l=Ce(e.right,t,r,n);switch(e.op){case O.AND:return s&&l;case O.OR:return s||l}}let o=L(e.left,t,r,n),i=L(e.right,t,r,n);switch(e.op){case O.EQ:return o==i;case O.NEQ:return o!=i;case O.GT:return o>i;case O.LT:return o<i;case O.GTE:return o>=i;case O.LTE:return o<=i;case O.IN:return Array.isArray(i)?i.includes(o):!1;case O.ADD:if(typeof o!="number"||typeof i!="number")throw new ne(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case O.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new ne(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},Fn=(e,t,r,n)=>{let o=e.op===Ye.NOT?Ce(e.operand,t,r,n):L(e.operand,t,r,n);if(e.op===Ye.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},qi=(e,t,r,n)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===m.VARIABLE)if(J(o.path,r,n)){let s=e.bodies[0];if(s.type===m.OBJECT&&s.properties.length<=5){let l={};for(let c of s.properties){let a=c.parsedKey?L(c.parsedKey,t,r,n):c.key,u=c.value;if(u.type===m.LITERAL)l[a]=u.value;else if(u.type===m.VARIABLE)l[a]=J(u.path,r,n);else if(u.type===m.INTERPOLATION){let f=[];for(let d of u.parts)if(typeof d=="string")f.push(d);else if(d.type===m.VARIABLE){let p=J(d.path,r,n);f.push(p!=null?String(p):"")}else{let p=L(d,t,r,n);f.push(p!=null?String(p):"")}l[a]=f.join("")}else l[a]=L(u,t,r,n)}return l}}else{let s=e.bodies[1];if(s.type===m.OBJECT&&s.properties.length<=5){let l={};for(let c of s.properties){let a=c.parsedKey?L(c.parsedKey,t,r,n):c.key,u=c.value;if(u.type===m.LITERAL)l[a]=u.value;else if(u.type===m.VARIABLE)l[a]=J(u.path,r,n);else if(u.type===m.INTERPOLATION){let f=[];for(let d of u.parts)if(typeof d=="string")f.push(d);else if(d.type===m.VARIABLE){let p=J(d.path,r,n);f.push(p!=null?String(p):"")}else{let p=L(d,t,r,n);f.push(p!=null?String(p):"")}l[a]=f.join("")}else l[a]=L(u,t,r,n)}return l}}}return null},Hi=(e,t,r,n)=>{let o=qi(e,t,r,n);if(o!==null)return o;for(let i=0;i<e.conditions.length;i++){let s=e.conditions[i];if(s===null||Ce(s,t,r,n))return L(e.bodies[i],t,r,n)}return Un},Yi=(e,t)=>{let r=e.body,n=e.itemVar;if(r.type===m.CONDITIONAL&&r.conditions.length===1&&r.conditions[0].type===m.VARIABLE){let o=r.conditions[0].path,i=r.bodies[0];if(o.startsWith(n+".")){let s=o.substring(n.length+1);if(i.type===m.OBJECT&&i.properties.length<=5){for(let c of i.properties)if(c.parsedKey)return null;let l=[];for(let c=0;c<t.length;c++){let a=t[c];if(a[s]){let u={};for(let f of i.properties){let d=f.key,p=f.value;if(p.type===m.LITERAL)u[d]=p.value;else if(p.type===m.VARIABLE){let h=p.path;if(h===n)u[d]=a;else if(h.startsWith(n+".")){let g=h.substring(n.length+1);u[d]=a[g]}else return null}else if(p.type===m.INTERPOLATION){let h=[],g=!0;for(let y of p.parts)if(typeof y=="string")h.push(y);else if(y.type===m.VARIABLE){let b=y.path;if(b===n)h.push(a!=null?String(a):"");else if(b.startsWith(n+".")){let A=b.substring(n.length+1),v=a[A];h.push(v!=null?String(v):"")}else{g=!1;break}}else{g=!1;break}if(!g)return null;u[d]=h.join("")}else return null}l.push(u)}}return l}}}return null},Gi=(e,t)=>{let r=e.body,n=e.itemVar,o=Yi(e,t);if(o!==null)return o;if(r.type===m.OBJECT&&r.properties.length<=5&&!r.whenCondition){for(let l of r.properties)if(l.parsedKey)return null;let i=[],s=!0;for(let l of r.properties){let c=l.key,a=l.value;if(a.type===m.LITERAL)i.push({key:c,type:"literal",value:a.value});else if(a.type===m.VARIABLE){let u=a.path;if(u===n)i.push({key:c,type:"item"});else if(u.startsWith(n+".")){let f=u.substring(n.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:c,type:"prop",prop:f});else{s=!1;break}}else{s=!1;break}}else if(a.type===m.INTERPOLATION&&a.parts.length===1){let u=a.parts[0];if(u.type===m.VARIABLE){let f=u.path;if(f===n)i.push({key:c,type:"item_string"});else if(f.startsWith(n+".")){let d=f.substring(n.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:c,type:"prop_string",prop:d});else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}if(s){let l=new Array(t.length);if(i.length===3&&i[0].type==="prop"&&i[0].key==="id"&&i[1].type==="prop_string"&&i[1].key==="title"&&i[2].type==="prop"&&i[2].key==="completed")for(let c=0;c<t.length;c++){let a=t[c];l[c]={id:a.id,title:a.title!=null?String(a.title):"",completed:a.completed}}else for(let c=0;c<t.length;c++){let a=t[c],u={};for(let f of i)if(f.type==="literal")u[f.key]=f.value;else if(f.type==="item")u[f.key]=a;else if(f.type==="prop")u[f.key]=a[f.prop];else if(f.type==="item_string")u[f.key]=a!=null?String(a):"";else if(f.type==="prop_string"){let d=a[f.prop];u[f.key]=d!=null?String(d):""}l[c]=u}return l}}return null},Ki=(e,t,r,n,o)=>{let i=[],s=e.body;if(s.type===m.OBJECT&&s.fast!==!1){let l=e.itemVar,c=e.indexVar;for(let a=0;a<o.length;a++){let u=o[a],f={},d={...n,[l]:u,...c&&{[c]:a}};d.__paths__||(d.__paths__=n.__paths__||{});let p=e.iterable.path||"";if(n&&n.__paths__&&p){let h=p.split("."),g=h[0];g in n.__paths__&&(p=n.__paths__[g],h.length>1&&(p+="."+h.slice(1).join(".")))}d.__paths__={...d.__paths__,[l]:`${p}[${a}]`,...c&&{[c]:a}};for(let h of s.properties){let g=h.parsedKey?L(h.parsedKey,t,r,d):h.key,y=h.value;if(y.type===m.LITERAL)f[g]=y.value;else if(y.type===m.VARIABLE){let b=y.path;if(b===l)f[g]=u;else if(b===c)f[g]=a;else if(b.startsWith(l+".")){let A=b.substring(l.length+1);!A.includes(".")&&!A.includes("[")?f[g]=u[A]:f[g]=J(b,r,{...n,[l]:u,...c&&{[c]:a}})}else f[g]=J(b,r,{...n,[l]:u,...c&&{[c]:a}})}else if(y.type===m.INTERPOLATION){let b=[];for(let A of y.parts)if(typeof A=="string")b.push(A);else if(A.type===m.VARIABLE){let v=A.path,S;if(v===l)S=u;else if(v===c)S=a;else if(v.startsWith(l+".")){let T=v.substring(l.length+1);!T.includes(".")&&!T.includes("[")?S=u[T]:S=J(v,r,{...n,[l]:u,...c&&{[c]:a}})}else S=J(v,r,{...n,[l]:u,...c&&{[c]:a}});b.push(S!=null?String(S):"")}else{let v={...n,[l]:u,...c&&{[c]:a}},S=L(A,t,r,v);b.push(S!=null?String(S):"")}f[g]=b.join("")}else{let b={...n,[l]:u,...c&&{[c]:a}};f[g]=L(y,t,r,b)}}i.push(f)}return i}return null},Ji=(e,t,r)=>{let n=e.body;if(n.type===m.OBJECT&&n.properties.length===1&&n.properties[0].key==="$if item.visible"){let i=n.properties[0].value;if(i.type===m.CONDITIONAL&&i.conditions.length===1&&i.conditions[0].type===m.VARIABLE&&i.conditions[0].path==="item.visible"){let s=i.bodies[0];if(s.type===m.OBJECT&&s.properties.length===2){let l=s.properties[0],c=s.properties[1];if(l.key==="id"&&l.value.type===m.VARIABLE&&l.value.path==="item.id"&&c.key==="$if item.highlighted"&&c.value.type===m.CONDITIONAL){let a=[];for(let u=0;u<t.length;u++){let f=t[u];if(f.visible){let d={id:f.id};f.highlighted?(d.highlight=!0,d.message=`This item is highlighted: ${f.name}`):(d.highlight=!1,d.message=f.name),a.push(d)}}return a}}}}return null},Xi=(e,t,r,n)=>{let o=L(e.iterable,t,r,n);if(!Array.isArray(o)){let a,u=!1;if(e.iterable.type===m.FUNCTION){u=!0;let d=e.iterable.args.map(p=>p.type===m.LITERAL?typeof p.value=="string"?`'${p.value}'`:String(p.value):p.type===m.VARIABLE?p.path:p.type===m.FUNCTION?`${p.name}(...)`:"?").join(", ");a=`${e.iterable.name}(${d})`}else a=e.iterable.path||"undefined";let f=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${a}`;throw Pn(f,o,u)}if(!e.indexVar){let a=Ji(e,o,e.itemVar);if(a!==null)return a}if(!e.indexVar){let a=Gi(e,o);if(a!==null)return a}let i=Ki(e,t,r,n,o);if(i!==null)return i;let s=[],l=e.iterable.path||"";if(n&&n.__paths__&&l){let a=l.split("."),u=a[0];u in n.__paths__&&(l=n.__paths__[u],a.length>1&&(l+="."+a.slice(1).join(".")))}let c=!1;e.body.type===m.ARRAY&&(e.body.items.length<=1?c=!1:c=e.body._shouldPreserveArray??=e.body.items.some(a=>a.type===m.OBJECT&&a.properties.some(u=>u.key.startsWith("$if ")||u.key.startsWith("$when "))));for(let a=0;a<o.length;a++){let u=e.indexVar?{...n,[e.itemVar]:o[a],[e.indexVar]:a}:{...n,[e.itemVar]:o[a]};u.__paths__||(u.__paths__=n.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${l}[${a}]`},e.indexVar&&(u.__paths__[e.indexVar]=a);let f=L(e.body,t,r,u);if(Array.isArray(f)&&f.length===1&&!c){let d=f[0];s.push(d===void 0?{}:d)}else s.push(f===void 0?{}:f)}return s},Qi=(e,t,r,n)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?L(o.parsedKey,t,r,n):o.key,s=o.value;if(s.type===m.OBJECT&&s.properties.length<=10&&!s.whenCondition){let l={},c={},a=!0;for(let u of s.properties){let f=u.parsedKey?L(u.parsedKey,t,r,n):u.key,d=u.value;if(d.type===m.LITERAL)c[f]=d.value;else if(d.type===m.VARIABLE)c[f]=J(d.path,r,n);else if(d.type===m.INTERPOLATION){let p=[];for(let h of d.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let g=J(h.path,r,n);p.push(g!=null?String(g):"")}else{a=!1;break}if(!a)break;c[f]=p.join("")}else if(d.type===m.OBJECT&&d.properties.length<=5){let p={};for(let h of d.properties){let g=h.key,y=h.value;if(y.type===m.LITERAL)p[g]=y.value;else if(y.type===m.VARIABLE)p[g]=J(y.path,r,n);else if(y.type===m.INTERPOLATION){let b=[];for(let A of y.parts)if(typeof A=="string")b.push(A);else if(A.type===m.VARIABLE){let v=J(A.path,r,n);b.push(v!=null?String(v):"")}else{a=!1;break}if(!a)break;p[g]=b.join("")}else{a=!1;break}}if(!a)break;c[f]=p}else{a=!1;break}}if(a)return l[i]=c,l}}return null},Zi=(e,t,r,n)=>{let o=t.functions||t;if(e.whenCondition&&!Ce(e.whenCondition,o,r,n))return;let i=Qi(e,t,r,n);if(i!==null)return i;if(e.fast){let a={};for(let u of e.properties){let f=u.parsedKey?L(u.parsedKey,t,r,n):u.key,d=u.value;if(d.type===m.LITERAL)a[f]=d.value;else if(d.type===m.VARIABLE)a[f]=J(d.path,r,n);else if(d.type===m.INTERPOLATION){let p=[];for(let h of d.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let g=J(h.path,r,n);p.push(g!=null?String(g):"")}else{let g=L(h,t,r,n);p.push(g!=null?String(g):"")}a[f]=p.join("")}else a[f]=L(d,t,r,n)}return a}let s={},l=null,c=!1;for(let a of e.properties)if(!a.key.startsWith("$if ")&&!a.key.match(/^\$if\s+\w+.*:?$/)&&!a.key.startsWith("$elif")&&!a.key.startsWith("$else")&&!a.key.startsWith("$for ")){c=!0;break}for(let a of e.properties)if(a.key.startsWith("$if ")||a.key.match(/^\$if\s+\w+.*:?$/)){let u=L(a.value,t,r,n);if(!c&&u!==null&&u!==void 0)return Array.isArray(u)&&u.length===1?u[0]:u;typeof u=="object"&&u!==null&&!Array.isArray(u)&&Object.assign(s,u)}else if(a.key.startsWith("$for ")){if(e.properties.length===1)return L(a.value,t,r,n)}else{let u=a.value;if(u&&u.type===m.OBJECT&&u.properties){let f=u.properties.find(d=>d.key.startsWith("$for "));if(f){let d=L(f.value,t,r,n);d!==void 0&&(s[a.key]=d)}else{let d=L(a.value,t,r,n);d!==void 0&&(s[a.key]=d)}}else{let f=a.parsedKey?L(a.parsedKey,t,r,n):a.key,d=L(a.value,t,r,n);d!==void 0&&(s[f]=d)}}return s},Un={},es=(e,t,r,n)=>{let o=[];for(let i of e.items)if(i.type===m.LOOP){let s=L(i,t,r,n);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=L(i,t,r,n);s!==Un&&s!==void 0&&o.push(s)}return o},ts=(e,t,r,n)=>{let{name:o,data:i,whenCondition:s}=e,l=t.partials||{},c=t.functions||t;if(s&&!Ce(s,c,r,n))return;if(!l[o])throw new ne(`Partial '${o}' is not defined`);let a=n._partialStack||[];if(a.includes(o))throw new ne(`Circular partial reference detected: ${o}`);let u=l[o],f=r,d={...n,_partialStack:[...a,o]};if(n){f={...r};for(let p of Object.keys(n))p.startsWith("_")||(f[p]=n[p])}if(i){let p=L(i,t,r,n);f={...f,...p}}return L(u,t,f,d)},rs=(e,t,r,n)=>{let{path:o}=e,i=o.split("."),s=i[0],l=i.slice(1);if(!n||!(s in n))throw new ne(`Path reference '#{${o}}' refers to '${s}' which is not a loop variable in the current scope`);if(n.__paths__||(n.__paths__={}),!(s in n.__paths__))throw new ne(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let c=n.__paths__[s];if(typeof c=="number"){if(l.length>0)throw new ne(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(c)}return l.length>0&&(c+="."+l.join(".")),c};var dr=Bi;var ns=/\$\{([^}]*)\}/g,os=/#\{([^}]*)\}/g,zn=(e,t={})=>{let r=e.match(/^(\w+)\((.*)\)$/);if(!r)return{isFunction:!1};let[,n,o]=r,i=is(o,t);return{isFunction:!0,type:m.FUNCTION,name:n,args:i}},is=(e,t={})=>e.trim()?ss(e).map(n=>as(n.trim(),t)):[],ss=e=>{let t=[],r="",n=0,o=!1,i="";for(let s=0;s<e.length;s++){let l=e[s],c=s>0?e[s-1]:"";!o&&(l==='"'||l==="'")?(o=!0,i=l,r+=l):o&&l===i&&c!=="\\"?(o=!1,i="",r+=l):!o&&l==="("?(n++,r+=l):!o&&l===")"?(n--,r+=l):!o&&l===","&&n===0?(t.push(r),r=""):r+=l}return r&&t.push(r),t},as=(e,t={})=>{if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:m.LITERAL,value:e.slice(1,-1)};if(/^-?\d+(\.\d+)?$/.test(e))return{type:m.LITERAL,value:parseFloat(e)};if(e==="true")return{type:m.LITERAL,value:!0};if(e==="false")return{type:m.LITERAL,value:!1};if(e==="null")return{type:m.LITERAL,value:null};let r=zn(e,t);if(r.isFunction)return{type:r.type,name:r.name,args:r.args};let n=e.trim(),o=[{op:" + ",type:"ADD"},{op:" - ",type:"SUBTRACT"}],i=-1,s=null;for(let{op:l,type:c}of o){let a=0;for(;a<n.length;){let u=Ne(n.substring(a),l);if(u===-1)break;let f=a+u;f>i&&(i=f,s={op:l,type:c}),a=f+l.length}}if(i!==-1)try{return X(n,t)}catch{return{type:m.VARIABLE,path:n}}return{type:m.VARIABLE,path:n}},Wn=/^\w+\(.*\)$/,cs=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,ls=e=>{if(!(!e||e.trim()===""||Wn.test(e))&&cs.test(e))throw e.includes("?")&&e.includes(":")?new E(`Complex expressions not supported in variable replacements - consider calculating the value in your data instead. Offending expression: "${e}"`):e.includes("||")||e.includes("&&")||e.includes("??")?new E(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new E(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},Bn=e=>{let t=e.trim();if(Wn.test(t))throw new E(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new E(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new E(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new E(`Logical operators not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("?")&&t.includes(":"))throw new E(`Complex expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);return{type:m.PATH_REFERENCE,path:t}},it=(e,t={})=>{let r=e.trim();ls(r);let n=zn(r,t);if(n.isFunction)return{type:n.type,name:n.name,args:n.args};if(r.includes("[")&&!/[\s+\-*/%|&?:]/.test(r)){let o=0;for(let i of r)i==="["?o++:i==="]"&&o--;if(o!==0)throw new Error("Invalid array index syntax")}return{type:m.VARIABLE,path:r}},pr=(e,t={})=>{let r=e,n=[];(e.includes("\\${")||e.includes("\\#{"))&&(r=e.replace(/\\\\(\$\{[^}]*\})/g,"\\DOUBLE_ESC_VAR$1"),r=r.replace(/\\\\(#\{[^}]*\})/g,"\\DOUBLE_ESC_PATH$1"),r=r.replace(/\\(\$\{[^}]*\})/g,(a,u)=>{let f=`__ESCAPED_${n.length}__`;return n.push(u),f}),r=r.replace(/\\(#\{[^}]*\})/g,(a,u)=>{let f=`__ESCAPED_${n.length}__`;return n.push(u),f}),r=r.replace(/\\DOUBLE_ESC_VAR/g,"\\"),r=r.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...r.matchAll(ns)],i=[...r.matchAll(os)],s=[...o.map(a=>({match:a,type:"variable"})),...i.map(a=>({match:a,type:"pathref"}))].sort((a,u)=>a.match.index-u.match.index);if(s.length===0){let a=r;for(let u=0;u<n.length;u++)a=a.replace(`__ESCAPED_${u}__`,n[u]);return{type:m.LITERAL,value:a}}if(s.length===1&&s[0].match[0]===r&&n.length===0){let{match:a,type:u}=s[0];try{return u==="variable"?it(a[1],t):Bn(a[1])}catch(f){if(f.message==="Invalid array index syntax")return{type:m.LITERAL,value:r};throw f}}let l=[],c=0;for(let{match:a,type:u}of s){let[f,d]=a,p=a.index;if(p>c){let h=r.substring(c,p);for(let g=0;g<n.length;g++)h=h.replace(`__ESCAPED_${g}__`,n[g]);h&&l.push(h)}try{let h;u==="variable"?h=it(d.trim(),t):h=Bn(d.trim()),l.push(h)}catch(h){if(h.message==="Invalid array index syntax")l.push(f);else throw h}c=p+f.length}if(c<r.length){let a=r.substring(c);for(let u=0;u<n.length;u++)a=a.replace(`__ESCAPED_${u}__`,n[u]);a&&l.push(a)}return{type:m.INTERPOLATION,parts:l}};var gr=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Yn=e=>Object.keys(e),Z=e=>e.join("."),Se=(e,t,r)=>{let n=Yn(e).filter(o=>!t.has(o));if(n.length>0)throw new E(`Unexpected key '${n[0]}' in condition JSON at '${Z(r)}'`)},_e=(e,t)=>typeof e=="string"?pr(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?fs(e,t):ds(e,t):{type:m.LITERAL,value:e},us=e=>{let{$each:t,...r}=e;if(typeof t!="string")throw new E("$each value must be a non-empty string");let n=t.trim();if(n==="")throw new E("$each value must be a non-empty string");if(Object.keys(r).length===0)throw new E("Empty $each body not allowed");if(r.$partial!==void 0)throw new E("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${n}`]:r}},fs=(e,t)=>{let r=[],n=!1;for(let o=0;o<e.length;o++){let i=e[o];if(typeof i=="object"&&i!==null&&!Array.isArray(i)){if(i.$each!==void 0)try{let c=us(i),a=Object.keys(c);if(a.length===1&&/^\$for(?::\w+)?\s/.test(a[0])){let u=Hn(a[0],c[a[0]],t,!0);r.push(u),n=!0;continue}}catch(c){throw c instanceof E?c:new E(c.message)}let l=Object.keys(i);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let c=Hn(l[0],i[l[0]],t);r.push(c),n=!0;continue}}let s=_e(i,t);r.push(s),(s.type===m.FUNCTION||s.type===m.CONDITIONAL||s.type===m.LOOP||s.type===m.PARTIAL||s.type===m.OBJECT&&!s.fast||s.type===m.ARRAY&&!s.fast)&&(n=!0)}return{type:m.ARRAY,items:r,fast:!n}},ds=(e,t)=>{let r=[],n=!1,o=null,i=Object.entries(e),s=0;if(e.$partial!==void 0){if(typeof e.$partial!="string")throw new E("$partial value must be a string");if(e.$partial.trim()==="")throw new E("$partial value cannot be an empty string");let c=["$if","$elif","$else","$for"],a=[];for(let[b]of i)for(let A of c)if(b===A||b.startsWith(A+" ")||b.startsWith(A+"#")){a.push(A);break}if(a.length>0)throw new E(`Cannot use $partial with ${a.join(", ")} at the same level. Wrap $partial in a parent object if you need conditionals.`);let{$partial:u,$when:f,...d}=e,p={},h=!1;for(let[b,A]of Object.entries(d)){let v=b;(b.startsWith("\\$")||b.startsWith("$$"))&&(v=b.slice(1)),p[v]=A,h=!0}let g=null;if(h&&(g=_e(p,t),g.type===m.OBJECT)){let b=!1;for(let A of g.properties)if(A.value.type===m.VARIABLE||A.value.type===m.INTERPOLATION||A.value.type===m.FUNCTION||A.value.type===m.CONDITIONAL||A.value.type===m.OBJECT&&!A.value.fast||A.value.type===m.ARRAY&&!A.value.fast){b=!0;break}b&&(g.fast=!1)}let y={type:m.PARTIAL,name:u,data:g};return f!==void 0&&(y.whenCondition=qn(f,t)),y}for(let[c,a]of i)if(c==="$when"){if(o!==null)throw new E("Multiple '$when' directives on the same object are not allowed");if(a==null)throw new E("Missing condition expression after '$when'");o=qn(a,t),n=!0}else if(c.startsWith("$when#")||c.startsWith("$when "))throw new E("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<i.length;){let[c,a]=i[s];if(c==="$when"){s++;continue}if(c==="$each")throw new E("$each can only be used inside arrays");if(c.startsWith("$if ")||c.match(/^\$if#\w+\s/)||c.match(/^\$if\s+\w+.*:$/)){let u=ps(i,s,t);r.push({key:c,value:u.node}),n=!0,s=u.nextIndex}else if(/^\$for(?::\w+)?\s/.test(c)){let u=c.match(/^\$for(?::(\w+))?\s/)?.[1]||"",f=u?`:${u}`:"";throw new E(`$for loops must be inside arrays - use '- $for${f} item in items:' instead of '$for${f} item in items:'. For cleaner object generation syntax, consider using $each.`)}else{if(c.startsWith("$elif ")||c.startsWith("$else"))throw new E(`'${c.split(" ")[0]}' without matching '$if'`);if(c==="$if"||c==="$if:")throw new E("Missing condition expression after '$if'");{let u=_e(a,t);(u.type===m.FUNCTION||u.type===m.CONDITIONAL||u.type===m.PARTIAL||u.type===m.OBJECT&&!u.fast||u.type===m.ARRAY&&!u.fast)&&(n=!0);let f=pr(c,t),d={key:c,value:u};(f.type!==m.LITERAL||f.value!==c)&&(d.parsedKey=f),r.push(d),s++}}}let l={type:m.OBJECT,properties:r,fast:!n};return o&&(l.whenCondition=o),l},ps=(e,t,r={})=>{let n=[],o=[],i=t,[s,l]=e[i],c=null,a;if(s.startsWith("$if#")){let f=s.match(/^\$if#(\w+)\s+(.+)$/);if(f)c=f[1],a=f[2];else throw new E(`Invalid conditional syntax: ${s}`)}else a=s.substring(4),a.endsWith(":")&&(a=a.slice(0,-1).trim());fr(a);let u=X(a,r);for(n.push(u),o.push(_e(l,r)),i++;i<e.length;){let[f,d]=e[i],p=!1,h;if(c?f.startsWith(`$elif#${c} `)?(h=f.substring(`$elif#${c} `.length),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(f===`$else#${c}`||f===`$else#${c}:`)&&(p=!0,h=null):f.startsWith("$elif ")?(h=f.substring(6),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(f==="$else"||f==="$else:")&&(p=!0,h=null),p){if(h===null)n.push(null);else{fr(h);let g=X(h,r);n.push(g)}if(o.push(_e(d,r)),i++,h===null)break}else break}return{node:{type:m.CONDITIONAL,conditions:n,bodies:o,id:c},nextIndex:i}},hr={eq:O.EQ,neq:O.NEQ,gt:O.GT,gte:O.GTE,lt:O.LT,lte:O.LTE,in:O.IN,add:O.ADD,sub:O.SUBTRACT},mr={all:O.AND,any:O.OR},hs=new Set(["var","literal","call","not",...Object.keys(hr),...Object.keys(mr)]),ms=(e,t,r)=>{if(!Array.isArray(e))throw new E(`Condition JSON operator '${t}' at '${Z(r)}' requires an array`);if(e.length!==2)throw new E(`Condition JSON operator '${t}' at '${Z(r)}' requires exactly 2 operands`);return e},gs=(e,t,r,n,o)=>{if(!Array.isArray(e))throw new E(`Condition JSON operator '${t}' at '${Z(o)}' requires an array`);if(e.length===0)throw new E(`Condition JSON operator '${t}' at '${Z(o)}' requires at least 1 condition`);return e.map((s,l)=>Ie(s,n,[...o,l])).reduce((s,l)=>({type:m.BINARY,op:r,left:s,right:l}))},ys=(e,t,r)=>{let n,o;if(typeof e.call=="string")n=e.call,o=e.args??[],Se(e,new Set(["call","args"]),r);else if(gr(e.call))n=e.call.name,o=e.call.args??[],Se(e,new Set(["call"]),r),Se(e.call,new Set(["name","args"]),[...r,"call"]);else throw new E(`Condition JSON call at '${Z(r)}' requires a function name`);if(typeof n!="string"||n.trim()==="")throw new E(`Condition JSON call at '${Z(r)}' requires a non-empty function name`);if(!/^\w+$/.test(n))throw new E(`Invalid condition JSON function name '${n}' at '${Z(r)}'`);if(!Array.isArray(o))throw new E(`Condition JSON call '${n}' at '${Z(r)}' requires args to be an array`);return{type:m.FUNCTION,name:n,args:o.map((i,s)=>Ie(i,t,[...r,"args",s]))}},Ie=(e,t={},r=["$when"])=>{if(typeof e=="string"||typeof e=="number"||typeof e=="boolean"||e===null)return{type:m.LITERAL,value:e};if(Array.isArray(e))throw new E(`Condition JSON array at '${Z(r)}' must be wrapped in an operator or { literal: [...] }`);if(!gr(e))throw new E(`Invalid condition JSON value at '${Z(r)}'`);let n=Yn(e);if(n.length===0)throw new E(`Condition JSON object at '${Z(r)}' must contain an operator`);let o=n.filter(s=>hs.has(s));if(o.length===0)throw new E(`Unknown condition JSON operator '${n[0]}' at '${Z(r)}'`);if(o.length>1)throw new E(`Condition JSON at '${Z(r)}' must contain exactly one operator`);let i=o.includes("call")?"call":o[0];if(i==="var"){if(Se(e,new Set(["var"]),r),typeof e.var!="string"||e.var.trim()==="")throw new E(`Condition JSON var at '${Z(r)}' requires a non-empty path`);return{type:m.VARIABLE,path:e.var}}if(i==="literal")return Se(e,new Set(["literal"]),r),{type:m.LITERAL,value:e.literal};if(i==="call")return ys(e,t,r);if(i==="not")return Se(e,new Set(["not"]),r),{type:m.UNARY,op:Ye.NOT,operand:Ie(e.not,t,[...r,"not"])};if(i in mr)return Se(e,new Set([i]),r),gs(e[i],i,mr[i],t,[...r,i]);if(i in hr){Se(e,new Set([i]),r);let s=ms(e[i],i,[...r,i]);return{type:m.BINARY,op:hr[i],left:Ie(s[0],t,[...r,i,0]),right:Ie(s[1],t,[...r,i,1])}}throw new E(`Unknown condition JSON operator '${i}' at '${Z(r)}'`)},qn=(e,t={})=>{if(e==null)throw new E("Missing condition expression after '$when'");if(typeof e=="string"){if(e.trim()==="")throw new E("Empty condition expression after '$when'");return X(e,t)}return gr(e)||Array.isArray(e)?Ie(e,t):{type:m.LITERAL,value:e}},X=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let a=e.slice(1,-1),u=0,f=!0;for(let d=0;d<a.length;d++)if(a[d]==="("?u++:a[d]===")"&&u--,u<0){f=!1;break}if(f&&u===0)return X(a,t)}let r=Ne(e,"||");if(r!==-1)return{type:m.BINARY,op:O.OR,left:X(e.substring(0,r).trim(),t),right:X(e.substring(r+2).trim(),t)};let n=Ne(e,"&&");if(n!==-1)return{type:m.BINARY,op:O.AND,left:X(e.substring(0,n).trim(),t),right:X(e.substring(n+2).trim(),t)};let o=[{op:">=",type:O.GTE},{op:"<=",type:O.LTE},{op:"==",type:O.EQ},{op:"!=",type:O.NEQ},{op:">",type:O.GT},{op:"<",type:O.LT},{op:" in ",type:O.IN}];for(let{op:a,type:u}of o){let f=Ne(e,a);if(f!==-1)return{type:m.BINARY,op:u,left:X(e.substring(0,f).trim(),t),right:X(e.substring(f+a.length).trim(),t)}}let i=-1,s=null,l=[{op:" + ",type:O.ADD},{op:" - ",type:O.SUBTRACT}];for(let{op:a,type:u}of l){let f=0;for(;f<e.length;){let d=Ne(e.substring(f),a);if(d===-1)break;let p=f+d;p>i&&(i=p,s={op:a,type:u}),f=p+a.length}}if(i!==-1&&s)return{type:m.BINARY,op:s.type,left:X(e.substring(0,i).trim(),t),right:X(e.substring(i+s.op.length).trim(),t)};let c=[" * "," / "," % "];for(let a of c)if(Ne(e,a)!==-1)throw new E(`Arithmetic operations are not allowed in conditionals: "${a}"`);return e.startsWith("!")?{type:m.UNARY,op:Ye.NOT,operand:X(e.substring(1).trim(),t)}:Gn(e,t)},Ne=(e,t)=>{let r=0,n=0;for(;n<=e.length-t.length;){if(e[n]==="(")r++;else if(e[n]===")")r--;else if(r===0&&e.substring(n,n+t.length)===t)return n;n++}return-1},bs=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}},Gn=(e,t)=>{let r=e.trim();if(r.match(/^(\w+)\((.*)\)$/))return it(r,t);let o=bs(r);if(o.type===m.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(r))return{type:m.VARIABLE,path:r};try{return it(r,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},Is=(e,t=!1)=>{let r=t?"$each":"$for";try{Dn(e)}catch(n){if(n instanceof E&&t){let o=n.message.replace(/\$for/g,"$each");throw new E(o.replace("Parse Error: ",""))}throw n}},Hn=(e,t,r,n=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let y=n?"$each":"$for";throw new E(`Invalid loop syntax (got: '${e.replace("$for",y)}')`)}let s=i[1],l=i[2].trim();Is(l,n);let c=l.match(/^(.+?)\s+in\s+(.+)$/);if(!c){let y=n?"$each":"$for";throw new E(`Invalid loop syntax - missing 'in' keyword (got: '${y} ${l}')`)}let a=c[1].trim(),u=c[2].trim(),f,d=null;if(a.includes(",")){let y=a.split(",").map(b=>b.trim());if(y.length!==2)throw new E(`Invalid loop variables: ${a}. Expected format: "item" or "item, index"`);f=y[0],d=y[1]}else f=a;let p=["this","undefined","null","true","false"];if(p.includes(f))throw new E(`Reserved variable name: ${f}`);if(d&&p.includes(d))throw new E(`Reserved variable name: ${d}`);let h=Gn(u,r),g=_e(t,r);return{type:m.LOOP,itemVar:f,indexVar:d,iterable:h,body:g,flatten:s!=="nested"}};var As=(e,t={})=>{let{functions:r={}}=t;return _e(e,r)},Ot=As;var st={};ki(st,{now:()=>ws});var ws=()=>Date.now();var Es=(e,t,r={})=>{let{functions:n={},partials:o={}}=r,i={...st,...n},s=Ot(e,{functions:i}),l={};for(let[c,a]of Object.entries(o))l[c]=Ot(a,{functions:i});return dr(s,t,{functions:i,partials:l})},se=Es;var vs=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",xs=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,Cs=(e,t)=>{if(vs(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new E("Empty condition expression");return X(e,t)}return Ie(e,t)},Ss=(e,t={},r={})=>{let n=xs(r),o={...st,...n},i=Cs(e,o);return!!Ce(i,{functions:o,partials:{}},t,{})},yr=Ss;var ct=(e,t={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return yr(e,t)},eo=(e,t,r={})=>{let n=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=c=>c,transformActionFirstArgument:l=c=>c}=r;for(let[c,a]of Object.entries(t))c!=="createInitialState"&&(c.startsWith("select")?o[c]=(...u)=>a(s(n),...u):i[c]=(...u)=>{let f;return n=ur(n,p=>{let h=a(l(p),...u);f=h!==void 0&&!ce(h)?h:void 0}),f});return{...o,...i}},kt=(e,t)=>r=>{let n=e(),o=Array.isArray(r)?r:[r];return ur(n,i=>{o.forEach(s=>{t.forEach(l=>{l(i,s)})})})};var _s=(e,t)=>{if(e.default!==void 0)return e.default;let r=["number","boolean","string","object"];if(!r.includes(e.type))throw new Error(`Invalid variable type: ${e.type} for variable ${t}. Expected one of: ${r.join(", ")}`);switch(e.type){case"number":return 0;case"boolean":return!1;case"string":return"";case"object":return{}}},he=(e,t)=>Object.prototype.hasOwnProperty.call(e??{},t),at=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),to=e=>{let t=ce(e)?Pe(e):e;return structuredClone(t)},Re=e=>he(e,"computed"),Ge=(e={},t={})=>Object.fromEntries(Object.entries(e??{}).filter(([r])=>!Re(t[r]))),Rs=e=>String(e).replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean),br=(e,t)=>{let r=e;for(let n of t){if(r==null)return;r=r[n]}return r},Os=(e,t={})=>{if(typeof e!="string"||e.trim()==="")throw new Error("Computed expression var requires a non-empty string path");let r=Rs(e),[n,o,...i]=r;if(n==="variables"){if(!o)return t.variables;let s=typeof t.resolveVariable=="function"?t.resolveVariable(o):t.variables?.[o];return br(s,i)}return n==="runtime"?br(t.runtime,r.slice(1)):br(t,r)},Ls=(e,t,r)=>{if(!Array.isArray(t))throw new Error(`Computed expression operator "${e}" requires an array`);if(r!==void 0&&t.length!==r)throw new Error(`Computed expression operator "${e}" requires ${r} operand(s)`)},Kn=(e,t)=>{if(!Array.isArray(t))throw new Error(`Computed expression operator "${e}" requires an array`);if(t.length===0)throw new Error(`Computed expression operator "${e}" requires at least one operand`)},$s=(e,t)=>{if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Computed expression operator "${e}" requires finite numeric operands`)},pe=(e,t,r,n)=>(Ls(e,t,n),t.map(o=>$t(o,r))),fe=(e,t,r,n)=>{let o=pe(e,t,r,n);return o.forEach(i=>$s(e,i)),o},ks=(e,t,r)=>{switch(e){case"var":return Os(t,r);case"add":{let[n,o]=fe(e,t,r,2);return n+o}case"sub":{let[n,o]=fe(e,t,r,2);return n-o}case"mul":{let[n,o]=fe(e,t,r,2);return n*o}case"div":{let[n,o]=fe(e,t,r,2);return n/o}case"mod":{let[n,o]=fe(e,t,r,2);return n%o}case"neg":{let[n]=fe(e,t,r,1);return-n}case"round":{let[n]=fe(e,t,r,1);return Math.round(n)}case"floor":{let[n]=fe(e,t,r,1);return Math.floor(n)}case"ceil":{let[n]=fe(e,t,r,1);return Math.ceil(n)}case"min":{let[n,o]=fe(e,t,r,2);return Math.min(n,o)}case"max":{let[n,o]=fe(e,t,r,2);return Math.max(n,o)}case"clamp":{let[n,o,i]=fe(e,t,r,3);return Math.min(i,Math.max(o,n))}case"eq":{let[n,o]=pe(e,t,r,2);return n==o}case"neq":{let[n,o]=pe(e,t,r,2);return n!=o}case"gt":{let[n,o]=pe(e,t,r,2);return n>o}case"gte":{let[n,o]=pe(e,t,r,2);return n>=o}case"lt":{let[n,o]=pe(e,t,r,2);return n<o}case"lte":{let[n,o]=pe(e,t,r,2);return n<=o}case"in":{let[n,o]=pe(e,t,r,2);return Array.isArray(o)?o.includes(n):!1}case"and":case"all":return Kn(e,t),t.every(n=>!!$t(n,r));case"or":case"any":return Kn(e,t),t.some(n=>!!$t(n,r));case"not":{let[n]=pe(e,t,r,1);return!n}case"length":{let[n]=pe(e,t,r,1);return typeof n=="string"||Array.isArray(n)?n.length:at(n)?Object.keys(n).length:0}case"includes":{let[n,o]=pe(e,t,r,2);return typeof n=="string"||Array.isArray(n)?n.includes(o):!1}case"literal":return to(t);default:throw new Error(`Unknown computed expression operator: ${e}`)}},$t=(e,t={})=>{if(e===null||typeof e!="object")return e;if(Array.isArray(e))throw new Error("Computed expression arrays are not valid; use value for literal arrays");let r=Object.entries(e);if(r.length!==1)throw new Error("Computed expression objects must contain exactly one operator");let[[n,o]]=r;return ks(n,o,t)},Ts=(e,t={})=>ct(e,{variables:t.variables,runtime:t.runtime}),Ds=(e,t)=>{if(!at(e))throw new Error(`${t} must be an object`);let r=he(e,"expr"),n=he(e,"value");if(r===n)throw new Error(`${t} must contain exactly one of expr or value`)},Ir=(e,t,r)=>(Ds(e,t),he(e,"value")?to(e.value):$t(e.expr,r)),Ps=(e,t={},r="unknown")=>{if(!at(e))throw new Error(`Computed variable "${r}" computed must be an object`);let n=he(e,"expr"),o=he(e,"value");if(he(e,"branches")){if(n||o)throw new Error(`Computed variable "${r}" cannot combine branches with expr or value`);if(!Array.isArray(e.branches))throw new Error(`Computed variable "${r}" branches must be an array`);if(e.branches.length===0)throw new Error(`Computed variable "${r}" branches must not be empty`);if(!at(e.default))throw new Error(`Computed variable "${r}" requires default`);for(let s=0;s<e.branches.length;s+=1){let l=e.branches[s];if(!at(l))throw new Error(`Computed variable "${r}" branch ${s} must be an object`);if(!he(l,"when"))throw new Error(`Computed variable "${r}" branch ${s} requires when`);if(Ts(l.when,t))return Ir(l,`Computed variable "${r}" branch ${s}`,t)}return Ir(e.default,`Computed variable "${r}" default`,t)}if(n===o)throw new Error(`Computed variable "${r}" must contain exactly one of expr, value, or branches`);return Ir(e,`Computed variable "${r}"`,t)},Ns=(e,t,r)=>{switch(t){case"number":if(typeof r!="number"||!Number.isFinite(r))throw new Error(`Computed variable "${e}" expected type number, got ${Array.isArray(r)?"array":typeof r}`);return;case"boolean":if(typeof r!="boolean")throw new Error(`Computed variable "${e}" expected type boolean, got ${Array.isArray(r)?"array":typeof r}`);return;case"string":if(typeof r!="string")throw new Error(`Computed variable "${e}" expected type string, got ${Array.isArray(r)?"array":typeof r}`);return;case"object":if(r===null||typeof r!="object")throw new Error(`Computed variable "${e}" expected type object, got ${typeof r}`);return;default:throw new Error(`Invalid variable type: ${t} for computed variable ${e}`)}},Tt=({variables:e={},runtime:t={},variableConfigs:r={},eager:n=!0}={})=>{let o=Ge(e,r),i=Object.entries(r).filter(([,f])=>Re(f)).map(([f])=>f),s={},l=[],c=f=>{if(he(s,f))return s[f];let d=r[f];if(!Re(d))return o[f];let p=l.indexOf(f);if(p>=0){let h=[...l.slice(p),f].join(" -> ");throw new Error(`Computed variable cycle detected: ${h}`)}l.push(f);try{let h=Ps(d.computed,u,f);return Ns(f,d.type,h),s[f]=h,h}finally{l.pop()}},a=new Proxy({},{get:(f,d)=>{if(typeof d=="string")return c(d)},has:(f,d)=>typeof d=="string"&&(he(o,d)||i.includes(d)),ownKeys:()=>[...new Set([...Object.keys(o),...i])],getOwnPropertyDescriptor:(f,d)=>{if(!(typeof d!="string"||!he(o,d)&&!i.includes(d)))return{enumerable:!0,configurable:!0}}}),u={variables:a,runtime:t,resolveVariable:c};return n?(i.forEach(f=>{c(f)}),{...o,...s}):a},Vs=({variables:e={},runtime:t={},variableConfigs:r,projectData:n}={})=>Tt({variables:e,runtime:t,variableConfigs:r??n?.resources?.variables??{},eager:!0}),Er=e=>{let t={},r={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([n,o])=>{if(Re(o))return;let i=_s(o,n);o.scope==="context"?t[n]=i:r[n]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}},Dt=(e,t)=>{let r=["context","device","account"];if(!e)throw new Error(`Variable scope is required for variable: ${t}`);if(!r.includes(e))throw new Error(`Invalid variable scope: ${e} for variable ${t}. Expected one of: ${r.join(", ")}`)},Pt=(e,t,r)=>{let n={number:["set","increment","decrement","multiply","divide"],boolean:["set","toggle"],string:["set"],object:["set"]},o=n[e];if(!o)throw new Error(`Unknown variable type: ${e} for variable ${r}`);if(!Object.values(n).flat().includes(t))throw new Error(`Unknown operation: ${t}`);if(!o.includes(t))throw new Error(`Operation "${t}" is not valid for variable "${r}" of type "${e}". Valid operations: ${o.join(", ")}`)},js=2,Jn=12,ro=(e=js)=>{if(!Number.isInteger(e)||e<0||e>Jn)throw new Error(`Operation "divide" requires roundTo to be an integer between 0 and ${Jn}.`);return e},Ms=(e,t)=>{let r=10**t;return Math.round((e+Number.EPSILON)*r)/r},Lt=e=>typeof e=="number"&&Number.isFinite(e),vr=(e,t,r,n,o={})=>{if(e==="number"){if(t==="set"&&!Lt(r))throw new Error(`Operation "set" requires value to be a number for variable "${n}".`);if(t==="multiply"&&!Lt(r))throw new Error(`Operation "multiply" requires value to be a number for variable "${n}".`);if(t==="divide"&&!Lt(r))throw new Error(`Operation "divide" requires value to be a number for variable "${n}".`);if(t==="divide"){if(r===0)throw new Error(`Operation "divide" requires value to be a non-zero number for variable "${n}".`);ro(o.roundTo)}}},Nt=(e,t,r,n={})=>{let o=(s,l,c)=>{let a=s??l;if(!Lt(a))throw new Error(`Operation "${t}" requires ${c} to be a number.`);return a},i=s=>{let l=o(s,void 0,"value");if(l===0)throw new Error(`Operation "${t}" requires value to be a non-zero number.`);return l};switch(t){case"set":return r;case"multiply":return o(e,1,"current value")*o(r,void 0,"value");case"divide":return Ms(o(e,0,"current value")/i(r),ro(n.roundTo));case"increment":return o(e,0,"current value")+o(r,1,"value");case"decrement":return o(e,0,"current value")-o(r,1,"value");case"toggle":return!e;default:throw new Error(`Unknown operation: ${t}`)}};var no=(e,t="DD/MM/YYYY - HH:mm")=>{if(!e)return"";let r=new Date(e),n=o=>String(o).padStart(2,"0");return t.replace("DD",n(r.getDate())).replace("MM",n(r.getMonth()+1)).replace("YYYY",r.getFullYear()).replace("YY",String(r.getFullYear()).slice(-2)).replace("HH",n(r.getHours())).replace("mm",n(r.getMinutes())).replace("ss",n(r.getSeconds()))},Fs=(e,t)=>{let r=i=>{if(!i)return;let s={};i.ui&&(s.ui=i.ui);let l=i.character?.sprite;return l&&Object.keys(l).length>0&&(s.sprite=l),Object.keys(s).length>0?s:void 0},n=r(e),o=r(t);return JSON.stringify(n)===JSON.stringify(o)?null:n&&!o?{changeType:"delete",data:e}:o&&!n?{changeType:"add",data:t}:o&&n?{changeType:"update",data:t}:null},Xn=e=>{if(e?.resourceId===void 0)return;let t={resourceId:e.resourceId};return e.transformId!==void 0&&(t.transformId=e.transformId),e.loop!==void 0&&(t.loop=e.loop),t},Qn=e=>{if(e?.colorId!==void 0)return{colorId:e.colorId}},Zn=(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,Us=(e,t)=>{let r={},n=Zn(Xn(e),Xn(t)),o=Zn(Qn(e),Qn(t));return n&&(r.resource=n),o&&(r.color=o),Object.keys(r).length>0?r:null},xr=(e={},t={})=>{let r={},n=["sfx","voice"],o=l=>{let c=e[l],a=t[l];a&&!c?r[l]={changeType:"add",data:a}:c&&!a?n.includes(l)||(r[l]={changeType:"delete",data:c}):c&&a&&JSON.stringify(c)!==JSON.stringify(a)&&(r[l]={changeType:"update",data:a})},i=Us(e.background,t.background);i&&(r.background=i),o("screen"),o("bgm"),o("voice");let s=Fs(e.dialogue,t.dialogue);return s&&(r.dialogue=s),o("choice"),o("form"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),r},Cr=(e={})=>{let t=structuredClone(e);t.background&&(t.background.animations?.playback?.continuity!=="persistent"&&delete t.background.animations,!t.background.resourceId&&!t.background.colorId&&delete t.background);let r=o=>{t[o]&&(delete t[o].animations,Object.keys(t[o]).length===0&&delete t[o])};r("layout"),r("choice"),r("form"),r("screen"),t.dialogue?.ui&&(delete t.dialogue.ui.animations,Object.keys(t.dialogue.ui).length===0&&delete t.dialogue.ui,Object.keys(t.dialogue).length===0&&delete t.dialogue),t.dialogue?.character?.sprite&&(delete t.dialogue.character.sprite.animations,Object.keys(t.dialogue.character.sprite).length===0&&delete t.dialogue.character.sprite,Object.keys(t.dialogue.character).length===0&&delete t.dialogue.character,Object.keys(t.dialogue).length===0&&delete t.dialogue);let n=(o,i)=>{let s=t[o]?.items;Array.isArray(s)&&(t[o].items=s.map(l=>{let c={...l};return delete c.animations,i(c)?c:null}).filter(Boolean),t[o].items.length===0&&delete t[o])};return n("character",o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId),n("visual",o=>o.resourceId||o.transformId),t},Bs=(e,t)=>{if(!e||!t)return;let r=e;for(let n of t.split(".")){if(r==null||!(n in Object(r)))return;r=r[n]}return r},zs=(e,t)=>{if(typeof e!="string")return e;if(e==="_event"){if(t==null)throw new Error('Action template binding "_event" requires event context "_event".');return t}if(!e.startsWith("_event."))return e;if(t==null)throw new Error(`Action template binding "${e}" requires event context "_event".`);let r=e.slice(7),n=Bs(t,r);if(n===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return n},Ws={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"])},oo=(e,t)=>{let r=e[e.length-1];return r?Ws[r]?.has(t)===!0:!1},Ar=(e,t,r=[])=>Array.isArray(e)?e.map(n=>Ar(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,oo(r,n)?o:Ar(o,t,[...r,n])])):zs(e,t),wr=(e,t,r=[])=>Array.isArray(e)?e.map(n=>wr(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,oo(r,n)?o:wr(o,t,[...r,n])])):typeof e=="string"?se(e,t):e,Sr=(e,t)=>{if(!t)return e;if(Object.prototype.hasOwnProperty.call(t,"event"))throw new Error('Action template context key "event" is no longer supported. Use "_event".');let r=Ar(e,t._event);return wr(r,t)};var oe=e=>structuredClone(ce(e)?Pe(e):e),Y=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),io=e=>e?.animations?.playback?.continuity==="persistent",B=(e,t)=>Y(e??{},t)&&e[t]!==void 0,lt=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:oe(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},qs=e=>B(e,"opacity")||B(e,"blur"),ao=["x","y","anchorX","anchorY","scaleX","scaleY","rotation","originX","originY"],Hs=e=>ao.some(t=>B(e,t)),Ys=(e,t,r)=>{let n=e[r];return n?.id===t?.id?n:e.find(o=>o.id===t?.id)},Gs=(e,t)=>{if(!t)return e;for(let r of ao)!B(e,r)&&B(t,r)&&(e[r]=t[r]),Y(e,r)&&e[r]===void 0&&delete e[r];return e},Ks=(e,t)=>(t&&(!B(e,"opacity")&&B(t,"opacity")&&(e.opacity=t.opacity),!B(e,"blur")&&B(t,"blur")&&(e.blur=oe(t.blur)),Y(e,"opacity")&&e.opacity===void 0&&delete e.opacity,Y(e,"blur")&&e.blur===void 0&&delete e.blur),e),co=(e,t,r=[])=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let n=e.map((o,i)=>{let s=Ys(r,o,i),l=t(o),c=qs(o),a=Hs(o),u=Y(o,"animations"),f=oe(o);return!l&&(c||a)&&s&&(f={...oe(s),...f},u||delete f.animations),Ks(Gs(f,s),s)}).filter(o=>t(o)||o.animations);return{hasValidItems:n.length>0,processedItems:n}},Js=e=>{if(e){if(e.character&&Y(e.character,"name"))return e.character.name;if(Y(e,"characterName"))return e.characterName}},lo=e=>!!e?.character&&Y(e.character,"sprite"),Xs=e=>{let t={},r=!1,n=Js(e);return n!==void 0&&(t.name=n,r=!0),lo(e)&&(t.sprite=oe(e.character.sprite),r=!0),r?t:void 0},so=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},Qs=({dialogueState:e,content:t,append:r=!1})=>{if(!r||!Array.isArray(t)){e.content=t,delete e.initialRevealedContent;return}let n=Array.isArray(e.content)?e.content:[];n.length>0?e.initialRevealedContent=n.map(o=>oe(o)):delete e.initialRevealedContent,e.content=[...n,...t]},Zs=()=>({}),ea=(e,t)=>{if(!t.screen)return;let r=B(t.screen,"opacity"),n=B(t.screen,"blur"),o=Y(t.screen,"animations");if(!r&&!n){o||delete e.screen;return}let i=e.screen,s={};if(r?s.opacity=t.screen.opacity:B(i,"opacity")&&(s.opacity=i.opacity),n?s.blur=oe(t.screen.blur):B(i,"blur")&&(s.blur=oe(i.blur)),Y(s,"opacity")&&s.opacity===void 0&&delete s.opacity,Y(s,"blur")&&s.blur===void 0&&delete s.blur,Object.keys(s).length===0){delete e.screen;return}e.screen=s},ta=(e,t)=>{if(t.background){let r=B(t.background,"resourceId"),n=B(t.background,"colorId"),o=B(t.background,"opacity"),i=B(t.background,"blur"),{animationsOnly:s,state:l}=lt(t.background,u=>B(u,"resourceId")||B(u,"colorId")||B(u,"opacity")||B(u,"blur"));if(s){e.background=e.background?{...oe(e.background),...l}:l;return}if(!r&&!n&&!o&&!i){delete e.background;return}let c=e.background,a=oe(t.background);if(!r&&c?.resourceId&&(a.resourceId=c.resourceId,!Y(a,"transformId")&&c.transformId&&(a.transformId=c.transformId)),!n&&c?.colorId&&(a.colorId=c.colorId),!o&&B(c,"opacity")&&(a.opacity=c.opacity),!i&&B(c,"blur")&&(a.blur=oe(c.blur)),Y(a,"resourceId")&&a.resourceId===void 0&&delete a.resourceId,Y(a,"colorId")&&a.colorId===void 0&&delete a.colorId,Y(a,"animations")&&a.animations===void 0&&delete a.animations,Y(a,"opacity")&&a.opacity===void 0&&delete a.opacity,Y(a,"blur")&&a.blur===void 0&&delete a.blur,!a.resourceId&&!a.colorId){delete e.background;return}c?.resourceId===a.resourceId&&c?.transformId===a.transformId&&!Y(a,"animations")&&io(c)&&(a.animations=oe(c.animations)),e.background=a}else e.background?.animations&&!io(e.background)&&(e.background.animations={})},ra=(e,t)=>{if(!t.dialogue){e.dialogue&&(so(e.dialogue),e.dialogue.mode==="adv"&&(e.dialogue.content=void 0,delete e.dialogue.initialRevealedContent,e.dialogue.persistCharacter!==!0&&(delete e.dialogue.characterId,delete e.dialogue.character)));return}e.dialogue||(e.dialogue={});let r=e.dialogue.mode;if(t.dialogue.ui){let{animationsOnly:a,state:u}=lt(t.dialogue.ui,f=>!!f.resourceId);a?e.dialogue.ui={...e.dialogue.ui,...u}:e.dialogue.ui={...t.dialogue.ui}}else e.dialogue?.ui?.animations&&(e.dialogue.ui.animations={});t.dialogue.mode==="adv"&&(e.dialogue.content=e.dialogue.content||void 0,e.dialogue.characterId=e.dialogue.characterId||void 0,e.dialogue.mode="adv"),t.dialogue.mode==="nvl"&&(e.dialogue?.mode!=="nvl"&&(e.dialogue.lines=[]),e.dialogue.mode="nvl");let n=t.dialogue.append===!0&&r!=="nvl"&&e.dialogue?.mode!=="nvl"&&Array.isArray(t.dialogue.content);t.dialogue.content!==void 0&&Qs({dialogueState:e.dialogue,content:t.dialogue.content,append:n});let o=Y(t.dialogue,"persistCharacter")?t.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;o?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let i=Y(t.dialogue,"characterId"),s=Xs(t.dialogue),l=s!==void 0,c=lo(t.dialogue);if(i?t.dialogue.characterId?e.dialogue.characterId=t.dialogue.characterId:delete e.dialogue.characterId:!o&&!n&&delete e.dialogue.characterId,l?e.dialogue.character=!i&&o&&e.dialogue.character?{...oe(e.dialogue.character),...s}:s:(i||!o&&!n)&&delete e.dialogue.character,c||so(e.dialogue),t.dialogue.clear){delete e.dialogue;return}if(t.dialogue?.clearPage&&e.dialogue?.mode==="nvl"&&(e.dialogue.lines=[]),e.dialogue?.mode==="nvl"&&t.dialogue.content!==void 0){let a={content:t.dialogue.content,characterId:e.dialogue.characterId??null};e.dialogue.character&&(a.character=oe(e.dialogue.character)),e.dialogue.lines.push(a)}},na=(e,t)=>{if(t.sfx){if(!t.sfx.items||t.sfx.items.length===0){delete e.sfx;return}e.sfx=t.sfx}else e.sfx&&delete e.sfx},oa=(e,t)=>{if(t.bgm){if(!t.bgm.resourceId){e.bgm=void 0;return}e.bgm={...t.bgm,loop:t.bgm.loop||t.bgm.loop===void 0}}},ia=(e,t)=>{if(t.visual){let{hasValidItems:r,processedItems:n}=co(t.visual.items,o=>!!o.resourceId,e.visual?.items||[]);r?e.visual={items:n}:delete e.visual}else e.visual?.items&&(e.visual.items=e.visual.items.map(r=>r.animations?{...r,animations:{}}:r))},sa=(e,t)=>{if(!t.character){e.character?.items&&(e.character.items=e.character.items.map(o=>o.animations?{...o,animations:{}}:o));return}let{hasValidItems:r,processedItems:n}=co(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId,e.character?.items||[]);r?e.character={items:n}:delete e.character},aa=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},ca=(e,t)=>{if(t.layout){let{animationsOnly:r,state:n}=lt(t.layout,o=>!!o.resourceId);if(r){e.layout=n;return}if(!t.layout.resourceId){delete e.layout;return}e.layout=t.layout}else e.layout&&delete e.layout},la=(e,t)=>{if(t.choice){let{animationsOnly:r,state:n}=lt(t.choice,o=>!!o.resourceId);if(r){e.choice={...e.choice,...n};return}if(!t.choice.resourceId){delete e.choice;return}e.choice=t.choice}else e.choice&&delete e.choice},ua=(e,t)=>{if(t.form){let{animationsOnly:r,state:n}=lt(t.form,o=>!!o.resourceId);if(r){e.form={...e.form,...n};return}if(!t.form.resourceId){delete e.form;return}e.form=oe(t.form)}else e.form&&delete e.form},fa=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},da=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},pa=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(r=>{delete e[r]})},Ve=e=>kt(Zs,[pa,ea,ta,na,oa,ia,ra,sa,aa,ca,la,ua,fa,da])(e);var ha=Object.freeze({dialogueTextSpeed:{source:"global.dialogueTextSpeed"},autoForwardDelay:{source:"global.autoForwardDelay"},skipUnseenText:{source:"global.skipUnseenText"},skipTransitionsAndAnimations:{source:"global.skipTransitionsAndAnimations"},soundVolume:{source:"global.soundVolume"},musicVolume:{source:"global.musicVolume"},muteAll:{source:"global.muteAll"},saveLoadPagination:{source:"context.runtime.saveLoadPagination"},menuPage:{source:"context.runtime.menuPage"},menuEntryPoint:{source:"context.runtime.menuEntryPoint"},autoMode:{source:"global.autoMode"},skipMode:{source:"global.skipMode"},dialogueUIHidden:{source:"global.dialogueUIHidden"},isLineCompleted:{source:"global.isLineCompleted"}}),je=Object.freeze({dialogueTextSpeed:50,autoForwardDelay:1e3,skipUnseenText:!1,skipTransitionsAndAnimations:!1,soundVolume:50,musicVolume:50,muteAll:!1,autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isLineCompleted:!1}),ut=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),uo=Object.freeze({dialogueTextSpeed:"number",autoForwardDelay:"number",skipUnseenText:"boolean",skipTransitionsAndAnimations:"boolean",soundVolume:"number",musicVolume:"number",muteAll:"boolean",saveLoadPagination:"number",menuPage:"string",menuEntryPoint:"string",autoMode:"boolean",skipMode:"boolean",dialogueUIHidden:"boolean",isLineCompleted:"boolean"}),_r=Object.freeze(["dialogueTextSpeed","autoForwardDelay","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),Rr=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),ma=(e,t)=>{if(t.startsWith("global.")){let r=t.slice(7);return e?.global?.[r]}if(t.startsWith("context.runtime.")){let r=t.slice(16),n=Array.isArray(e?.contexts)?e.contexts:[];return n[n.length-1]?.runtime?.[r]}},Ke=e=>Object.fromEntries(Object.entries(ha).map(([t,r])=>{let n=ma(e,r.source),o=n!==void 0?n:je[t]??ut[t];return[t,o]})),Ee=(e,t)=>Ke(e)[t],fo=(e={})=>Object.fromEntries(_r.map(t=>[t,e[t]??je[t]]));var Je=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}),ve=Object.freeze({BEHIND_BACKGROUND:Je.VISUAL_BEHIND_BACKGROUND,BEHIND_CHARACTER:Je.VISUAL_BEHIND_CHARACTER,BEHIND_DIALOGUE:Je.VISUAL_BEHIND_DIALOGUE,BEHIND_CHOICE:Je.VISUAL_BEHIND_CHOICE,FOREGROUND:Je.VISUAL_FOREGROUND}),Or=ve.BEHIND_DIALOGUE,Lr=Object.freeze(Object.values(ve).sort((e,t)=>e-t));var Oe={objectValues:e=>Object.entries(e).map(([t,r])=>({id:t,...r})),formatDate:no},ga=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,ya=(e,t)=>{let r=String(t||"").trim();if(!r)return;let n=r.match(/[A-Za-z_][A-Za-z0-9_]*|\[\d+\]/g)||[],o=e;for(let i of n){if(i.startsWith("[")){let s=Number(i.slice(1,-1));o=Array.isArray(o)?o[s]:void 0;continue}o=o?.[i]}return o},jt=(e,t,r)=>{if(Array.isArray(e)){let o=[];for(let i of e){if(i&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===1){let[s]=Object.keys(i),l=ga.exec(s);if(l){let[,c,a,u]=l,f=ya(t,u);if(!Array.isArray(f))continue;let d=Array.isArray(i[s])?i[s]:[];f.forEach((p,h)=>{let g={...t,[c]:p};a&&(g[a]=h),d.forEach(y=>{let b=jt(y,g,r),A=se(b,g,r);Array.isArray(A)?o.push(...A):o.push(A)})});continue}}o.push(jt(i,t,r))}return o}if(!e||typeof e!="object")return e;let n={};return Object.entries(e).forEach(([o,i])=>{n[o]=jt(i,t,r)}),n},Gr=({animationType:e,animationId:t,animationPath:r})=>{if(e!==void 0&&!(e==="update"||e==="transition"))throw new Error(`[${r}] Animation "${t}" has unsupported type "${e}". Use "update" or "transition".`)},ba=({id:e,targetId:t,animation:r,playback:n,animationPath:o="animation"})=>{let i=structuredClone(r);return Gr({animationType:i.type,animationId:e,animationPath:o}),delete i.name,delete i.playback,i.id=e,i.targetId=t,n&&(i.playback=structuredClone(n)),i},Ia=(e,{animationId:t="animation",animationPath:r="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return Gr({animationType:e.type,animationId:t,animationPath:r}),e.type},Aa=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},wa=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},Kr=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),xo=e=>e?.playback?.continuity==="persistent",Vr=e=>Array.isArray(e)?e.map(Vr):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((t,r)=>(t[r]=Vr(e[r]),t),{}),Ft=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let t=structuredClone(e);return delete t.playback,JSON.stringify(Vr(t))},Co=(e=[])=>e.filter(t=>xo(t)).map(t=>structuredClone(t)),So=e=>Array.isArray(e?.keyframes)?e.keyframes.reduce((t,r)=>{let n=typeof r?.duration=="number"&&Number.isFinite(r.duration)?r.duration:0;return t+n},0):0,$r=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((t,r)=>Math.max(t,So(r)),0),_o=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max($r(e.tween),$r(e.prev?.tween),$r(e.next?.tween),So(e.mask?.progress)),po=({animationInstances:e,activePersistentAnimations:t})=>{if(!Array.isArray(e)||e.length===0||!Array.isArray(t)||t.length===0)return!1;let r=new Set(t.map(Ft).filter(Boolean));return e.some(n=>{if(!xo(n))return!1;let o=Ft(n);return o?r.has(o):!1})},me=({animationInstances:e,isLineCompleted:t,skipTransitionsAndAnimations:r,activePersistentAnimations:n,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||r?!1:i&&!t||po({animationInstances:e,activePersistentAnimations:n})?!0:i?!1:po({animationInstances:e,activePersistentAnimations:o}),Ea=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),va=(e,t)=>{if(Ea(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},xa=({resources:e,animationId:t,playback:r,instanceId:n,targetId:o,animationPath:i="animation"})=>{if(!t||!o)return!1;let s=e?.animations?.[t];return s?ba({id:n,targetId:o,animation:s,playback:r,animationPath:i}):null},Ca=(e,{defaultTargetId:t,defaultId:r,animationPath:n="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return Gr({animationType:o.type,animationId:o.id??r,animationPath:n}),o.id??=r,o.targetId??=t,o},Jr=({animations:e,transitions:t,defaultTargetId:r,idPrefix:n,animationPathPrefix:o=n})=>{t.forEach((i,s)=>{e.push(Ca(i,{defaultTargetId:r,defaultId:`${n}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},jr=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let r=se(e,t);return r&&typeof r=="object"?e:r},Mr=(e,t)=>{if(e===void 0)return[];if(!Array.isArray(e)||e.some(r=>r===null||typeof r!="object"||Array.isArray(r)))throw new Error(`${t} must be an array of objects`);return e},Sa=({content:e,path:t,variables:r})=>Mr(e,t).reduce((n,o)=>{let i=jr(o.text,{variables:r});return n+`${i??""}`.length},0),ho=(e=[])=>{let t=new Map;for(let r of e)r?.id&&t.set(r.id,(t.get(r.id)??0)+1);return new Set(Array.from(t.entries()).filter(([,r])=>r>1).map(([r])=>r))},Vt=(e,t=0,r=new Set)=>{if(!r.has(e?.id))return`character-container-${e.id}`;let n=e?.sprites?.map(({resourceId:o})=>o)||[];return n.length===0?`character-container-${e.id}`:`character-container-${e.id}-${t}-${n.join("-")}`},kr=(e,t)=>{if(!t.transformId)throw new Error(`Visual item "${t.id}" requires transformId`);let r=e.transforms?.[t.transformId];if(!r)throw new Error(`Transform "${t.transformId}" not found for visual item "${t.id}"`);return r},_a=(e,t={})=>{if(!t?.transformId)return;let r=e.transforms?.[t.transformId];if(!r)throw new Error(`Transform "${t.transformId}" not found for background`);return r},Ra=(e={},t)=>{if(t){if(e.images?.[t])return"sprite";if(e.videos?.[t])return"video";if(e.layouts?.[t])return"container"}},Fr=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},Oa=(e={})=>e.textStyles||{},La=(e={})=>e.images||{},$a=(e={})=>e.colors||{},ka=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,ft=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,Qe=(e,t,r)=>{if(typeof e!="string"||e.length===0)throw new Error(`${r} at "${t}" must resolve to a non-empty string`)},mo=(e,t,r)=>{if(e===void 0)return 1;if(typeof e!="number"||!Number.isFinite(e))throw new Error(`${t} for text style "${r}" must be a number between 0 and 1`);if(e<0||e>1)throw new Error(`${t} for text style "${r}" must be a number between 0 and 1`);return e},Xr=(e,t)=>{if(typeof e!="string"||!ka.test(e))throw new Error(`${t} must resolve to a hex color`);return e.length===4?`#${e.slice(1).split("").map(r=>r.repeat(2)).join("")}`:e},go=(e,t,r)=>{let n=Xr(e,r);if(t===1)return n;let o=Number.parseInt(n.slice(1,3),16),i=Number.parseInt(n.slice(3,5),16),s=Number.parseInt(n.slice(5,7),16);return`rgba(${o}, ${i}, ${s}, ${t})`},Ta=(e={},t)=>{let r=Oa(e)?.[t];if(!r)throw new Error(`Text style "${t}" not found`);let n=e.fonts?.[r.fontId];if(!n)throw new Error(`Font "${r.fontId}" not found for text style "${t}"`);let o=e.colors?.[r.colorId];if(!o)throw new Error(`Color "${r.colorId}" not found for text style "${t}"`);let i=mo(r.colorAlpha,"colorAlpha",t),s={fontFamily:n.fileId,fontSize:r.fontSize??16,fontWeight:r.fontWeight??"400",fontStyle:r.fontStyle??"normal",lineHeight:r.lineHeight??1.2,fill:go(o.hex,i,`Color "${r.colorId}" for text style "${t}"`)};if(r.align!==void 0&&(s.align=r.align),r.wordWrap!==void 0&&(s.wordWrap=r.wordWrap),r.breakWords!==void 0&&(s.breakWords=r.breakWords),r.wordWrapWidth!==void 0&&(s.wordWrapWidth=r.wordWrapWidth),r.strokeColorId){let l=e.colors?.[r.strokeColorId];if(!l)throw new Error(`Stroke color "${r.strokeColorId}" not found for text style "${t}"`);let c=mo(r.strokeAlpha,"strokeAlpha",t);s.strokeColor=go(l.hex,c,`Stroke color "${r.strokeColorId}" for text style "${t}"`)}else if(r.strokeAlpha!==void 0)throw new Error(`strokeAlpha for text style "${t}" requires strokeColorId`);return r.strokeWidth!==void 0&&(s.strokeWidth=r.strokeWidth),s},Ur=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>Ur(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;if(Object.prototype.hasOwnProperty.call(e,"textStyle"))throw new Error(`Inline textStyle is not allowed in layout elements at "${r}". Use textStyleId instead`);let n={};for(let[o,i]of Object.entries(e))o!=="textStyleId"&&(n[o]=Ur(i,t,ft(r,o)));return e.textStyleId!==void 0&&(Qe(e.textStyleId,r,"textStyleId"),n.textStyle=Ta(t,e.textStyleId)),n},Qr=(e={},t)=>{let r=$a(e)?.[t];if(!r)throw new Error(`Color "${t}" not found`);return Xr(r.hex,`Color "${t}"`)},Ro=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",Tr=(e,t,r)=>{let n=e?.[t];if(!(!n||typeof n!="object"||Array.isArray(n))&&Object.prototype.hasOwnProperty.call(n,"fill"))throw new Error(`Inline ${t}.fill is not allowed in rect layout elements at "${r}". Use ${Ro(`${t}.fill`)} instead`)},Da=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>dt(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;let n={};for(let[o,i]of Object.entries(e))o!=="colorId"&&(n[o]=dt(i,t,ft(r,o)));return e.colorId!==void 0&&(Qe(e.colorId,r,"colorId"),n.fill=Qr(t,e.colorId)),n},dt=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>dt(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="rect"){if(Object.prototype.hasOwnProperty.call(e,"fill"))throw new Error(`Inline fill is not allowed in rect layout elements at "${r}". Use ${Ro("fill")} instead`);Tr(e,"hover",r),Tr(e,"click",r),Tr(e,"rightClick",r)}let n={};for(let[o,i]of Object.entries(e))if(!(e.type==="rect"&&o==="colorId")){if(e.type==="rect"&&(o==="hover"||o==="click"||o==="rightClick")){n[o]=Da(i,t,ft(r,o));continue}n[o]=dt(i,t,ft(r,o))}return e.type==="rect"&&e.colorId!==void 0&&(Qe(e.colorId,r,"colorId"),n.fill=Qr(t,e.colorId)),n},Dr=(e={},t)=>{let r=La(e)?.[t];return r||null},Oo=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",yo=(e,t,r,n)=>{let o=e?.[t];if(!(!o||typeof o!="object"||Array.isArray(o))&&Object.prototype.hasOwnProperty.call(o,n))throw new Error(`Inline ${t}.${n} is not allowed in sprite layout elements at "${r}". Use ${Oo(`${t}.${n}`)} instead`)},bo=(e,t,r)=>{let n=e[t];e[t]={...n&&typeof n=="object"&&!Array.isArray(n)?n:{},src:r}},Br=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>Br(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="sprite"){for(let o of["url","src","hoverUrl","hoverSrc","clickUrl","clickSrc"])if(Object.prototype.hasOwnProperty.call(e,o))throw new Error(`Inline ${o} is not allowed in sprite layout elements at "${r}". Use ${Oo(o)} instead`);yo(e,"hover",r,"src"),yo(e,"click",r,"src")}let n={};for(let[o,i]of Object.entries(e))e.type==="sprite"&&(o==="imageId"||o==="hoverImageId"||o==="clickImageId")||(n[o]=Br(i,t,ft(r,o)));if(e.type==="sprite"&&e.imageId!==void 0){Qe(e.imageId,r,"imageId");let o=Dr(t,e.imageId),i=o?.fileId??e.imageId;n.src=i,n.width===void 0&&o?.width!==void 0&&(n.width=o.width),n.height===void 0&&o?.height!==void 0&&(n.height=o.height)}return e.type==="sprite"&&e.hoverImageId!==void 0&&(Qe(e.hoverImageId,r,"hoverImageId"),bo(n,"hover",Dr(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(Qe(e.clickImageId,r,"clickImageId"),bo(n,"click",Dr(t,e.clickImageId)?.fileId??e.clickImageId)),n},Zr=(e,t={},r="root")=>Br(dt(Ur(e,t,r),t,r),t,r),Le=Zr,Fe=(e=[])=>e.find(t=>t.id==="story"),Pa="#000000",zr="bg-cg-background-color",Na=({resources:e={},background:t={},screen:r})=>t?.colorId===void 0?Xr(r?.backgroundColor??Pa,"screen.backgroundColor"):Qr(e,t.colorId),Lo=(e={})=>{if(Kr(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},Va=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},Io=(e={},{includeDefaultAlpha:t=!1}={})=>{let r=Lo(e),n=Va(e),o={};return(t||r!==void 0)&&(o.alpha=r??1),n&&(o.blur=n),o},ja=(e={})=>{if(Kr(e,"opacity"))return typeof e.opacity=="number"?e.opacity:void 0},Ma=(e={})=>{if(!(!e.blur||typeof e.blur!="object"||Array.isArray(e.blur)))return e.blur},$o=(e={})=>{let t=ja(e),r=Ma(e),n={};return t!==void 0&&(n.alpha=t),r&&(n.blur=r),n},Mt=(e={})=>$o(e),Me=(e={},t={})=>{let r={x:t.x??e.x,y:t.y??e.y,anchorX:t.anchorX??e.anchorX,anchorY:t.anchorY??e.anchorY,rotation:t.rotation??e.rotation,scaleX:t.scaleX??e.scaleX,scaleY:t.scaleY??e.scaleY},n=t.originX??e.originX,o=t.originY??e.originY;return n!==void 0&&(r.originX=n),o!==void 0&&(r.originY=o),r},Fa=({resources:e,background:t,screen:r={width:1920,height:1080},includeOpacity:n=!1})=>{let o={id:zr,type:"rect",x:0,y:0,width:r?.width??1920,height:r?.height??1080,fill:Na({resources:e,background:t,screen:r})};if(n){let i=Lo(t);i!==void 0&&(o.alpha=i)}return o},Ua=(e={},t)=>t?!!(e.images?.[t]||e.videos?.[t]||e.layouts?.[t]):!1,Ao=({resources:e={},resourceId:t,colorId:r})=>{let n=Ra(e,t);return t&&(n||r===void 0)?{resourceId:t,targetId:Fr({resourceId:t,kind:n})}:r!==void 0?{resourceId:zr,targetId:zr}:{resourceId:void 0,targetId:void 0}},ko=100,Bt=ko,To=(e,t)=>e*t/ko,Ba=(e={},t=Bt)=>e?.muteAll?0:To(t,e?.soundVolume??je.soundVolume),za=(e={},t=Bt)=>e?.muteAll?0:To(t,e?.musicVolume??je.musicVolume),Wa=({item:e,index:t}={})=>`sfx:${t}:${e?.resourceId}`,ge=({variables:e,runtime:t,saveSlots:r=[],dialogueState:n,includeInactiveAdvDialogue:o=!1,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,confirmDialog:f,form:d,historyDialogue:p=[],characters:h={},dialogueUIHidden:g,skipOnlyViewedLines:y,skipTransitionsAndAnimations:b}={})=>{let A={dialogueTextSpeed:t?.dialogueTextSpeed??50,autoForwardDelay:t?.autoForwardDelay??1e3,skipUnseenText:t?.skipUnseenText??!1,skipTransitionsAndAnimations:t?.skipTransitionsAndAnimations??!1,soundVolume:t?.soundVolume??50,musicVolume:t?.musicVolume??50,muteAll:t?.muteAll??!1,saveLoadPagination:t?.saveLoadPagination??1,menuPage:t?.menuPage??"",menuEntryPoint:t?.menuEntryPoint??"",autoMode:t?.autoMode??s??!1,skipMode:t?.skipMode??l??!1,dialogueUIHidden:t?.dialogueUIHidden??g??!1,isLineCompleted:t?.isLineCompleted??i??!1},v=Ja({dialogueState:n,includeInactiveAdvDialogue:o,characters:h,variables:e}),S={variables:e,runtime:A,saveSlots:r,isChoiceVisible:c,isFormVisible:a,canRollback:u,confirmDialog:f,form:d,historyDialogue:p,characters:h};return v&&(S.dialogue=v,S.dialogueLines=v.lines),S},wo=100,Ut=(e,t)=>{if(Array.isArray(e))return e.map(n=>Ut(n,t));if(!e||typeof e!="object")return e;let r={...e};return Object.keys(r).forEach(n=>{r[n]=Ut(r[n],t)}),r.type==="text-revealing"?t(r):r},qa=e=>Ut(e,t=>({...t,revealEffect:"none"})),Ha=e=>Ut(e,t=>{let r=Number(t.speed??t.displaySpeed),n=Number.isFinite(r)?Math.max(r,wo):wo;return{...t,speed:n,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:n}:{}}}),$e=(e,{isLineCompleted:t=!1,skipMode:r=!1,skipTransitionsAndAnimations:n=!1}={})=>t||n?qa(e):r?Ha(e):e,Do=({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 r=t.click?.payload;if(!r||typeof r!="object"||Array.isArray(r))return t;let n=r.actions,o=n&&typeof n=="object"&&!Array.isArray(n)&&Object.prototype.hasOwnProperty.call(n,"nextLine")?{...n.nextLine,bypassChoice:!0}:void 0;return{...t,click:{...t.click,payload:{...r,bypassChoice:!0,...o?{actions:{...n,nextLine:o}}:{}}}}},Ya=new Set(["click","change","submit","focusEvent","blurEvent","selectionChange","compositionStart","compositionUpdate","compositionEnd"]),Ga="submit",Pr=(e,t)=>{let r=e?.payload&&typeof e.payload=="object"&&!Array.isArray(e.payload)?e.payload:{},n=r.actions&&typeof r.actions=="object"?r.actions:{};return{...e||{},payload:{...r,actions:{...n,...t}}}},qr=(e,t)=>{if(Array.isArray(e))return e.map(o=>qr(o,t));if(!e||typeof e!="object")return e;let r={};for(let[o,i]of Object.entries(e))r[o]=qr(i,t);let n=r;if(n.type==="input"&&typeof n.field=="string"){let o=t?.fields?.[n.field];if(o){let i={updateFormField:{formKey:t.key,field:o.id,value:"_event.value"}};n={...n,value:o.value,placeholder:n.placeholder===void 0?o.placeholder:n.placeholder,multiline:n.multiline===void 0?o.multiline:n.multiline,...n.maxLength===void 0&&o.maxLength!==void 0?{maxLength:o.maxLength}:{},change:Pr(n.change,i),submit:Pr(n.submit,t.submitActions)}}}return n.formRole===Ga?{...n,click:Pr(n.click,t.submitActions)}:n},Hr=(e,t)=>{if(Array.isArray(e))return e.map(n=>Hr(n,t));if(!e||typeof e!="object")return e;let r={};for(let[n,o]of Object.entries(e))r[n]=Hr(o,t);for(let n of Ya){let o=r[n]?.payload;!o||typeof o!="object"||Array.isArray(o)||(r[n]={...r[n],payload:{...o,_interactionSource:"form"}})}return r},Yr=({characterId:e,character:t,characterName:r,characters:n={}}={})=>{let o=e?n?.[e]:void 0,i=t?.name!==void 0?t.name:r!==void 0?r:o?.name||"";return{...o||{},...t||{},name:i}},Po=(e=[],t={})=>e.map(r=>{let n=Yr({characterId:r.characterId,character:r.character,characterName:r.characterName,characters:t}),o=typeof r.text=="string"?r.text:Array.isArray(r.content)?r.content.map(i=>i?.text??"").join(""):"";return{...r,text:o,character:n,characterName:n.name}}),Ka=e=>!(!e||e.mode==="adv"&&e.content===void 0),Ja=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:r={},variables:n}={})=>{if(!t&&!Ka(e))return;let o=e.content===void 0?[{text:""}]:Mr(e.content,"dialogue.content"),i=e.content===void 0?0:Sa({content:e.initialRevealedContent,path:"dialogue.initialRevealedContent",variables:n}),s=(e.lines||[]).map((c,a)=>{let u=Mr(c.content,`dialogue.lines[${a}].content`),f=Yr({characterId:c.characterId,character:c.character,characterName:c.characterName,characters:r});return{...c,content:u.map(d=>({...d,text:jr(d.text,{variables:n})})),character:f,characterName:f.name}}),l=Yr({characterId:e.characterId,character:e.character,characters:r});return{characterId:e.characterId,persistCharacter:e.persistCharacter,character:l,content:o.map(c=>({...c,text:jr(c.text,{variables:n})})),initialRevealedCharacters:i,lines:s}},No=({container:e,resources:t,templateData:r,isLineCompleted:n=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=se(e,r,{functions:Oe});return Le($e(s,{isLineCompleted:n,skipMode:o,skipTransitionsAndAnimations:i}),t)},Nr=(e,t={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(t),Eo=({renderStateKeyboard:e,keyboard:t,phase:r})=>{!t||typeof t!="object"||Array.isArray(t)||Object.entries(t).forEach(([n,o])=>{let i=e[n]??{},s=r==="keydown"?o?.keydown:o?.keyup;if(r==="keydown"&&s&&typeof s=="object"){e[n]={...i,keydown:{payload:Nr(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[n].keyup={payload:Nr(o.keyup)});return}e[n]={...i,[r]:{payload:Nr(o)}}})},Xa=(e={},t={})=>{let r={};return Eo({renderStateKeyboard:r,keyboard:e,phase:"keydown"}),Eo({renderStateKeyboard:r,keyboard:t,phase:"keyup"}),Object.keys(r).length>0?r:void 0},xe=({animationsDef:e,resources:t,previousResourceId:r,currentResourceId:n,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:l})=>{if(!e)return[];let c=[],a=({instanceId:b,targetId:A})=>{let v=xa({resources:t,animationId:p,playback:h,instanceId:b,targetId:A,animationPath:s});v&&c.push(v)},u=r!=null&&r!==!1,f=n!=null&&n!==!1,d=o&&i&&o===i;va(e,s);let p=Aa(e),h=wa(e),g=t?.animations?.[p],y=Ia(g,{animationId:p,animationPath:s});if(y==="update")return f&&i?a({instanceId:`${l}-animation-update`,targetId:i}):u&&o&&a({instanceId:`${l}-animation-update`,targetId:o}),c;if(y==="transition"){let b=`${l}-animation-transition`,A=h?.continuity==="persistent"?b:`${l}-animation-in`;if(u&&f&&d)return a({instanceId:b,targetId:i}),c;u&&a({instanceId:`${l}-animation-out`,targetId:o}),f&&a({instanceId:A,targetId:i})}return c},Qa=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),Za=(e,{presentationState:t,previousPresentationState:r,currentLineActions:n,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:l,variables:c,runtime:a,activePersistentAnimations:u,restoredPersistentAnimations:f,autoMode:d,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:b,saveSlots:A=[]})=>{let{elements:v,animations:S}=e;if(t.background){let T=n===void 0?!0:Kr(n?.background??{},"animations"),w=v.find(W=>W.id==="story");if(!w)return e;let D=_a(o,t.background),F=r?.background?.resourceId,V=r?.background?.colorId,N=t.background.resourceId??(t.background.animations?F:void 0),j=t.background.colorId??(t.background.animations?V:void 0),U=Ua(o,N),q={...t.background,colorId:j};if((j!==void 0||U)&&w.children.push(Fa({resources:o,background:q,screen:i,includeOpacity:!U})),N){let{images:W={},videos:x={}}=o,_=W[N]||x[N];if(_){let P=x[N]!==void 0,re={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...D},H={id:Fr({resourceId:N,kind:P?"video":"sprite"}),type:P?"video":"sprite",src:_.fileId,width:_.width,height:_.height,...Io(t.background,{includeDefaultAlpha:!0}),...Me(re)};P&&(H.loop=t.background.loop??!1,H.volume=_.volume??50),w.children.push(H)}}if(N){let{layouts:W={}}=o,x=W[N];if(x){let _={id:Fr({resourceId:N,kind:"container"}),type:"container",children:x.elements,...Io(t.background)};D&&Object.assign(_,Me({x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...D}));let P=se(_,ge({variables:c,runtime:a,saveSlots:A,dialogueState:t.dialogue,isLineCompleted:s,autoMode:d,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:b,characters:o.characters||{},skipTransitionsAndAnimations:l}),{functions:Oe});w.children.push(Le($e(P,{isLineCompleted:s,skipMode:p,skipTransitionsAndAnimations:l}),o))}}let G=Ao({resources:o,resourceId:F,colorId:V}),ie=Ao({resources:o,resourceId:N,colorId:j}),te=xe({animationsDef:t.background.animations,resources:o,previousResourceId:G.resourceId,currentResourceId:ie.resourceId,previousTargetId:G.targetId,currentTargetId:ie.targetId,animationPath:"background.animations",idPrefix:"bg-cg"});me({animationInstances:te,isLineCompleted:s,skipTransitionsAndAnimations:l,activePersistentAnimations:u,restoredPersistentAnimations:f,isAuthoredOnCurrentLine:T})&&S.push(...te)}return e},ec=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:l,animations:c}=e;if(t.character&&n){let a=l.find(h=>h.id==="story");if(!a)return e;let u=t.character.items||[],f=r?.character?.items||[],d=ho(u),p=ho(f);for(let h=0;h<u.length;h++){let g=u[h],{transformId:y,sprites:b}=g,A=f.find(j=>j.id===g.id),v=f.findIndex(j=>j.id===g.id),S=A?.sprites&&A.sprites.length>0,T=b&&b.length>0,w=v>=0?Vt(A,v,p):void 0,D=xe({animationsDef:g.animations,resources:n,previousResourceId:w,currentResourceId:T?Vt(g,h,d):void 0,previousTargetId:w,currentTargetId:T?Vt(g,h,d):void 0,animationPath:`character.items[${h}].animations`,idPrefix:"character"});if(g.animations&&!b&&!y&&S&&me({animationInstances:D,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){c.push(...D);continue}if(g.animations&&!b&&!y)continue;if(!b||b.length===0||!y){console.warn("Character item missing sprites or transformId:",g);continue}let F=Vt(g,h,d),V=n.transforms[y];if(!V){console.warn("Transform not found:",y);continue}let N={type:"container",id:F,...Me(V,g),...Mt(g),children:[]};for(let j of b){let U=n.images[j.resourceId];if(!U){console.warn(`Image resource not found: ${j.resourceId}`);continue}N.children.push({type:"sprite",id:`${F}-${j.id}`,src:U.fileId,width:U.width,height:U.height,x:0,y:0})}a.children.push(N),me({animationInstances:D,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...D)}}return e},Vo=(e,t)=>{if(!Lr.includes(e))throw new Error(`${t} must be one of: ${Lr.join(", ")}.`)},tc=(e,t)=>{let r=e.layer??(e.resourceId?void 0:t?.layer)??Or;return Vo(r,`Visual item "${e.id}" layer`),r},rc=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,runtime:l,activePersistentAnimations:c,autoMode:a,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,form:h,saveSlots:g=[],visualLayer:y})=>{let{elements:b,animations:A}=e;if(t.visual&&n){let v=b.find(w=>w.id==="story");if(!v)return e;let S=t.visual.items,T=r?.visual?.items||[];y!==void 0&&Vo(y,"visualLayer");for(let w of S){let D=T.find(N=>N.id===w.id),F=tc(w,D);if(y!==void 0&&F!==y)continue;if(w.resourceId){let{images:N={},videos:j={},spritesheets:U={}}=n,q=U[w.resourceId];if(q){let G=kr(n,w),ie=w.animationName;if(ie){let te=q.animations?.[ie];if(!te)throw new Error(`Animation '${ie}' not found in spritesheet resource '${w.resourceId}'`);let W=Mt(w),x={id:`visual-${w.id}`,type:"animated-sprite",...Me(G,w),width:w.width??q.width,height:w.height??q.height,alpha:W.alpha??w.alpha??1,spritesheetSrc:q.fileId,spritesheetData:q.jsonData,animation:{frames:te.frames,animationSpeed:w.animationSpeed??te.animationSpeed??.5,loop:w.loop??te.loop??!0}};W.blur&&(x.blur=W.blur),v.children.push(structuredClone(x))}}else{let G=N[w.resourceId]||j[w.resourceId];if(G){let ie=j[w.resourceId]!==void 0,te=kr(n,w),W={id:`visual-${w.id}`,type:ie?"video":"sprite",src:G.fileId,width:G.width,height:G.height,...Me(te,w)};Object.assign(W,Mt(w)),ie&&(W.loop=G.loop??!1,W.volume=G.volume??50),v.children.push(W)}}}if(w.resourceId){let{layouts:N={}}=n,j=N[w.resourceId];if(j){let U=kr(n,w),q={id:`visual-${w.id}`,type:"container",children:structuredClone(j.elements),...Me(U,w)};Object.assign(q,Mt(w));let G=se(q,ge({variables:s,runtime:l,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:o,autoMode:a,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:i}),{functions:Oe});v.children.push(Le($e(G,{isLineCompleted:o,skipMode:u,skipTransitionsAndAnimations:i}),n))}}let V=xe({animationsDef:w.animations,resources:n,previousResourceId:D?.resourceId,currentResourceId:w.resourceId,previousTargetId:D?.resourceId?`visual-${w.id}`:void 0,currentTargetId:w.resourceId?`visual-${w.id}`:void 0,animationPath:`visual.items[${w.id}].animations`,idPrefix:w.id});me({animationInstances:V,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:c})&&A.push(...V)}}return e},Xe="dialogue-character-sprite",vo=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,nc=(e,{presentationState:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:l}=e,c=Fe(e.elements);if(!c)return e;let a=t.dialogue?.character?.sprite,u=r?.dialogue?.character?.sprite,f=vo(a),d=vo(u),p=xe({animationsDef:a?.animations,resources:n,previousResourceId:d?Xe:void 0,currentResourceId:f?Xe:void 0,previousTargetId:d?Xe:void 0,currentTargetId:f?Xe:void 0,animationPath:"dialogue.character.sprite.animations",idPrefix:"dialogue-character-sprite"});if(!f)return a?.animations&&d&&me({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...p),e;let h=n.transforms?.[a.transformId];if(!h)return console.warn("Transform not found:",a.transformId),e;let g={type:"container",id:Xe,...Me(h),children:[]};for(let y of a.items){let b=n.images?.[y.resourceId];if(!b){console.warn(`Image resource not found: ${y.resourceId}`);continue}g.children.push({type:"sprite",id:`${Xe}-${y.id}`,src:b.fileId,width:b.width,height:b.height,x:0,y:0})}return c.children.push(g),me({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...p),e},oc=(e,{presentationState:t,previousPresentationState:r,resources:n={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:c,canRollback:a,form:u,skipOnlyViewedLines:f,isLineCompleted:d,skipTransitionsAndAnimations:p,variables:h,runtime:g,activePersistentAnimations:y,saveSlots:b=[]})=>{let{elements:A,animations:v}=e;if(!t.dialogue||o)return e;let S=A.find(w=>w.id==="story");if(!S)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:w={}}=n,D=w[t.dialogue.ui.resourceId];if(D){let F={elements:D.elements},V=ge({variables:h,runtime:g,saveSlots:b,dialogueState:t.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:d,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:c,canRollback:a,form:u,characters:n.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:f,skipTransitionsAndAnimations:p}),N={functions:Oe},j=jt(F,V,N),U=se(j,V,N),q=Le($e(U?.elements,{isLineCompleted:d,skipMode:s,skipTransitionsAndAnimations:p}),n);if(Array.isArray(q))for(let G of q)S.children.push(G);else q&&S.children.push(q)}}nc(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:d,skipTransitionsAndAnimations:p,activePersistentAnimations:y});let T=xe({animationsDef:t.dialogue.ui?.animations,resources:n,previousResourceId:r?.dialogue?.ui?.resourceId,currentResourceId:t.dialogue.ui?.resourceId,previousTargetId:r?.dialogue?.ui?.resourceId?"dialogue-container":void 0,currentTargetId:t.dialogue.ui?.resourceId?"dialogue-container":void 0,animationPath:"dialogue.ui.animations",idPrefix:"dialogue-ui"});return me({animationInstances:T,isLineCompleted:d,skipTransitionsAndAnimations:p,activePersistentAnimations:y})&&v.push(...T),e},ic=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,runtime:c,autoMode:a,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,form:h,activePersistentAnimations:g,saveSlots:y=[]})=>{let{elements:b,animations:A}=e;if(t.choice&&n){let v=Fe(b);if(!v)return e;let S=n?.layouts[t.choice.resourceId];if(S&&S.elements){let w={elements:S.elements},D=se(w,{...ge({variables:l,runtime:c,saveSlots:y,dialogueState:t.dialogue,isLineCompleted:i,autoMode:a,skipMode:u,isChoiceVisible:f??!!t.choice,isFormVisible:d,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}},{functions:Oe}),F=Wr(Le($e(D?.elements,{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),n));if(Array.isArray(F))for(let V of F)v.children.push(V);else F&&v.children.push(F)}let T=xe({animationsDef:t.choice.animations,resources:n,previousResourceId:r?.choice?.resourceId,currentResourceId:t.choice.resourceId,previousTargetId:r?.choice?.resourceId?"choice-container":void 0,currentTargetId:t.choice.resourceId?"choice-container":void 0,animationPath:"choice.animations",idPrefix:"choice"});me({animationInstances:T,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:g})&&A.push(...T)}return e},sc=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,runtime:c,autoMode:a,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,activePersistentAnimations:h,saveSlots:g=[],form:y})=>{let{elements:b,animations:A}=e;if(!y?.resourceId||!n)return e;let v=Fe(b);if(!v)return e;let S=n?.layouts?.[y.resourceId];if(!S)return console.warn(`Form layout not found: ${y.resourceId}`),e;let T={id:"form-container",type:"container",x:0,y:0,children:S.elements||[]},w={...ge({variables:l,runtime:c,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:i,autoMode:a,skipMode:u,isChoiceVisible:f,isFormVisible:d,canRollback:p,characters:n.characters||{},skipTransitionsAndAnimations:s,form:y}),form:y},D=se(T,w,{functions:Oe}),F=Hr(Le($e(qr(D,y),{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),n),y);F&&v.children.push(F);let V=xe({animationsDef:y.animations,resources:n,previousResourceId:r?.form?.resourceId,currentResourceId:y.resourceId,previousTargetId:r?.form?.resourceId?"form-container":void 0,currentTargetId:y.resourceId?"form-container":void 0,animationPath:"form.animations",idPrefix:"form"});return me({animationInstances:V,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:h})&&A.push(...V),e},ac=(e,{presentationState:t,resources:r={},variables:n,runtime:o,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,form:f,saveSlots:d=[],skipTransitionsAndAnimations:p})=>{if(!t.control?.resourceId)return e;let h=r.controls?.[t.control.resourceId];if(!h)return e;let g=Xa(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=Fe(e.elements);if(!y)return e;let b={id:`control-${t.control.resourceId}`,type:"container",x:0,y:0,children:h.elements};return y.children.push(No({container:b,resources:r,templateData:ge({variables:n,runtime:o,saveSlots:d,dialogueState:t.dialogue,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,form:f,characters:r.characters||{},skipTransitionsAndAnimations:p}),isLineCompleted:i,skipMode:l,skipTransitionsAndAnimations:p})),e},cc=(e,{presentationState:t,resources:r,runtime:n,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&r){if(!Fe(i))return e;let c=r.sounds[t.bgm.resourceId];if(!c)return e;let a=ge({variables:o,runtime:n}).runtime;s.push({id:"bgm",type:"sound",src:c.fileId,loop:t.bgm.loop??!0,volume:za(a,t.bgm.volume??c.volume??Bt),startDelayMs:t.bgm.startDelayMs??null})}return e},lc=(e,{presentationState:t,resources:r,runtime:n})=>{let{audio:o}=e;if(t.sfx&&r){let i=t.sfx.items;for(let[s,l]of i.entries()){let c=r.sounds?.[l.resourceId];c&&o.push({id:Wa({item:l,index:s}),type:"sound",src:c.fileId,loop:l.loop??c.loop??!1,volume:Ba(n,l.volume??c.volume??Bt),startDelayMs:l.startDelayMs??c.startDelayMs??null})}}return e},uc=(e,t,r)=>{if(!(!t||!r))return e?.voices?.[t]?.[r]},fc=(e={},t={})=>t.muteAll?0:e.volume??t.soundVolume??50,dc=(e,{presentationState:t,resources:r,currentSceneId:n,runtime:o,variables:i})=>{let{audio:s}=e;if(!t?.voice)return e;let l=t.voice,{resourceId:c,loop:a,startDelayMs:u}=l,f=uc(r,n,c);if(!f)return e;let d=ge({variables:i,runtime:o}).runtime;return s.push({id:`voice-${n}-${c}`,type:"sound",src:f.fileId,volume:fc(l,d),loop:a??!1,startDelayMs:u??null}),e},pc=(e,{presentationState:t,previousPresentationState:r,resources:n={},variables:o,runtime:i,autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,form:f,saveSlots:d=[],isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})=>{let{elements:y,animations:b}=e;if(t.layout){let T=Fe(y);if(!T)return e;let w=n.layouts[t.layout.resourceId];if(!w)return e;Array.isArray(w.transitions)&&!p&&!h&&Jr({animations:b,transitions:w.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let D={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:w.elements||[]};T.children.push(No({container:D,resources:n,templateData:ge({variables:o,runtime:i,saveSlots:d,dialogueState:t.dialogue,isLineCompleted:p,autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,form:f,characters:n.characters||{},skipTransitionsAndAnimations:h}),isLineCompleted:p,skipMode:l,skipTransitionsAndAnimations:h}))}let A=r?.layout?.resourceId,v=t.layout?.resourceId,S=xe({animationsDef:t.layout?.animations,resources:n,previousResourceId:A,currentResourceId:v,previousTargetId:A?`layout-${A}`:void 0,currentTargetId:v?`layout-${v}`:void 0,animationPath:"layout.animations",idPrefix:"layout"});return me({animationInstances:S,isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})&&b.push(...S),e},hc=(e,{currentLineActions:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:l}=e,c=t?.screen?.animations;if(!c)return e;let a=r!=null,u=xe({animationsDef:c,resources:n,previousResourceId:a?"story":void 0,currentResourceId:"story",previousTargetId:a?"story":void 0,currentTargetId:"story",animationPath:"screen.animations",idPrefix:"screen"});return me({animationInstances:u,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(...u),e},mc=(e,{presentationState:t})=>{let r=Fe(e.elements);return!r||!t?.screen||Object.assign(r,$o(t.screen)),e},gc=(e,{presentationState:t,resources:r={},variables:n,runtime:o,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:c,canRollback:a,form:u,overlayStack:f=[],dialogueHistory:d=[],saveSlots:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:b,animations:A}=e;return f&&f.length>0&&f.forEach((v,S)=>{let T=r.layouts[v.resourceId];if(!T){console.warn(`Overlay layout not found: ${v.resourceId}`);return}Array.isArray(T.transitions)&&(y||Jr({animations:A,transitions:T.transitions,defaultTargetId:`overlayStack-${S}`,idPrefix:`overlayStack-${S}`,animationPathPrefix:`overlayStack[${S}]`}));let w={id:`overlayStack-${S}`,type:"container",x:0,y:0,children:[Do({id:`overlayStack-${S}-blocker`,screen:h}),...T.elements||[]]},D=Po(d,r.characters),F=ge({variables:n,runtime:o,saveSlots:p,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:i,skipMode:s,isChoiceVisible:l,isFormVisible:c,canRollback:a,form:u,historyDialogue:D,characters:r.characters||{},skipTransitionsAndAnimations:y}),V=se(w,F,{functions:Oe}),[N,...j]=V.children||[],U=Le($e({...V,children:j},{isLineCompleted:g,skipMode:s,skipTransitionsAndAnimations:y}),r);b.push({...U,children:N?[N,...U.children||[]]:U.children})}),e},yc=(e,{presentationState:t,resources:r={},variables:n,runtime:o,saveSlots:i=[],autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,form:f,confirmDialog:d,dialogueHistory:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:b,animations:A}=e;if(!d?.resourceId)return e;let v=r.layouts?.[d.resourceId];if(!v)return console.warn(`ConfirmDialog layout not found: ${d.resourceId}`),e;Array.isArray(v.transitions)&&!y&&Jr({animations:A,transitions:v.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let S={id:"confirmDialog",type:"container",x:0,y:0,children:[Do({id:"confirmDialog-blocker",screen:h}),...v.elements||[]]},T=Po(p,r.characters),w=se(S,ge({variables:n,runtime:o,saveSlots:i,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:s,skipMode:l,isChoiceVisible:c,isFormVisible:a,canRollback:u,form:f,confirmDialog:d,historyDialogue:T,characters:r.characters||{},skipTransitionsAndAnimations:y}),{functions:Oe}),[D,...F]=w.children||[],V=Le($e({...w,children:F},{isLineCompleted:g,skipMode:l,skipTransitionsAndAnimations:y}),r);return b.push({...V,children:D?[D,...V.children||[]]:V.children}),e},pt=e=>(t,r)=>rc(t,{...r,visualLayer:e}),bc=pt(ve.BEHIND_BACKGROUND),Ic=pt(ve.BEHIND_CHARACTER),Ac=pt(ve.BEHIND_DIALOGUE),wc=pt(ve.BEHIND_CHOICE),Ec=pt(ve.FOREGROUND),jo=e=>kt(Qa,[ac,bc,Za,Ic,ec,Ac,oc,wc,ic,sc,pc,Ec,mc,hc,cc,lc,dc,gc,yc])(e);var zt={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},zo=1,en="choice",Wt="form",Yt=()=>({manual:{...zt.manual},auto:{...zt.auto},applyMode:zt.applyMode}),tn=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let r=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...Yt()},r&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},k=e=>{let t=ce(e)?Pe(e):e;return structuredClone(t)},$=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Gt=e=>String(e),Wo=()=>({sections:[],resources:[]}),vc=e=>$(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):Wo(),xc=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",Cc=({sectionId:e,lineId:t,content:r,dialogueState:n,characterName:o})=>({sectionId:e,lineId:t,content:r,text:xc(r),characterId:n.characterId,character:{...n.character||{},name:o},characterName:o}),Sc=()=>({resourceId:void 0}),_c=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},rn=(e,t)=>{let r=e?.story?.scenes??{};for(let[n,o]of Object.entries(r))if(o?.sections?.[t])return{sceneId:n,section:o.sections[t]};return{sceneId:void 0,section:void 0}},qo=e=>{let t=e?.story?.scenes??{},r=new Map;for(let[n,o]of Object.entries(t)){let i=o?.sections??{};for(let s of Object.keys(i)){let l=r.get(s);if(l!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${l}" and "${n}". Section IDs must be globally unique.`);r.set(s,n)}}},Ho=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},Yo=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==zo)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},Rc=(e,t={})=>{let r;try{r=Yo(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let n={...t,formatVersion:r,slotId:Ho(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete n.slotKey,delete n.date,n},Oc=(e={})=>Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Rc(t,r)])),Go=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:r})=>Iu(r));return t.length>0?t:void 0},Lc=e=>{!$(e)||!Array.isArray(e.timeline)||e.timeline.forEach(t=>{if(!$(t))return;let r=Go(t.executedActions);if(r){t.executedActions=r;return}delete t.executedActions})},Mo=(e,t,r,n="viewedRegistry")=>{let o=t==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[o]:String(e)};if(!$(e))throw new Error(`Malformed ${n}.${t}[${r}] entry.`);if(typeof e[o]!="string"||e[o].length===0)throw new Error(`Malformed ${n}.${t}[${r}] entry: missing ${o}.`);if(t==="sections"){let i={sectionId:e.sectionId};if(e.lastLineId!==void 0&&e.lastLineId!==null&&typeof e.lastLineId!="string")throw new Error(`Malformed ${n}.sections[${r}] entry: invalid lastLineId.`);return typeof e.lastLineId=="string"&&e.lastLineId.length>0&&(i.lastLineId=e.lastLineId),i}return{resourceId:e.resourceId}},$c=(e,t="viewedRegistry")=>{if(e===void 0)return Wo();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 r=e.sections??[],n=e.resources??[];return{sections:Object.values(Object.fromEntries(r.map((o,i)=>{let s=Mo(o,"sections",i,t);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(n.map((o,i)=>{let s=Mo(o,"resources",i,t);return[s.resourceId,s]})))}},Ko=(e,t,r)=>{if(!$(e))throw new Error(`Malformed save slot ${r}.`);let{sectionId:n,lineId:o}=e;if(typeof n!="string"||n.length===0)throw new Error(`Malformed save slot ${r}: missing sectionId.`);if(typeof o!="string"||o.length===0)throw new Error(`Malformed save slot ${r}: missing lineId.`);let{sceneId:i,section:s}=rn(t,n);if(!s)throw new Error(`Malformed save slot ${r}: section "${n}" does not exist in projectData.`);if(!s.lines?.some(c=>c.id===o))throw new Error(`Malformed save slot ${r}: line "${o}" does not exist in section "${n}".`);return{sceneId:i,sectionId:n,lineId:o}},kc=(e,t,r)=>{if(!$(e)||!Array.isArray(e.timeline))return ht({pointer:t,replayStartIndex:1});let n=e.timeline.flatMap((l,c)=>{if(!$(l))return[];try{let a=Ko(l,r,`rollback.timeline[${c}]`),u=Ht({sectionId:a.sectionId,lineId:a.lineId,rollbackPolicy:l.rollbackPolicy}),f=Go(k(l.executedActions));return f&&(u.executedActions=f),[u]}catch{return[]}});if(n.length===0)return ht({pointer:t,replayStartIndex:1});let o=typeof e.currentIndex=="number"?Math.trunc(e.currentIndex):n.length-1;(o<0||o>=n.length)&&(o=n.length-1);let i=n[o];if(i?.sectionId!==t.sectionId||i?.lineId!==t.lineId){let l=n.findLastIndex(c=>c.sectionId===t.sectionId&&c.lineId===t.lineId);l>=0?o=l:(n.push(Ht({sectionId:t.sectionId,lineId:t.lineId})),o=n.length-1)}let s=typeof e.replayStartIndex=="number"?Math.min(Math.max(Math.trunc(e.replayStartIndex),0),o):0;return{currentIndex:o,isRestoring:!1,replayStartIndex:s,timeline:n}},Tc=(e,t,r)=>{if(!$(e))throw new Error(`Malformed save slot contexts[${r}] entry.`);let n=sn(t),o=Ko(e.pointers?.read,t,`contexts[${r}].pointers.read`);if(e.variables!==void 0&&!$(e.variables))throw new Error(`Malformed save slot contexts[${r}].variables entry.`);if(e.runtime!==void 0&&!$(e.runtime))throw new Error(`Malformed save slot contexts[${r}].runtime entry.`);let i=e.variables?Ge(k(e.variables),t.resources?.variables??{}):{},s=Hc({loadedContextRuntime:$(e.runtime)?k(e.runtime):{}}),l={currentPointerMode:"read",pointers:{read:o},configuration:$(e.configuration)?k(e.configuration):{},views:Array.isArray(e.views)?k(e.views):[],bgm:$(e.bgm)?k(e.bgm):{resourceId:void 0},variables:{...n,...i},rollback:kc(e.rollback,o,t)};return s&&(l.runtime=s),l},Dc=(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((r,n)=>Tc(r,t,n))}},Pc=(e,t)=>{if(!$(e))throw new Error("Malformed save slot.");let r=Yo(e.formatVersion);return{...e,formatVersion:r,state:Dc(e.state,t)}},Fo=(e,t,{required:r=!1}={})=>{if(e===void 0){if(r)throw new Error(`showConfirmDialog requires ${t}`);return{hideConfirmDialog:{}}}if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`showConfirmDialog ${t} must be an action object`);let n=k(e);return Object.prototype.hasOwnProperty.call(n,"hideConfirmDialog")||(n.hideConfirmDialog={}),n},Nc=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:Fo(e.confirmActions,"confirmActions",{required:!0}),cancelActions:Fo(e.cancelActions,"cancelActions")}},et=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},Vc=e=>($(e.global.formDrafts)||(e.global.formDrafts={}),e.global.formDrafts),tt=e=>{Object.prototype.hasOwnProperty.call(e.global,"formDrafts")&&(e.global.formDrafts={})},Jo=e=>{if(!(!$(e)||!e.animations))return{animations:k(e.animations)}},jc=(e,t)=>{let r=Jo(t);if(r){e.global.pendingScreenTransition=r;return}delete e.global.pendingScreenTransition},Mc=e=>{let t=e?.id??e?.resourceId;return typeof t=="string"&&t.length>0?t:void 0},Fc=(e,t)=>{let r=e?.sectionId,n=e?.lineId;if(!(!r||!n||!t))return`${r}:${n}:${t}`},qt=e=>String(e??""),Xo=(e,t)=>{let r=qt(t);return e?.trim===!0?r.trim():r},Uc=e=>$(e?.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,t])=>$(t)).map(([t,r])=>[t,{id:t,...k(r)}])):{},Bc=(e,t)=>{if(!t||!$(e.global.formDrafts))return;let r=e.global.formDrafts[t];return $(r)?r:void 0},Qo=(e,t)=>{let r=Vc(e);$(r[t])||(r[t]={values:{},touched:{},errors:{},submitted:!1});let n=r[t];return $(n.values)||(n.values={}),$(n.touched)||(n.touched={}),$(n.errors)||(n.errors={}),typeof n.submitted!="boolean"&&(n.submitted=!1),n},nn=(e,t)=>{let r=Xo(e,t);return e?.required===!0&&r.length===0?"required":null},zc=({state:e,pointer:t})=>{if(!t?.sectionId||!t?.lineId)return{};let n=ee({state:e},{sectionId:t.sectionId})?.lines||[],o=n.findIndex(i=>i.id===t.lineId);return o<0?{}:Ve(n.slice(0,o+1).map(i=>i.actions||{}))},Wc=({state:e,form:t,pointer:r})=>{if(!t?.resourceId)return null;let n=Mc(t),o=Fc(r,n);if(!n||!o)return null;let i=Bc(e,o),s=Uc(t),l=fn({state:e}),c={},a=[],u={},f=!0;return Object.entries(s).forEach(([d,p])=>{let h=qt(l?.[p.variableId]),g=Object.prototype.hasOwnProperty.call(i?.values??{},d)?qt(i.values[d]):h,y=i?.touched?.[d]===!0,b=nn(p,g),A=i?.submitted||y?b:null,v=typeof p.maxLength=="number"?Math.max(0,Math.round(p.maxLength)):void 0,S={id:d,variableId:p.variableId,value:g,initialValue:h,valid:!b,error:A,touched:y,required:p.required===!0,trim:p.trim===!0,placeholder:p.placeholder===void 0?"":String(p.placeholder),multiline:p.multiline===!0,...v!==void 0?{maxLength:v}:{}};b&&(f=!1),c[d]=S,a.push(S),u[d]=g}),{id:n,key:o,resourceId:t.resourceId,animations:t.animations,valid:f,submitted:i?.submitted===!0,fields:c,fieldList:a,values:u,submitActions:{submitForm:{formKey:o,actions:k(t.submitActions??{})}},cancelActions:{cancelForm:{formKey:o,actions:k(t.cancelActions??{})}}}},Ue=[],Uo="line",on="interaction",Ht=({sectionId:e,lineId:t,rollbackPolicy:r})=>({sectionId:e,lineId:t,rollbackPolicy:r??"free"}),sn=e=>{let{contextVariableDefaultValues:t}=Er(e??{});return k(t)},Zo=()=>({...k(ut)}),ei=({loadedRuntime:e,runtimeIds:t,defaults:r={},path:n})=>{if(e===void 0)return{runtimeState:k(r),hasLoadedValues:!1};if(!$(e))throw new Error(`Malformed ${n}.`);let o=k(r),i=!1;return t.forEach(s=>{e[s]!==void 0&&(o[s]=ti(s,k(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},qc=({loadedGlobalRuntime:e={}})=>ei({loadedRuntime:e,runtimeIds:_r,defaults:je,path:"global.runtime"}).runtimeState,Hc=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:r}=ei({loadedRuntime:e,runtimeIds:Rr,defaults:Zo(),path:"context.runtime"});return r?t:void 0},an=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},Yc=e=>e.runtime?(Rr.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=k(ut[t]))}),e.runtime):(e.runtime=Zo(),e.runtime),Gc=e=>fo(e.global),Kc=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:Gc(e)}})},Jc=e=>uo[e],Xc=(e,t)=>{let r=Jc(e);if(r==="number"){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} requires a finite numeric value`);return}if(r==="boolean"){if(typeof t!="boolean")throw new Error(`${e} requires a boolean value`);return}if(r==="string"){if(typeof t!="string")throw new Error(`${e} requires a string value`);return}throw new Error(`Unsupported runtime field "${e}"`)},ti=(e,t)=>(Xc(e,t),e==="saveLoadPagination"?Math.max(1,Math.trunc(t)):t),ri=(e,t,r)=>{let n=ti(t,r);if(t in ut){let o=an(e);if(!o)return n;let i=Yc(o);return i[t]=n,n}return e.global[t]=n,n},ni=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:k(e)},configuration:{},views:[],bgm:Sc(),variables:sn(t),rollback:ht({pointer:e})}),rt=e=>e?(e.currentPointerMode="read",$(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,Qc=(e,{queueRender:t=!0}={})=>{let r=e.contexts?.[e.contexts.length-1],n=r?.pointers?.read;if(!r||!n?.sectionId||!n?.lineId)return null;let o=ni({pointer:n,projectData:e.projectData});return e.contexts[e.contexts.length-1]=o,Zc(e,{queueRender:t}),o},Zc=(e,{queueRender:t=!0}={})=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,et(e),tt(e),e.global.nextLineConfig=Yt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"}),t&&e.global.pendingEffects.push({name:"render"})},oi=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},ht=({pointer:e,replayStartIndex:t=0})=>{let r=e?.sectionId&&e?.lineId;return{currentIndex:r?0:-1,isRestoring:!1,replayStartIndex:t,timeline:r?[Ht({sectionId:e.sectionId,lineId:e.lineId})]:[]}},ze=(e,t={})=>{if(e?.rollback)return oi(e.rollback),Array.isArray(e.rollback.timeline)||(e.rollback.timeline=[]),typeof e.rollback.currentIndex!="number"&&(e.rollback.currentIndex=e.rollback.timeline.length>0?e.rollback.timeline.length-1:-1),typeof e.rollback.isRestoring!="boolean"&&(e.rollback.isRestoring=!1),typeof e.rollback.replayStartIndex!="number"&&(e.rollback.replayStartIndex=0),e.rollback;let r=e?.pointers?.read;return e.rollback=ht({pointer:r,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},cn=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return;let n=ze(r);if(n.isRestoring)return;n.currentIndex<n.timeline.length-1&&(n.timeline=n.timeline.slice(0,n.currentIndex+1));let o=n.timeline[n.timeline.length-1];if(o?.sectionId===t.sectionId&&o?.lineId===t.lineId&&(o?.rollbackPolicy??"free")===(t.rollbackPolicy??"free")){n.currentIndex=n.timeline.length-1;return}n.timeline.push(Ht(t)),n.currentIndex=n.timeline.length-1},el=e=>{let r=e.contexts?.[e.contexts.length-1]?.rollback;if(!r||r.isRestoring||!Array.isArray(r.timeline)||typeof r.currentIndex!="number")return null;let n=Ue[Ue.length-1],o=typeof n?.checkpointIndex=="number"?n.checkpointIndex:r.currentIndex;return o<0||o>=r.timeline.length?null:(typeof n?.checkpointIndex!="number"&&o<r.timeline.length-1&&(r.timeline=r.timeline.slice(0,o+1)),r.timeline[o]??null)},tl=({state:e},t={})=>{let r=t?.source===Uo?Uo:on,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?(Ue.push({checkpointIndex:null,source:r}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),Ue.push({checkpointIndex:o.currentIndex,source:r}),e)},rl=({state:e})=>(Ue.pop(),e),Ae=(e,t,r)=>{let o=Ue[Ue.length-1]?.source??on;if(!Au(t,o))return;let i=el(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:k(r)}))},Bo=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return;let n=t?.operations??[];for(let{variableId:o,op:i,value:s,roundTo:l}of n){let c=e.projectData.resources?.variables?.[o],a=c?.scope,u=c?.type;if(Re(c))throw new Error(`Cannot update computed variable: ${o}`);if(c?.readonly===!0)throw new Error(`Cannot update readonly variable: ${o}`);Dt(a,o),Pt(u,i,o),vr(u,i,s,o,{roundTo:l}),a==="context"&&(r.variables[o]=Nt(r.variables[o],i,s,{roundTo:l}))}},nl=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:r,payload:n})=>{wu(e,r,n)})},ol=(e,t)=>{let{sectionId:r,lineId:n}=t,s=ee({state:e},{sectionId:r})?.lines?.find(l=>l.id===n)?.actions;s&&Object.entries(s).forEach(([l,c])=>{wi(e,l,c)})},ii=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let n=ze(r),o=n.timeline[t];if(!o)return e;e.global.autoMode&>({state:e}),e.global.skipMode&&Be({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),n.isRestoring=!0,n.currentIndex=t;try{r.variables=sn(e.projectData),delete r.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=k(zt),e.global.overlayStack=[],et(e),tt(e),e.global.isLineCompleted=!0;let i=n.replayStartIndex??0;for(let l=i;l<=t;l++)l>i&&tn(e),ol(e,n.timeline[l]),nl(e,n.timeline[l]);let s=rt(r);s.read={sectionId:o.sectionId,lineId:o.lineId},e.global.pendingEffects=e.global.pendingEffects.filter(l=>l?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{n.isRestoring=!1}return e},il=e=>{let{projectData:t}=e,r=e.global??{},{saveSlots:n={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=r;qo(t);let l=t.story.initialSceneId,c=t.story.scenes[l],a=c.initialSectionId,u=c.sections[a],f={sceneId:l,sectionId:a,lineId:u.initialLineId??u.lines[0].id},{globalVariablesDefaultValues:d}=Er(t),p={...d,...Ge(o,t.resources?.variables??{})};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,formDrafts:{},accountViewedRegistry:$c(s,"accountViewedRegistry"),nextLineConfig:Yt(),saveSlots:Oc(n),overlayStack:[],variables:p,...qc({loadedGlobalRuntime:i})},contexts:[ni({pointer:f,projectData:t})]}},sl=({state:e})=>e.global.overlayStack||[],al=({state:e})=>e.global.pendingEffects,si=({state:e})=>e.global.skipMode,cl=({state:e})=>e.global.autoMode,ai=({state:e})=>e.global.dialogueUIHidden,ci=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],r=t[t.length-1];if(!r)return[];let{sectionId:n,lineId:o}=r.pointers.read,i=ee({state:e},{sectionId:n});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(u=>u.id===o),l=i.lines.slice(0,s+1),c=[],a={};for(let u of l){let f=u.actions||{};if(a=Ve([a,f]),!f.dialogue)continue;let d=a.dialogue||{},p="";d.character?.name!==void 0?p=d.character.name:d.characterId&&(p=e.projectData.resources?.characters?.[d.characterId]?.name||"");let h=Cc({sectionId:n,lineId:u.id,content:f.dialogue.append===!0?d.content:f.dialogue.content,dialogueState:d,characterName:p});if(f.dialogue.append===!0&&c.length>0){c[c.length-1]={...c[c.length-1],content:h.content,text:h.text,characterId:h.characterId,character:h.character,characterName:h.characterName};continue}c.push(h)}return c},ll=({state:e})=>e.global.confirmDialog??null,mt=({state:e},{pointer:t}={})=>{let r=t??ye({state:e})?.pointer,n=zc({state:e,pointer:r});return Wc({state:e,form:n.form,pointer:r})},ul=({state:e},{pointer:t}={})=>!!mt({state:e},{pointer:t}),we=({state:e},{pointer:t}={})=>{let r=mt({state:e},{pointer:t});if(r)return{source:Wt,formId:r.id,formKey:r.key};let n=li({state:e,pointer:t});return n?{source:en,resourceId:n}:null},fl=({state:e,registry:t},r)=>{let{sectionId:n,lineId:o}=r,s=(Array.isArray(t?.sections)?t.sections:[]).find(u=>u.sectionId===n);if(!s)return!1;if(s.lastLineId===void 0||o===void 0)return!0;let l=ee({state:e},{sectionId:n});if(!l||!l.lines||!Array.isArray(l.lines))return s.lastLineId===o;let c=l.lines.findIndex(u=>u.id===s.lastLineId),a=l.lines.findIndex(u=>u.id===o);return c===-1||a===-1?s.lastLineId===o:a<=c},dl=({registry:e},t)=>{let{resourceId:r}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===r)},ln=({state:e},t)=>fl({state:e,registry:e.global.accountViewedRegistry},t),pl=({state:e},t)=>dl({registry:e.global.accountViewedRegistry},t),hl=({state:e})=>e.global.nextLineConfig,li=({state:e,pointer:t}={})=>{let r=t??ye({state:e})?.pointer;if(!r)return;let n=r?.sectionId,o=r?.lineId,s=ee({state:e},{sectionId:n})?.lines||[],l=s.findIndex(a=>a.id===o);if(l<0)return;let c;for(let a of s.slice(0,l+1)){let u=a?.actions;if(u?.cleanAll&&(c=void 0),!u||!Object.prototype.hasOwnProperty.call(u,"choice")){c=void 0;continue}let f=u.choice;if(f?.resourceId){c=f.resourceId;continue}f?.animations||(c=void 0)}return c},ui=({state:e})=>!!li({state:e}),ml=({state:e})=>structuredClone(e),fi=({state:e})=>e.global.saveSlots,gl=({state:e},t)=>{let r=t?.slotId,n=Gt(r);return e.global.saveSlots[n]},un=({state:e})=>Ke(e),yl=({state:e},t)=>Ee(e,t?.runtimeId),fn=({state:e})=>{let t={...e.global?.variables??{},...an(e)?.variables??{}};return Tt({variables:t,runtime:Ke(e),variableConfigs:e.projectData.resources?.variables??{}})},ye=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],r=t[t.length-1];if(r)return{currentPointerMode:"read",pointer:r.pointers?.read}},ee=({state:e},t)=>{let{sectionId:r}=t;return rn(e.projectData,r).section},dn=({state:e})=>{let t=ye({state:e});if(!t?.pointer)return;let{sectionId:r,lineId:n}=t.pointer,o=ee({state:e},{sectionId:r});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===n)},di=({state:e})=>{let{sectionId:t,lineId:r}=ye({state:e}).pointer,o=ee({state:e},{sectionId:t})?.lines||[],i=o.findIndex(a=>a.id===r),l=o.slice(0,i+1).map(a=>{let u=a.actions||{},f={};return Object.keys(u).forEach(d=>{f[d]=u[d]}),f});return Ve(l)},bl=({state:e})=>{let t=pi({state:e}),n=dn({state:e})?.actions??{},o=Ve([t??{},n]);return xr(t??{},o??{})},Il=({state:e},{sectionId:t})=>{let r=ee({state:e},{sectionId:t});if(!r?.lines)return[];let n=[],o={};for(let i of r.lines){let s=i.actions||{},l=Ve([o,s]),c=xr(o,l);n.push({id:i.id,changes:c,presentationState:l}),o=Cr(l)}return n},Al=({state:e},{sectionId:t,includePresentationState:r=!1})=>{let n=Il({state:e},{sectionId:t});return r?{lines:n}:{lines:n.map(({presentationState:o,...i})=>i)}},pi=({state:e})=>{let{sectionId:t,lineId:r}=ye({state:e}).pointer,o=ee({state:e},{sectionId:t})?.lines||[],i=o.findIndex(c=>c.id===r);if(i<=0)return null;let l=o.slice(0,i).map(c=>{let a=c.actions||{},u={};return Object.keys(a).forEach(f=>{u[f]=a[f]}),u});return Cr(Ve(l))},pn=({state:e},{slotsPerPage:t=6}={})=>{let o=((un({state:e}).saveLoadPagination??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let l=o+s,c=e.global.saveSlots&&e.global.saveSlots[Gt(l)]||{};i.push({...c,slotId:l})}return{saveSlots:i}},wl=fi,El=pn,vl=e=>{let r=e.contexts?.[e.contexts.length-1]?.rollback;return!r||!Array.isArray(r.timeline)||typeof r.currentIndex!="number"?!1:r.currentIndex>=0&&r.currentIndex<r.timeline.length-1},xl=({state:e},t={})=>{let r=di({state:e}),n=pi({state:e}),o=dn({state:e})?.actions??{},i=e.global.pendingScreenTransition,s=i?.animations?{...o,screen:k(i)}:o,l=i?.animations&&n===null?{}:n,{sectionId:c}=ye({state:e}).pointer,{sceneId:a}=rn(e.projectData,c),u=un({state:e}),f=t?.activePersistentAnimations??[],d=t?.restoredPersistentAnimations??[],p=mt({state:e}),h=ui({state:e}),g=fn({state:e}),{saveSlots:y}=pn({state:e}),b=vl(e);return jo({presentationState:r,previousPresentationState:l,currentLineActions:s,resources:e.projectData.resources,currentSceneId:a,screen:e.projectData.screen,dialogueUIHidden:u.dialogueUIHidden,autoMode:u.autoMode,skipMode:u.skipMode,isChoiceVisible:h,isFormVisible:!!p,canRollback:vi({state:e}),skipOnlyViewedLines:!u.skipUnseenText,isLineCompleted:u.isLineCompleted,skipTransitionsAndAnimations:!!u.skipTransitionsAndAnimations||b,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,form:p,dialogueHistory:ci({state:e}),saveSlots:y,variables:g,runtime:u,activePersistentAnimations:f,restoredPersistentAnimations:d})},Cl=({state:e},t)=>(e.global.confirmDialog=Nc(t),e.global.pendingEffects.push({name:"render"}),e),Sl=({state:e})=>(e.global.confirmDialog&&(et(e),e.global.pendingEffects.push({name:"render"})),e),_l=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),Ae(e,"pushOverlay",t),e),Rl=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),Ae(e,"popOverlay",void 0),e),Ol=({state:e},t)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=t),e.global.pendingEffects.push({name:"render"}),Ae(e,"replaceLastOverlay",t),e),Ll=({state:e})=>(e.global.overlayStack=[],et(e),tt(e),e.global.pendingEffects.push({name:"render"}),Ae(e,"clearOverlays",void 0),e),$l=e=>{e.global.autoMode&&(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"})),e.global.skipMode&&(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"})),e.global.nextLineConfig?.auto?.enabled&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},Kt=(e,t,{screenTransition:r}={})=>{e.global.isLineCompleted=!1,jc(e,r),tt(e);let n=we({state:e},{pointer:t}),o=n?.source===en,i=n?.source===Wt;return n&&$l(e),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:o,isFormVisible:i,activeInteraction:n}},hi=({state:e})=>(we({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:Ee(e,"autoForwardDelay")}}),e.global.pendingEffects.push({name:"render"})),e),gt=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),kl=({state:e})=>{let t=e.global.autoMode;return we({state:e})&&!t||(t?gt({state:e}):hi({state:e})),e},mi=({state:e})=>(we({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),Be=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Tl=({state:e})=>{let t=si({state:e});return we({state:e})&&!t||(t?Be({state:e}):mi({state:e})),e},Jt=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),Ae(e,"showDialogueUI",void 0),e),gi=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),Ae(e,"hideDialogueUI",void 0),e),Dl=({state:e})=>(ai({state:e})?Jt({state:e}):gi({state:e}),e),We=(e,t,r)=>(ri(e,t,r),Kc(e),e.global.pendingEffects.push({name:"render"}),e),yt=(e,t,r,n)=>{let o=ri(e,t,r);return e.global.pendingEffects.push({name:"render"}),Ae(e,n,{value:o}),e},Pl=({state:e},t)=>We(e,"dialogueTextSpeed",t?.value),Nl=({state:e},t)=>We(e,"autoForwardDelay",t?.value),Vl=({state:e},t)=>We(e,"skipUnseenText",t?.value),jl=({state:e},t)=>We(e,"skipTransitionsAndAnimations",t?.value),Ml=({state:e},t)=>We(e,"soundVolume",t?.value),Fl=({state:e},t)=>We(e,"musicVolume",t?.value),Ul=({state:e},t)=>We(e,"muteAll",t?.value),Bl=({state:e},t)=>yt(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),zl=({state:e})=>{let t=Ee(e,"saveLoadPagination")+1;return yt(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},Wl=({state:e})=>{let t=Ee(e,"saveLoadPagination")-1;return yt(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},ql=({state:e},t)=>yt(e,"menuPage",t?.value,"setMenuPage"),Hl=({state:e},t)=>yt(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),Yl=({state:e})=>(e.global.pendingEffects=[],e),Gl=({state:e},t)=>(e.global.pendingEffects.push(t),e),yi=(e,{sectionId:t,resetStoryState:r=!1,screen:n})=>{let o=!!Jo(n),i=ee({state:e},{sectionId:t});if(!i)return console.warn(`Section not found: ${t}`),e;let s=i.lines?.[0];if(!s)return console.warn(`Section ${t} has no lines`),e;if(r&&!Qc(e,{queueRender:!o}))return e;e.global.autoMode&>({state:e}),r&&e.global.skipMode&&Be({state:e});let l=e.contexts?.[e.contexts.length-1];if(l){let c=rt(l),a=c.read;r||Ze(e,{sectionId:a?.sectionId,lineId:a?.lineId}),l.rollback||ze(l,{compatibilityAnchor:!0}),c.read={sectionId:t,lineId:s.id},r?l.rollback=ht({pointer:c.read}):cn(e,{sectionId:t,lineId:s.id})}return Kt(e,l?.pointers?.read,{screenTransition:n}),e},Kl=({state:e},t)=>yi(e,{sectionId:t?.sectionId,resetStoryState:!0,screen:t?.screen}),bi=e=>(e.global.accountViewedRegistry=vc(e.global.accountViewedRegistry),e.global.accountViewedRegistry),hn=(e,t)=>{!Array.isArray(t)||t.length===0||e.global.pendingEffects.push({name:"applyScopedDataUpdates",payload:{updates:t.map(r=>({scope:r.scope,path:r.path,op:r.op,value:k(r.value)}))}})},Ii=(e,t)=>{hn(e,[{scope:"account",path:"viewedRegistry",op:"markViewed",value:{sections:(Array.isArray(t?.sections)?t.sections:[]).map(r=>({sectionId:r.sectionId,...r.lastLineId===void 0?{}:{lineId:r.lastLineId}})),resources:Array.isArray(t?.resources)?t.resources:[]}}])},Jl=(e,t,{sectionId:r,lineId:n})=>{if(!r||!n)return!1;let o=$(t)?t:{};Array.isArray(o.sections)||(o.sections=[]);let i=o.sections.find(s=>s.sectionId===r);if(i){if(i.lastLineId===void 0)return!1;let s=ee({state:e},{sectionId:r});if(s?.lines){let l=s.lines.findIndex(a=>a.id===i.lastLineId),c=s.lines.findIndex(a=>a.id===n);if(l===-1||c>l)return i.lastLineId===n?!1:(i.lastLineId=n,!0)}else return i.lastLineId===n?!1:(i.lastLineId=n,!0);return!1}else return o.sections.push({sectionId:r,lastLineId:n}),!0},Ze=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;Jl(e,bi(e),t)&&Ii(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},Xl=({state:e},t)=>(Ze(e,t),e.global.pendingEffects.push({name:"render"}),e),Ql=({state:e},t)=>{let{resourceId:r}=t;if(e.global.accountViewedRegistry!==void 0){let n=bi(e);n.resources.find(i=>i.resourceId===r)||(n.resources.push({resourceId:r}),Ii(e,{sections:[],resources:[{resourceId:r}]}))}return e.global.pendingEffects.push({name:"render"}),e},Ai=({state:e},t)=>{let r=_c(t.manual),{auto:n,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,l=e.contexts?.[e.contexts.length-1]?.rollback?.isRestoring===!0;r&&n?(e.global.nextLineConfig={manual:r,auto:n},o!==void 0?e.global.nextLineConfig.applyMode=o:s!==void 0&&(e.global.nextLineConfig.applyMode=s)):(r&&(e.global.nextLineConfig.manual=r),n&&(e.global.nextLineConfig.auto=n),o!==void 0&&(e.global.nextLineConfig.applyMode=o));let c=e.global.nextLineConfig.auto?.enabled,a=we({state:e});return!l&&!a&&c===!0&&!i?e.global.nextLineConfig.auto?.trigger==="fromStart"?e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):e.global.isLineCompleted&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):!l&&c===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),Ae(e,"setNextLineConfig",t),e},Zl=({state:e},t)=>{let r=t?.slotId;if(r==null||r==="")throw new Error("saveSlot requires slotId");let{thumbnailImage:n}=t,o=t?.savedAt,i=Gt(r),s=k(e.contexts);s?.forEach(a=>{rt(a),oi(a.rollback),Lc(a.rollback)});let l={contexts:s},c={formatVersion:zo,slotId:Ho(r),savedAt:typeof o=="number"?o:Date.now(),image:n,state:l};return e.global.saveSlots[i]=c,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},eu=({state:e},t)=>{let r=t?.slotId;if(r==null||r==="")throw new Error("loadSlot requires slotId");let n=Gt(r),o=e.global.saveSlots[n];if(o){let i=Pc(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=Yt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,et(e),tt(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},tu=({state:e},t)=>{let{projectData:r}=t;qo(r),e.projectData=r;let n=r?.resources?.variables??{};return Object.prototype.hasOwnProperty.call(e.global??{},"variables")&&(e.global.variables=Ge(e.global.variables,n)),e.contexts?.forEach(o=>{Object.prototype.hasOwnProperty.call(o??{},"variables")&&(o.variables=Ge(o.variables,n))}),et(e),tt(e),e.global.pendingEffects.push({name:"render"}),e},ru=({state:e},t)=>{let{sectionId:r,lineId:n}=t;if(!n)return console.warn("jumpToLine requires lineId parameter"),e;let o=e.contexts[e.contexts.length-1];if(!o)return console.warn("No context available for jumpToLine"),e;let i=r||o.pointers.read?.sectionId;if(r&&!ee({state:e},{sectionId:r}))return console.warn(`Section not found: ${r}`),e;let s=ee({state:e},{sectionId:i});if(!s?.lines||!Array.isArray(s.lines))return console.warn(`Section ${i} has no lines`),e;if(!s.lines.find(a=>a.id===n))return console.warn(`Line not found: ${n} in section ${i}`),e;let c=rt(o);return c.read={sectionId:i,lineId:n},Kt(e,c.read),e},nu=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return Jt({state:e}),e;let r=we({state:e});if(r?.source===en&&t?.bypassChoice!==!0||r?.source===Wt&&t?._interactionSource!==Wt)return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let u=ye({state:e})?.pointer,f=u?.sectionId,d=u?.lineId;f&&d&&Ze(e,{sectionId:f,lineId:d}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:Ee(e,"autoForwardDelay")}});let p=e.global.nextLineConfig;return p?.auto?.enabled&&p.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:p.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e}let n=ye({state:e})?.pointer,o=n?.sectionId,i=ee({state:e},{sectionId:o}),s=e.contexts[e.contexts.length-1],l=i?.lines||[],a=l.findIndex(u=>u.id===n?.lineId)+1;if(a<l.length){let u=l[a],f=!Ee(e,"skipUnseenText");if(e.global.skipMode&&f&&!ln({state:e},{sectionId:o,lineId:u.id}))return Be({state:e}),e;if(s&&!s.rollback&&ze(s,{compatibilityAnchor:!0}),s){let h=rt(s),g=h.read?.lineId;g&&o&&Ze(e,{sectionId:o,lineId:g}),h.read={sectionId:o,lineId:u.id}}cn(e,{sectionId:o,lineId:u.id}),tn(e);let{activeInteraction:d}=Kt(e,{sectionId:o,lineId:u.id}),p=e.global.nextLineConfig;p?.auto?.enabled&&!d&&p.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:p.auto.delay}})}else e.global.autoMode&>({state:e}),e.global.skipMode&&Be({state:e});return e},ou=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0,delete e.global.pendingScreenTransition;let t=we({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:Ee(e,"autoForwardDelay")}});let r=ye({state:e})?.pointer,n=r?.sectionId,o=r?.lineId;n&&o&&Ze(e,{sectionId:n,lineId:o});let i=e.global.nextLineConfig;return i?.auto?.enabled&&!t&&i.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:i.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e},iu=({state:e},t)=>yi(e,{sectionId:t?.sectionId,screen:t?.screen}),su=({state:e})=>{if(e.global.dialogueUIHidden)return Jt({state:e}),e;if(we({state:e}))return e;let t=ye({state:e})?.pointer,r=t?.sectionId,n=ee({state:e},{sectionId:r}),o=e.contexts[e.contexts.length-1],i=n?.lines||[],l=i.findIndex(c=>c.id===t?.lineId)+1;if(l<i.length){let c=i[l],a=!Ee(e,"skipUnseenText");if(e.global.skipMode&&a&&!ln({state:e},{sectionId:r,lineId:c.id}))return Be({state:e}),e;if(o&&!o.rollback&&ze(o,{compatibilityAnchor:!0}),o){let f=rt(o),d=f.read?.lineId;d&&r&&Ze(e,{sectionId:r,lineId:d}),f.read={sectionId:r,lineId:c.id}}cn(e,{sectionId:r,lineId:c.id}),tn(e);let{activeInteraction:u}=Kt(e,{sectionId:r,lineId:c.id});e.global.nextLineConfig.auto?.enabled&&!u&&e.global.nextLineConfig.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}})}else e.global.nextLineConfig.auto?.enabled&&(e.global.nextLineConfig.auto.enabled=!1,e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}));return e},mn=(e,t={})=>{let r=mt({state:e});return!r||t.formKey&&t.formKey!==r.key||t.formId&&t.formId!==r.id?null:r},au=(e,t)=>{if(!t.variableId)throw new Error(`form field "${t.id}" requires variableId`);let r=e.projectData.resources?.variables?.[t.variableId],n=r?.scope,o=r?.type;if(Re(r))throw new Error(`Cannot update computed variable: ${t.variableId}`);if(r?.readonly===!0)throw new Error(`Cannot update readonly variable: ${t.variableId}`);return Dt(n,t.variableId),Pt(o,"set",t.variableId),{variableConfig:r,scope:n}},cu=(e,t)=>({id:e.id,key:e.key,valid:!0,values:k(t),fields:k(e.fields),fieldList:k(e.fieldList)}),lu=({state:e},t={})=>{let r=mn(e,t),n=t.field;if(!r?.fields?.[n])return e;let o=Qo(e,r.key),i=qt(t.value),s=r.fields[n],l=nn(s,i);return o.values[n]=i,o.touched[n]=!0,l?o.errors[n]=l:delete o.errors[n],e.global.pendingEffects.push({name:"render"}),e},uu=({state:e},t={})=>{let r=mn(e,t);if(!r)return{submitted:!1,valid:!1,reason:"inactive"};let n=Qo(e,r.key);n.submitted=!0;let o={},i={};if(Object.entries(r.fields).forEach(([f,d])=>{let p=Object.prototype.hasOwnProperty.call(n.values,f)?n.values[f]:d.value,h=nn(d,p);n.touched[f]=!0,h&&(i[f]=h),o[f]=Xo(d,p)}),n.errors=i,Object.keys(i).length>0)return e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!1,errors:k(i),form:{id:r.id,key:r.key,values:k(o)}};let s=e.contexts[e.contexts.length-1];if(s?.rollback?.isRestoring)return{submitted:!1,valid:!1,reason:"restoring"};let l=!1,c=[],a=[];Object.entries(r.fields).forEach(([f,d])=>{let{scope:p}=au(e,d),h=p==="context"?s.variables:e.global.variables,g=o[f];h[d.variableId]=Nt(h[d.variableId],"set",g),p==="context"&&(l=!0,a.push({variableId:d.variableId,op:"set",value:g})),(p==="device"||p==="account")&&c.push({scope:p,path:`variables.${d.variableId}`,op:"set",value:k(h[d.variableId])})}),l&&Ae(e,"updateVariable",{id:"submitForm",operations:a}),hn(e,c);let u=cu(r,o);return delete e.global.formDrafts[r.key],e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!0,form:u}},fu=({state:e},t={})=>{let r=mn(e,t);return r?(delete e.global.formDrafts?.[r.key],e.global.pendingEffects.push({name:"render"}),{cancelled:!0,form:{id:r.id,key:r.key,values:k(r.values),fields:k(r.fields),fieldList:k(r.fieldList)}}):{cancelled:!1,reason:"inactive"}},du=({state:e},t)=>{let{id:r,operations:n=[]}=t;if(!r)throw new Error("updateVariable requires an id field");if(typeof r!="string"||!/^[a-zA-Z0-9]+$/.test(r))throw new Error(`updateVariable id must be alphanumeric, got: "${r}"`);let o=e.contexts[e.contexts.length-1];if(o?.rollback?.isRestoring)return e;let i=!1,s=[],l=[];return n.forEach(({variableId:c,op:a,value:u,roundTo:f})=>{let d=e.projectData.resources?.variables?.[c],p=d?.scope,h=d?.type;if(Re(d))throw new Error(`Cannot update computed variable: ${c}`);if(d?.readonly===!0)throw new Error(`Cannot update readonly variable: ${c}`);Dt(p,c),Pt(h,a,c),vr(h,a,u,c,{roundTo:f});let g=p==="context"?o.variables:e.global.variables;if(p==="context"){i=!0;let y={variableId:c,op:a,value:u};f!==void 0&&(y.roundTo=f),l.push(y)}g[c]=Nt(g[c],a,u,{roundTo:f}),(p==="device"||p==="account")&&s.push({scope:p,path:`variables.${c}`,op:"set",value:k(g[c])})}),i&&Ae(e,"updateVariable",{id:r,operations:l}),hn(e,s),e.global.pendingEffects.push({name:"render"}),e},pu=e=>(t,r)=>e({state:t},r),hu=e=>({variables:Tt({variables:{...e.global?.variables??{},...an(e)?.variables??{}},runtime:Ke(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1}),runtime:Ke(e)}),mu=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")},gu=(e,t,r)=>{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!==r-1)throw new Error("conditional else branch must be the last branch")},yu=(e,t)=>{mu(t);for(let r=0;r<t.branches.length;r+=1){let n=t.branches[r];if(gu(n,r,t.branches.length),!(Object.prototype.hasOwnProperty.call(n,"when")&&!ct(n.when,hu(e)))){Object.entries(n.actions).forEach(([i,s])=>{wi(e,i,s)});return}}},bu={conditional:{replayLine:yu},updateVariable:{recordSources:[on],replayLine:Bo,replayRecorded:Bo,persistInSaveSlot:!0},setNextLineConfig:{replayLine:pu(Ai)}},Xt=e=>bu[e]??null,Iu=e=>Xt(e)?.persistInSaveSlot===!0,Au=(e,t)=>{let r=Xt(e)?.recordSources;return Array.isArray(r)&&r.includes(t)},wu=(e,t,r)=>{Xt(t)?.replayRecorded?.(e,r)},wi=(e,t,r)=>{Xt(t)?.replayLine?.(e,r)},Ei=({state:e},t)=>{let{offset:r}=t;if(r===void 0||typeof r!="number")return console.warn("selectLineIdByOffset requires a numeric offset"),null;let n=e.contexts[e.contexts.length-1];if(!n)return null;let o=n.rollback;if(!Array.isArray(o?.timeline)||typeof o?.currentIndex!="number")return null;let i=o.currentIndex+r;if(i<0||i>=o.timeline.length)return null;let s=o.timeline[i];return{sectionId:s.sectionId,lineId:s.lineId}},vi=({state:e})=>Ei({state:e},{offset:-1})!==null,Eu=({state:e},t)=>{let{offset:r=-1}=t;if(r>=0)throw new Error("rollbackByOffset requires a negative offset");let n=e.contexts?.[e.contexts.length-1];if(!n)return e;let o=ze(n,{compatibilityAnchor:!n.rollback}),i=o.currentIndex+r;return i<0||i>=o.timeline.length?e:ii(e,i)},vu=({state:e},t)=>{let{sectionId:r,lineId:n}=t,o=e.contexts[e.contexts.length-1];if(!o)throw new Error("No context available for rollbackToLine");let i=ze(o,{compatibilityAnchor:!o.rollback}),l=i.timeline.slice(0,i.currentIndex+1).findLastIndex(c=>c.sectionId===r&&c.lineId===n);if(l===-1)throw new Error(`Line ${n} not found in section ${r} rollback timeline`);return l===i.currentIndex?e:ii(e,l)},xi=e=>{let t=il(e);return eo(t,{selectPendingEffects:al,selectSkipMode:si,selectAutoMode:cl,selectIsChoiceVisible:ui,selectIsFormVisible:ul,selectActiveInteraction:we,selectActiveForm:mt,selectDialogueUIHidden:ai,selectDialogueHistory:ci,selectConfirmDialog:ll,selectIsLineAccountViewed:ln,selectIsResourceAccountViewed:pl,selectNextLineConfig:hl,selectSystemState:ml,selectSaveSlotMap:fi,selectSaveSlots:wl,selectSaveSlot:gl,selectRuntime:un,selectRuntimeValue:yl,selectAllVariables:fn,selectCurrentPointer:ye,selectSection:ee,selectCurrentLine:dn,selectPresentationState:di,selectPresentationChanges:bl,selectSectionLineChanges:Al,selectSaveSlotPage:pn,selectCurrentPageSlots:El,selectRenderState:xl,selectOverlayStack:sl,selectLineIdByOffset:Ei,selectCanRollback:vi,startAutoMode:hi,stopAutoMode:gt,toggleAutoMode:kl,startSkipMode:mi,stopSkipMode:Be,toggleSkipMode:Tl,showDialogueUI:Jt,hideDialogueUI:gi,toggleDialogueUI:Dl,setDialogueTextSpeed:Pl,setAutoForwardDelay:Nl,setSkipUnseenText:Vl,setSkipTransitionsAndAnimations:jl,setSoundVolume:Ml,setMusicVolume:Fl,setMuteAll:Ul,setSaveLoadPagination:Bl,incrementSaveLoadPagination:zl,decrementSaveLoadPagination:Wl,setMenuPage:ql,setMenuEntryPoint:Hl,showConfirmDialog:Cl,hideConfirmDialog:Sl,resetStoryAtSection:Kl,clearPendingEffects:Yl,appendPendingEffect:Gl,beginRollbackActionBatch:tl,endRollbackActionBatch:rl,addViewedLine:Xl,addViewedResource:Ql,setNextLineConfig:Ai,saveSlot:Zl,loadSlot:eu,updateProjectData:tu,sectionTransition:iu,jumpToLine:ru,nextLine:nu,markLineCompleted:ou,rollbackToLine:vu,rollbackByOffset:Eu,pushOverlay:_l,popOverlay:Rl,replaceLastOverlay:Ol,clearOverlays:Ll,updateFormField:lu,submitForm:uu,cancelForm:fu,updateVariable:du,nextLineFromSystem:su},{transformActionFirstArgument:n=>({state:n}),transformSelectorFirstArgument:n=>({state:n})})};var xu="route-engine",Cu="projectPersistence";var Si=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),Q=e=>Object.prototype.toString.call(e)==="[object Object]",Ci="variables.",Su=(e={})=>{let t=Q(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!Q(r)||typeof r.sectionId!="string"||r.sectionId.length===0?null:{sectionId:r.sectionId,...typeof r.lineId=="string"?{lineId:r.lineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(r=>typeof r=="string"||typeof r=="number"?{resourceId:String(r)}:!Q(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},_u=(e={})=>{let t=Q(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!Q(r)||typeof r.sectionId!="string"||r.sectionId.length===0?null:{sectionId:r.sectionId,...typeof r.lastLineId=="string"?{lastLineId:r.lastLineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(r=>typeof r=="string"||typeof r=="number"?{resourceId:String(r)}:!Q(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},Ru=(e,t)=>{let r=_u(e),n=Su(t),o=r.sections.map(s=>({...s})),i=r.resources.map(s=>({...s}));return n.sections.forEach(s=>{let l=o.find(c=>c.sectionId===s.sectionId);if(!l){o.push({sectionId:s.sectionId,...s.lineId===void 0?{}:{lastLineId:s.lineId}});return}if(l.lastLineId!==void 0){if(s.lineId===void 0){delete l.lastLineId;return}l.lastLineId=s.lineId}}),n.resources.forEach(s=>{i.find(c=>c.resourceId===s.resourceId)||i.push({...s})}),{sections:o,resources:i}},_i=(e={})=>{let t=Q(e)?e:{};return{saveSlots:Q(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:Q(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:Q(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:Q(t.globalRuntime)?t.globalRuntime:{},accountViewedRegistry:Q(t.accountViewedRegistry)?t.accountViewedRegistry:{}}},Ou=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((t,r)=>{if(!Q(t))throw new Error(`Malformed applyScopedDataUpdates.updates[${r}] entry.`);let n=t.path?.startsWith(Ci)?t.path.slice(Ci.length):null;if(n!==null){if(!["device","account"].includes(t.scope))throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${r}].`);if(n.length===0)throw new Error(`Malformed applyScopedDataUpdates path "${t.path}" at updates[${r}].`);if(t.op!=="set")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${r}].`);return{scope:t.scope,path:t.path,op:t.op,value:t.value,variableId:n}}if(t.path==="viewedRegistry"){if(t.scope!=="account")throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${r}].`);if(t.op!=="markViewed")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${r}].`);return t}throw typeof t.path!="string"?new Error(`Malformed applyScopedDataUpdates path at updates[${r}].`):new Error(`Unsupported applyScopedDataUpdates path "${t.path}" at updates[${r}].`)})},Lu=(e,t)=>{let r={};return Ou(t).forEach(n=>{if(n.path==="viewedRegistry"){r.accountViewedRegistry=Ru(r.accountViewedRegistry??e.accountViewedRegistry,n.value);return}let o=n.scope==="device"?"globalDeviceVariables":"globalAccountVariables";r[o]={...e[o],...r[o],[n.variableId]:n.value}}),r},gn=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},$u=e=>{let t=gn(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},ku=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},Tu=({indexedDB:e,databaseName:t,objectStoreName:r})=>new Promise((n,o)=>{let i=e.open(t,1);i.onupgradeneeded=()=>{let s=i.result;s.objectStoreNames.contains(r)||s.createObjectStore(r,{keyPath:"namespace"})},i.onsuccess=()=>{n(i.result)},i.onerror=()=>{o(i.error??new Error(`Failed to open IndexedDB database "${t}".`))}}),Du=async({databasePromise:e,objectStoreName:t,namespace:r})=>{let n=await e;return new Promise((o,i)=>{let c=n.transaction(t,"readonly").objectStore(t).get(r);c.onsuccess=()=>{o(c.result??null)},c.onerror=()=>{i(c.error??new Error(`Failed to read persisted namespace "${r}" from IndexedDB.`))}})},bt=async({databasePromise:e,objectStoreName:t,namespace:r,patch:n})=>{let o=await e;return new Promise((i,s)=>{let l=o.transaction(t,"readwrite"),c=l.objectStore(t),a=c.get(r),u=!1,f=p=>{u||(u=!0,s(p))},d=()=>{u||(u=!0,i())};a.onerror=()=>{f(a.error??new Error(`Failed to read persisted namespace "${r}" before updating IndexedDB.`))},a.onsuccess=()=>{let p=_i(a.result),h=typeof n=="function"?n(p):n,g={namespace:r,version:1,...Si(),...p,...h},y=c.put(g);y.onerror=()=>{f(y.error??new Error(`Failed to persist namespace "${r}" to IndexedDB.`))}},l.oncomplete=()=>{d()},l.onerror=()=>{f(l.error??new Error(`IndexedDB transaction failed while updating namespace "${r}".`))},l.onabort=()=>{f(l.error??new Error(`IndexedDB transaction aborted while updating namespace "${r}".`))}})},Pu=async({databasePromise:e,objectStoreName:t,namespace:r})=>{let n=await e;return new Promise((o,i)=>{let s=n.transaction(t,"readwrite"),c=s.objectStore(t).delete(r),a=!1,u=d=>{a||(a=!0,i(d))},f=()=>{a||(a=!0,o())};c.onerror=()=>{u(c.error??new Error(`Failed to clear persisted namespace "${r}" from IndexedDB.`))},s.oncomplete=()=>{f()},s.onerror=()=>{u(s.error??new Error(`IndexedDB transaction failed while clearing namespace "${r}".`))},s.onabort=()=>{u(s.error??new Error(`IndexedDB transaction aborted while clearing namespace "${r}".`))}})},yn=(e={})=>{let{indexedDB:t,databaseName:r=xu,objectStoreName:n=Cu,namespace:o}=e,i=ku(t),s=$u(o),l=Tu({indexedDB:i,databaseName:r,objectStoreName:n});return{namespace:s,load:async()=>{let c=await Du({databasePromise:l,objectStoreName:n,namespace:s});return{...Si(),..._i(c)}},clear:async()=>Pu({databasePromise:l,objectStoreName:n,namespace:s}),saveSlots:async c=>bt({databasePromise:l,objectStoreName:n,namespace:s,patch:{saveSlots:Q(c)?c:{}}}),saveGlobalDeviceVariables:async c=>bt({databasePromise:l,objectStoreName:n,namespace:s,patch:{globalDeviceVariables:Q(c)?c:{}}}),saveGlobalAccountVariables:async c=>bt({databasePromise:l,objectStoreName:n,namespace:s,patch:{globalAccountVariables:Q(c)?c:{}}}),saveGlobalRuntime:async c=>bt({databasePromise:l,objectStoreName:n,namespace:s,patch:{globalRuntime:Q(c)?c:{}}}),applyScopedDataUpdates:async c=>bt({databasePromise:l,objectStoreName:n,namespace:s,patch:a=>Lu(a,c)})}},Nu=yn;var Vu=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),ju=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),Ri="conditional",bn="form",Mu=new Set(["submitForm","cancelForm"]),It=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function In(e){let t,r=0,n=null,o=new Map,i=new Map,s=new Map,{handlePendingEffects:l}=e,c=(I=new Map,C=Date.now())=>new Map(Array.from(I.entries()).filter(([,R])=>C<R.expiresAt).map(([R,M])=>[R,{animation:structuredClone(M.animation),startedAt:M.startedAt,expiresAt:M.expiresAt}])),a=(I=new Map)=>Array.from(I.values()).map(C=>structuredClone(C.animation)),u=(I=Date.now())=>{o=new Map(Array.from(o.entries()).filter(([,C])=>I<C.expiresAt))},f=()=>{for(;t.selectPendingEffects().length>0;){let I=[...t.selectPendingEffects()];t.clearPendingEffects();try{l(I)}catch(C){throw t.clearPendingEffects(),I.forEach(R=>{t.appendPendingEffect(R)}),C}}},d=({initialState:I,namespace:C})=>{t=xi(I),r=0,n=gn(C),o=new Map,i=new Map,s=new Map,t.appendPendingEffect({name:"handleLineActions"}),f()},p=()=>n,h=()=>t.selectPresentationState(),g=()=>t.selectPresentationChanges(),y=I=>t.selectSectionLineChanges(I),b=(I={})=>{r+=1;let C=Date.now();u(C);let R=i.size>0,M=c(o,C),z=R?c(i,C):new Map,be={...t.selectRenderState({activePersistentAnimations:a(M),restoredPersistentAnimations:a(z)}),id:`render-${r}`};return s.set(be.id,{builtAt:C,persistentAnimationSessions:new Map([...z.entries(),...M.entries()]),usedRestoredPersistentAnimationSessions:R}),be},A=(I={})=>b(I),v=(I={})=>b(I),S=I=>{let C=typeof I?.id=="string"&&I.id.length>0?I.id:null,R=C?s.get(C):null;C&&s.delete(C);let M=new Map;Co(I?.animations).forEach(z=>{let ue=Ft(z);if(!ue)return;let be=R?.persistentAnimationSessions?.get(ue)??o.get(ue),wt=Math.max(0,_o(z)),En=be?.startedAt??R?.builtAt??Date.now();M.set(ue,{animation:structuredClone(z),startedAt:En,expiresAt:En+wt})}),o=M,R?.usedRestoredPersistentAnimationSessions&&(i=new Map)},T=()=>t.selectSystemState(),w=()=>t.selectSaveSlotMap(),D=I=>t.selectSaveSlot(I),F=I=>t.selectSaveSlotPage(I),V=()=>t.selectSkipMode(),N=()=>t.selectAutoMode(),j=()=>t.selectRuntime(),U=()=>t.selectIsChoiceVisible(),q=()=>t.selectIsFormVisible(),G=()=>t.selectActiveInteraction(),ie=(I,C,R={})=>I!=="nextLine"||!It(C)?C:R.bypassChoice===!0?{...C,bypassChoice:!0}:R.interactionSource===bn?{...C,_interactionSource:bn}:C,te=(I,C)=>{if(!t[I])return;Vu.has(I)&&(ju.has(I)?i=c(o):i=new Map,o=new Map);let R=t[I](C);return f(),R},W=(I,C,R,M={})=>{if(I===Ri){let z=_(R),ue=Sr({[I]:C},z);H(ue[I],R,M);return}te(I,C)},x=(I,C)=>{W(I,C)},_=I=>{if(!I)return{variables:t.selectAllVariables?t.selectAllVariables():void 0,runtime:t.selectRuntime?t.selectRuntime():{}};if(Object.prototype.hasOwnProperty.call(I,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:C,...R}=I,M=t.selectAllVariables?t.selectAllVariables():void 0;return{...R,_event:C,variables:M,runtime:t.selectRuntime?t.selectRuntime():{}}},P=I=>{if(!It(I))throw new Error("conditional action payload must be an object");if(!Array.isArray(I.branches))throw new Error("conditional action requires branches array");if(I.branches.length===0)throw new Error("conditional action requires at least one branch")},re=(I,C,R)=>{if(!It(I))throw new Error(`conditional branch at index ${C} must be an object`);if(!It(I.actions))throw new Error(`conditional branch at index ${C} requires actions object`);if(!Object.prototype.hasOwnProperty.call(I,"when")&&C!==R-1)throw new Error("conditional else branch must be the last branch")},H=(I,C,R)=>{P(I);for(let M=0;M<I.branches.length;M+=1){let z=I.branches[M];re(z,M,I.branches.length);let ue=_(C);if(!(Object.prototype.hasOwnProperty.call(z,"when")&&!ct(z.when,ue))){Zt(z.actions,C,R);return}}},K=(I,C)=>({...I??{},_form:C}),At=(I,C,R,M)=>{let z=te(I,C),ue=z?.submitted===!0&&z.valid===!0,be=z?.cancelled===!0;!ue&&!be||It(C.actions)&&Zt(C.actions,K(R,z.form),{...M,interactionSource:bn})},qe=(I,C,R,M)=>{let z=_(R),be=Sr({[I]:C},z)[I];if(I===Ri){H(be,R,M);return}let wt=ie(I,be,M);if(Mu.has(I)){At(I,wt,R,M);return}te(I,wt)},Zt=(I,C,R)=>{Object.entries(I).forEach(([M,z])=>{qe(M,z,C,R)})},wn=(I,C,R={})=>{t.beginRollbackActionBatch({source:R.rollbackSource});try{Zt(I,C,R)}finally{t.endRollbackActionBatch({})}};return{init:d,handleAction:W,handleInternalAction:x,handleActions:wn,selectRenderState:A,prepareRenderState:v,commitRenderState:S,selectPresentationState:h,selectPresentationChanges:g,selectSectionLineChanges:y,selectSystemState:T,selectSaveSlotMap:w,selectSaveSlot:D,selectSaveSlotPage:F,selectSaveSlots:w,selectRuntime:j,selectIsChoiceVisible:U,selectIsFormVisible:q,selectActiveInteraction:G,handleLineActions:()=>{let I=t.selectCurrentLine();return I?.actions?(wn(I.actions,void 0,{rollbackSource:"line"}),!0):!1},getNamespace:p}}var An=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:r=>{e=r},addElapsed:r=>{e+=r},getCallback:()=>t,setCallback:r=>{t=r}}},Fu=80,Li=({engine:e,routeGraphics:t,trackRenderDispatch:r},n)=>{let o=e.prepareRenderState?.(n)??e.selectRenderState(n);r?.(o),t.render(o),e.commitRenderState?.(o)},Uu=({engine:e,routeGraphics:t,trackRenderDispatch:r,getRenderDispatchCount:n},o)=>{let i=n?.()??0,s=e.handleLineActions();(n?.()??0)===i&&Li({engine:e,routeGraphics:t,trackRenderDispatch:r},o)},Bu=({engine:e,ticker:t,autoTimer:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let l=n.delay??1e3;r.getElapsed()>=l&&(t.remove(i),r.setCallback(null),r.setElapsed(0),Qt(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},zu=({ticker:e,autoTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},Wu=({engine:e,ticker:t,skipTimer:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let l=n?.delay??Fu;r.getElapsed()>=l&&(r.setElapsed(0),Qt(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},qu=({ticker:e,skipTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},Hu=({engine:e,ticker:t,nextLineConfigTimerState:r},n)=>{let o=r.getCallback();o&&t.remove(o),r.setElapsed(0);let i=s=>{r.addElapsed(s.deltaMS);let l=n.delay??1e3;r.getElapsed()>=l&&(r.setElapsed(0),Qt(e,"nextLineFromSystem",{}),t.remove(i),r.setCallback(null))};r.setCallback(i),t.add(i)},Yu=({ticker:e,nextLineConfigTimerState:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},Gu=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveSlots(t?.saveSlots))},Ku=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalDeviceVariables(t?.globalDeviceVariables))},Ju=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalAccountVariables(t?.globalAccountVariables))},Xu=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalRuntime(t?.globalRuntime))},Qu=({enqueuePersistenceWrite:e},t)=>{e(r=>{if(typeof r.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return r.applyScopedDataUpdates(t?.updates)})},Oi={render:Li,saveSlots:Gu,saveGlobalDeviceVariables:Ku,saveGlobalAccountVariables:Ju,saveGlobalRuntime:Xu,applyScopedDataUpdates:Qu,handleLineActions:Uu,startAutoNextTimer:Bu,clearAutoNextTimer:zu,startSkipNextTimer:Wu,clearSkipNextTimer:qu,nextLineConfigTimer:Hu,clearNextLineConfigTimer:Yu},Zu=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),Qt=(e,t,r)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,r)},ef=(e=[])=>{let t=new Set,r=[];for(let n=e.length-1;n>=0;n-=1){let o=e[n];if(typeof o?.name!="string"||o.name.length===0)throw new Error("Pending effect is missing a valid name.");if(!Zu.has(o.name)){r.unshift(o);continue}t.has(o.name)||(t.add(o.name),r.unshift(o))}return r},tf=({getEngine:e,routeGraphics:t,ticker:r,handleUnhandledEffect:n,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:l})=>{let c=An(),a=An(),u=An(),f=s??null,d=Promise.resolve(),p=null,h=null,g=!1,y=0,b=x=>{if(o){o(x);return}console.error("RouteEngine persistence write failed.",x)},A=()=>{if(f)return f;let x=e();return f=yn({indexedDB:i,namespace:l??x?.getNamespace?.()}),f},v=x=>{d=d.catch(()=>{}).then(()=>{let _=A();return x(_)}).catch(_=>{b(_)})},S=x=>{let _=typeof x?.id=="string"&&x.id.length>0?x.id:null;y+=1,p=_,g=!1},T=()=>y,w=(x={})=>{if(x?.aborted===!0)return!1;let _=typeof x?.id=="string"&&x.id.length>0?x.id:null;return _?_!==p||_===h?!1:(h=_,!0):p!==null||g?!1:(g=!0,!0)},D=(x,_={})=>{if(x!=="renderComplete"||!w(_))return!1;let P=e();return Qt(P,"markLineCompleted",{}),!0},F=new Set(["updateFormField","submitForm","cancelForm"]),V=x=>typeof x?.selectActiveInteraction=="function"?x.selectActiveInteraction():typeof x?.selectIsChoiceVisible=="function"&&x.selectIsChoiceVisible()?{source:"choice"}:null,N=x=>x?._formKey??x?.formKey,j=(x,_)=>N(x)===_?.formKey,U=(x,_)=>!x||typeof x!="object"||Array.isArray(x)||x._interactionSource!==_?.source?!1:_.source==="form"?j(x,_):!0,q=(x,_)=>!x||typeof x!="object"||Array.isArray(x)||_?.source!=="form"?!1:j(x,_),G=(x={},_)=>{let P=x?.actions;return _?.source==="form"?U(x,_)?!0:!P||typeof P!="object"||Array.isArray(P)?!1:Object.entries(P).some(([re,H])=>F.has(re)&&q(H,_)):U(x,_)?!0:!P||typeof P!="object"||Array.isArray(P)?!1:Object.values(P).some(re=>U(re,_))},ie=(x,_={})=>{if(!_?.actions)return!1;let P=V(x);return!P||P.source==="choice"?!1:!G(_,P)},te=({preprocessPayload:x,onEvent:_}={})=>async(P,re={})=>{let H=e();if(ie(H,re))return _?.(P,re);let K=await x?.(P,re)??re;if(ie(H,K))return _?.(P,K);if(D(P,K),K?.actions){let At=K?._event?{_event:K._event}:K?.event?{_event:K.event}:void 0,qe;K?.bypassChoice===!0?qe={bypassChoice:!0}:K?._interactionSource&&(qe={interactionSource:K._interactionSource}),qe?H.handleActions(K.actions,At,qe):H.handleActions(K.actions,At)}return _?.(P,K)},W=x=>{let _=e(),P=ef(x);P.forEach(H=>{if(!Oi[H.name]&&!n)throw new Error(`Unhandled pending effect "${H.name}".`)});let re={engine:_,routeGraphics:t,ticker:r,autoTimer:c,skipTimer:a,nextLineConfigTimerState:u,trackRenderDispatch:S,getRenderDispatchCount:T,enqueuePersistenceWrite:v};for(let H of P){let K=Oi[H.name];if(K){K(re,H.payload);continue}n(H,re)}};return W.handleRouteGraphicsEvent=D,W.createRouteGraphicsEventHandler=te,W},rf=tf;var nf=(e,t={})=>{let{resources:r={}}=t;return Zr(e,r)};var vd=In;export{Or as DEFAULT_VISUAL_LAYER,Je as RENDER_LAYER,ve as VISUAL_LAYER,rf as createEffectsHandler,Nu as createIndexedDbPersistence,vd as default,Vs as resolveComputedVariables,nf as resolveLayoutReferences};
|
package/package.json
CHANGED