route-engine-js 1.12.1 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- var Bo=Object.defineProperty;var Uo=(e,t)=>{for(var n in t)Bo(e,n,{get:t[n],enumerable:!0})};var Yn=Symbol.for("immer-nothing"),Un=Symbol.for("immer-draftable"),X=Symbol.for("immer-state");function te(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var Le=Object.getPrototypeOf;function ie(e){return!!e&&!!e[X]}function be(e){return e?Hn(e)||Array.isArray(e)||!!e[Un]||!!e.constructor?.[Un]||ct(e)||lt(e):!1}var Fo=Object.prototype.constructor.toString();function Hn(e){if(!e||typeof e!="object")return!1;let t=Le(e);if(t===null)return!0;let n=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return n===Object?!0:typeof n=="function"&&Function.toString.call(n)===Fo}function ot(e,t){at(e)===0?Reflect.ownKeys(e).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function at(e){let t=e[X];return t?t.type_:Array.isArray(e)?1:ct(e)?2:lt(e)?3:0}function Pt(e,t){return at(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Jn(e,t,n){let r=at(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function zo(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function ct(e){return e instanceof Map}function lt(e){return e instanceof Set}function ye(e){return e.copy_||e.base_}function Tt(e,t){if(ct(e))return new Map(e);if(lt(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let n=Hn(e);if(t===!0||t==="class_only"&&!n){let r=Object.getOwnPropertyDescriptors(e);delete r[X];let o=Reflect.ownKeys(r);for(let i=0;i<o.length;i++){let s=o[i],a=r[s];a.writable===!1&&(a.writable=!0,a.configurable=!0),(a.get||a.set)&&(r[s]={configurable:!0,writable:!0,enumerable:a.enumerable,value:e[s]})}return Object.create(Le(e),r)}else{let r=Le(e);if(r!==null&&n)return{...e};let o=Object.create(r);return Object.assign(o,e)}}function Mt(e,t=!1){return ut(e)||ie(e)||!be(e)||(at(e)>1&&(e.set=e.add=e.clear=e.delete=Wo),Object.freeze(e),t&&Object.entries(e).forEach(([n,r])=>Mt(r,!0))),e}function Wo(){te(2)}function ut(e){return Object.isFrozen(e)}var qo={};function Ie(e){let t=qo[e];return t||te(0,e),t}var Ue;function Kn(){return Ue}function Yo(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function Fn(e,t){t&&(Ie("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Nt(e){Dt(e),e.drafts_.forEach(Ho),e.drafts_=null}function Dt(e){e===Ue&&(Ue=e.parent_)}function zn(e){return Ue=Yo(Ue,e)}function Ho(e){let t=e[X];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function Wn(e,t){t.unfinalizedDrafts_=t.drafts_.length;let n=t.drafts_[0];return e!==void 0&&e!==n?(n[X].modified_&&(Nt(t),te(4)),be(e)&&(e=it(t,e),t.parent_||st(t,e)),t.patches_&&Ie("Patches").generateReplacementPatches_(n[X].base_,e,t.patches_,t.inversePatches_)):e=it(t,n,[]),Nt(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Yn?e:void 0}function it(e,t,n){if(ut(t))return t;let r=t[X];if(!r)return ot(t,(o,i)=>qn(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return st(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;let o=r.copy_,i=o,s=!1;r.type_===3&&(i=new Set(o),o.clear(),s=!0),ot(i,(a,c)=>qn(e,r,o,a,c,n,s)),st(e,o,!1),n&&e.patches_&&Ie("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function qn(e,t,n,r,o,i,s){if(ie(o)){let a=i&&t&&t.type_!==3&&!Pt(t.assigned_,r)?i.concat(r):void 0,c=it(e,o,a);if(Jn(n,r,c),ie(c))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if(be(o)&&!ut(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;it(e,o),(!t||!t.scope_.parent_)&&typeof r!="symbol"&&Object.prototype.propertyIsEnumerable.call(n,r)&&st(e,o)}}function st(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&Mt(t,n)}function Jo(e,t){let n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:Kn(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=r,i=Bt;n&&(o=[r],i=Fe);let{revoke:s,proxy:a}=Proxy.revocable(o,i);return r.draft_=a,r.revoke_=s,a}var Bt={get(e,t){if(t===X)return e;let n=ye(e);if(!Pt(n,t))return Ko(e,n,t);let r=n[t];return e.finalized_||!be(r)?r:r===Lt(e.base_,t)?(kt(e),e.copy_[t]=jt(r,e)):r},has(e,t){return t in ye(e)},ownKeys(e){return Reflect.ownKeys(ye(e))},set(e,t,n){let r=Gn(ye(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){let o=Lt(ye(e),t),i=o?.[X];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(zo(n,o)&&(n!==void 0||Pt(e.base_,t)))return!0;kt(e),Vt(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return Lt(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,kt(e),Vt(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let n=ye(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){te(11)},getPrototypeOf(e){return Le(e.base_)},setPrototypeOf(){te(12)}},Fe={};ot(Bt,(e,t)=>{Fe[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});Fe.deleteProperty=function(e,t){return Fe.set.call(this,e,t,void 0)};Fe.set=function(e,t,n){return Bt.set.call(this,e[0],t,n,e[0])};function Lt(e,t){let n=e[X];return(n?ye(n):e)[t]}function Ko(e,t,n){let r=Gn(t,n);return r?"value"in r?r.value:r.get?.call(e.draft_):void 0}function Gn(e,t){if(!(t in e))return;let n=Le(e);for(;n;){let r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=Le(n)}}function Vt(e){e.modified_||(e.modified_=!0,e.parent_&&Vt(e.parent_))}function kt(e){e.copy_||(e.copy_=Tt(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Go=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){let i=n;n=t;let s=this;return function(c=i,...l){return s.produce(c,u=>n.call(this,u,...l))}}typeof n!="function"&&te(6),r!==void 0&&typeof r!="function"&&te(7);let o;if(be(t)){let i=zn(this),s=jt(t,void 0),a=!0;try{o=n(s),a=!1}finally{a?Nt(i):Dt(i)}return Fn(i,r),Wn(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===Yn&&(o=void 0),this.autoFreeze_&&Mt(o,!0),r){let i=[],s=[];Ie("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else te(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...a)=>this.produceWithPatches(s,c=>t(c,...a));let r,o;return[this.produce(t,n,(s,a)=>{r=s,o=a}),r,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){be(e)||te(8),ie(e)&&(e=ze(e));let t=zn(this),n=jt(e,void 0);return n[X].isManual_=!0,Dt(t),n}finishDraft(e,t){let n=e&&e[X];(!n||!n.isManual_)&&te(9);let{scope_:r}=n;return Fn(r,t),Wn(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){let o=t[n];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}n>-1&&(t=t.slice(n+1));let r=Ie("Patches").applyPatches_;return ie(e)?r(e,t):this.produce(e,o=>r(o,t))}};function jt(e,t){let n=ct(e)?Ie("MapSet").proxyMap_(e,t):lt(e)?Ie("MapSet").proxySet_(e,t):Jo(e,t);return(t?t.scope_:Kn()).drafts_.push(n),n}function ze(e){return ie(e)||te(10,e),Xn(e)}function Xn(e){if(!be(e)||ut(e))return e;let t=e[X],n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=Tt(e,t.scope_.immer_.useStrictShallowCopy_)}else n=Tt(e,!0);return ot(n,(r,o)=>{Jn(n,r,Xn(o))}),t&&(t.finalized_=!1),n}var Q=new Go,Ut=Q.produce,Sl=Q.produceWithPatches.bind(Q),_l=Q.setAutoFreeze.bind(Q),$l=Q.setUseStrictShallowCopy.bind(Q),Rl=Q.applyPatches.bind(Q),Ol=Q.createDraft.bind(Q),Ll=Q.finishDraft.bind(Q);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},$={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},ke={NOT:0};var A=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},K=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var Ft=e=>{if(!e||e.trim()==="")throw new A("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let n=e.includes("===")?"==":"!=";throw new A(`Invalid comparison operator '${e.includes("===")?"===":"!=="}' - did you mean '${n}'? (got: '${e}')`)}let t=["<",">","<=",">=","==","!="];for(let n of t)if(e.trim().endsWith(n))throw new A(`Incomplete comparison expression - missing right operand (got: '${e}')`)},Qn=e=>{if(e.trim().endsWith(" in"))throw new A(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new A(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,n]=e.split(" in ");if(!n||n.trim()==="")throw new A(`Missing iterable expression after 'in' (got: '$for ${e}')`);let r=t.includes(",")?t.split(",").map(o=>o.trim()):[t.trim()];for(let o of r){if(!o)throw new A(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new A(`Invalid loop syntax (got: '$for ${e}')`)}};var Zn=(e,t,n=!1)=>{if(t===null)return new K(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new K(`Cannot iterate over undefined value at '$for ${e}'`);let r=typeof t;return n?new K(`Cannot iterate over non-array value in loop '${e}' - got ${r} instead`):new K(`Cannot iterate over non-array value (got: ${r}) at '$for ${e}'`)},er=(e,t)=>{let n=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new K(`Unknown function '${e}' (${n})`)};var Xo=(e,t,n={})=>{let r={},o={};n&&typeof n=="object"&&(n.functions!==void 0||n.partials!==void 0?(r=n.functions||{},o=n.partials||{}):typeof n=="object"&&(r=n));let s=R(e,{functions:r,partials:o},t,{});return s===void 0?{}:s},R=(e,t,n,r)=>{let o=t.functions||t;if(e.var&&!e.type)return U(e.var,n,r);if(e.type===m.LITERAL)return e.value;if(e.type===m.VARIABLE)return U(e.path,n,r);if(e.type===m.INTERPOLATION)return Zo(e.parts,t,n,r);switch(e.type){case m.FUNCTION:return nr(e,t,n,r);case m.BINARY:return rr(e,t,n,r);case m.UNARY:return or(e,t,n,r);case m.CONDITIONAL:return ti(e,t,n,r);case m.LOOP:return si(e,t,n,r);case m.OBJECT:return ci(e,t,n,r);case m.ARRAY:return li(e,t,n,r);case m.PARTIAL:return ui(e,t,n,r);case m.PATH_REFERENCE:return fi(e,t,n,r);default:throw new Error(`Unknown node type: ${e.type}`)}},tr=new Map,Qo=e=>{let t=[],n="",r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(i==="[")n&&(t.push({type:"property",value:n}),n=""),r=!0;else if(i==="]"){if(r&&n){let s=n.trim();if(/^\d+$/.test(s))t.push({type:"index",value:parseInt(s,10)});else if(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'")){let a=s.slice(1,-1);t.push({type:"property",value:a})}else t.push({type:"property",value:s});n=""}r=!1}else n+=i}return n&&t.push({type:"property",value:n}),t},U=(e,t,n)=>{if(!e)return;if(e in n)return n[e];let r=tr.get(e);if(!r){let i=[],s="",a=0;for(let c=0;c<e.length;c++){let l=e[c];l==="["?(a++,s+=l):l==="]"?(a--,s+=l):l==="."&&a===0?s&&(i.push(s),s=""):s+=l}s&&i.push(s),r=[];for(let c of i){let l=Qo(c.trim());r.push(...l)}tr.set(e,r)}let o=t;for(let i=0;i<r.length;i++){let s=r[i];if(s.type==="property"&&s.value in n){o=n[s.value];continue}if(o==null)return;(s.type==="property"||s.type==="index")&&(o=o[s.value])}return o},Zo=(e,t,n,r)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=R(i,t,n,r);o.push(s!=null?String(s):"")}return o.join("")},nr=(e,t,n,r)=>{let o=t.functions||t,i=o[e.name];if(!i)throw er(e.name,o);let s=e.args.map(a=>R(a,t,n,r));return i(...s)},he=(e,t,n,r)=>{if(e.var&&!e.type)return U(e.var,n,r);switch(e.type){case m.VARIABLE:return U(e.path,n,r);case m.LITERAL:return e.value;case m.BINARY:return rr(e,t,n,r);case m.UNARY:return or(e,t,n,r);case m.FUNCTION:return nr(e,t,n,r);default:return R(e,t,n,r)}},rr=(e,t,n,r)=>{if(e.op===$.AND||e.op===$.OR){let s=he(e.left,t,n,r),a=he(e.right,t,n,r);switch(e.op){case $.AND:return s&&a;case $.OR:return s||a}}let o=R(e.left,t,n,r),i=R(e.right,t,n,r);switch(e.op){case $.EQ:return o==i;case $.NEQ:return o!=i;case $.GT:return o>i;case $.LT:return o<i;case $.GTE:return o>=i;case $.LTE:return o<=i;case $.IN:return Array.isArray(i)?i.includes(o):!1;case $.ADD:if(typeof o!="number"||typeof i!="number")throw new K(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case $.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new K(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},or=(e,t,n,r)=>{let o=e.op===ke.NOT?he(e.operand,t,n,r):R(e.operand,t,n,r);if(e.op===ke.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},ei=(e,t,n,r)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===m.VARIABLE)if(U(o.path,n,r)){let s=e.bodies[0];if(s.type===m.OBJECT&&s.properties.length<=5){let a={};for(let c of s.properties){let l=c.parsedKey?R(c.parsedKey,t,n,r):c.key,u=c.value;if(u.type===m.LITERAL)a[l]=u.value;else if(u.type===m.VARIABLE)a[l]=U(u.path,n,r);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=U(d.path,n,r);f.push(p!=null?String(p):"")}else{let p=R(d,t,n,r);f.push(p!=null?String(p):"")}a[l]=f.join("")}else a[l]=R(u,t,n,r)}return a}}else{let s=e.bodies[1];if(s.type===m.OBJECT&&s.properties.length<=5){let a={};for(let c of s.properties){let l=c.parsedKey?R(c.parsedKey,t,n,r):c.key,u=c.value;if(u.type===m.LITERAL)a[l]=u.value;else if(u.type===m.VARIABLE)a[l]=U(u.path,n,r);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=U(d.path,n,r);f.push(p!=null?String(p):"")}else{let p=R(d,t,n,r);f.push(p!=null?String(p):"")}a[l]=f.join("")}else a[l]=R(u,t,n,r)}return a}}}return null},ti=(e,t,n,r)=>{let o=ei(e,t,n,r);if(o!==null)return o;for(let i=0;i<e.conditions.length;i++){let s=e.conditions[i];if(s===null||he(s,t,n,r))return R(e.bodies[i],t,n,r)}return ir},ni=(e,t)=>{let n=e.body,r=e.itemVar;if(n.type===m.CONDITIONAL&&n.conditions.length===1&&n.conditions[0].type===m.VARIABLE){let o=n.conditions[0].path,i=n.bodies[0];if(o.startsWith(r+".")){let s=o.substring(r.length+1);if(i.type===m.OBJECT&&i.properties.length<=5){for(let c of i.properties)if(c.parsedKey)return null;let a=[];for(let c=0;c<t.length;c++){let l=t[c];if(l[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===r)u[d]=l;else if(h.startsWith(r+".")){let y=h.substring(r.length+1);u[d]=l[y]}else return null}else if(p.type===m.INTERPOLATION){let h=[],y=!0;for(let I of p.parts)if(typeof I=="string")h.push(I);else if(I.type===m.VARIABLE){let b=I.path;if(b===r)h.push(l!=null?String(l):"");else if(b.startsWith(r+".")){let g=b.substring(r.length+1),x=l[g];h.push(x!=null?String(x):"")}else{y=!1;break}}else{y=!1;break}if(!y)return null;u[d]=h.join("")}else return null}a.push(u)}}return a}}}return null},ri=(e,t)=>{let n=e.body,r=e.itemVar,o=ni(e,t);if(o!==null)return o;if(n.type===m.OBJECT&&n.properties.length<=5&&!n.whenCondition){for(let a of n.properties)if(a.parsedKey)return null;let i=[],s=!0;for(let a of n.properties){let c=a.key,l=a.value;if(l.type===m.LITERAL)i.push({key:c,type:"literal",value:l.value});else if(l.type===m.VARIABLE){let u=l.path;if(u===r)i.push({key:c,type:"item"});else if(u.startsWith(r+".")){let f=u.substring(r.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:c,type:"prop",prop:f});else{s=!1;break}}else{s=!1;break}}else if(l.type===m.INTERPOLATION&&l.parts.length===1){let u=l.parts[0];if(u.type===m.VARIABLE){let f=u.path;if(f===r)i.push({key:c,type:"item_string"});else if(f.startsWith(r+".")){let d=f.substring(r.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:c,type:"prop_string",prop:d});else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}if(s){let a=new Array(t.length);if(i.length===3&&i[0].type==="prop"&&i[0].key==="id"&&i[1].type==="prop_string"&&i[1].key==="title"&&i[2].type==="prop"&&i[2].key==="completed")for(let c=0;c<t.length;c++){let l=t[c];a[c]={id:l.id,title:l.title!=null?String(l.title):"",completed:l.completed}}else for(let c=0;c<t.length;c++){let l=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]=l;else if(f.type==="prop")u[f.key]=l[f.prop];else if(f.type==="item_string")u[f.key]=l!=null?String(l):"";else if(f.type==="prop_string"){let d=l[f.prop];u[f.key]=d!=null?String(d):""}a[c]=u}return a}}return null},oi=(e,t,n,r,o)=>{let i=[],s=e.body;if(s.type===m.OBJECT&&s.fast!==!1){let a=e.itemVar,c=e.indexVar;for(let l=0;l<o.length;l++){let u=o[l],f={},d={...r,[a]:u,...c&&{[c]:l}};d.__paths__||(d.__paths__=r.__paths__||{});let p=e.iterable.path||"";if(r&&r.__paths__&&p){let h=p.split("."),y=h[0];y in r.__paths__&&(p=r.__paths__[y],h.length>1&&(p+="."+h.slice(1).join(".")))}d.__paths__={...d.__paths__,[a]:`${p}[${l}]`,...c&&{[c]:l}};for(let h of s.properties){let y=h.parsedKey?R(h.parsedKey,t,n,d):h.key,I=h.value;if(I.type===m.LITERAL)f[y]=I.value;else if(I.type===m.VARIABLE){let b=I.path;if(b===a)f[y]=u;else if(b===c)f[y]=l;else if(b.startsWith(a+".")){let g=b.substring(a.length+1);!g.includes(".")&&!g.includes("[")?f[y]=u[g]:f[y]=U(b,n,{...r,[a]:u,...c&&{[c]:l}})}else f[y]=U(b,n,{...r,[a]:u,...c&&{[c]:l}})}else if(I.type===m.INTERPOLATION){let b=[];for(let g of I.parts)if(typeof g=="string")b.push(g);else if(g.type===m.VARIABLE){let x=g.path,C;if(x===a)C=u;else if(x===c)C=l;else if(x.startsWith(a+".")){let O=x.substring(a.length+1);!O.includes(".")&&!O.includes("[")?C=u[O]:C=U(x,n,{...r,[a]:u,...c&&{[c]:l}})}else C=U(x,n,{...r,[a]:u,...c&&{[c]:l}});b.push(C!=null?String(C):"")}else{let x={...r,[a]:u,...c&&{[c]:l}},C=R(g,t,n,x);b.push(C!=null?String(C):"")}f[y]=b.join("")}else{let b={...r,[a]:u,...c&&{[c]:l}};f[y]=R(I,t,n,b)}}i.push(f)}return i}return null},ii=(e,t,n)=>{let r=e.body;if(r.type===m.OBJECT&&r.properties.length===1&&r.properties[0].key==="$if item.visible"){let i=r.properties[0].value;if(i.type===m.CONDITIONAL&&i.conditions.length===1&&i.conditions[0].type===m.VARIABLE&&i.conditions[0].path==="item.visible"){let s=i.bodies[0];if(s.type===m.OBJECT&&s.properties.length===2){let a=s.properties[0],c=s.properties[1];if(a.key==="id"&&a.value.type===m.VARIABLE&&a.value.path==="item.id"&&c.key==="$if item.highlighted"&&c.value.type===m.CONDITIONAL){let l=[];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),l.push(d)}}return l}}}}return null},si=(e,t,n,r)=>{let o=R(e.iterable,t,n,r);if(!Array.isArray(o)){let l,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(", ");l=`${e.iterable.name}(${d})`}else l=e.iterable.path||"undefined";let f=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${l}`;throw Zn(f,o,u)}if(!e.indexVar){let l=ii(e,o,e.itemVar);if(l!==null)return l}if(!e.indexVar){let l=ri(e,o);if(l!==null)return l}let i=oi(e,t,n,r,o);if(i!==null)return i;let s=[],a=e.iterable.path||"";if(r&&r.__paths__&&a){let l=a.split("."),u=l[0];u in r.__paths__&&(a=r.__paths__[u],l.length>1&&(a+="."+l.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(l=>l.type===m.OBJECT&&l.properties.some(u=>u.key.startsWith("$if ")||u.key.startsWith("$when "))));for(let l=0;l<o.length;l++){let u=e.indexVar?{...r,[e.itemVar]:o[l],[e.indexVar]:l}:{...r,[e.itemVar]:o[l]};u.__paths__||(u.__paths__=r.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${a}[${l}]`},e.indexVar&&(u.__paths__[e.indexVar]=l);let f=R(e.body,t,n,u);if(Array.isArray(f)&&f.length===1&&!c){let d=f[0];s.push(d===void 0?{}:d)}else s.push(f===void 0?{}:f)}return s},ai=(e,t,n,r)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?R(o.parsedKey,t,n,r):o.key,s=o.value;if(s.type===m.OBJECT&&s.properties.length<=10&&!s.whenCondition){let a={},c={},l=!0;for(let u of s.properties){let f=u.parsedKey?R(u.parsedKey,t,n,r):u.key,d=u.value;if(d.type===m.LITERAL)c[f]=d.value;else if(d.type===m.VARIABLE)c[f]=U(d.path,n,r);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 y=U(h.path,n,r);p.push(y!=null?String(y):"")}else{l=!1;break}if(!l)break;c[f]=p.join("")}else if(d.type===m.OBJECT&&d.properties.length<=5){let p={};for(let h of d.properties){let y=h.key,I=h.value;if(I.type===m.LITERAL)p[y]=I.value;else if(I.type===m.VARIABLE)p[y]=U(I.path,n,r);else if(I.type===m.INTERPOLATION){let b=[];for(let g of I.parts)if(typeof g=="string")b.push(g);else if(g.type===m.VARIABLE){let x=U(g.path,n,r);b.push(x!=null?String(x):"")}else{l=!1;break}if(!l)break;p[y]=b.join("")}else{l=!1;break}}if(!l)break;c[f]=p}else{l=!1;break}}if(l)return a[i]=c,a}}return null},ci=(e,t,n,r)=>{let o=t.functions||t;if(e.whenCondition&&!he(e.whenCondition,o,n,r))return;let i=ai(e,t,n,r);if(i!==null)return i;if(e.fast){let l={};for(let u of e.properties){let f=u.parsedKey?R(u.parsedKey,t,n,r):u.key,d=u.value;if(d.type===m.LITERAL)l[f]=d.value;else if(d.type===m.VARIABLE)l[f]=U(d.path,n,r);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 y=U(h.path,n,r);p.push(y!=null?String(y):"")}else{let y=R(h,t,n,r);p.push(y!=null?String(y):"")}l[f]=p.join("")}else l[f]=R(d,t,n,r)}return l}let s={},a=null,c=!1;for(let l of e.properties)if(!l.key.startsWith("$if ")&&!l.key.match(/^\$if\s+\w+.*:?$/)&&!l.key.startsWith("$elif")&&!l.key.startsWith("$else")&&!l.key.startsWith("$for ")){c=!0;break}for(let l of e.properties)if(l.key.startsWith("$if ")||l.key.match(/^\$if\s+\w+.*:?$/)){let u=R(l.value,t,n,r);if(!c&&u!==null&&u!==void 0)return Array.isArray(u)&&u.length===1?u[0]:u;typeof u=="object"&&u!==null&&!Array.isArray(u)&&Object.assign(s,u)}else if(l.key.startsWith("$for ")){if(e.properties.length===1)return R(l.value,t,n,r)}else{let u=l.value;if(u&&u.type===m.OBJECT&&u.properties){let f=u.properties.find(d=>d.key.startsWith("$for "));if(f){let d=R(f.value,t,n,r);d!==void 0&&(s[l.key]=d)}else{let d=R(l.value,t,n,r);d!==void 0&&(s[l.key]=d)}}else{let f=l.parsedKey?R(l.parsedKey,t,n,r):l.key,d=R(l.value,t,n,r);d!==void 0&&(s[f]=d)}}return s},ir={},li=(e,t,n,r)=>{let o=[];for(let i of e.items)if(i.type===m.LOOP){let s=R(i,t,n,r);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=R(i,t,n,r);s!==ir&&s!==void 0&&o.push(s)}return o},ui=(e,t,n,r)=>{let{name:o,data:i,whenCondition:s}=e,a=t.partials||{},c=t.functions||t;if(s&&!he(s,c,n,r))return;if(!a[o])throw new K(`Partial '${o}' is not defined`);let l=r._partialStack||[];if(l.includes(o))throw new K(`Circular partial reference detected: ${o}`);let u=a[o],f=n,d={...r,_partialStack:[...l,o]};if(r){f={...n};for(let p of Object.keys(r))p.startsWith("_")||(f[p]=r[p])}if(i){let p=R(i,t,n,r);f={...f,...p}}return R(u,t,f,d)},fi=(e,t,n,r)=>{let{path:o}=e,i=o.split("."),s=i[0],a=i.slice(1);if(!r||!(s in r))throw new K(`Path reference '#{${o}}' refers to '${s}' which is not a loop variable in the current scope`);if(r.__paths__||(r.__paths__={}),!(s in r.__paths__))throw new K(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let c=r.__paths__[s];if(typeof c=="number"){if(a.length>0)throw new K(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(c)}return a.length>0&&(c+="."+a.join(".")),c};var zt=Xo;var di=/\$\{([^}]*)\}/g,pi=/#\{([^}]*)\}/g,ar=(e,t={})=>{let n=e.match(/^(\w+)\((.*)\)$/);if(!n)return{isFunction:!1};let[,r,o]=n,i=hi(o,t);return{isFunction:!0,type:m.FUNCTION,name:r,args:i}},hi=(e,t={})=>e.trim()?mi(e).map(r=>gi(r.trim(),t)):[],mi=e=>{let t=[],n="",r=0,o=!1,i="";for(let s=0;s<e.length;s++){let a=e[s],c=s>0?e[s-1]:"";!o&&(a==='"'||a==="'")?(o=!0,i=a,n+=a):o&&a===i&&c!=="\\"?(o=!1,i="",n+=a):!o&&a==="("?(r++,n+=a):!o&&a===")"?(r--,n+=a):!o&&a===","&&r===0?(t.push(n),n=""):n+=a}return n&&t.push(n),t},gi=(e,t={})=>{if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:m.LITERAL,value:e.slice(1,-1)};if(/^-?\d+(\.\d+)?$/.test(e))return{type:m.LITERAL,value:parseFloat(e)};if(e==="true")return{type:m.LITERAL,value:!0};if(e==="false")return{type:m.LITERAL,value:!1};if(e==="null")return{type:m.LITERAL,value:null};let n=ar(e,t);if(n.isFunction)return{type:n.type,name:n.name,args:n.args};let r=e.trim(),o=[{op:" + ",type:"ADD"},{op:" - ",type:"SUBTRACT"}],i=-1,s=null;for(let{op:a,type:c}of o){let l=0;for(;l<r.length;){let u=we(r.substring(l),a);if(u===-1)break;let f=l+u;f>i&&(i=f,s={op:a,type:c}),l=f+a.length}}if(i!==-1)try{return W(r,t)}catch{return{type:m.VARIABLE,path:r}}return{type:m.VARIABLE,path:r}},cr=/^\w+\(.*\)$/,yi=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,bi=e=>{if(!(!e||e.trim()===""||cr.test(e))&&yi.test(e))throw e.includes("?")&&e.includes(":")?new A(`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 A(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new A(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},sr=e=>{let t=e.trim();if(cr.test(t))throw new A(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new A(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new A(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new A(`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 A(`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}},We=(e,t={})=>{let n=e.trim();bi(n);let r=ar(n,t);if(r.isFunction)return{type:r.type,name:r.name,args:r.args};if(n.includes("[")&&!/[\s+\-*/%|&?:]/.test(n)){let o=0;for(let i of n)i==="["?o++:i==="]"&&o--;if(o!==0)throw new Error("Invalid array index syntax")}return{type:m.VARIABLE,path:n}},Wt=(e,t={})=>{let n=e,r=[];(e.includes("\\${")||e.includes("\\#{"))&&(n=e.replace(/\\\\(\$\{[^}]*\})/g,"\\DOUBLE_ESC_VAR$1"),n=n.replace(/\\\\(#\{[^}]*\})/g,"\\DOUBLE_ESC_PATH$1"),n=n.replace(/\\(\$\{[^}]*\})/g,(l,u)=>{let f=`__ESCAPED_${r.length}__`;return r.push(u),f}),n=n.replace(/\\(#\{[^}]*\})/g,(l,u)=>{let f=`__ESCAPED_${r.length}__`;return r.push(u),f}),n=n.replace(/\\DOUBLE_ESC_VAR/g,"\\"),n=n.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...n.matchAll(di)],i=[...n.matchAll(pi)],s=[...o.map(l=>({match:l,type:"variable"})),...i.map(l=>({match:l,type:"pathref"}))].sort((l,u)=>l.match.index-u.match.index);if(s.length===0){let l=n;for(let u=0;u<r.length;u++)l=l.replace(`__ESCAPED_${u}__`,r[u]);return{type:m.LITERAL,value:l}}if(s.length===1&&s[0].match[0]===n&&r.length===0){let{match:l,type:u}=s[0];try{return u==="variable"?We(l[1],t):sr(l[1])}catch(f){if(f.message==="Invalid array index syntax")return{type:m.LITERAL,value:n};throw f}}let a=[],c=0;for(let{match:l,type:u}of s){let[f,d]=l,p=l.index;if(p>c){let h=n.substring(c,p);for(let y=0;y<r.length;y++)h=h.replace(`__ESCAPED_${y}__`,r[y]);h&&a.push(h)}try{let h;u==="variable"?h=We(d.trim(),t):h=sr(d.trim()),a.push(h)}catch(h){if(h.message==="Invalid array index syntax")a.push(f);else throw h}c=p+f.length}if(c<n.length){let l=n.substring(c);for(let u=0;u<r.length;u++)l=l.replace(`__ESCAPED_${u}__`,r[u]);l&&a.push(l)}return{type:m.INTERPOLATION,parts:a}};var Ht=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),fr=e=>Object.keys(e),J=e=>e.join("."),me=(e,t,n)=>{let r=fr(e).filter(o=>!t.has(o));if(r.length>0)throw new A(`Unexpected key '${r[0]}' in condition JSON at '${J(n)}'`)},ge=(e,t)=>typeof e=="string"?Wt(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?wi(e,t):Ai(e,t):{type:m.LITERAL,value:e},Ii=e=>{let{$each:t,...n}=e;if(typeof t!="string")throw new A("$each value must be a non-empty string");let r=t.trim();if(r==="")throw new A("$each value must be a non-empty string");if(Object.keys(n).length===0)throw new A("Empty $each body not allowed");if(n.$partial!==void 0)throw new A("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${r}`]:n}},wi=(e,t)=>{let n=[],r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(typeof i=="object"&&i!==null&&!Array.isArray(i)){if(i.$each!==void 0)try{let c=Ii(i),l=Object.keys(c);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let u=ur(l[0],c[l[0]],t,!0);n.push(u),r=!0;continue}}catch(c){throw c instanceof A?c:new A(c.message)}let a=Object.keys(i);if(a.length===1&&/^\$for(?::\w+)?\s/.test(a[0])){let c=ur(a[0],i[a[0]],t);n.push(c),r=!0;continue}}let s=ge(i,t);n.push(s),(s.type===m.FUNCTION||s.type===m.CONDITIONAL||s.type===m.LOOP||s.type===m.PARTIAL||s.type===m.OBJECT&&!s.fast||s.type===m.ARRAY&&!s.fast)&&(r=!0)}return{type:m.ARRAY,items:n,fast:!r}},Ai=(e,t)=>{let n=[],r=!1,o=null,i=Object.entries(e),s=0;if(e.$partial!==void 0){if(typeof e.$partial!="string")throw new A("$partial value must be a string");if(e.$partial.trim()==="")throw new A("$partial value cannot be an empty string");let c=["$if","$elif","$else","$for"],l=[];for(let[b]of i)for(let g of c)if(b===g||b.startsWith(g+" ")||b.startsWith(g+"#")){l.push(g);break}if(l.length>0)throw new A(`Cannot use $partial with ${l.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,g]of Object.entries(d)){let x=b;(b.startsWith("\\$")||b.startsWith("$$"))&&(x=b.slice(1)),p[x]=g,h=!0}let y=null;if(h&&(y=ge(p,t),y.type===m.OBJECT)){let b=!1;for(let g of y.properties)if(g.value.type===m.VARIABLE||g.value.type===m.INTERPOLATION||g.value.type===m.FUNCTION||g.value.type===m.CONDITIONAL||g.value.type===m.OBJECT&&!g.value.fast||g.value.type===m.ARRAY&&!g.value.fast){b=!0;break}b&&(y.fast=!1)}let I={type:m.PARTIAL,name:u,data:y};return f!==void 0&&(I.whenCondition=lr(f,t)),I}for(let[c,l]of i)if(c==="$when"){if(o!==null)throw new A("Multiple '$when' directives on the same object are not allowed");if(l==null)throw new A("Missing condition expression after '$when'");o=lr(l,t),r=!0}else if(c.startsWith("$when#")||c.startsWith("$when "))throw new A("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<i.length;){let[c,l]=i[s];if(c==="$when"){s++;continue}if(c==="$each")throw new A("$each can only be used inside arrays");if(c.startsWith("$if ")||c.match(/^\$if#\w+\s/)||c.match(/^\$if\s+\w+.*:$/)){let u=Ei(i,s,t);n.push({key:c,value:u.node}),r=!0,s=u.nextIndex}else if(/^\$for(?::\w+)?\s/.test(c)){let u=c.match(/^\$for(?::(\w+))?\s/)?.[1]||"",f=u?`:${u}`:"";throw new A(`$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 A(`'${c.split(" ")[0]}' without matching '$if'`);if(c==="$if"||c==="$if:")throw new A("Missing condition expression after '$if'");{let u=ge(l,t);(u.type===m.FUNCTION||u.type===m.CONDITIONAL||u.type===m.PARTIAL||u.type===m.OBJECT&&!u.fast||u.type===m.ARRAY&&!u.fast)&&(r=!0);let f=Wt(c,t),d={key:c,value:u};(f.type!==m.LITERAL||f.value!==c)&&(d.parsedKey=f),n.push(d),s++}}}let a={type:m.OBJECT,properties:n,fast:!r};return o&&(a.whenCondition=o),a},Ei=(e,t,n={})=>{let r=[],o=[],i=t,[s,a]=e[i],c=null,l;if(s.startsWith("$if#")){let f=s.match(/^\$if#(\w+)\s+(.+)$/);if(f)c=f[1],l=f[2];else throw new A(`Invalid conditional syntax: ${s}`)}else l=s.substring(4),l.endsWith(":")&&(l=l.slice(0,-1).trim());Ft(l);let u=W(l,n);for(r.push(u),o.push(ge(a,n)),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)r.push(null);else{Ft(h);let y=W(h,n);r.push(y)}if(o.push(ge(d,n)),i++,h===null)break}else break}return{node:{type:m.CONDITIONAL,conditions:r,bodies:o,id:c},nextIndex:i}},qt={eq:$.EQ,neq:$.NEQ,gt:$.GT,gte:$.GTE,lt:$.LT,lte:$.LTE,in:$.IN,add:$.ADD,sub:$.SUBTRACT},Yt={all:$.AND,any:$.OR},xi=new Set(["var","literal","call","not",...Object.keys(qt),...Object.keys(Yt)]),vi=(e,t,n)=>{if(!Array.isArray(e))throw new A(`Condition JSON operator '${t}' at '${J(n)}' requires an array`);if(e.length!==2)throw new A(`Condition JSON operator '${t}' at '${J(n)}' requires exactly 2 operands`);return e},Ci=(e,t,n,r,o)=>{if(!Array.isArray(e))throw new A(`Condition JSON operator '${t}' at '${J(o)}' requires an array`);if(e.length===0)throw new A(`Condition JSON operator '${t}' at '${J(o)}' requires at least 1 condition`);return e.map((s,a)=>se(s,r,[...o,a])).reduce((s,a)=>({type:m.BINARY,op:n,left:s,right:a}))},Si=(e,t,n)=>{let r,o;if(typeof e.call=="string")r=e.call,o=e.args??[],me(e,new Set(["call","args"]),n);else if(Ht(e.call))r=e.call.name,o=e.call.args??[],me(e,new Set(["call"]),n),me(e.call,new Set(["name","args"]),[...n,"call"]);else throw new A(`Condition JSON call at '${J(n)}' requires a function name`);if(typeof r!="string"||r.trim()==="")throw new A(`Condition JSON call at '${J(n)}' requires a non-empty function name`);if(!/^\w+$/.test(r))throw new A(`Invalid condition JSON function name '${r}' at '${J(n)}'`);if(!Array.isArray(o))throw new A(`Condition JSON call '${r}' at '${J(n)}' requires args to be an array`);return{type:m.FUNCTION,name:r,args:o.map((i,s)=>se(i,t,[...n,"args",s]))}},se=(e,t={},n=["$when"])=>{if(typeof e=="string"||typeof e=="number"||typeof e=="boolean"||e===null)return{type:m.LITERAL,value:e};if(Array.isArray(e))throw new A(`Condition JSON array at '${J(n)}' must be wrapped in an operator or { literal: [...] }`);if(!Ht(e))throw new A(`Invalid condition JSON value at '${J(n)}'`);let r=fr(e);if(r.length===0)throw new A(`Condition JSON object at '${J(n)}' must contain an operator`);let o=r.filter(s=>xi.has(s));if(o.length===0)throw new A(`Unknown condition JSON operator '${r[0]}' at '${J(n)}'`);if(o.length>1)throw new A(`Condition JSON at '${J(n)}' must contain exactly one operator`);let i=o.includes("call")?"call":o[0];if(i==="var"){if(me(e,new Set(["var"]),n),typeof e.var!="string"||e.var.trim()==="")throw new A(`Condition JSON var at '${J(n)}' requires a non-empty path`);return{type:m.VARIABLE,path:e.var}}if(i==="literal")return me(e,new Set(["literal"]),n),{type:m.LITERAL,value:e.literal};if(i==="call")return Si(e,t,n);if(i==="not")return me(e,new Set(["not"]),n),{type:m.UNARY,op:ke.NOT,operand:se(e.not,t,[...n,"not"])};if(i in Yt)return me(e,new Set([i]),n),Ci(e[i],i,Yt[i],t,[...n,i]);if(i in qt){me(e,new Set([i]),n);let s=vi(e[i],i,[...n,i]);return{type:m.BINARY,op:qt[i],left:se(s[0],t,[...n,i,0]),right:se(s[1],t,[...n,i,1])}}throw new A(`Unknown condition JSON operator '${i}' at '${J(n)}'`)},lr=(e,t={})=>{if(e==null)throw new A("Missing condition expression after '$when'");if(typeof e=="string"){if(e.trim()==="")throw new A("Empty condition expression after '$when'");return W(e,t)}return Ht(e)||Array.isArray(e)?se(e,t):{type:m.LITERAL,value:e}},W=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let l=e.slice(1,-1),u=0,f=!0;for(let d=0;d<l.length;d++)if(l[d]==="("?u++:l[d]===")"&&u--,u<0){f=!1;break}if(f&&u===0)return W(l,t)}let n=we(e,"||");if(n!==-1)return{type:m.BINARY,op:$.OR,left:W(e.substring(0,n).trim(),t),right:W(e.substring(n+2).trim(),t)};let r=we(e,"&&");if(r!==-1)return{type:m.BINARY,op:$.AND,left:W(e.substring(0,r).trim(),t),right:W(e.substring(r+2).trim(),t)};let o=[{op:">=",type:$.GTE},{op:"<=",type:$.LTE},{op:"==",type:$.EQ},{op:"!=",type:$.NEQ},{op:">",type:$.GT},{op:"<",type:$.LT},{op:" in ",type:$.IN}];for(let{op:l,type:u}of o){let f=we(e,l);if(f!==-1)return{type:m.BINARY,op:u,left:W(e.substring(0,f).trim(),t),right:W(e.substring(f+l.length).trim(),t)}}let i=-1,s=null,a=[{op:" + ",type:$.ADD},{op:" - ",type:$.SUBTRACT}];for(let{op:l,type:u}of a){let f=0;for(;f<e.length;){let d=we(e.substring(f),l);if(d===-1)break;let p=f+d;p>i&&(i=p,s={op:l,type:u}),f=p+l.length}}if(i!==-1&&s)return{type:m.BINARY,op:s.type,left:W(e.substring(0,i).trim(),t),right:W(e.substring(i+s.op.length).trim(),t)};let c=[" * "," / "," % "];for(let l of c)if(we(e,l)!==-1)throw new A(`Arithmetic operations are not allowed in conditionals: "${l}"`);return e.startsWith("!")?{type:m.UNARY,op:ke.NOT,operand:W(e.substring(1).trim(),t)}:dr(e,t)},we=(e,t)=>{let n=0,r=0;for(;r<=e.length-t.length;){if(e[r]==="(")n++;else if(e[r]===")")n--;else if(n===0&&e.substring(r,r+t.length)===t)return r;r++}return-1},_i=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}},dr=(e,t)=>{let n=e.trim();if(n.match(/^(\w+)\((.*)\)$/))return We(n,t);let o=_i(n);if(o.type===m.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(n))return{type:m.VARIABLE,path:n};try{return We(n,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},$i=(e,t=!1)=>{let n=t?"$each":"$for";try{Qn(e)}catch(r){if(r instanceof A&&t){let o=r.message.replace(/\$for/g,"$each");throw new A(o.replace("Parse Error: ",""))}throw r}},ur=(e,t,n,r=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let I=r?"$each":"$for";throw new A(`Invalid loop syntax (got: '${e.replace("$for",I)}')`)}let s=i[1],a=i[2].trim();$i(a,r);let c=a.match(/^(.+?)\s+in\s+(.+)$/);if(!c){let I=r?"$each":"$for";throw new A(`Invalid loop syntax - missing 'in' keyword (got: '${I} ${a}')`)}let l=c[1].trim(),u=c[2].trim(),f,d=null;if(l.includes(",")){let I=l.split(",").map(b=>b.trim());if(I.length!==2)throw new A(`Invalid loop variables: ${l}. Expected format: "item" or "item, index"`);f=I[0],d=I[1]}else f=l;let p=["this","undefined","null","true","false"];if(p.includes(f))throw new A(`Reserved variable name: ${f}`);if(d&&p.includes(d))throw new A(`Reserved variable name: ${d}`);let h=dr(u,n),y=ge(t,n);return{type:m.LOOP,itemVar:f,indexVar:d,iterable:h,body:y,flatten:s!=="nested"}};var Ri=(e,t={})=>{let{functions:n={}}=t;return ge(e,n)},ft=Ri;var qe={};Uo(qe,{now:()=>Oi});var Oi=()=>Date.now();var Li=(e,t,n={})=>{let{functions:r={},partials:o={}}=n,i={...qe,...r},s=ft(e,{functions:i}),a={};for(let[c,l]of Object.entries(o))a[c]=ft(l,{functions:i});return zt(s,t,{functions:i,partials:a})},Z=Li;var ki=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",Pi=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,Ti=(e,t)=>{if(ki(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new A("Empty condition expression");return W(e,t)}return se(e,t)},Ni=(e,t={},n={})=>{let r=Pi(n),o={...qe,...r},i=Ti(e,o);return!!he(i,{functions:o,partials:{}},t,{})},Ae=Ni;var hr=(e,t,n={})=>{let r=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=c=>c,transformActionFirstArgument:a=c=>c}=n;for(let[c,l]of Object.entries(t))c!=="createInitialState"&&(c.startsWith("select")?o[c]=(...u)=>l(s(r),...u):i[c]=(...u)=>{r=Ut(r,d=>l(a(d),...u))});return{...o,...i}},pt=(e,t)=>n=>{let r=e(),o=Array.isArray(n)?n:[n];return Ut(r,i=>{o.forEach(s=>{t.forEach(a=>{a(i,s)})})})};var Di=(e,t)=>{if(e.default!==void 0)return e.default;let n=["number","boolean","string","object"];if(!n.includes(e.type))throw new Error(`Invalid variable type: ${e.type} for variable ${t}. Expected one of: ${n.join(", ")}`);switch(e.type){case"number":return 0;case"boolean":return!1;case"string":return"";case"object":return{}}},re=(e,t)=>Object.prototype.hasOwnProperty.call(e??{},t),Ye=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),mr=e=>{let t=ie(e)?ze(e):e;return structuredClone(t)},Ee=e=>re(e,"computed"),Pe=(e={},t={})=>Object.fromEntries(Object.entries(e??{}).filter(([n])=>!Ee(t[n]))),Vi=e=>String(e).replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean),Jt=(e,t)=>{let n=e;for(let r of t){if(n==null)return;n=n[r]}return n},ji=(e,t={})=>{if(typeof e!="string"||e.trim()==="")throw new Error("Computed expression var requires a non-empty string path");let n=Vi(e),[r,o,...i]=n;if(r==="variables"){if(!o)return t.variables;let s=typeof t.resolveVariable=="function"?t.resolveVariable(o):t.variables?.[o];return Jt(s,i)}return r==="runtime"?Jt(t.runtime,n.slice(1)):Jt(t,n)},Mi=(e,t,n)=>{if(!Array.isArray(t))throw new Error(`Computed expression operator "${e}" requires an array`);if(n!==void 0&&t.length!==n)throw new Error(`Computed expression operator "${e}" requires ${n} operand(s)`)},pr=(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`)},Bi=(e,t)=>{if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Computed expression operator "${e}" requires finite numeric operands`)},ne=(e,t,n,r)=>(Mi(e,t,r),t.map(o=>dt(o,n))),ee=(e,t,n,r)=>{let o=ne(e,t,n,r);return o.forEach(i=>Bi(e,i)),o},Ui=(e,t,n)=>{switch(e){case"var":return ji(t,n);case"add":{let[r,o]=ee(e,t,n,2);return r+o}case"sub":{let[r,o]=ee(e,t,n,2);return r-o}case"mul":{let[r,o]=ee(e,t,n,2);return r*o}case"div":{let[r,o]=ee(e,t,n,2);return r/o}case"mod":{let[r,o]=ee(e,t,n,2);return r%o}case"neg":{let[r]=ee(e,t,n,1);return-r}case"round":{let[r]=ee(e,t,n,1);return Math.round(r)}case"floor":{let[r]=ee(e,t,n,1);return Math.floor(r)}case"ceil":{let[r]=ee(e,t,n,1);return Math.ceil(r)}case"min":{let[r,o]=ee(e,t,n,2);return Math.min(r,o)}case"max":{let[r,o]=ee(e,t,n,2);return Math.max(r,o)}case"clamp":{let[r,o,i]=ee(e,t,n,3);return Math.min(i,Math.max(o,r))}case"eq":{let[r,o]=ne(e,t,n,2);return r==o}case"neq":{let[r,o]=ne(e,t,n,2);return r!=o}case"gt":{let[r,o]=ne(e,t,n,2);return r>o}case"gte":{let[r,o]=ne(e,t,n,2);return r>=o}case"lt":{let[r,o]=ne(e,t,n,2);return r<o}case"lte":{let[r,o]=ne(e,t,n,2);return r<=o}case"in":{let[r,o]=ne(e,t,n,2);return Array.isArray(o)?o.includes(r):!1}case"and":case"all":return pr(e,t),t.every(r=>!!dt(r,n));case"or":case"any":return pr(e,t),t.some(r=>!!dt(r,n));case"not":{let[r]=ne(e,t,n,1);return!r}case"length":{let[r]=ne(e,t,n,1);return typeof r=="string"||Array.isArray(r)?r.length:Ye(r)?Object.keys(r).length:0}case"includes":{let[r,o]=ne(e,t,n,2);return typeof r=="string"||Array.isArray(r)?r.includes(o):!1}case"literal":return mr(t);default:throw new Error(`Unknown computed expression operator: ${e}`)}},dt=(e,t={})=>{if(e===null||typeof e!="object")return e;if(Array.isArray(e))throw new Error("Computed expression arrays are not valid; use value for literal arrays");let n=Object.entries(e);if(n.length!==1)throw new Error("Computed expression objects must contain exactly one operator");let[[r,o]]=n;return Ui(r,o,t)},Fi=(e,t={})=>Ae(e,{variables:t.variables,runtime:t.runtime}),zi=(e,t)=>{if(!Ye(e))throw new Error(`${t} must be an object`);let n=re(e,"expr"),r=re(e,"value");if(n===r)throw new Error(`${t} must contain exactly one of expr or value`)},Kt=(e,t,n)=>(zi(e,t),re(e,"value")?mr(e.value):dt(e.expr,n)),Wi=(e,t={},n="unknown")=>{if(!Ye(e))throw new Error(`Computed variable "${n}" computed must be an object`);let r=re(e,"expr"),o=re(e,"value");if(re(e,"branches")){if(r||o)throw new Error(`Computed variable "${n}" cannot combine branches with expr or value`);if(!Array.isArray(e.branches))throw new Error(`Computed variable "${n}" branches must be an array`);if(e.branches.length===0)throw new Error(`Computed variable "${n}" branches must not be empty`);if(!Ye(e.default))throw new Error(`Computed variable "${n}" requires default`);for(let s=0;s<e.branches.length;s+=1){let a=e.branches[s];if(!Ye(a))throw new Error(`Computed variable "${n}" branch ${s} must be an object`);if(!re(a,"when"))throw new Error(`Computed variable "${n}" branch ${s} requires when`);if(Fi(a.when,t))return Kt(a,`Computed variable "${n}" branch ${s}`,t)}return Kt(e.default,`Computed variable "${n}" default`,t)}if(r===o)throw new Error(`Computed variable "${n}" must contain exactly one of expr, value, or branches`);return Kt(e,`Computed variable "${n}"`,t)},qi=(e,t,n)=>{switch(t){case"number":if(typeof n!="number"||!Number.isFinite(n))throw new Error(`Computed variable "${e}" expected type number, got ${Array.isArray(n)?"array":typeof n}`);return;case"boolean":if(typeof n!="boolean")throw new Error(`Computed variable "${e}" expected type boolean, got ${Array.isArray(n)?"array":typeof n}`);return;case"string":if(typeof n!="string")throw new Error(`Computed variable "${e}" expected type string, got ${Array.isArray(n)?"array":typeof n}`);return;case"object":if(n===null||typeof n!="object")throw new Error(`Computed variable "${e}" expected type object, got ${typeof n}`);return;default:throw new Error(`Invalid variable type: ${t} for computed variable ${e}`)}},ht=({variables:e={},runtime:t={},variableConfigs:n={},eager:r=!0}={})=>{let o=Pe(e,n),i=Object.entries(n).filter(([,f])=>Ee(f)).map(([f])=>f),s={},a=[],c=f=>{if(re(s,f))return s[f];let d=n[f];if(!Ee(d))return o[f];let p=a.indexOf(f);if(p>=0){let h=[...a.slice(p),f].join(" -> ");throw new Error(`Computed variable cycle detected: ${h}`)}a.push(f);try{let h=Wi(d.computed,u,f);return qi(f,d.type,h),s[f]=h,h}finally{a.pop()}},l=new Proxy({},{get:(f,d)=>{if(typeof d=="string")return c(d)},has:(f,d)=>typeof d=="string"&&(re(o,d)||i.includes(d)),ownKeys:()=>[...new Set([...Object.keys(o),...i])],getOwnPropertyDescriptor:(f,d)=>{if(!(typeof d!="string"||!re(o,d)&&!i.includes(d)))return{enumerable:!0,configurable:!0}}}),u={variables:l,runtime:t,resolveVariable:c};return r?(i.forEach(f=>{c(f)}),{...o,...s}):l},Yi=({variables:e={},runtime:t={},variableConfigs:n,projectData:r}={})=>ht({variables:e,runtime:t,variableConfigs:n??r?.resources?.variables??{},eager:!0}),Qt=e=>{let t={},n={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([r,o])=>{if(Ee(o))return;let i=Di(o,r);o.scope==="context"?t[r]=i:n[r]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}},Zt=(e,t)=>{let n=["context","device","account"];if(!e)throw new Error(`Variable scope is required for variable: ${t}`);if(!n.includes(e))throw new Error(`Invalid variable scope: ${e} for variable ${t}. Expected one of: ${n.join(", ")}`)},en=(e,t,n)=>{let r={number:["set","increment","decrement","multiply","divide"],boolean:["set","toggle"],string:["set"],object:["set"]},o=r[e];if(!o)throw new Error(`Unknown variable type: ${e} for variable ${n}`);if(!Object.values(r).flat().includes(t))throw new Error(`Unknown operation: ${t}`);if(!o.includes(t))throw new Error(`Operation "${t}" is not valid for variable "${n}" of type "${e}". Valid operations: ${o.join(", ")}`)},tn=(e,t,n)=>{switch(t){case"set":return n;case"multiply":return(e??1)*n;case"divide":return(e??0)/n;case"increment":return(e??0)+(n??1);case"decrement":return(e??0)-(n??1);case"toggle":return!e;default:throw new Error(`Unknown operation: ${t}`)}};var gr=(e,t="DD/MM/YYYY - HH:mm")=>{if(!e)return"";let n=new Date(e),r=o=>String(o).padStart(2,"0");return t.replace("DD",r(n.getDate())).replace("MM",r(n.getMonth()+1)).replace("YYYY",n.getFullYear()).replace("YY",String(n.getFullYear()).slice(-2)).replace("HH",r(n.getHours())).replace("mm",r(n.getMinutes())).replace("ss",r(n.getSeconds()))},Hi=(e,t)=>{let n=i=>{if(!i)return;let s={};i.ui&&(s.ui=i.ui);let a=i.character?.sprite;return a&&Object.keys(a).length>0&&(s.sprite=a),Object.keys(s).length>0?s:void 0},r=n(e),o=n(t);return JSON.stringify(r)===JSON.stringify(o)?null:r&&!o?{changeType:"delete",data:e}:o&&!r?{changeType:"add",data:t}:o&&r?{changeType:"update",data:t}:null},nn=(e={},t={})=>{let n={},r=["sfx","voice"],o=s=>{let a=e[s],c=t[s];c&&!a?n[s]={changeType:"add",data:c}:a&&!c?r.includes(s)||(n[s]={changeType:"delete",data:a}):a&&c&&JSON.stringify(a)!==JSON.stringify(c)&&(n[s]={changeType:"update",data:c})};o("background"),o("bgm"),o("voice");let i=Hi(e.dialogue,t.dialogue);return i&&(n.dialogue=i),o("choice"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),n},rn=(e={})=>{let t=structuredClone(e);t.background&&(t.background.animations?.playback?.continuity!=="persistent"&&delete t.background.animations,t.background.resourceId||delete t.background);let n=o=>{t[o]&&(delete t[o].animations,Object.keys(t[o]).length===0&&delete t[o])};n("layout"),n("choice"),t.dialogue?.ui&&(delete t.dialogue.ui.animations,Object.keys(t.dialogue.ui).length===0&&delete t.dialogue.ui,Object.keys(t.dialogue).length===0&&delete t.dialogue),t.dialogue?.character?.sprite&&(delete t.dialogue.character.sprite.animations,Object.keys(t.dialogue.character.sprite).length===0&&delete t.dialogue.character.sprite,Object.keys(t.dialogue.character).length===0&&delete t.dialogue.character,Object.keys(t.dialogue).length===0&&delete t.dialogue);let r=(o,i)=>{let s=t[o]?.items;Array.isArray(s)&&(t[o].items=s.map(a=>{let c={...a};return delete c.animations,i(c)?c:null}).filter(Boolean),t[o].items.length===0&&delete t[o])};return r("character",o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId),r("visual",o=>o.resourceId||o.transformId),t},Ji=(e,t)=>{if(!e||!t)return;let n=e;for(let r of t.split(".")){if(n==null||!(r in Object(n)))return;n=n[r]}return n},Ki=(e,t)=>{if(typeof e!="string")return e;if(e==="_event"){if(t==null)throw new Error('Action template binding "_event" requires event context "_event".');return t}if(!e.startsWith("_event."))return e;if(t==null)throw new Error(`Action template binding "${e}" requires event context "_event".`);let n=e.slice(7),r=Ji(t,n);if(r===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return r},Gi={conditional:new Set(["branches"]),updateProjectData:new Set(["projectData"]),showConfirmDialog:new Set(["confirmActions","cancelActions"])},yr=(e,t)=>{let n=e[e.length-1];return n?Gi[n]?.has(t)===!0:!1},Gt=(e,t,n=[])=>Array.isArray(e)?e.map(r=>Gt(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,yr(n,r)?o:Gt(o,t,[...n,r])])):Ki(e,t),Xt=(e,t,n=[])=>Array.isArray(e)?e.map(r=>Xt(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,yr(n,r)?o:Xt(o,t,[...n,r])])):typeof e=="string"?Z(e,t):e,on=(e,t)=>{if(!t)return e;if(Object.prototype.hasOwnProperty.call(t,"event"))throw new Error('Action template context key "event" is no longer supported. Use "_event".');let n=Gt(e,t._event);return Xt(n,t)};var mt=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:structuredClone(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},wr=(e,t)=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let n=e.map(r=>structuredClone(r)).filter(r=>t(r)||r.animations);return{hasValidItems:n.length>0,processedItems:n}},Te=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),br=e=>e?.animations?.playback?.continuity==="persistent",Xi=e=>{if(e){if(e.character&&Te(e.character,"name"))return e.character.name;if(Te(e,"characterName"))return e.characterName}},Ar=e=>!!e?.character&&Te(e.character,"sprite"),Qi=e=>{let t={},n=!1,r=Xi(e);return r!==void 0&&(t.name=r,n=!0),Ar(e)&&(t.sprite=structuredClone(e.character.sprite),n=!0),n?t:void 0},Ir=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},Zi=({dialogueState:e,content:t,append:n=!1})=>{if(!n||!Array.isArray(t)){e.content=t,delete e.initialRevealedContent;return}let r=Array.isArray(e.content)?e.content:[];r.length>0?e.initialRevealedContent=r.map(o=>structuredClone(o)):delete e.initialRevealedContent,e.content=[...r,...t]},es=()=>({}),ts=(e,t)=>{if(t.background){let{animationsOnly:n,state:r}=mt(t.background,s=>!!s.resourceId);if(n){e.background=e.background?.resourceId?{...structuredClone(e.background),...r}:r;return}if(!t.background.resourceId){delete e.background;return}let o=structuredClone(t.background),i=e.background;i?.resourceId===o.resourceId&&i?.transformId===o.transformId&&!Te(o,"animations")&&br(i)&&(o.animations=structuredClone(i.animations)),e.background=o}else e.background?.animations&&!br(e.background)&&(e.background.animations={})},ns=(e,t)=>{if(!t.dialogue){e.dialogue&&(Ir(e.dialogue),e.dialogue.mode==="adv"&&(e.dialogue.content=void 0,delete e.dialogue.initialRevealedContent,e.dialogue.persistCharacter!==!0&&(delete e.dialogue.characterId,delete e.dialogue.character)));return}e.dialogue||(e.dialogue={});let n=e.dialogue.mode;if(t.dialogue.ui){let{animationsOnly:l,state:u}=mt(t.dialogue.ui,f=>!!f.resourceId);l?e.dialogue.ui={...e.dialogue.ui,...u}:e.dialogue.ui={...t.dialogue.ui}}else e.dialogue?.ui?.animations&&(e.dialogue.ui.animations={});t.dialogue.mode==="adv"&&(e.dialogue.content=e.dialogue.content||void 0,e.dialogue.characterId=e.dialogue.characterId||void 0,e.dialogue.mode="adv"),t.dialogue.mode==="nvl"&&(e.dialogue?.mode!=="nvl"&&(e.dialogue.lines=[]),e.dialogue.mode="nvl");let r=t.dialogue.append===!0&&n!=="nvl"&&e.dialogue?.mode!=="nvl"&&Array.isArray(t.dialogue.content);t.dialogue.content!==void 0&&Zi({dialogueState:e.dialogue,content:t.dialogue.content,append:r});let o=Te(t.dialogue,"persistCharacter")?t.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;o?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let i=Te(t.dialogue,"characterId"),s=Qi(t.dialogue),a=s!==void 0,c=Ar(t.dialogue);if(i?t.dialogue.characterId?e.dialogue.characterId=t.dialogue.characterId:delete e.dialogue.characterId:!o&&!r&&delete e.dialogue.characterId,a?e.dialogue.character=!i&&o&&e.dialogue.character?{...structuredClone(e.dialogue.character),...s}:s:(i||!o&&!r)&&delete e.dialogue.character,c||Ir(e.dialogue),t.dialogue.clear){delete e.dialogue;return}if(t.dialogue?.clearPage&&e.dialogue?.mode==="nvl"&&(e.dialogue.lines=[]),e.dialogue?.mode==="nvl"&&t.dialogue.content!==void 0){let l={content:t.dialogue.content,characterId:e.dialogue.characterId??null};e.dialogue.character&&(l.character=structuredClone(e.dialogue.character)),e.dialogue.lines.push(l)}},rs=(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},os=(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}}},is=(e,t)=>{if(t.visual){let{hasValidItems:n,processedItems:r}=wr(t.visual.items,o=>!!o.resourceId);n?e.visual={items:r}:delete e.visual}else e.visual?.items&&(e.visual.items=e.visual.items.map(n=>n.animations?{...n,animations:{}}:n))},ss=(e,t)=>{if(!t.character){e.character?.items&&(e.character.items=e.character.items.map(o=>o.animations?{...o,animations:{}}:o));return}let{hasValidItems:n,processedItems:r}=wr(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId);n?e.character={items:r}:delete e.character},as=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},cs=(e,t)=>{if(t.layout){let{animationsOnly:n,state:r}=mt(t.layout,o=>!!o.resourceId);if(n){e.layout=r;return}if(!t.layout.resourceId){delete e.layout;return}e.layout=t.layout}else e.layout&&delete e.layout},ls=(e,t)=>{if(t.choice){let{animationsOnly:n,state:r}=mt(t.choice,o=>!!o.resourceId);if(n){e.choice={...e.choice,...r};return}if(!t.choice.resourceId){delete e.choice;return}e.choice=t.choice}else e.choice&&delete e.choice},us=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},fs=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},ds=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(n=>{delete e[n]})},Ne=e=>pt(es,[ds,ts,rs,os,is,ns,ss,as,cs,ls,us,fs])(e);var xe={objectValues:e=>Object.entries(e).map(([t,n])=>({id:t,...n})),formatDate:gr},ps=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,hs=(e,t)=>{let n=String(t||"").trim();if(!n)return;let r=n.match(/[A-Za-z_][A-Za-z0-9_]*|\[\d+\]/g)||[],o=e;for(let i of r){if(i.startsWith("[")){let s=Number(i.slice(1,-1));o=Array.isArray(o)?o[s]:void 0;continue}o=o?.[i]}return o},bt=(e,t,n)=>{if(Array.isArray(e)){let o=[];for(let i of e){if(i&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===1){let[s]=Object.keys(i),a=ps.exec(s);if(a){let[,c,l,u]=a,f=hs(t,u);if(!Array.isArray(f))continue;let d=Array.isArray(i[s])?i[s]:[];f.forEach((p,h)=>{let y={...t,[c]:p};l&&(y[l]=h),d.forEach(I=>{let b=bt(I,y,n),g=Z(b,y,n);Array.isArray(g)?o.push(...g):o.push(g)})});continue}}o.push(bt(i,t,n))}return o}if(!e||typeof e!="object")return e;let r={};return Object.entries(e).forEach(([o,i])=>{r[o]=bt(i,t,n)}),r},bn=({animationType:e,animationId:t,animationPath:n})=>{if(e!==void 0&&!(e==="update"||e==="transition"))throw new Error(`[${n}] Animation "${t}" has unsupported type "${e}". Use "update" or "transition".`)},ms=({id:e,targetId:t,animation:n,playback:r,animationPath:o="animation"})=>{let i=structuredClone(n);return bn({animationType:i.type,animationId:e,animationPath:o}),delete i.name,delete i.playback,i.id=e,i.targetId=t,r&&(i.playback=structuredClone(r)),i},gs=(e,{animationId:t="animation",animationPath:n="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return bn({animationType:e.type,animationId:t,animationPath:n}),e.type},ys=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},bs=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},Is=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),kr=e=>e?.playback?.continuity==="persistent",fn=e=>Array.isArray(e)?e.map(fn):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((t,n)=>(t[n]=fn(e[n]),t),{}),It=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let t=structuredClone(e);return delete t.playback,JSON.stringify(fn(t))},Pr=(e=[])=>e.filter(t=>kr(t)).map(t=>structuredClone(t)),Tr=e=>Array.isArray(e?.keyframes)?e.keyframes.reduce((t,n)=>{let r=typeof n?.duration=="number"&&Number.isFinite(n.duration)?n.duration:0;return t+r},0):0,sn=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((t,n)=>Math.max(t,Tr(n)),0),Nr=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max(sn(e.tween),sn(e.prev?.tween),sn(e.next?.tween),Tr(e.mask?.progress)),Er=({animationInstances:e,activePersistentAnimations:t})=>{if(!Array.isArray(e)||e.length===0||!Array.isArray(t)||t.length===0)return!1;let n=new Set(t.map(It).filter(Boolean));return e.some(r=>{if(!kr(r))return!1;let o=It(r);return o?n.has(o):!1})},ue=({animationInstances:e,isLineCompleted:t,skipTransitionsAndAnimations:n,activePersistentAnimations:r,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||n?!1:i&&!t||Er({animationInstances:e,activePersistentAnimations:r})?!0:i?!1:Er({animationInstances:e,activePersistentAnimations:o}),ws=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),As=(e,t)=>{if(ws(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},Es=({resources:e,animationId:t,playback:n,instanceId:r,targetId:o,animationPath:i="animation"})=>{if(!t||!o)return!1;let s=e?.animations?.[t];return s?ms({id:r,targetId:o,animation:s,playback:n,animationPath:i}):null},xs=({hasPrevious:e,hasCurrent:t,previousResourceId:n,currentResourceId:r,sharedTarget:o})=>!e&&t?"enter":e&&!t?"exit":e&&t?n===r&&o?"update":"replace":"none",vs=({animationType:e,animationId:t,animationPath:n,lifecycle:r})=>{if(!(e!=="update"||r==="update"))throw new Error(`[${n}] Animation "${t}" has type "update", but update animations can only be used when the same target persists across the state change. Use type "transition" for enter, exit, and replace.`)},Cs=(e,{defaultTargetId:t,defaultId:n,animationPath:r="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return bn({animationType:o.type,animationId:o.id??n,animationPath:r}),o.id??=n,o.targetId??=t,o},In=({animations:e,transitions:t,defaultTargetId:n,idPrefix:r,animationPathPrefix:o=r})=>{t.forEach((i,s)=>{e.push(Cs(i,{defaultTargetId:n,defaultId:`${r}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},dn=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let n=Z(e,t);return n&&typeof n=="object"?e:n},pn=(e,t)=>{if(e===void 0)return[];if(!Array.isArray(e)||e.some(n=>n===null||typeof n!="object"||Array.isArray(n)))throw new Error(`${t} must be an array of objects`);return e},Ss=({content:e,path:t,variables:n})=>pn(e,t).reduce((r,o)=>{let i=dn(o.text,{variables:n});return r+`${i??""}`.length},0),xr=(e=[])=>{let t=new Map;for(let n of e)n?.id&&t.set(n.id,(t.get(n.id)??0)+1);return new Set(Array.from(t.entries()).filter(([,n])=>n>1).map(([n])=>n))},gt=(e,t=0,n=new Set)=>{if(!n.has(e?.id))return`character-container-${e.id}`;let r=e?.sprites?.map(({resourceId:o})=>o)||[];return r.length===0?`character-container-${e.id}`:`character-container-${e.id}-${t}-${r.join("-")}`},an=(e,t)=>{if(!t.transformId)throw new Error(`Visual item "${t.id}" requires transformId`);let n=e.transforms?.[t.transformId];if(!n)throw new Error(`Transform "${t.transformId}" not found for visual item "${t.id}"`);return n},_s=(e,t={})=>{if(!t?.transformId)return;let n=e.transforms?.[t.transformId];if(!n)throw new Error(`Transform "${t.transformId}" not found for background`);return n},vr=(e={},t)=>{if(t){if(e.images?.[t])return"sprite";if(e.videos?.[t])return"video";if(e.layouts?.[t])return"container"}},yt=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},$s=(e={})=>e.textStyles||{},Rs=(e={})=>e.images||{},Os=(e={})=>e.colors||{},Ls=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,He=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,Ve=(e,t,n)=>{if(typeof e!="string"||e.length===0)throw new Error(`${n} at "${t}" must resolve to a non-empty string`)},Cr=(e,t,n)=>{if(e===void 0)return 1;if(typeof e!="number"||!Number.isFinite(e))throw new Error(`${t} for text style "${n}" must be a number between 0 and 1`);if(e<0||e>1)throw new Error(`${t} for text style "${n}" must be a number between 0 and 1`);return e},Dr=(e,t)=>{if(typeof e!="string"||!Ls.test(e))throw new Error(`${t} must resolve to a hex color`);return e.length===4?`#${e.slice(1).split("").map(n=>n.repeat(2)).join("")}`:e},Sr=(e,t,n)=>{let r=Dr(e,n);if(t===1)return r;let o=Number.parseInt(r.slice(1,3),16),i=Number.parseInt(r.slice(3,5),16),s=Number.parseInt(r.slice(5,7),16);return`rgba(${o}, ${i}, ${s}, ${t})`},ks=(e={},t)=>{let n=$s(e)?.[t];if(!n)throw new Error(`Text style "${t}" not found`);let r=e.fonts?.[n.fontId];if(!r)throw new Error(`Font "${n.fontId}" not found for text style "${t}"`);let o=e.colors?.[n.colorId];if(!o)throw new Error(`Color "${n.colorId}" not found for text style "${t}"`);let i=Cr(n.colorAlpha,"colorAlpha",t),s={fontFamily:r.fileId,fontSize:n.fontSize??16,fontWeight:n.fontWeight??"400",fontStyle:n.fontStyle??"normal",lineHeight:n.lineHeight??1.2,fill:Sr(o.hex,i,`Color "${n.colorId}" for text style "${t}"`)};if(n.align!==void 0&&(s.align=n.align),n.wordWrap!==void 0&&(s.wordWrap=n.wordWrap),n.breakWords!==void 0&&(s.breakWords=n.breakWords),n.wordWrapWidth!==void 0&&(s.wordWrapWidth=n.wordWrapWidth),n.strokeColorId){let a=e.colors?.[n.strokeColorId];if(!a)throw new Error(`Stroke color "${n.strokeColorId}" not found for text style "${t}"`);let c=Cr(n.strokeAlpha,"strokeAlpha",t);s.strokeColor=Sr(a.hex,c,`Stroke color "${n.strokeColorId}" for text style "${t}"`)}else if(n.strokeAlpha!==void 0)throw new Error(`strokeAlpha for text style "${t}" requires strokeColorId`);return n.strokeWidth!==void 0&&(s.strokeWidth=n.strokeWidth),s},hn=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>hn(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(Object.prototype.hasOwnProperty.call(e,"textStyle"))throw new Error(`Inline textStyle is not allowed in layout elements at "${n}". Use textStyleId instead`);let r={};for(let[o,i]of Object.entries(e))o!=="textStyleId"&&(r[o]=hn(i,t,He(n,o)));return e.textStyleId!==void 0&&(Ve(e.textStyleId,n,"textStyleId"),r.textStyle=ks(t,e.textStyleId)),r},Vr=(e={},t)=>{let n=Os(e)?.[t];if(!n)throw new Error(`Color "${t}" not found`);return Dr(n.hex,`Color "${t}"`)},jr=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",cn=(e,t,n)=>{let r=e?.[t];if(!(!r||typeof r!="object"||Array.isArray(r))&&Object.prototype.hasOwnProperty.call(r,"fill"))throw new Error(`Inline ${t}.fill is not allowed in rect layout elements at "${n}". Use ${jr(`${t}.fill`)} instead`)},Ps=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>Je(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;let r={};for(let[o,i]of Object.entries(e))o!=="colorId"&&(r[o]=Je(i,t,He(n,o)));return e.colorId!==void 0&&(Ve(e.colorId,n,"colorId"),r.fill=Vr(t,e.colorId)),r},Je=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>Je(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="rect"){if(Object.prototype.hasOwnProperty.call(e,"fill"))throw new Error(`Inline fill is not allowed in rect layout elements at "${n}". Use ${jr("fill")} instead`);cn(e,"hover",n),cn(e,"click",n),cn(e,"rightClick",n)}let r={};for(let[o,i]of Object.entries(e))if(!(e.type==="rect"&&o==="colorId")){if(e.type==="rect"&&(o==="hover"||o==="click"||o==="rightClick")){r[o]=Ps(i,t,He(n,o));continue}r[o]=Je(i,t,He(n,o))}return e.type==="rect"&&e.colorId!==void 0&&(Ve(e.colorId,n,"colorId"),r.fill=Vr(t,e.colorId)),r},ln=(e={},t)=>{let n=Rs(e)?.[t];return n||null},Mr=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",_r=(e,t,n,r)=>{let o=e?.[t];if(!(!o||typeof o!="object"||Array.isArray(o))&&Object.prototype.hasOwnProperty.call(o,r))throw new Error(`Inline ${t}.${r} is not allowed in sprite layout elements at "${n}". Use ${Mr(`${t}.${r}`)} instead`)},$r=(e,t,n)=>{let r=e[t];e[t]={...r&&typeof r=="object"&&!Array.isArray(r)?r:{},src:n}},mn=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>mn(o,t,`${n}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="sprite"){for(let o of["url","src","hoverUrl","hoverSrc","clickUrl","clickSrc"])if(Object.prototype.hasOwnProperty.call(e,o))throw new Error(`Inline ${o} is not allowed in sprite layout elements at "${n}". Use ${Mr(o)} instead`);_r(e,"hover",n,"src"),_r(e,"click",n,"src")}let r={};for(let[o,i]of Object.entries(e))e.type==="sprite"&&(o==="imageId"||o==="hoverImageId"||o==="clickImageId")||(r[o]=mn(i,t,He(n,o)));if(e.type==="sprite"&&e.imageId!==void 0){Ve(e.imageId,n,"imageId");let o=ln(t,e.imageId),i=o?.fileId??e.imageId;r.src=i,r.width===void 0&&o?.width!==void 0&&(r.width=o.width),r.height===void 0&&o?.height!==void 0&&(r.height=o.height)}return e.type==="sprite"&&e.hoverImageId!==void 0&&(Ve(e.hoverImageId,n,"hoverImageId"),$r(r,"hover",ln(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(Ve(e.clickImageId,n,"clickImageId"),$r(r,"click",ln(t,e.clickImageId)?.fileId??e.clickImageId)),r},wn=(e,t={},n="root")=>mn(Je(hn(e,t,n),t,n),t,n),ve=wn,Ke=(e=[])=>e.find(t=>t.id==="story");var Ts=(e={})=>e?.muteAll?0:e?.musicVolume??50,ae=({variables:e,runtime:t,saveSlots:n=[],dialogueState:r,includeInactiveAdvDialogue:o=!1,isLineCompleted:i,autoMode:s,skipMode:a,isChoiceVisible:c,canRollback:l,confirmDialog:u,historyDialogue:f=[],characters:d={},dialogueUIHidden:p,skipOnlyViewedLines:h,skipTransitionsAndAnimations:y}={})=>{let I={dialogueTextSpeed:t?.dialogueTextSpeed??50,autoForwardDelay:t?.autoForwardDelay??1e3,skipUnseenText:t?.skipUnseenText??!1,skipTransitionsAndAnimations:t?.skipTransitionsAndAnimations??!1,soundVolume:t?.soundVolume??50,musicVolume:t?.musicVolume??50,muteAll:t?.muteAll??!1,saveLoadPagination:t?.saveLoadPagination??1,menuPage:t?.menuPage??"",menuEntryPoint:t?.menuEntryPoint??"",autoMode:t?.autoMode??s??!1,skipMode:t?.skipMode??a??!1,dialogueUIHidden:t?.dialogueUIHidden??p??!1,isLineCompleted:t?.isLineCompleted??i??!1},b=js({dialogueState:r,includeInactiveAdvDialogue:o,characters:d,variables:e}),g={variables:e,runtime:I,saveSlots:n,isChoiceVisible:c,canRollback:l,confirmDialog:u,historyDialogue:f,characters:d};return b&&(g.dialogue=b,g.dialogueLines=b.lines),g},Rr=100,wt=(e,t)=>{if(Array.isArray(e))return e.map(r=>wt(r,t));if(!e||typeof e!="object")return e;let n={...e};return Object.keys(n).forEach(r=>{n[r]=wt(n[r],t)}),n.type==="text-revealing"?t(n):n},Ns=e=>wt(e,t=>({...t,revealEffect:"none"})),Ds=e=>wt(e,t=>{let n=Number(t.speed??t.displaySpeed),r=Number.isFinite(n)?Math.max(n,Rr):Rr;return{...t,speed:r,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:r}:{}}}),Ce=(e,{isLineCompleted:t=!1,skipMode:n=!1,skipTransitionsAndAnimations:r=!1}={})=>t||r?Ns(e):n?Ds(e):e,Br=({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:{}}}}),gn=e=>{if(Array.isArray(e))return e.map(gn);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=gn(s);let n=t.click?.payload;if(!n||typeof n!="object"||Array.isArray(n))return t;let r=n.actions,o=r&&typeof r=="object"&&!Array.isArray(r)&&Object.prototype.hasOwnProperty.call(r,"nextLine")?{...r.nextLine,_interactionSource:"choice"}:void 0;return{...t,click:{...t.click,payload:{...n,_interactionSource:"choice",...o?{actions:{...r,nextLine:o}}:{}}}}},yn=({characterId:e,character:t,characterName:n,characters:r={}}={})=>{let o=e?r?.[e]:void 0,i=t?.name!==void 0?t.name:n!==void 0?n:o?.name||"";return{...o||{},...t||{},name:i}},Ur=(e=[],t={})=>e.map(n=>{let r=yn({characterId:n.characterId,character:n.character,characterName:n.characterName,characters:t}),o=typeof n.text=="string"?n.text:Array.isArray(n.content)?n.content.map(i=>i?.text??"").join(""):"";return{...n,text:o,character:r,characterName:r.name}}),Vs=e=>!(!e||e.mode==="adv"&&e.content===void 0),js=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:n={},variables:r}={})=>{if(!t&&!Vs(e))return;let o=e.content===void 0?[{text:""}]:pn(e.content,"dialogue.content"),i=e.content===void 0?0:Ss({content:e.initialRevealedContent,path:"dialogue.initialRevealedContent",variables:r}),s=(e.lines||[]).map((c,l)=>{let u=pn(c.content,`dialogue.lines[${l}].content`),f=yn({characterId:c.characterId,character:c.character,characterName:c.characterName,characters:n});return{...c,content:u.map(d=>({...d,text:dn(d.text,{variables:r})})),character:f,characterName:f.name}}),a=yn({characterId:e.characterId,character:e.character,characters:n});return{characterId:e.characterId,persistCharacter:e.persistCharacter,character:a,content:o.map(c=>({...c,text:dn(c.text,{variables:r})})),initialRevealedCharacters:i,lines:s}},Fr=({container:e,resources:t,templateData:n,isLineCompleted:r=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=Z(e,n,{functions:xe});return ve(Ce(s,{isLineCompleted:r,skipMode:o,skipTransitionsAndAnimations:i}),t)},un=(e,t={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(t),Or=({renderStateKeyboard:e,keyboard:t,phase:n})=>{!t||typeof t!="object"||Array.isArray(t)||Object.entries(t).forEach(([r,o])=>{let i=e[r]??{},s=n==="keydown"?o?.keydown:o?.keyup;if(n==="keydown"&&s&&typeof s=="object"){e[r]={...i,keydown:{payload:un(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[r].keyup={payload:un(o.keyup)});return}e[r]={...i,[n]:{payload:un(o)}}})},Ms=(e={},t={})=>{let n={};return Or({renderStateKeyboard:n,keyboard:e,phase:"keydown"}),Or({renderStateKeyboard:n,keyboard:t,phase:"keyup"}),Object.keys(n).length>0?n:void 0},Se=({animationsDef:e,resources:t,previousResourceId:n,currentResourceId:r,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:a,allowIncomingUpdateFallback:c=!1})=>{if(!e)return[];let l=[],u=({instanceId:C,targetId:O})=>{let L=Es({resources:t,animationId:y,playback:I,instanceId:C,targetId:O,animationPath:s});L&&l.push(L)},f=n!=null&&n!==!1,d=r!=null&&r!==!1,p=o&&i&&o===i,h=xs({hasPrevious:f,hasCurrent:d,previousResourceId:n,currentResourceId:r,sharedTarget:p});As(e,s);let y=ys(e),I=bs(e),b=t?.animations?.[y],g=gs(b,{animationId:y,animationPath:s}),x=c&&g==="update"&&h!=="update"&&d&&i;if(x||vs({animationType:g,animationId:y,animationPath:s,lifecycle:h}),g==="update")return f&&d&&n===r&&p?u({instanceId:`${a}-animation-update`,targetId:i}):x&&u({instanceId:`${a}-animation-update`,targetId:i}),l;if(g==="transition"){let C=`${a}-animation-transition`,O=I?.continuity==="persistent"?C:`${a}-animation-in`;if(f&&d&&p)return u({instanceId:C,targetId:i}),l;f&&u({instanceId:`${a}-animation-out`,targetId:o}),d&&u({instanceId:O,targetId:i})}return l},Bs=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),Us=(e,{presentationState:t,previousPresentationState:n,currentLineActions:r,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:a,variables:c,runtime:l,activePersistentAnimations:u,restoredPersistentAnimations:f,autoMode:d,skipMode:p,isChoiceVisible:h,canRollback:y,saveSlots:I=[]})=>{let{elements:b,animations:g}=e;if(t.background){let x=r===void 0?!0:Is(r?.background??{},"animations"),C=b.find(P=>P.id==="story");if(!C)return e;let O=_s(o,t.background),L=n?.background?.resourceId,_=t.background.resourceId??(t.background.animations?L:void 0),D=vr(o,L),N=vr(o,_);if(_){let{images:P={},videos:E={}}=o,S=P[_]||E[_];if(S){let M=E[_]!==void 0,z={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...O},q={id:yt({resourceId:_,kind:M?"video":"sprite"}),type:M?"video":"sprite",x:z.x,y:z.y,src:S.fileId,width:S.width,height:S.height,alpha:1,anchorX:z.anchorX,anchorY:z.anchorY,rotation:z.rotation,scaleX:z.scaleX,scaleY:z.scaleY};M&&(q.loop=t.background.loop??!1,q.volume=S.volume??50),C.children.push(q)}}if(_){let{layouts:P={}}=o,E=P[_];if(E){let S={id:yt({resourceId:_,kind:"container"}),type:"container",children:E.elements};O&&Object.assign(S,{x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...O});let M=Z(S,ae({variables:c,runtime:l,saveSlots:I,dialogueState:t.dialogue,isLineCompleted:s,autoMode:d,skipMode:p,isChoiceVisible:h,canRollback:y,characters:o.characters||{},skipTransitionsAndAnimations:a}),{functions:xe});C.children.push(ve(Ce(M,{isLineCompleted:s,skipMode:p,skipTransitionsAndAnimations:a}),o))}}let k=Se({animationsDef:t.background.animations,resources:o,previousResourceId:L,currentResourceId:_,previousTargetId:yt({resourceId:L,kind:D}),currentTargetId:yt({resourceId:_,kind:N}),animationPath:"background.animations",idPrefix:"bg-cg",allowIncomingUpdateFallback:!0});ue({animationInstances:k,isLineCompleted:s,skipTransitionsAndAnimations:a,activePersistentAnimations:u,restoredPersistentAnimations:f,isAuthoredOnCurrentLine:x})&&g.push(...k)}return e},Fs=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:a,animations:c}=e;if(t.character&&r){let l=a.find(h=>h.id==="story");if(!l)return e;let u=t.character.items||[],f=n?.character?.items||[],d=xr(u),p=xr(f);for(let h=0;h<u.length;h++){let y=u[h],{transformId:I,sprites:b}=y,g=f.find(P=>P.id===y.id),x=f.findIndex(P=>P.id===y.id),C=g?.sprites&&g.sprites.length>0,O=b&&b.length>0,L=x>=0?gt(g,x,p):void 0,_=Se({animationsDef:y.animations,resources:r,previousResourceId:L,currentResourceId:O?gt(y,h,d):void 0,previousTargetId:L,currentTargetId:O?gt(y,h,d):void 0,animationPath:`character.items[${h}].animations`,idPrefix:"character"});if(y.animations&&!b&&!I&&C&&ue({animationInstances:_,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){c.push(..._);continue}if(y.animations&&!b&&!I)continue;if(!b||b.length===0||!I){console.warn("Character item missing sprites or transformId:",y);continue}let D=gt(y,h,d),N=r.transforms[I];if(!N){console.warn("Transform not found:",I);continue}let k={type:"container",id:D,x:y.x??N.x,y:y.y??N.y,anchorX:N.anchorX,anchorY:N.anchorY,rotation:N.rotation,scaleX:N.scaleX,scaleY:N.scaleY,children:[]};for(let P of b){let E=r.images[P.resourceId];if(!E){console.warn(`Image resource not found: ${P.resourceId}`);continue}k.children.push({type:"sprite",id:`${D}-${P.id}`,src:E.fileId,width:E.width,height:E.height,x:0,y:0})}l.children.push(k),ue({animationInstances:_,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(..._)}}return e},zs=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,runtime:a,activePersistentAnimations:c,autoMode:l,skipMode:u,isChoiceVisible:f,canRollback:d,saveSlots:p=[]})=>{let{elements:h,animations:y}=e;if(t.visual&&r){let I=h.find(g=>g.id==="story");if(!I)return e;let b=t.visual.items;for(let g of b){if(g.resourceId){let{images:L={},videos:_={},spritesheets:D={}}=r,N=D[g.resourceId];if(N){let k=an(r,g),P=g.animationName;if(P){let E=N.animations?.[P];if(!E)throw new Error(`Animation '${P}' not found in spritesheet resource '${g.resourceId}'`);let S={id:`visual-${g.id}`,type:"animated-sprite",x:g.x??k.x,y:g.y??k.y,width:g.width??N.width,height:g.height??N.height,alpha:g.alpha??1,anchorX:k.anchorX,anchorY:k.anchorY,rotation:k.rotation,scaleX:k.scaleX,scaleY:k.scaleY,spritesheetSrc:N.fileId,spritesheetData:N.jsonData,animation:{frames:E.frames,animationSpeed:g.animationSpeed??E.animationSpeed??.5,loop:g.loop??E.loop??!0}};I.children.push(structuredClone(S))}}else{let k=L[g.resourceId]||_[g.resourceId];if(k){let P=_[g.resourceId]!==void 0,E=an(r,g),S={id:`visual-${g.id}`,type:P?"video":"sprite",src:k.fileId,width:k.width,height:k.height,x:E.x,y:E.y,anchorX:E.anchorX,anchorY:E.anchorY,rotation:E.rotation,scaleX:E.scaleX,scaleY:E.scaleY};P&&(S.loop=k.loop??!1,S.volume=k.volume??50),I.children.push(S)}}}if(g.resourceId){let{layouts:L={}}=r,_=L[g.resourceId];if(_){let D=an(r,g),N={id:`visual-${g.id}`,type:"container",children:structuredClone(_.elements),x:D.x,y:D.y,anchorX:D.anchorX,anchorY:D.anchorY,rotation:D.rotation,scaleX:D.scaleX,scaleY:D.scaleY},k=Z(N,ae({variables:s,runtime:a,saveSlots:p,dialogueState:t.dialogue,isLineCompleted:o,autoMode:l,skipMode:u,isChoiceVisible:f,canRollback:d,characters:r.characters||{},skipTransitionsAndAnimations:i}),{functions:xe});I.children.push(ve(Ce(k,{isLineCompleted:o,skipMode:u,skipTransitionsAndAnimations:i}),r))}}let C=(n?.visual?.items||[]).find(L=>L.id===g.id),O=Se({animationsDef:g.animations,resources:r,previousResourceId:C?.resourceId,currentResourceId:g.resourceId,previousTargetId:C?.resourceId?`visual-${g.id}`:void 0,currentTargetId:g.resourceId?`visual-${g.id}`:void 0,animationPath:`visual.items[${g.id}].animations`,idPrefix:g.id});ue({animationInstances:O,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:c})&&y.push(...O)}}return e},De="dialogue-character-sprite",Lr=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,Ws=(e,{presentationState:t,previousPresentationState:n,resources:r={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:a}=e,c=Ke(e.elements);if(!c)return e;let l=t.dialogue?.character?.sprite,u=n?.dialogue?.character?.sprite,f=Lr(l),d=Lr(u),p=Se({animationsDef:l?.animations,resources:r,previousResourceId:d?De:void 0,currentResourceId:f?De:void 0,previousTargetId:d?De:void 0,currentTargetId:f?De:void 0,animationPath:"dialogue.character.sprite.animations",idPrefix:"dialogue-character-sprite"});if(!f)return l?.animations&&d&&ue({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...p),e;let h=r.transforms?.[l.transformId];if(!h)return console.warn("Transform not found:",l.transformId),e;let y={type:"container",id:De,x:h.x,y:h.y,anchorX:h.anchorX,anchorY:h.anchorY,rotation:h.rotation,scaleX:h.scaleX,scaleY:h.scaleY,children:[]};for(let I of l.items){let b=r.images?.[I.resourceId];if(!b){console.warn(`Image resource not found: ${I.resourceId}`);continue}y.children.push({type:"sprite",id:`${De}-${I.id}`,src:b.fileId,width:b.width,height:b.height,x:0,y:0})}return c.children.push(y),ue({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...p),e},qs=(e,{presentationState:t,previousPresentationState:n,resources:r={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:c,skipOnlyViewedLines:l,isLineCompleted:u,skipTransitionsAndAnimations:f,variables:d,runtime:p,activePersistentAnimations:h,saveSlots:y=[]})=>{let{elements:I,animations:b}=e;if(!t.dialogue||o)return e;let g=I.find(C=>C.id==="story");if(!g)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:C={}}=r,O=C[t.dialogue.ui.resourceId];if(O){let L={elements:O.elements},_=ae({variables:d,runtime:p,saveSlots:y,dialogueState:t.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:u,autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:c,characters:r.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:l,skipTransitionsAndAnimations:f}),D={functions:xe},N=bt(L,_,D),k=Z(N,_,D),P=ve(Ce(k?.elements,{isLineCompleted:u,skipMode:s,skipTransitionsAndAnimations:f}),r);if(Array.isArray(P))for(let E of P)g.children.push(E);else P&&g.children.push(P)}}Ws(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:u,skipTransitionsAndAnimations:f,activePersistentAnimations:h});let x=Se({animationsDef:t.dialogue.ui?.animations,resources:r,previousResourceId:n?.dialogue?.ui?.resourceId,currentResourceId:t.dialogue.ui?.resourceId,previousTargetId:n?.dialogue?.ui?.resourceId?"dialogue-container":void 0,currentTargetId:t.dialogue.ui?.resourceId?"dialogue-container":void 0,animationPath:"dialogue.ui.animations",idPrefix:"dialogue-ui"});return ue({animationInstances:x,isLineCompleted:u,skipTransitionsAndAnimations:f,activePersistentAnimations:h})&&b.push(...x),e},Ys=(e,{presentationState:t,previousPresentationState:n,resources:r,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:a,runtime:c,autoMode:l,skipMode:u,isChoiceVisible:f,canRollback:d,activePersistentAnimations:p,saveSlots:h=[]})=>{let{elements:y,animations:I}=e;if(t.choice&&r){let b=Ke(y);if(!b)return e;let g=r?.layouts[t.choice.resourceId];if(g&&g.elements){let C={elements:g.elements},O=Z(C,{...ae({variables:a,runtime:c,saveSlots:h,dialogueState:t.dialogue,isLineCompleted:i,autoMode:l,skipMode:u,isChoiceVisible:f??!!t.choice,canRollback:d,characters:r.characters||{},skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}},{functions:xe}),L=gn(ve(Ce(O?.elements,{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),r));if(Array.isArray(L))for(let _ of L)b.children.push(_);else L&&b.children.push(L)}let x=Se({animationsDef:t.choice.animations,resources:r,previousResourceId:n?.choice?.resourceId,currentResourceId:t.choice.resourceId,previousTargetId:n?.choice?.resourceId?"choice-container":void 0,currentTargetId:t.choice.resourceId?"choice-container":void 0,animationPath:"choice.animations",idPrefix:"choice"});ue({animationInstances:x,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:p})&&I.push(...x)}return e},Hs=(e,{presentationState:t,resources:n={},variables:r,runtime:o,isLineCompleted:i,autoMode:s,skipMode:a,isChoiceVisible:c,canRollback:l,saveSlots:u=[],skipTransitionsAndAnimations:f})=>{if(!t.control?.resourceId)return e;let d=n.controls?.[t.control.resourceId];if(!d)return e;let p=Ms(d.keyboard,d.keyup);if(p&&Object.keys(p).length>0&&(e.global.keyboard=p),!Array.isArray(d.elements)||d.elements.length===0)return e;let h=Ke(e.elements);if(!h)return e;let y={id:`control-${t.control.resourceId}`,type:"container",x:0,y:0,children:d.elements};return h.children.push(Fr({container:y,resources:n,templateData:ae({variables:r,runtime:o,saveSlots:u,dialogueState:t.dialogue,isLineCompleted:i,autoMode:s,skipMode:a,isChoiceVisible:c,canRollback:l,characters:n.characters||{},skipTransitionsAndAnimations:f}),isLineCompleted:i,skipMode:a,skipTransitionsAndAnimations:f})),e},Js=(e,{presentationState:t,resources:n,runtime:r,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&n){if(!Ke(i))return e;let c=n.sounds[t.bgm.resourceId];if(!c)return e;let l=ae({variables:o,runtime:r}).runtime;s.push({id:"bgm",type:"sound",src:c.fileId,loop:t.bgm.loop??!0,volume:Ts(l),startDelayMs:t.bgm.startDelayMs??null})}return e},Ks=(e,{presentationState:t,resources:n})=>{let{audio:r}=e;if(t.sfx&&n){let o=t.sfx.items;for(let i of o){let s=n.sounds?.[i.resourceId];s&&r.push({id:i.id,type:"sound",src:s.fileId,loop:i.loop??s.loop??!1,volume:i.volume??s.volume??50,startDelayMs:i.startDelayMs??s.startDelayMs??null})}}return e},Gs=(e,t,n)=>{if(!(!t||!n))return e?.voices?.[t]?.[n]},Xs=(e={},t={})=>t.muteAll?0:e.volume??t.soundVolume??50,Qs=(e,{presentationState:t,resources:n,currentSceneId:r,runtime:o,variables:i})=>{let{audio:s}=e;if(!t?.voice)return e;let a=t.voice,{resourceId:c,loop:l,startDelayMs:u}=a,f=Gs(n,r,c);if(!f)return e;let d=ae({variables:i,runtime:o}).runtime;return s.push({id:`voice-${r}-${c}`,type:"sound",src:f.fileId,volume:Xs(a,d),loop:l??!1,startDelayMs:u??null}),e},Zs=(e,{presentationState:t,previousPresentationState:n,resources:r={},variables:o,runtime:i,autoMode:s,skipMode:a,isChoiceVisible:c,canRollback:l,saveSlots:u=[],isLineCompleted:f,skipTransitionsAndAnimations:d,activePersistentAnimations:p})=>{let{elements:h,animations:y}=e;if(t.layout){let x=Ke(h);if(!x)return e;let C=r.layouts[t.layout.resourceId];if(!C)return e;Array.isArray(C.transitions)&&!f&&!d&&In({animations:y,transitions:C.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let O={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:C.elements||[]};x.children.push(Fr({container:O,resources:r,templateData:ae({variables:o,runtime:i,saveSlots:u,dialogueState:t.dialogue,isLineCompleted:f,autoMode:s,skipMode:a,isChoiceVisible:c,canRollback:l,characters:r.characters||{},skipTransitionsAndAnimations:d}),isLineCompleted:f,skipMode:a,skipTransitionsAndAnimations:d}))}let I=n?.layout?.resourceId,b=t.layout?.resourceId,g=Se({animationsDef:t.layout?.animations,resources:r,previousResourceId:I,currentResourceId:b,previousTargetId:I?`layout-${I}`:void 0,currentTargetId:b?`layout-${b}`:void 0,animationPath:"layout.animations",idPrefix:"layout"});return ue({animationInstances:g,isLineCompleted:f,skipTransitionsAndAnimations:d,activePersistentAnimations:p})&&y.push(...g),e},ea=(e,{presentationState:t,resources:n={},variables:r,runtime:o,autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:c,overlayStack:l=[],dialogueHistory:u=[],saveSlots:f=[],screen:d,isLineCompleted:p,skipTransitionsAndAnimations:h})=>{let{elements:y,animations:I}=e;return l&&l.length>0&&l.forEach((b,g)=>{let x=n.layouts[b.resourceId];if(!x){console.warn(`Overlay layout not found: ${b.resourceId}`);return}Array.isArray(x.transitions)&&(h||In({animations:I,transitions:x.transitions,defaultTargetId:`overlayStack-${g}`,idPrefix:`overlayStack-${g}`,animationPathPrefix:`overlayStack[${g}]`}));let C={id:`overlayStack-${g}`,type:"container",x:0,y:0,children:[Br({id:`overlayStack-${g}-blocker`,screen:d}),...x.elements||[]]},O=Ur(u,n.characters),L=ae({variables:r,runtime:o,saveSlots:f,dialogueState:t?.dialogue,isLineCompleted:p,autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:c,historyDialogue:O,characters:n.characters||{},skipTransitionsAndAnimations:h}),_=Z(C,L,{functions:xe}),[D,...N]=_.children||[],k=ve(Ce({..._,children:N},{isLineCompleted:p,skipMode:s,skipTransitionsAndAnimations:h}),n);y.push({...k,children:D?[D,...k.children||[]]:k.children})}),e},ta=(e,{presentationState:t,resources:n={},variables:r,runtime:o,saveSlots:i=[],autoMode:s,skipMode:a,isChoiceVisible:c,canRollback:l,confirmDialog:u,dialogueHistory:f=[],screen:d,isLineCompleted:p,skipTransitionsAndAnimations:h})=>{let{elements:y,animations:I}=e;if(!u?.resourceId)return e;let b=n.layouts?.[u.resourceId];if(!b)return console.warn(`ConfirmDialog layout not found: ${u.resourceId}`),e;Array.isArray(b.transitions)&&!h&&In({animations:I,transitions:b.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let g={id:"confirmDialog",type:"container",x:0,y:0,children:[Br({id:"confirmDialog-blocker",screen:d}),...b.elements||[]]},x=Ur(f,n.characters),C=Z(g,ae({variables:r,runtime:o,saveSlots:i,dialogueState:t?.dialogue,isLineCompleted:p,autoMode:s,skipMode:a,isChoiceVisible:c,canRollback:l,confirmDialog:u,historyDialogue:x,characters:n.characters||{},skipTransitionsAndAnimations:h}),{functions:xe}),[O,...L]=C.children||[],_=ve(Ce({...C,children:L},{isLineCompleted:p,skipMode:a,skipTransitionsAndAnimations:h}),n);return y.push({..._,children:O?[O,..._.children||[]]:_.children}),e},zr=e=>pt(Bs,[Hs,Us,Fs,zs,qs,Ys,Zs,Js,Ks,Qs,ea,ta])(e);var na=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"}}),At=Object.freeze({dialogueTextSpeed:50,autoForwardDelay:1e3,skipUnseenText:!1,skipTransitionsAndAnimations:!1,soundVolume:50,musicVolume:50,muteAll:!1,autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isLineCompleted:!1}),Ge=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),Wr=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"}),An=Object.freeze(["dialogueTextSpeed","autoForwardDelay","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),En=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),ra=(e,t)=>{if(t.startsWith("global.")){let n=t.slice(7);return e?.global?.[n]}if(t.startsWith("context.runtime.")){let n=t.slice(16),r=Array.isArray(e?.contexts)?e.contexts:[];return r[r.length-1]?.runtime?.[n]}},je=e=>Object.fromEntries(Object.entries(na).map(([t,n])=>{let r=ra(e,n.source),o=r!==void 0?r:At[t]??Ge[t];return[t,o]})),fe=(e,t)=>je(e)[t],qr=(e={})=>Object.fromEntries(An.map(t=>[t,e[t]??At[t]]));var Et={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},Gr=1,vt=()=>({manual:{...Et.manual},auto:{...Et.auto},applyMode:Et.applyMode}),xn=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let n=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...vt()},n&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},F=e=>{let t=ie(e)?ze(e):e;return structuredClone(t)},j=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Ct=e=>String(e),Xr=()=>({sections:[],resources:[]}),oa=e=>j(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):Xr(),ia=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",sa=({sectionId:e,lineId:t,content:n,dialogueState:r,characterName:o})=>({sectionId:e,lineId:t,content:n,text:ia(n),characterId:r.characterId,character:{...r.character||{},name:o},characterName:o}),aa=()=>({resourceId:void 0}),ca=e=>{if(!j(e))return e;let t={...e};return Object.prototype.hasOwnProperty.call(t,"requireComplete")&&!Object.prototype.hasOwnProperty.call(t,"requireLineCompleted")&&(t.requireLineCompleted=t.requireComplete),delete t.requireComplete,t},vn=(e,t)=>{let n=e?.story?.scenes??{};for(let[r,o]of Object.entries(n))if(o?.sections?.[t])return{sceneId:r,section:o.sections[t]};return{sceneId:void 0,section:void 0}},Qr=e=>{let t=e?.story?.scenes??{},n=new Map;for(let[r,o]of Object.entries(t)){let i=o?.sections??{};for(let s of Object.keys(i)){let a=n.get(s);if(a!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${a}" and "${r}". Section IDs must be globally unique.`);n.set(s,r)}}},Zr=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},eo=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==Gr)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},la=(e,t={})=>{let n;try{n=eo(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let r={...t,formatVersion:n,slotId:Zr(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete r.slotKey,delete r.date,r},ua=(e={})=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,la(t,n)])),to=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:n})=>Bc(n));return t.length>0?t:void 0},fa=e=>{!j(e)||!Array.isArray(e.timeline)||e.timeline.forEach(t=>{if(!j(t))return;let n=to(t.executedActions);if(n){t.executedActions=n;return}delete t.executedActions})},Yr=(e,t,n,r="viewedRegistry")=>{let o=t==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[o]:String(e)};if(!j(e))throw new Error(`Malformed ${r}.${t}[${n}] entry.`);if(typeof e[o]!="string"||e[o].length===0)throw new Error(`Malformed ${r}.${t}[${n}] entry: missing ${o}.`);if(t==="sections"){let i={sectionId:e.sectionId};if(e.lastLineId!==void 0&&e.lastLineId!==null&&typeof e.lastLineId!="string")throw new Error(`Malformed ${r}.sections[${n}] entry: invalid lastLineId.`);return typeof e.lastLineId=="string"&&e.lastLineId.length>0&&(i.lastLineId=e.lastLineId),i}return{resourceId:e.resourceId}},da=(e,t="viewedRegistry")=>{if(e===void 0)return Xr();if(!j(e))throw new Error(`Malformed ${t}.`);if(e.sections!==void 0&&!Array.isArray(e.sections))throw new Error(`Malformed ${t}.sections.`);if(e.resources!==void 0&&!Array.isArray(e.resources))throw new Error(`Malformed ${t}.resources.`);let n=e.sections??[],r=e.resources??[];return{sections:Object.values(Object.fromEntries(n.map((o,i)=>{let s=Yr(o,"sections",i,t);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(r.map((o,i)=>{let s=Yr(o,"resources",i,t);return[s.resourceId,s]})))}},no=(e,t,n)=>{if(!j(e))throw new Error(`Malformed save slot ${n}.`);let{sectionId:r,lineId:o}=e;if(typeof r!="string"||r.length===0)throw new Error(`Malformed save slot ${n}: missing sectionId.`);if(typeof o!="string"||o.length===0)throw new Error(`Malformed save slot ${n}: missing lineId.`);let{sceneId:i,section:s}=vn(t,r);if(!s)throw new Error(`Malformed save slot ${n}: section "${r}" does not exist in projectData.`);if(!s.lines?.some(c=>c.id===o))throw new Error(`Malformed save slot ${n}: line "${o}" does not exist in section "${r}".`);return{sceneId:i,sectionId:r,lineId:o}},pa=(e,t,n)=>{if(!j(e)||!Array.isArray(e.timeline))return Xe({pointer:t,replayStartIndex:1});let r=e.timeline.flatMap((a,c)=>{if(!j(a))return[];try{let l=no(a,n,`rollback.timeline[${c}]`),u=xt({sectionId:l.sectionId,lineId:l.lineId,rollbackPolicy:a.rollbackPolicy}),f=to(F(a.executedActions));return f&&(u.executedActions=f),[u]}catch{return[]}});if(r.length===0)return Xe({pointer:t,replayStartIndex:1});let o=typeof e.currentIndex=="number"?Math.trunc(e.currentIndex):r.length-1;(o<0||o>=r.length)&&(o=r.length-1);let i=r[o];if(i?.sectionId!==t.sectionId||i?.lineId!==t.lineId){let a=r.findLastIndex(c=>c.sectionId===t.sectionId&&c.lineId===t.lineId);a>=0?o=a:(r.push(xt({sectionId:t.sectionId,lineId:t.lineId})),o=r.length-1)}let s=typeof e.replayStartIndex=="number"?Math.min(Math.max(Math.trunc(e.replayStartIndex),0),o):0;return{currentIndex:o,isRestoring:!1,replayStartIndex:s,timeline:r}},ha=(e,t,n)=>{if(!j(e))throw new Error(`Malformed save slot contexts[${n}] entry.`);let r=Sn(t),o=no(e.pointers?.read,t,`contexts[${n}].pointers.read`);if(e.variables!==void 0&&!j(e.variables))throw new Error(`Malformed save slot contexts[${n}].variables entry.`);if(e.runtime!==void 0&&!j(e.runtime))throw new Error(`Malformed save slot contexts[${n}].runtime entry.`);let i=e.variables?Pe(F(e.variables),t.resources?.variables??{}):{},s=Ia({loadedContextRuntime:j(e.runtime)?F(e.runtime):{}}),a={currentPointerMode:"read",pointers:{read:o},configuration:j(e.configuration)?F(e.configuration):{},views:Array.isArray(e.views)?F(e.views):[],bgm:j(e.bgm)?F(e.bgm):{resourceId:void 0},variables:{...r,...i},rollback:pa(e.rollback,o,t)};return s&&(a.runtime=s),a},ma=(e,t)=>{if(!j(e))throw new Error("Malformed save slot state.");if(!Array.isArray(e.contexts)||e.contexts.length===0)throw new Error("Malformed save slot state: contexts must be a non-empty array.");return{contexts:e.contexts.map((n,r)=>ha(n,t,r))}},ga=(e,t)=>{if(!j(e))throw new Error("Malformed save slot.");let n=eo(e.formatVersion);return{...e,formatVersion:n,state:ma(e.state,t)}},Hr=(e,t,{required:n=!1}={})=>{if(e===void 0){if(n)throw new Error(`showConfirmDialog requires ${t}`);return{hideConfirmDialog:{}}}if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`showConfirmDialog ${t} must be an action object`);let r=F(e);return Object.prototype.hasOwnProperty.call(r,"hideConfirmDialog")||(r.hideConfirmDialog={}),r},ya=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:Hr(e.confirmActions,"confirmActions",{required:!0}),cancelActions:Hr(e.cancelActions,"cancelActions")}},Me=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},_e=[],Jr="line",Cn="interaction",xt=({sectionId:e,lineId:t,rollbackPolicy:n})=>({sectionId:e,lineId:t,rollbackPolicy:n??"free"}),Sn=e=>{let{contextVariableDefaultValues:t}=Qt(e??{});return F(t)},ro=()=>({...F(Ge)}),oo=({loadedRuntime:e,runtimeIds:t,defaults:n={},path:r})=>{if(e===void 0)return{runtimeState:F(n),hasLoadedValues:!1};if(!j(e))throw new Error(`Malformed ${r}.`);let o=F(n),i=!1;return t.forEach(s=>{e[s]!==void 0&&(o[s]=io(s,F(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},ba=({loadedGlobalRuntime:e={}})=>oo({loadedRuntime:e,runtimeIds:An,defaults:At,path:"global.runtime"}).runtimeState,Ia=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:n}=oo({loadedRuntime:e,runtimeIds:En,defaults:ro(),path:"context.runtime"});return n?t:void 0},_n=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},wa=e=>e.runtime?(En.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=F(Ge[t]))}),e.runtime):(e.runtime=ro(),e.runtime),Aa=e=>qr(e.global),Ea=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:Aa(e)}})},xa=e=>Wr[e],va=(e,t)=>{let n=xa(e);if(n==="number"){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} requires a finite numeric value`);return}if(n==="boolean"){if(typeof t!="boolean")throw new Error(`${e} requires a boolean value`);return}if(n==="string"){if(typeof t!="string")throw new Error(`${e} requires a string value`);return}throw new Error(`Unsupported runtime field "${e}"`)},io=(e,t)=>(va(e,t),e==="saveLoadPagination"?Math.max(1,Math.trunc(t)):t),so=(e,t,n)=>{let r=io(t,n);if(t in Ge){let o=_n(e);if(!o)return r;let i=wa(o);return i[t]=r,r}return e.global[t]=r,r},ao=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:F(e)},configuration:{},views:[],bgm:aa(),variables:Sn(t),rollback:Xe({pointer:e})}),Be=e=>e?(e.currentPointerMode="read",j(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,Ca=e=>{let t=e.contexts?.[e.contexts.length-1],n=t?.pointers?.read;if(!t||!n?.sectionId||!n?.lineId)return null;let r=ao({pointer:n,projectData:e.projectData});return e.contexts[e.contexts.length-1]=r,Sa(e),r},Sa=e=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,Me(e),e.global.nextLineConfig=vt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})},co=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},Xe=({pointer:e,replayStartIndex:t=0})=>{let n=e?.sectionId&&e?.lineId;return{currentIndex:n?0:-1,isRestoring:!1,replayStartIndex:t,timeline:n?[xt({sectionId:e.sectionId,lineId:e.lineId})]:[]}},Re=(e,t={})=>{if(e?.rollback)return co(e.rollback),Array.isArray(e.rollback.timeline)||(e.rollback.timeline=[]),typeof e.rollback.currentIndex!="number"&&(e.rollback.currentIndex=e.rollback.timeline.length>0?e.rollback.timeline.length-1:-1),typeof e.rollback.isRestoring!="boolean"&&(e.rollback.isRestoring=!1),typeof e.rollback.replayStartIndex!="number"&&(e.rollback.replayStartIndex=0),e.rollback;let n=e?.pointers?.read;return e.rollback=Xe({pointer:n,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},$n=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return;let r=Re(n);if(r.isRestoring)return;r.currentIndex<r.timeline.length-1&&(r.timeline=r.timeline.slice(0,r.currentIndex+1));let o=r.timeline[r.timeline.length-1];if(o?.sectionId===t.sectionId&&o?.lineId===t.lineId&&(o?.rollbackPolicy??"free")===(t.rollbackPolicy??"free")){r.currentIndex=r.timeline.length-1;return}r.timeline.push(xt(t)),r.currentIndex=r.timeline.length-1},_a=e=>{let n=e.contexts?.[e.contexts.length-1]?.rollback;if(!n||n.isRestoring||!Array.isArray(n.timeline)||typeof n.currentIndex!="number")return null;let r=_e[_e.length-1],o=typeof r?.checkpointIndex=="number"?r.checkpointIndex:n.currentIndex;return o<0||o>=n.timeline.length?null:(typeof r?.checkpointIndex!="number"&&o<n.timeline.length-1&&(n.timeline=n.timeline.slice(0,o+1)),n.timeline[o]??null)},$a=({state:e},t={})=>{let n=t?.source===Jr?Jr:Cn,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?(_e.push({checkpointIndex:null,source:n}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),_e.push({checkpointIndex:o.currentIndex,source:n}),e)},Ra=({state:e})=>(_e.pop(),e),de=(e,t,n)=>{let o=_e[_e.length-1]?.source??Cn;if(!Uc(t,o))return;let i=_a(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:F(n)}))},Kr=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return;let r=t?.operations??[];for(let{variableId:o,op:i,value:s}of r){let a=e.projectData.resources?.variables?.[o],c=a?.scope,l=a?.type;if(Ee(a))throw new Error(`Cannot update computed variable: ${o}`);if(a?.readonly===!0)throw new Error(`Cannot update readonly variable: ${o}`);Zt(c,o),en(l,i,o),c==="context"&&(n.variables[o]=tn(n.variables[o],i,s))}},Oa=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:n,payload:r})=>{Fc(e,n,r)})},La=(e,t)=>{let{sectionId:n,lineId:r}=t,s=G({state:e},{sectionId:n})?.lines?.find(a=>a.id===r)?.actions;s&&Object.entries(s).forEach(([a,c])=>{_o(e,a,c)})},lo=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return e;let r=Re(n),o=r.timeline[t];if(!o)return e;e.global.autoMode&&Ze({state:e}),e.global.skipMode&&$e({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),r.isRestoring=!0,r.currentIndex=t;try{n.variables=Sn(e.projectData),delete n.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=F(Et),e.global.overlayStack=[],Me(e),e.global.isLineCompleted=!0;let i=r.replayStartIndex??0;for(let a=i;a<=t;a++)a>i&&xn(e),La(e,r.timeline[a]),Oa(e,r.timeline[a]);let s=Be(n);s.read={sectionId:o.sectionId,lineId:o.lineId},e.global.pendingEffects=e.global.pendingEffects.filter(a=>a?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{r.isRestoring=!1}return e},ka=e=>{let{projectData:t}=e,n=e.global??{},{saveSlots:r={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=n;Qr(t);let a=t.story.initialSceneId,c=t.story.scenes[a],l=c.initialSectionId,u=c.sections[l],f={sceneId:a,sectionId:l,lineId:u.initialLineId??u.lines[0].id},{globalVariablesDefaultValues:d}=Qt(t),p={...d,...Pe(o,t.resources?.variables??{})};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,accountViewedRegistry:da(s,"accountViewedRegistry"),nextLineConfig:vt(),saveSlots:ua(r),overlayStack:[],variables:p,...ba({loadedGlobalRuntime:i})},contexts:[ao({pointer:f,projectData:t})]}},Pa=({state:e})=>e.global.overlayStack||[],Ta=({state:e})=>e.global.pendingEffects,uo=({state:e})=>e.global.skipMode,Na=({state:e})=>e.global.autoMode,fo=({state:e})=>e.global.dialogueUIHidden,po=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],n=t[t.length-1];if(!n)return[];let{sectionId:r,lineId:o}=n.pointers.read,i=G({state:e},{sectionId:r});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(u=>u.id===o),a=i.lines.slice(0,s+1),c=[],l={};for(let u of a){let f=u.actions||{};if(l=Ne([l,f]),!f.dialogue)continue;let d=l.dialogue||{},p="";d.character?.name!==void 0?p=d.character.name:d.characterId&&(p=e.projectData.resources?.characters?.[d.characterId]?.name||"");let h=sa({sectionId:r,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},Da=({state:e})=>e.global.confirmDialog??null,Va=({state:e,registry:t},n)=>{let{sectionId:r,lineId:o}=n,s=(Array.isArray(t?.sections)?t.sections:[]).find(u=>u.sectionId===r);if(!s)return!1;if(s.lastLineId===void 0||o===void 0)return!0;let a=G({state:e},{sectionId:r});if(!a||!a.lines||!Array.isArray(a.lines))return s.lastLineId===o;let c=a.lines.findIndex(u=>u.id===s.lastLineId),l=a.lines.findIndex(u=>u.id===o);return c===-1||l===-1?s.lastLineId===o:l<=c},ja=({registry:e},t)=>{let{resourceId:n}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===n)},Rn=({state:e},t)=>Va({state:e,registry:e.global.accountViewedRegistry},t),Ma=({state:e},t)=>ja({registry:e.global.accountViewedRegistry},t),Ba=({state:e})=>e.global.nextLineConfig,ho=({state:e,pointer:t}={})=>{let n=t??ce({state:e})?.pointer;if(!n)return;let r=n?.sectionId,o=n?.lineId,s=G({state:e},{sectionId:r})?.lines||[],a=s.findIndex(l=>l.id===o);if(a<0)return;let c;for(let l of s.slice(0,a+1)){let u=l?.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},le=({state:e})=>!!ho({state:e}),Ua=({state:e})=>structuredClone(e),mo=({state:e})=>e.global.saveSlots,Fa=({state:e},t)=>{let n=t?.slotId,r=Ct(n);return e.global.saveSlots[r]},On=({state:e})=>je(e),za=({state:e},t)=>fe(e,t?.runtimeId),go=({state:e})=>{let t={...e.global?.variables??{},..._n(e)?.variables??{}};return ht({variables:t,runtime:je(e),variableConfigs:e.projectData.resources?.variables??{}})},ce=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],n=t[t.length-1];if(n)return{currentPointerMode:"read",pointer:n.pointers?.read}},G=({state:e},t)=>{let{sectionId:n}=t;return vn(e.projectData,n).section},Ln=({state:e})=>{let t=ce({state:e});if(!t?.pointer)return;let{sectionId:n,lineId:r}=t.pointer,o=G({state:e},{sectionId:n});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===r)},yo=({state:e})=>{let{sectionId:t,lineId:n}=ce({state:e}).pointer,o=G({state:e},{sectionId:t})?.lines||[],i=o.findIndex(l=>l.id===n),a=o.slice(0,i+1).map(l=>{let u=l.actions||{},f={};return Object.keys(u).forEach(d=>{f[d]=u[d]}),f});return Ne(a)},Wa=({state:e})=>{let t=bo({state:e}),r=Ln({state:e})?.actions??{},o=Ne([t??{},r]);return nn(t??{},o??{})},qa=({state:e},{sectionId:t})=>{let n=G({state:e},{sectionId:t});if(!n?.lines)return[];let r=[],o={};for(let i of n.lines){let s=i.actions||{},a=Ne([o,s]),c=nn(o,a);r.push({id:i.id,changes:c,presentationState:a}),o=rn(a)}return r},Ya=({state:e},{sectionId:t,includePresentationState:n=!1})=>{let r=qa({state:e},{sectionId:t});return n?{lines:r}:{lines:r.map(({presentationState:o,...i})=>i)}},bo=({state:e})=>{let{sectionId:t,lineId:n}=ce({state:e}).pointer,o=G({state:e},{sectionId:t})?.lines||[],i=o.findIndex(c=>c.id===n);if(i<=0)return null;let a=o.slice(0,i).map(c=>{let l=c.actions||{},u={};return Object.keys(l).forEach(f=>{u[f]=l[f]}),u});return rn(Ne(a))},kn=({state:e},{slotsPerPage:t=6}={})=>{let o=((On({state:e}).saveLoadPagination??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let a=o+s,c=e.global.saveSlots&&e.global.saveSlots[Ct(a)]||{};i.push({...c,slotId:a})}return{saveSlots:i}},Ha=mo,Ja=kn,Ka=e=>{let n=e.contexts?.[e.contexts.length-1]?.rollback;return!n||!Array.isArray(n.timeline)||typeof n.currentIndex!="number"?!1:n.currentIndex>=0&&n.currentIndex<n.timeline.length-1},Ga=({state:e},t={})=>{let n=yo({state:e}),r=bo({state:e}),o=Ln({state:e})?.actions??{},{sectionId:i}=ce({state:e}).pointer,{sceneId:s}=vn(e.projectData,i),a=On({state:e}),c=t?.activePersistentAnimations??[],l=t?.restoredPersistentAnimations??[],u=go({state:e}),{saveSlots:f}=kn({state:e}),d=Ka(e);return zr({presentationState:n,previousPresentationState:r,currentLineActions:o,resources:e.projectData.resources,currentSceneId:s,screen:e.projectData.screen,dialogueUIHidden:a.dialogueUIHidden,autoMode:a.autoMode,skipMode:a.skipMode,isChoiceVisible:le({state:e}),canRollback:Ro({state:e}),skipOnlyViewedLines:!a.skipUnseenText,isLineCompleted:a.isLineCompleted,skipTransitionsAndAnimations:!!a.skipTransitionsAndAnimations||d,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,dialogueHistory:po({state:e}),saveSlots:f,variables:u,runtime:a,activePersistentAnimations:c,restoredPersistentAnimations:l})},Xa=({state:e},t)=>(e.global.confirmDialog=ya(t),e.global.pendingEffects.push({name:"render"}),e),Qa=({state:e})=>(e.global.confirmDialog&&(Me(e),e.global.pendingEffects.push({name:"render"})),e),Za=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),de(e,"pushOverlay",t),e),ec=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),de(e,"popOverlay",void 0),e),tc=({state:e},t)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=t),e.global.pendingEffects.push({name:"render"}),de(e,"replaceLastOverlay",t),e),nc=({state:e})=>(e.global.overlayStack=[],Me(e),e.global.pendingEffects.push({name:"render"}),de(e,"clearOverlays",void 0),e),rc=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"})},St=(e,t)=>{e.global.isLineCompleted=!1;let n=!!ho({state:e,pointer:t});return n&&rc(e),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:n}},Io=({state:e})=>(le({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:fe(e,"autoForwardDelay")}}),e.global.pendingEffects.push({name:"render"})),e),Ze=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),oc=({state:e})=>{let t=e.global.autoMode;return le({state:e})&&!t||(t?Ze({state:e}):Io({state:e})),e},wo=({state:e})=>(le({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),$e=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),ic=({state:e})=>{let t=uo({state:e});return le({state:e})&&!t||(t?$e({state:e}):wo({state:e})),e},_t=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),de(e,"showDialogueUI",void 0),e),Ao=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),de(e,"hideDialogueUI",void 0),e),sc=({state:e})=>(fo({state:e})?_t({state:e}):Ao({state:e}),e),Oe=(e,t,n)=>(so(e,t,n),Ea(e),e.global.pendingEffects.push({name:"render"}),e),et=(e,t,n,r)=>{let o=so(e,t,n);return e.global.pendingEffects.push({name:"render"}),de(e,r,{value:o}),e},ac=({state:e},t)=>Oe(e,"dialogueTextSpeed",t?.value),cc=({state:e},t)=>Oe(e,"autoForwardDelay",t?.value),lc=({state:e},t)=>Oe(e,"skipUnseenText",t?.value),uc=({state:e},t)=>Oe(e,"skipTransitionsAndAnimations",t?.value),fc=({state:e},t)=>Oe(e,"soundVolume",t?.value),dc=({state:e},t)=>Oe(e,"musicVolume",t?.value),pc=({state:e},t)=>Oe(e,"muteAll",t?.value),hc=({state:e},t)=>et(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),mc=({state:e})=>{let t=fe(e,"saveLoadPagination")+1;return et(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},gc=({state:e})=>{let t=fe(e,"saveLoadPagination")-1;return et(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},yc=({state:e},t)=>et(e,"menuPage",t?.value,"setMenuPage"),bc=({state:e},t)=>et(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),Ic=({state:e})=>(e.global.pendingEffects=[],e),wc=({state:e},t)=>(e.global.pendingEffects.push(t),e),Eo=(e,{sectionId:t,resetStoryState:n=!1})=>{let r=G({state:e},{sectionId:t});if(!r)return console.warn(`Section not found: ${t}`),e;let o=r.lines?.[0];if(!o)return console.warn(`Section ${t} has no lines`),e;if(n&&!Ca(e))return e;e.global.autoMode&&Ze({state:e}),e.global.skipMode&&$e({state:e});let i=e.contexts?.[e.contexts.length-1];if(i){let s=Be(i);i.rollback||Re(i,{compatibilityAnchor:!0}),s.read={sectionId:t,lineId:o.id},n?i.rollback=Xe({pointer:s.read}):$n(e,{sectionId:t,lineId:o.id})}return St(e,i?.pointers?.read),e},Ac=({state:e},t)=>Eo(e,{sectionId:t?.sectionId,resetStoryState:!0}),xo=e=>(e.global.accountViewedRegistry=oa(e.global.accountViewedRegistry),e.global.accountViewedRegistry),vo=(e,t)=>{!Array.isArray(t)||t.length===0||e.global.pendingEffects.push({name:"applyScopedDataUpdates",payload:{updates:t.map(n=>({scope:n.scope,path:n.path,op:n.op,value:F(n.value)}))}})},Co=(e,t)=>{vo(e,[{scope:"account",path:"viewedRegistry",op:"markViewed",value:{sections:(Array.isArray(t?.sections)?t.sections:[]).map(n=>({sectionId:n.sectionId,...n.lastLineId===void 0?{}:{lineId:n.lastLineId}})),resources:Array.isArray(t?.resources)?t.resources:[]}}])},Ec=(e,t,{sectionId:n,lineId:r})=>{if(!n||!r)return!1;let o=j(t)?t:{};Array.isArray(o.sections)||(o.sections=[]);let i=o.sections.find(s=>s.sectionId===n);if(i){if(i.lastLineId===void 0)return!1;let s=G({state:e},{sectionId:n});if(s?.lines){let a=s.lines.findIndex(l=>l.id===i.lastLineId),c=s.lines.findIndex(l=>l.id===r);if(a===-1||c>a)return i.lastLineId===r?!1:(i.lastLineId=r,!0)}else return i.lastLineId===r?!1:(i.lastLineId=r,!0);return!1}else return o.sections.push({sectionId:n,lastLineId:r}),!0},Qe=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;Ec(e,xo(e),t)&&Co(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},xc=({state:e},t)=>(Qe(e,t),e.global.pendingEffects.push({name:"render"}),e),vc=({state:e},t)=>{let{resourceId:n}=t;if(e.global.accountViewedRegistry!==void 0){let r=xo(e);r.resources.find(i=>i.resourceId===n)||(r.resources.push({resourceId:n}),Co(e,{sections:[],resources:[{resourceId:n}]}))}return e.global.pendingEffects.push({name:"render"}),e},So=({state:e},t)=>{let n=ca(t.manual),{auto:r,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,a=e.contexts?.[e.contexts.length-1]?.rollback?.isRestoring===!0;n&&r?(e.global.nextLineConfig={manual:n,auto:r},o!==void 0?e.global.nextLineConfig.applyMode=o:s!==void 0&&(e.global.nextLineConfig.applyMode=s)):(n&&(e.global.nextLineConfig.manual=n),r&&(e.global.nextLineConfig.auto=r),o!==void 0&&(e.global.nextLineConfig.applyMode=o));let c=e.global.nextLineConfig.auto?.enabled,l=le({state:e});return!a&&!l&&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}}):!a&&c===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),de(e,"setNextLineConfig",t),e},Cc=({state:e},t)=>{let n=t?.slotId;if(n==null||n==="")throw new Error("saveSlot requires slotId");let{thumbnailImage:r}=t,o=t?.savedAt,i=Ct(n),s=F(e.contexts);s?.forEach(l=>{Be(l),co(l.rollback),fa(l.rollback)});let a={contexts:s},c={formatVersion:Gr,slotId:Zr(n),savedAt:typeof o=="number"?o:Date.now(),image:r,state:a};return e.global.saveSlots[i]=c,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},Sc=({state:e},t)=>{let n=t?.slotId;if(n==null||n==="")throw new Error("loadSlot requires slotId");let r=Ct(n),o=e.global.saveSlots[r];if(o){let i=ga(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=vt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,Me(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},_c=({state:e},t)=>{let{projectData:n}=t;Qr(n),e.projectData=n;let r=n?.resources?.variables??{};return Object.prototype.hasOwnProperty.call(e.global??{},"variables")&&(e.global.variables=Pe(e.global.variables,r)),e.contexts?.forEach(o=>{Object.prototype.hasOwnProperty.call(o??{},"variables")&&(o.variables=Pe(o.variables,r))}),Me(e),e.global.pendingEffects.push({name:"render"}),e},$c=({state:e},t)=>{let{sectionId:n,lineId:r}=t;if(!r)return console.warn("jumpToLine requires lineId parameter"),e;let o=e.contexts[e.contexts.length-1];if(!o)return console.warn("No context available for jumpToLine"),e;let i=n||o.pointers.read?.sectionId;if(n&&!G({state:e},{sectionId:n}))return console.warn(`Section not found: ${n}`),e;let s=G({state:e},{sectionId:i});if(!s?.lines||!Array.isArray(s.lines))return console.warn(`Section ${i} has no lines`),e;if(!s.lines.find(l=>l.id===r))return console.warn(`Line not found: ${r} in section ${i}`),e;let c=Be(o);return c.read={sectionId:i,lineId:r},St(e,c.read),e},Rc=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return _t({state:e}),e;if(le({state:e})&&t?._interactionSource!=="choice")return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0;let l=ce({state:e})?.pointer,u=l?.sectionId,f=l?.lineId;u&&f&&Qe(e,{sectionId:u,lineId:f}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:fe(e,"autoForwardDelay")}});let d=e.global.nextLineConfig;return d?.auto?.enabled&&d.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:d.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e}let n=ce({state:e})?.pointer,r=n?.sectionId,o=G({state:e},{sectionId:r}),i=e.contexts[e.contexts.length-1],s=o?.lines||[],c=s.findIndex(l=>l.id===n?.lineId)+1;if(c<s.length){let l=s[c],u=!fe(e,"skipUnseenText");if(e.global.skipMode&&u&&!Rn({state:e},{sectionId:r,lineId:l.id}))return $e({state:e}),e;if(i&&!i.rollback&&Re(i,{compatibilityAnchor:!0}),i){let p=Be(i),h=p.read?.lineId;h&&r&&Qe(e,{sectionId:r,lineId:h}),p.read={sectionId:r,lineId:l.id}}$n(e,{sectionId:r,lineId:l.id}),xn(e);let{isChoiceVisible:f}=St(e,{sectionId:r,lineId:l.id}),d=e.global.nextLineConfig;d?.auto?.enabled&&!f&&d.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:d.auto.delay}})}else e.global.autoMode&&Ze({state:e}),e.global.skipMode&&$e({state:e});return e},Oc=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0;let t=le({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:fe(e,"autoForwardDelay")}});let n=ce({state:e})?.pointer,r=n?.sectionId,o=n?.lineId;r&&o&&Qe(e,{sectionId:r,lineId:o});let i=e.global.nextLineConfig;return i?.auto?.enabled&&!t&&i.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:i.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e},Lc=({state:e},t)=>Eo(e,{sectionId:t?.sectionId}),kc=({state:e})=>{if(e.global.dialogueUIHidden)return _t({state:e}),e;if(le({state:e}))return e;let t=ce({state:e})?.pointer,n=t?.sectionId,r=G({state:e},{sectionId:n}),o=e.contexts[e.contexts.length-1],i=r?.lines||[],a=i.findIndex(c=>c.id===t?.lineId)+1;if(a<i.length){let c=i[a],l=!fe(e,"skipUnseenText");if(e.global.skipMode&&l&&!Rn({state:e},{sectionId:n,lineId:c.id}))return $e({state:e}),e;if(o&&!o.rollback&&Re(o,{compatibilityAnchor:!0}),o){let f=Be(o),d=f.read?.lineId;d&&n&&Qe(e,{sectionId:n,lineId:d}),f.read={sectionId:n,lineId:c.id}}$n(e,{sectionId:n,lineId:c.id}),xn(e);let{isChoiceVisible:u}=St(e,{sectionId:n,lineId:c.id});e.global.nextLineConfig.auto?.enabled&&!u&&e.global.nextLineConfig.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}})}else e.global.nextLineConfig.auto?.enabled&&(e.global.nextLineConfig.auto.enabled=!1,e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}));return e},Pc=({state:e},t)=>{let{id:n,operations:r=[]}=t;if(!n)throw new Error("updateVariable requires an id field");if(typeof n!="string"||!/^[a-zA-Z0-9]+$/.test(n))throw new Error(`updateVariable id must be alphanumeric, got: "${n}"`);let o=e.contexts[e.contexts.length-1];if(o?.rollback?.isRestoring)return e;let i=!1,s=[],a=[];return r.forEach(({variableId:c,op:l,value:u})=>{let f=e.projectData.resources?.variables?.[c],d=f?.scope,p=f?.type;if(Ee(f))throw new Error(`Cannot update computed variable: ${c}`);if(f?.readonly===!0)throw new Error(`Cannot update readonly variable: ${c}`);Zt(d,c),en(p,l,c);let h=d==="context"?o.variables:e.global.variables;d==="context"&&(i=!0,a.push({variableId:c,op:l,value:u})),h[c]=tn(h[c],l,u),(d==="device"||d==="account")&&s.push({scope:d,path:`variables.${c}`,op:"set",value:F(h[c])})}),i&&de(e,"updateVariable",{id:n,operations:a}),vo(e,s),e.global.pendingEffects.push({name:"render"}),e},Tc=e=>(t,n)=>e({state:t},n),Nc=e=>({variables:ht({variables:{...e.global?.variables??{},..._n(e)?.variables??{}},runtime:je(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1}),runtime:je(e)}),Dc=e=>{if(!j(e))throw new Error("conditional action payload must be an object");if(!Array.isArray(e.branches))throw new Error("conditional action requires branches array");if(e.branches.length===0)throw new Error("conditional action requires at least one branch")},Vc=(e,t,n)=>{if(!j(e))throw new Error(`conditional branch at index ${t} must be an object`);if(!j(e.actions))throw new Error(`conditional branch at index ${t} requires actions object`);if(!Object.prototype.hasOwnProperty.call(e,"when")&&t!==n-1)throw new Error("conditional else branch must be the last branch")},jc=(e,t)=>{Dc(t);for(let n=0;n<t.branches.length;n+=1){let r=t.branches[n];if(Vc(r,n,t.branches.length),!(Object.prototype.hasOwnProperty.call(r,"when")&&!Ae(r.when,Nc(e)))){Object.entries(r.actions).forEach(([i,s])=>{_o(e,i,s)});return}}},Mc={conditional:{replayLine:jc},updateVariable:{recordSources:[Cn],replayLine:Kr,replayRecorded:Kr,persistInSaveSlot:!0},setNextLineConfig:{replayLine:Tc(So)}},$t=e=>Mc[e]??null,Bc=e=>$t(e)?.persistInSaveSlot===!0,Uc=(e,t)=>{let n=$t(e)?.recordSources;return Array.isArray(n)&&n.includes(t)},Fc=(e,t,n)=>{$t(t)?.replayRecorded?.(e,n)},_o=(e,t,n)=>{$t(t)?.replayLine?.(e,n)},$o=({state:e},t)=>{let{offset:n}=t;if(n===void 0||typeof n!="number")return console.warn("selectLineIdByOffset requires a numeric offset"),null;let r=e.contexts[e.contexts.length-1];if(!r)return null;let o=r.rollback;if(!Array.isArray(o?.timeline)||typeof o?.currentIndex!="number")return null;let i=o.currentIndex+n;if(i<0||i>=o.timeline.length)return null;let s=o.timeline[i];return{sectionId:s.sectionId,lineId:s.lineId}},Ro=({state:e})=>$o({state:e},{offset:-1})!==null,zc=({state:e},t)=>{let{offset:n=-1}=t;if(n>=0)throw new Error("rollbackByOffset requires a negative offset");let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let o=Re(r,{compatibilityAnchor:!r.rollback}),i=o.currentIndex+n;return i<0||i>=o.timeline.length?e:lo(e,i)},Wc=({state:e},t)=>{let{sectionId:n,lineId:r}=t,o=e.contexts[e.contexts.length-1];if(!o)throw new Error("No context available for rollbackToLine");let i=Re(o,{compatibilityAnchor:!o.rollback}),a=i.timeline.slice(0,i.currentIndex+1).findLastIndex(c=>c.sectionId===n&&c.lineId===r);if(a===-1)throw new Error(`Line ${r} not found in section ${n} rollback timeline`);return a===i.currentIndex?e:lo(e,a)},Oo=e=>{let t=ka(e);return hr(t,{selectPendingEffects:Ta,selectSkipMode:uo,selectAutoMode:Na,selectIsChoiceVisible:le,selectDialogueUIHidden:fo,selectDialogueHistory:po,selectConfirmDialog:Da,selectIsLineAccountViewed:Rn,selectIsResourceAccountViewed:Ma,selectNextLineConfig:Ba,selectSystemState:Ua,selectSaveSlotMap:mo,selectSaveSlots:Ha,selectSaveSlot:Fa,selectRuntime:On,selectRuntimeValue:za,selectAllVariables:go,selectCurrentPointer:ce,selectSection:G,selectCurrentLine:Ln,selectPresentationState:yo,selectPresentationChanges:Wa,selectSectionLineChanges:Ya,selectSaveSlotPage:kn,selectCurrentPageSlots:Ja,selectRenderState:Ga,selectOverlayStack:Pa,selectLineIdByOffset:$o,selectCanRollback:Ro,startAutoMode:Io,stopAutoMode:Ze,toggleAutoMode:oc,startSkipMode:wo,stopSkipMode:$e,toggleSkipMode:ic,showDialogueUI:_t,hideDialogueUI:Ao,toggleDialogueUI:sc,setDialogueTextSpeed:ac,setAutoForwardDelay:cc,setSkipUnseenText:lc,setSkipTransitionsAndAnimations:uc,setSoundVolume:fc,setMusicVolume:dc,setMuteAll:pc,setSaveLoadPagination:hc,incrementSaveLoadPagination:mc,decrementSaveLoadPagination:gc,setMenuPage:yc,setMenuEntryPoint:bc,showConfirmDialog:Xa,hideConfirmDialog:Qa,resetStoryAtSection:Ac,clearPendingEffects:Ic,appendPendingEffect:wc,beginRollbackActionBatch:$a,endRollbackActionBatch:Ra,addViewedLine:xc,addViewedResource:vc,setNextLineConfig:So,saveSlot:Cc,loadSlot:Sc,updateProjectData:_c,sectionTransition:Lc,jumpToLine:$c,nextLine:Rc,markLineCompleted:Oc,rollbackToLine:Wc,rollbackByOffset:zc,pushOverlay:Za,popOverlay:ec,replaceLastOverlay:tc,clearOverlays:nc,updateVariable:Pc,nextLineFromSystem:kc},{transformActionFirstArgument:r=>({state:r}),transformSelectorFirstArgument:r=>({state:r})})};var qc="route-engine",Yc="projectPersistence";var ko=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),H=e=>Object.prototype.toString.call(e)==="[object Object]",Lo="variables.",Hc=(e={})=>{let t=H(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(n=>typeof n=="string"||typeof n=="number"?{sectionId:String(n)}:!H(n)||typeof n.sectionId!="string"||n.sectionId.length===0?null:{sectionId:n.sectionId,...typeof n.lineId=="string"?{lineId:n.lineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(n=>typeof n=="string"||typeof n=="number"?{resourceId:String(n)}:!H(n)||typeof n.resourceId!="string"||n.resourceId.length===0?null:{resourceId:n.resourceId}).filter(Boolean)}},Jc=(e={})=>{let t=H(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(n=>typeof n=="string"||typeof n=="number"?{sectionId:String(n)}:!H(n)||typeof n.sectionId!="string"||n.sectionId.length===0?null:{sectionId:n.sectionId,...typeof n.lastLineId=="string"?{lastLineId:n.lastLineId}:{}}).filter(Boolean),resources:(Array.isArray(t.resources)?t.resources:[]).map(n=>typeof n=="string"||typeof n=="number"?{resourceId:String(n)}:!H(n)||typeof n.resourceId!="string"||n.resourceId.length===0?null:{resourceId:n.resourceId}).filter(Boolean)}},Kc=(e,t)=>{let n=Jc(e),r=Hc(t),o=n.sections.map(s=>({...s})),i=n.resources.map(s=>({...s}));return r.sections.forEach(s=>{let a=o.find(c=>c.sectionId===s.sectionId);if(!a){o.push({sectionId:s.sectionId,...s.lineId===void 0?{}:{lastLineId:s.lineId}});return}if(a.lastLineId!==void 0){if(s.lineId===void 0){delete a.lastLineId;return}a.lastLineId=s.lineId}}),r.resources.forEach(s=>{i.find(c=>c.resourceId===s.resourceId)||i.push({...s})}),{sections:o,resources:i}},Po=(e={})=>{let t=H(e)?e:{};return{saveSlots:H(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:H(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:H(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:H(t.globalRuntime)?t.globalRuntime:{},accountViewedRegistry:H(t.accountViewedRegistry)?t.accountViewedRegistry:{}}},Gc=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((t,n)=>{if(!H(t))throw new Error(`Malformed applyScopedDataUpdates.updates[${n}] entry.`);let r=t.path?.startsWith(Lo)?t.path.slice(Lo.length):null;if(r!==null){if(!["device","account"].includes(t.scope))throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${n}].`);if(r.length===0)throw new Error(`Malformed applyScopedDataUpdates path "${t.path}" at updates[${n}].`);if(t.op!=="set")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${n}].`);return{scope:t.scope,path:t.path,op:t.op,value:t.value,variableId:r}}if(t.path==="viewedRegistry"){if(t.scope!=="account")throw new Error(`Unsupported applyScopedDataUpdates scope "${t.scope}" at updates[${n}].`);if(t.op!=="markViewed")throw new Error(`Unsupported applyScopedDataUpdates operation "${t.op}" at updates[${n}].`);return t}throw typeof t.path!="string"?new Error(`Malformed applyScopedDataUpdates path at updates[${n}].`):new Error(`Unsupported applyScopedDataUpdates path "${t.path}" at updates[${n}].`)})},Xc=(e,t)=>{let n={};return Gc(t).forEach(r=>{if(r.path==="viewedRegistry"){n.accountViewedRegistry=Kc(n.accountViewedRegistry??e.accountViewedRegistry,r.value);return}let o=r.scope==="device"?"globalDeviceVariables":"globalAccountVariables";n[o]={...e[o],...n[o],[r.variableId]:r.value}}),n},Pn=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},Qc=e=>{let t=Pn(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},Zc=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},el=({indexedDB:e,databaseName:t,objectStoreName:n})=>new Promise((r,o)=>{let i=e.open(t,1);i.onupgradeneeded=()=>{let s=i.result;s.objectStoreNames.contains(n)||s.createObjectStore(n,{keyPath:"namespace"})},i.onsuccess=()=>{r(i.result)},i.onerror=()=>{o(i.error??new Error(`Failed to open IndexedDB database "${t}".`))}}),tl=async({databasePromise:e,objectStoreName:t,namespace:n})=>{let r=await e;return new Promise((o,i)=>{let c=r.transaction(t,"readonly").objectStore(t).get(n);c.onsuccess=()=>{o(c.result??null)},c.onerror=()=>{i(c.error??new Error(`Failed to read persisted namespace "${n}" from IndexedDB.`))}})},tt=async({databasePromise:e,objectStoreName:t,namespace:n,patch:r})=>{let o=await e;return new Promise((i,s)=>{let a=o.transaction(t,"readwrite"),c=a.objectStore(t),l=c.get(n),u=!1,f=p=>{u||(u=!0,s(p))},d=()=>{u||(u=!0,i())};l.onerror=()=>{f(l.error??new Error(`Failed to read persisted namespace "${n}" before updating IndexedDB.`))},l.onsuccess=()=>{let p=Po(l.result),h=typeof r=="function"?r(p):r,y={namespace:n,version:1,...ko(),...p,...h},I=c.put(y);I.onerror=()=>{f(I.error??new Error(`Failed to persist namespace "${n}" to IndexedDB.`))}},a.oncomplete=()=>{d()},a.onerror=()=>{f(a.error??new Error(`IndexedDB transaction failed while updating namespace "${n}".`))},a.onabort=()=>{f(a.error??new Error(`IndexedDB transaction aborted while updating namespace "${n}".`))}})},nl=async({databasePromise:e,objectStoreName:t,namespace:n})=>{let r=await e;return new Promise((o,i)=>{let s=r.transaction(t,"readwrite"),c=s.objectStore(t).delete(n),l=!1,u=d=>{l||(l=!0,i(d))},f=()=>{l||(l=!0,o())};c.onerror=()=>{u(c.error??new Error(`Failed to clear persisted namespace "${n}" from IndexedDB.`))},s.oncomplete=()=>{f()},s.onerror=()=>{u(s.error??new Error(`IndexedDB transaction failed while clearing namespace "${n}".`))},s.onabort=()=>{u(s.error??new Error(`IndexedDB transaction aborted while clearing namespace "${n}".`))}})},Tn=(e={})=>{let{indexedDB:t,databaseName:n=qc,objectStoreName:r=Yc,namespace:o}=e,i=Zc(t),s=Qc(o),a=el({indexedDB:i,databaseName:n,objectStoreName:r});return{namespace:s,load:async()=>{let c=await tl({databasePromise:a,objectStoreName:r,namespace:s});return{...ko(),...Po(c)}},clear:async()=>nl({databasePromise:a,objectStoreName:r,namespace:s}),saveSlots:async c=>tt({databasePromise:a,objectStoreName:r,namespace:s,patch:{saveSlots:H(c)?c:{}}}),saveGlobalDeviceVariables:async c=>tt({databasePromise:a,objectStoreName:r,namespace:s,patch:{globalDeviceVariables:H(c)?c:{}}}),saveGlobalAccountVariables:async c=>tt({databasePromise:a,objectStoreName:r,namespace:s,patch:{globalAccountVariables:H(c)?c:{}}}),saveGlobalRuntime:async c=>tt({databasePromise:a,objectStoreName:r,namespace:s,patch:{globalRuntime:H(c)?c:{}}}),applyScopedDataUpdates:async c=>tt({databasePromise:a,objectStoreName:r,namespace:s,patch:l=>Xc(l,c)})}},rl=Tn;var ol=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),il=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),To="conditional",No="choice",Rt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function Nn(e){let t,n=0,r=null,o=new Map,i=new Map,s=new Map,{handlePendingEffects:a}=e,c=(w=new Map,v=Date.now())=>new Map(Array.from(w.entries()).filter(([,T])=>v<T.expiresAt).map(([T,V])=>[T,{animation:structuredClone(V.animation),startedAt:V.startedAt,expiresAt:V.expiresAt}])),l=(w=new Map)=>Array.from(w.values()).map(v=>structuredClone(v.animation)),u=(w=Date.now())=>{o=new Map(Array.from(o.entries()).filter(([,v])=>w<v.expiresAt))},f=()=>{for(;t.selectPendingEffects().length>0;){let w=[...t.selectPendingEffects()];t.clearPendingEffects();try{a(w)}catch(v){throw t.clearPendingEffects(),w.forEach(T=>{t.appendPendingEffect(T)}),v}}},d=({initialState:w,namespace:v})=>{t=Oo(w),n=0,r=Pn(v),o=new Map,i=new Map,s=new Map,t.appendPendingEffect({name:"handleLineActions"}),f()},p=()=>r,h=()=>t.selectPresentationState(),y=()=>t.selectPresentationChanges(),I=w=>t.selectSectionLineChanges(w),b=(w={})=>{n+=1;let v=Date.now();u(v);let T=i.size>0,V=c(o,v),Y=T?c(i,v):new Map,pe={...t.selectRenderState({activePersistentAnimations:l(V),restoredPersistentAnimations:l(Y)}),id:`render-${n}`};return s.set(pe.id,{builtAt:v,persistentAnimationSessions:new Map([...Y.entries(),...V.entries()]),usedRestoredPersistentAnimationSessions:T}),pe},g=(w={})=>b(w),x=(w={})=>b(w),C=w=>{let v=typeof w?.id=="string"&&w.id.length>0?w.id:null,T=v?s.get(v):null;v&&s.delete(v);let V=new Map;Pr(w?.animations).forEach(Y=>{let oe=It(Y);if(!oe)return;let pe=T?.persistentAnimationSessions?.get(oe)??o.get(oe),Mo=Math.max(0,Nr(Y)),Bn=pe?.startedAt??T?.builtAt??Date.now();V.set(oe,{animation:structuredClone(Y),startedAt:Bn,expiresAt:Bn+Mo})}),o=V,T?.usedRestoredPersistentAnimationSessions&&(i=new Map)},O=()=>t.selectSystemState(),L=()=>t.selectSaveSlotMap(),_=w=>t.selectSaveSlot(w),D=w=>t.selectSaveSlotPage(w),N=()=>t.selectSkipMode(),k=()=>t.selectAutoMode(),P=()=>t.selectRuntime(),E=()=>t.selectIsChoiceVisible(),S=(w,v,T={})=>T.interactionSource!==No||w!=="nextLine"||!Rt(v)?v:{...v,_interactionSource:No},M=(w,v)=>{t[w]&&(ol.has(w)&&(il.has(w)?i=c(o):i=new Map,o=new Map),t[w](v),f())},z=(w,v,T,V={})=>{if(w===To){let Y=B(T),oe=on({[w]:v},Y);Vn(oe[w],T,V);return}M(w,v)},q=(w,v)=>{z(w,v)},B=w=>{if(!w)return{variables:t.selectAllVariables?t.selectAllVariables():void 0,runtime:t.selectRuntime?t.selectRuntime():{}};if(Object.prototype.hasOwnProperty.call(w,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:v,...T}=w,V=t.selectAllVariables?t.selectAllVariables():void 0;return{...T,_event:v,variables:V,runtime:t.selectRuntime?t.selectRuntime():{}}},nt=w=>{if(!Rt(w))throw new Error("conditional action payload must be an object");if(!Array.isArray(w.branches))throw new Error("conditional action requires branches array");if(w.branches.length===0)throw new Error("conditional action requires at least one branch")},rt=(w,v,T)=>{if(!Rt(w))throw new Error(`conditional branch at index ${v} must be an object`);if(!Rt(w.actions))throw new Error(`conditional branch at index ${v} requires actions object`);if(!Object.prototype.hasOwnProperty.call(w,"when")&&v!==T-1)throw new Error("conditional else branch must be the last branch")},Vn=(w,v,T)=>{nt(w);for(let V=0;V<w.branches.length;V+=1){let Y=w.branches[V];rt(Y,V,w.branches.length);let oe=B(v);if(!(Object.prototype.hasOwnProperty.call(Y,"when")&&!Ae(Y.when,oe))){jn(Y.actions,v,T);return}}},jo=(w,v,T,V)=>{let Y=B(T),pe=on({[w]:v},Y)[w];if(w===To){Vn(pe,T,V);return}M(w,S(w,pe,V))},jn=(w,v,T)=>{Object.entries(w).forEach(([V,Y])=>{jo(V,Y,v,T)})},Mn=(w,v,T={})=>{t.beginRollbackActionBatch({source:T.rollbackSource});try{jn(w,v,T)}finally{t.endRollbackActionBatch({})}};return{init:d,handleAction:z,handleInternalAction:q,handleActions:Mn,selectRenderState:g,prepareRenderState:x,commitRenderState:C,selectPresentationState:h,selectPresentationChanges:y,selectSectionLineChanges:I,selectSystemState:O,selectSaveSlotMap:L,selectSaveSlot:_,selectSaveSlotPage:D,selectSaveSlots:L,selectRuntime:P,selectIsChoiceVisible:E,handleLineActions:()=>{let w=t.selectCurrentLine();return w?.actions?(Mn(w.actions,void 0,{rollbackSource:"line"}),!0):!1},getNamespace:p}}var Dn=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:n=>{e=n},addElapsed:n=>{e+=n},getCallback:()=>t,setCallback:n=>{t=n}}},sl=80,Vo=({engine:e,routeGraphics:t,trackRenderDispatch:n},r)=>{let o=e.prepareRenderState?.(r)??e.selectRenderState(r);n?.(o),t.render(o),e.commitRenderState?.(o)},al=({engine:e,routeGraphics:t,trackRenderDispatch:n,getRenderDispatchCount:r},o)=>{let i=r?.()??0,s=e.handleLineActions();(r?.()??0)===i&&Vo({engine:e,routeGraphics:t,trackRenderDispatch:n},o)},cl=({engine:e,ticker:t,autoTimer:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let a=r.delay??1e3;n.getElapsed()>=a&&(t.remove(i),n.setCallback(null),n.setElapsed(0),Ot(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},ll=({ticker:e,autoTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},ul=({engine:e,ticker:t,skipTimer:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let a=r?.delay??sl;n.getElapsed()>=a&&(n.setElapsed(0),Ot(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},fl=({ticker:e,skipTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},dl=({engine:e,ticker:t,nextLineConfigTimerState:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let a=r.delay??1e3;n.getElapsed()>=a&&(n.setElapsed(0),Ot(e,"nextLineFromSystem",{}),t.remove(i),n.setCallback(null))};n.setCallback(i),t.add(i)},pl=({ticker:e,nextLineConfigTimerState:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},hl=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveSlots(t?.saveSlots))},ml=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalDeviceVariables(t?.globalDeviceVariables))},gl=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalAccountVariables(t?.globalAccountVariables))},yl=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalRuntime(t?.globalRuntime))},bl=({enqueuePersistenceWrite:e},t)=>{e(n=>{if(typeof n.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return n.applyScopedDataUpdates(t?.updates)})},Do={render:Vo,saveSlots:hl,saveGlobalDeviceVariables:ml,saveGlobalAccountVariables:gl,saveGlobalRuntime:yl,applyScopedDataUpdates:bl,handleLineActions:al,startAutoNextTimer:cl,clearAutoNextTimer:ll,startSkipNextTimer:ul,clearSkipNextTimer:fl,nextLineConfigTimer:dl,clearNextLineConfigTimer:pl},Il=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),Ot=(e,t,n)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,n)},wl=(e=[])=>{let t=new Set,n=[];for(let r=e.length-1;r>=0;r-=1){let o=e[r];if(typeof o?.name!="string"||o.name.length===0)throw new Error("Pending effect is missing a valid name.");if(!Il.has(o.name)){n.unshift(o);continue}t.has(o.name)||(t.add(o.name),n.unshift(o))}return n},Al=({getEngine:e,routeGraphics:t,ticker:n,handleUnhandledEffect:r,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:a})=>{let c=Dn(),l=Dn(),u=Dn(),f=s??null,d=Promise.resolve(),p=null,h=null,y=!1,I=0,b=E=>{if(o){o(E);return}console.error("RouteEngine persistence write failed.",E)},g=()=>{if(f)return f;let E=e();return f=Tn({indexedDB:i,namespace:a??E?.getNamespace?.()}),f},x=E=>{d=d.catch(()=>{}).then(()=>{let S=g();return E(S)}).catch(S=>{b(S)})},C=E=>{let S=typeof E?.id=="string"&&E.id.length>0?E.id:null;I+=1,p=S,y=!1},O=()=>I,L=(E={})=>{if(E?.aborted===!0)return!1;let S=typeof E?.id=="string"&&E.id.length>0?E.id:null;return S?S!==p||S===h?!1:(h=S,!0):p!==null||y?!1:(y=!0,!0)},_=(E,S={})=>{if(E!=="renderComplete"||!L(S))return!1;let M=e();return Ot(M,"markLineCompleted",{}),!0},D=(E={})=>{if(E?._interactionSource==="choice")return!0;let S=E?.actions;return!S||typeof S!="object"||Array.isArray(S)?!1:Object.values(S).some(M=>M?._interactionSource==="choice")},N=(E,S={})=>!S?.actions||typeof E?.selectIsChoiceVisible!="function"||!E.selectIsChoiceVisible()?!1:!D(S),k=({preprocessPayload:E,onEvent:S}={})=>async(M,z={})=>{let q=e();if(N(q,z))return S?.(M,z);let B=await E?.(M,z)??z;if(N(q,B))return S?.(M,B);if(_(M,B),B?.actions){let nt=B?._event?{_event:B._event}:B?.event?{_event:B.event}:void 0,rt=B?._interactionSource?{interactionSource:B._interactionSource}:void 0;rt?q.handleActions(B.actions,nt,rt):q.handleActions(B.actions,nt)}return S?.(M,B)},P=E=>{let S=e(),M=wl(E);M.forEach(q=>{if(!Do[q.name]&&!r)throw new Error(`Unhandled pending effect "${q.name}".`)});let z={engine:S,routeGraphics:t,ticker:n,autoTimer:c,skipTimer:l,nextLineConfigTimerState:u,trackRenderDispatch:C,getRenderDispatchCount:O,enqueuePersistenceWrite:x};for(let q of M){let B=Do[q.name];if(B){B(z,q.payload);continue}r(q,z)}};return P.handleRouteGraphicsEvent=_,P.createRouteGraphicsEventHandler=k,P},El=Al;var xl=(e,t={})=>{let{resources:n={}}=t;return wn(e,n)};var Bu=Nn;export{El as createEffectsHandler,rl as createIndexedDbPersistence,Bu as default,Yi as resolveComputedVariables,xl as resolveLayoutReferences};
1
+ var oi=Object.defineProperty;var ii=(e,t)=>{for(var r in t)oi(e,r,{get:t[r],enumerable:!0})};var on=Symbol.for("immer-nothing"),Zr=Symbol.for("immer-draftable"),ee=Symbol.for("immer-state");function ie(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var Ne=Object.getPrototypeOf;function te(e){return!!e&&!!e[ee]}function Se(e){return e?sn(e)||Array.isArray(e)||!!e[Zr]||!!e.constructor?.[Zr]||gt(e)||yt(e):!1}var si=Object.prototype.constructor.toString();function sn(e){if(!e||typeof e!="object")return!1;let t=Ne(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)===si}function dt(e,t){mt(e)===0?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,n)=>t(n,r,e))}function mt(e){let t=e[ee];return t?t.type_:Array.isArray(e)?1:gt(e)?2:yt(e)?3:0}function Wt(e,t){return mt(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function an(e,t,r){let n=mt(e);n===2?e.set(t,r):n===3?e.add(r):e[t]=r}function ai(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function gt(e){return e instanceof Map}function yt(e){return e instanceof Set}function Ce(e){return e.copy_||e.base_}function qt(e,t){if(gt(e))return new Map(e);if(yt(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=sn(e);if(t===!0||t==="class_only"&&!r){let n=Object.getOwnPropertyDescriptors(e);delete n[ee];let o=Reflect.ownKeys(n);for(let i=0;i<o.length;i++){let s=o[i],a=n[s];a.writable===!1&&(a.writable=!0,a.configurable=!0),(a.get||a.set)&&(n[s]={configurable:!0,writable:!0,enumerable:a.enumerable,value:e[s]})}return Object.create(Ne(e),n)}else{let n=Ne(e);if(n!==null&&r)return{...e};let o=Object.create(n);return Object.assign(o,e)}}function Gt(e,t=!1){return bt(e)||te(e)||!Se(e)||(mt(e)>1&&(e.set=e.add=e.clear=e.delete=ci),Object.freeze(e),t&&Object.entries(e).forEach(([r,n])=>Gt(n,!0))),e}function ci(){ie(2)}function bt(e){return Object.isFrozen(e)}var li={};function _e(e){let t=li[e];return t||ie(0,e),t}var Ke;function cn(){return Ke}function ui(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function en(e,t){t&&(_e("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Yt(e){Kt(e),e.drafts_.forEach(fi),e.drafts_=null}function Kt(e){e===Ke&&(Ke=e.parent_)}function tn(e){return Ke=ui(Ke,e)}function fi(e){let t=e[ee];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function rn(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[ee].modified_&&(Yt(t),ie(4)),Se(e)&&(e=pt(t,e),t.parent_||ht(t,e)),t.patches_&&_e("Patches").generateReplacementPatches_(r[ee].base_,e,t.patches_,t.inversePatches_)):e=pt(t,r,[]),Yt(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==on?e:void 0}function pt(e,t,r){if(bt(t))return t;let n=t[ee];if(!n)return dt(t,(o,i)=>nn(e,n,t,o,i,r)),t;if(n.scope_!==e)return t;if(!n.modified_)return ht(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),dt(i,(a,c)=>nn(e,n,o,a,c,r,s)),ht(e,o,!1),r&&e.patches_&&_e("Patches").generatePatches_(n,r,e.patches_,e.inversePatches_)}return n.copy_}function nn(e,t,r,n,o,i,s){if(te(o)){let a=i&&t&&t.type_!==3&&!Wt(t.assigned_,n)?i.concat(n):void 0,c=pt(e,o,a);if(an(r,n,c),te(c))e.canAutoFreeze_=!1;else return}else s&&r.add(o);if(Se(o)&&!bt(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;pt(e,o),(!t||!t.scope_.parent_)&&typeof n!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,n)&&ht(e,o)}}function ht(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&Gt(t,r)}function di(e,t){let r=Array.isArray(e),n={type_:r?1:0,scope_:t?t.scope_:cn(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=n,i=Xt;r&&(o=[n],i=He);let{revoke:s,proxy:a}=Proxy.revocable(o,i);return n.draft_=a,n.revoke_=s,a}var Xt={get(e,t){if(t===ee)return e;let r=Ce(e);if(!Wt(r,t))return pi(e,r,t);let n=r[t];return e.finalized_||!Se(n)?n:n===Bt(e.base_,t)?(zt(e),e.copy_[t]=Jt(n,e)):n},has(e,t){return t in Ce(e)},ownKeys(e){return Reflect.ownKeys(Ce(e))},set(e,t,r){let n=ln(Ce(e),t);if(n?.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){let o=Bt(Ce(e),t),i=o?.[ee];if(i&&i.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(ai(r,o)&&(r!==void 0||Wt(e.base_,t)))return!0;zt(e),Ht(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 Bt(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,zt(e),Ht(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=Ce(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:n.enumerable,value:r[t]}},defineProperty(){ie(11)},getPrototypeOf(e){return Ne(e.base_)},setPrototypeOf(){ie(12)}},He={};dt(Xt,(e,t)=>{He[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});He.deleteProperty=function(e,t){return He.set.call(this,e,t,void 0)};He.set=function(e,t,r){return Xt.set.call(this,e[0],t,r,e[0])};function Bt(e,t){let r=e[ee];return(r?Ce(r):e)[t]}function pi(e,t,r){let n=ln(t,r);return n?"value"in n?n.value:n.get?.call(e.draft_):void 0}function ln(e,t){if(!(t in e))return;let r=Ne(e);for(;r;){let n=Object.getOwnPropertyDescriptor(r,t);if(n)return n;r=Ne(r)}}function Ht(e){e.modified_||(e.modified_=!0,e.parent_&&Ht(e.parent_))}function zt(e){e.copy_||(e.copy_=qt(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var hi=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,...l){return s.produce(c,f=>r.call(this,f,...l))}}typeof r!="function"&&ie(6),n!==void 0&&typeof n!="function"&&ie(7);let o;if(Se(t)){let i=tn(this),s=Jt(t,void 0),a=!0;try{o=r(s),a=!1}finally{a?Yt(i):Kt(i)}return en(i,n),rn(o,i)}else if(!t||typeof t!="object"){if(o=r(t),o===void 0&&(o=t),o===on&&(o=void 0),this.autoFreeze_&&Gt(o,!0),n){let i=[],s=[];_e("Patches").generateReplacementPatches_(t,o,i,s),n(i,s)}return o}else ie(1,t)},this.produceWithPatches=(t,r)=>{if(typeof t=="function")return(s,...a)=>this.produceWithPatches(s,c=>t(c,...a));let n,o;return[this.produce(t,r,(s,a)=>{n=s,o=a}),n,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){Se(e)||ie(8),te(e)&&(e=$e(e));let t=tn(this),r=Jt(e,void 0);return r[ee].isManual_=!0,Kt(t),r}finishDraft(e,t){let r=e&&e[ee];(!r||!r.isManual_)&&ie(9);let{scope_:n}=r;return en(n,t),rn(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=_e("Patches").applyPatches_;return te(e)?n(e,t):this.produce(e,o=>n(o,t))}};function Jt(e,t){let r=gt(e)?_e("MapSet").proxyMap_(e,t):yt(e)?_e("MapSet").proxySet_(e,t):di(e,t);return(t?t.scope_:cn()).drafts_.push(r),r}function $e(e){return te(e)||ie(10,e),un(e)}function un(e){if(!Se(e)||bt(e))return e;let t=e[ee],r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=qt(e,t.scope_.immer_.useStrictShallowCopy_)}else r=qt(e,!0);return dt(r,(n,o)=>{an(r,n,un(o))}),t&&(t.finalized_=!1),r}var re=new hi,Qt=re.produce,cu=re.produceWithPatches.bind(re),lu=re.setAutoFreeze.bind(re),uu=re.setUseStrictShallowCopy.bind(re),fu=re.applyPatches.bind(re),du=re.createDraft.bind(re),pu=re.finishDraft.bind(re);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},R={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},Ve={NOT:0};var v=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},Q=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var Zt=e=>{if(!e||e.trim()==="")throw new v("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let r=e.includes("===")?"==":"!=";throw new v(`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 v(`Incomplete comparison expression - missing right operand (got: '${e}')`)},fn=e=>{if(e.trim().endsWith(" in"))throw new v(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new v(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,r]=e.split(" in ");if(!r||r.trim()==="")throw new v(`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 v(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new v(`Invalid loop syntax (got: '$for ${e}')`)}};var dn=(e,t,r=!1)=>{if(t===null)return new Q(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new Q(`Cannot iterate over undefined value at '$for ${e}'`);let n=typeof t;return r?new Q(`Cannot iterate over non-array value in loop '${e}' - got ${n} instead`):new Q(`Cannot iterate over non-array value (got: ${n}) at '$for ${e}'`)},pn=(e,t)=>{let r=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new Q(`Unknown function '${e}' (${r})`)};var mi=(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=k(e,{functions:n,partials:o},t,{});return s===void 0?{}:s},k=(e,t,r,n)=>{let o=t.functions||t;if(e.var&&!e.type)return Y(e.var,r,n);if(e.type===m.LITERAL)return e.value;if(e.type===m.VARIABLE)return Y(e.path,r,n);if(e.type===m.INTERPOLATION)return yi(e.parts,t,r,n);switch(e.type){case m.FUNCTION:return mn(e,t,r,n);case m.BINARY:return gn(e,t,r,n);case m.UNARY:return yn(e,t,r,n);case m.CONDITIONAL:return Ii(e,t,r,n);case m.LOOP:return xi(e,t,r,n);case m.OBJECT:return Si(e,t,r,n);case m.ARRAY:return _i(e,t,r,n);case m.PARTIAL:return $i(e,t,r,n);case m.PATH_REFERENCE:return Ri(e,t,r,n);default:throw new Error(`Unknown node type: ${e.type}`)}},hn=new Map,gi=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 a=s.slice(1,-1);t.push({type:"property",value:a})}else t.push({type:"property",value:s});r=""}n=!1}else r+=i}return r&&t.push({type:"property",value:r}),t},Y=(e,t,r)=>{if(!e)return;if(e in r)return r[e];let n=hn.get(e);if(!n){let i=[],s="",a=0;for(let c=0;c<e.length;c++){let l=e[c];l==="["?(a++,s+=l):l==="]"?(a--,s+=l):l==="."&&a===0?s&&(i.push(s),s=""):s+=l}s&&i.push(s),n=[];for(let c of i){let l=gi(c.trim());n.push(...l)}hn.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},yi=(e,t,r,n)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=k(i,t,r,n);o.push(s!=null?String(s):"")}return o.join("")},mn=(e,t,r,n)=>{let o=t.functions||t,i=o[e.name];if(!i)throw pn(e.name,o);let s=e.args.map(a=>k(a,t,r,n));return i(...s)},ye=(e,t,r,n)=>{if(e.var&&!e.type)return Y(e.var,r,n);switch(e.type){case m.VARIABLE:return Y(e.path,r,n);case m.LITERAL:return e.value;case m.BINARY:return gn(e,t,r,n);case m.UNARY:return yn(e,t,r,n);case m.FUNCTION:return mn(e,t,r,n);default:return k(e,t,r,n)}},gn=(e,t,r,n)=>{if(e.op===R.AND||e.op===R.OR){let s=ye(e.left,t,r,n),a=ye(e.right,t,r,n);switch(e.op){case R.AND:return s&&a;case R.OR:return s||a}}let o=k(e.left,t,r,n),i=k(e.right,t,r,n);switch(e.op){case R.EQ:return o==i;case R.NEQ:return o!=i;case R.GT:return o>i;case R.LT:return o<i;case R.GTE:return o>=i;case R.LTE:return o<=i;case R.IN:return Array.isArray(i)?i.includes(o):!1;case R.ADD:if(typeof o!="number"||typeof i!="number")throw new Q(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case R.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new Q(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},yn=(e,t,r,n)=>{let o=e.op===Ve.NOT?ye(e.operand,t,r,n):k(e.operand,t,r,n);if(e.op===Ve.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},bi=(e,t,r,n)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===m.VARIABLE)if(Y(o.path,r,n)){let s=e.bodies[0];if(s.type===m.OBJECT&&s.properties.length<=5){let a={};for(let c of s.properties){let l=c.parsedKey?k(c.parsedKey,t,r,n):c.key,f=c.value;if(f.type===m.LITERAL)a[l]=f.value;else if(f.type===m.VARIABLE)a[l]=Y(f.path,r,n);else if(f.type===m.INTERPOLATION){let u=[];for(let d of f.parts)if(typeof d=="string")u.push(d);else if(d.type===m.VARIABLE){let p=Y(d.path,r,n);u.push(p!=null?String(p):"")}else{let p=k(d,t,r,n);u.push(p!=null?String(p):"")}a[l]=u.join("")}else a[l]=k(f,t,r,n)}return a}}else{let s=e.bodies[1];if(s.type===m.OBJECT&&s.properties.length<=5){let a={};for(let c of s.properties){let l=c.parsedKey?k(c.parsedKey,t,r,n):c.key,f=c.value;if(f.type===m.LITERAL)a[l]=f.value;else if(f.type===m.VARIABLE)a[l]=Y(f.path,r,n);else if(f.type===m.INTERPOLATION){let u=[];for(let d of f.parts)if(typeof d=="string")u.push(d);else if(d.type===m.VARIABLE){let p=Y(d.path,r,n);u.push(p!=null?String(p):"")}else{let p=k(d,t,r,n);u.push(p!=null?String(p):"")}a[l]=u.join("")}else a[l]=k(f,t,r,n)}return a}}}return null},Ii=(e,t,r,n)=>{let o=bi(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||ye(s,t,r,n))return k(e.bodies[i],t,r,n)}return bn},Ai=(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 a=[];for(let c=0;c<t.length;c++){let l=t[c];if(l[s]){let f={};for(let u of i.properties){let d=u.key,p=u.value;if(p.type===m.LITERAL)f[d]=p.value;else if(p.type===m.VARIABLE){let h=p.path;if(h===n)f[d]=l;else if(h.startsWith(n+".")){let g=h.substring(n.length+1);f[d]=l[g]}else return null}else if(p.type===m.INTERPOLATION){let h=[],g=!0;for(let y of p.parts)if(typeof y=="string")h.push(y);else if(y.type===m.VARIABLE){let I=y.path;if(I===n)h.push(l!=null?String(l):"");else if(I.startsWith(n+".")){let w=I.substring(n.length+1),x=l[w];h.push(x!=null?String(x):"")}else{g=!1;break}}else{g=!1;break}if(!g)return null;f[d]=h.join("")}else return null}a.push(f)}}return a}}}return null},wi=(e,t)=>{let r=e.body,n=e.itemVar,o=Ai(e,t);if(o!==null)return o;if(r.type===m.OBJECT&&r.properties.length<=5&&!r.whenCondition){for(let a of r.properties)if(a.parsedKey)return null;let i=[],s=!0;for(let a of r.properties){let c=a.key,l=a.value;if(l.type===m.LITERAL)i.push({key:c,type:"literal",value:l.value});else if(l.type===m.VARIABLE){let f=l.path;if(f===n)i.push({key:c,type:"item"});else if(f.startsWith(n+".")){let u=f.substring(n.length+1);if(!u.includes(".")&&!u.includes("["))i.push({key:c,type:"prop",prop:u});else{s=!1;break}}else{s=!1;break}}else if(l.type===m.INTERPOLATION&&l.parts.length===1){let f=l.parts[0];if(f.type===m.VARIABLE){let u=f.path;if(u===n)i.push({key:c,type:"item_string"});else if(u.startsWith(n+".")){let d=u.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 a=new Array(t.length);if(i.length===3&&i[0].type==="prop"&&i[0].key==="id"&&i[1].type==="prop_string"&&i[1].key==="title"&&i[2].type==="prop"&&i[2].key==="completed")for(let c=0;c<t.length;c++){let l=t[c];a[c]={id:l.id,title:l.title!=null?String(l.title):"",completed:l.completed}}else for(let c=0;c<t.length;c++){let l=t[c],f={};for(let u of i)if(u.type==="literal")f[u.key]=u.value;else if(u.type==="item")f[u.key]=l;else if(u.type==="prop")f[u.key]=l[u.prop];else if(u.type==="item_string")f[u.key]=l!=null?String(l):"";else if(u.type==="prop_string"){let d=l[u.prop];f[u.key]=d!=null?String(d):""}a[c]=f}return a}}return null},vi=(e,t,r,n,o)=>{let i=[],s=e.body;if(s.type===m.OBJECT&&s.fast!==!1){let a=e.itemVar,c=e.indexVar;for(let l=0;l<o.length;l++){let f=o[l],u={},d={...n,[a]:f,...c&&{[c]:l}};d.__paths__||(d.__paths__=n.__paths__||{});let p=e.iterable.path||"";if(n&&n.__paths__&&p){let h=p.split("."),g=h[0];g in n.__paths__&&(p=n.__paths__[g],h.length>1&&(p+="."+h.slice(1).join(".")))}d.__paths__={...d.__paths__,[a]:`${p}[${l}]`,...c&&{[c]:l}};for(let h of s.properties){let g=h.parsedKey?k(h.parsedKey,t,r,d):h.key,y=h.value;if(y.type===m.LITERAL)u[g]=y.value;else if(y.type===m.VARIABLE){let I=y.path;if(I===a)u[g]=f;else if(I===c)u[g]=l;else if(I.startsWith(a+".")){let w=I.substring(a.length+1);!w.includes(".")&&!w.includes("[")?u[g]=f[w]:u[g]=Y(I,r,{...n,[a]:f,...c&&{[c]:l}})}else u[g]=Y(I,r,{...n,[a]:f,...c&&{[c]:l}})}else if(y.type===m.INTERPOLATION){let I=[];for(let w of y.parts)if(typeof w=="string")I.push(w);else if(w.type===m.VARIABLE){let x=w.path,b;if(x===a)b=f;else if(x===c)b=l;else if(x.startsWith(a+".")){let O=x.substring(a.length+1);!O.includes(".")&&!O.includes("[")?b=f[O]:b=Y(x,r,{...n,[a]:f,...c&&{[c]:l}})}else b=Y(x,r,{...n,[a]:f,...c&&{[c]:l}});I.push(b!=null?String(b):"")}else{let x={...n,[a]:f,...c&&{[c]:l}},b=k(w,t,r,x);I.push(b!=null?String(b):"")}u[g]=I.join("")}else{let I={...n,[a]:f,...c&&{[c]:l}};u[g]=k(y,t,r,I)}}i.push(u)}return i}return null},Ei=(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 a=s.properties[0],c=s.properties[1];if(a.key==="id"&&a.value.type===m.VARIABLE&&a.value.path==="item.id"&&c.key==="$if item.highlighted"&&c.value.type===m.CONDITIONAL){let l=[];for(let f=0;f<t.length;f++){let u=t[f];if(u.visible){let d={id:u.id};u.highlighted?(d.highlight=!0,d.message=`This item is highlighted: ${u.name}`):(d.highlight=!1,d.message=u.name),l.push(d)}}return l}}}}return null},xi=(e,t,r,n)=>{let o=k(e.iterable,t,r,n);if(!Array.isArray(o)){let l,f=!1;if(e.iterable.type===m.FUNCTION){f=!0;let d=e.iterable.args.map(p=>p.type===m.LITERAL?typeof p.value=="string"?`'${p.value}'`:String(p.value):p.type===m.VARIABLE?p.path:p.type===m.FUNCTION?`${p.name}(...)`:"?").join(", ");l=`${e.iterable.name}(${d})`}else l=e.iterable.path||"undefined";let u=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${l}`;throw dn(u,o,f)}if(!e.indexVar){let l=Ei(e,o,e.itemVar);if(l!==null)return l}if(!e.indexVar){let l=wi(e,o);if(l!==null)return l}let i=vi(e,t,r,n,o);if(i!==null)return i;let s=[],a=e.iterable.path||"";if(n&&n.__paths__&&a){let l=a.split("."),f=l[0];f in n.__paths__&&(a=n.__paths__[f],l.length>1&&(a+="."+l.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(l=>l.type===m.OBJECT&&l.properties.some(f=>f.key.startsWith("$if ")||f.key.startsWith("$when "))));for(let l=0;l<o.length;l++){let f=e.indexVar?{...n,[e.itemVar]:o[l],[e.indexVar]:l}:{...n,[e.itemVar]:o[l]};f.__paths__||(f.__paths__=n.__paths__||{}),f.__paths__={...f.__paths__,[e.itemVar]:`${a}[${l}]`},e.indexVar&&(f.__paths__[e.indexVar]=l);let u=k(e.body,t,r,f);if(Array.isArray(u)&&u.length===1&&!c){let d=u[0];s.push(d===void 0?{}:d)}else s.push(u===void 0?{}:u)}return s},Ci=(e,t,r,n)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?k(o.parsedKey,t,r,n):o.key,s=o.value;if(s.type===m.OBJECT&&s.properties.length<=10&&!s.whenCondition){let a={},c={},l=!0;for(let f of s.properties){let u=f.parsedKey?k(f.parsedKey,t,r,n):f.key,d=f.value;if(d.type===m.LITERAL)c[u]=d.value;else if(d.type===m.VARIABLE)c[u]=Y(d.path,r,n);else if(d.type===m.INTERPOLATION){let p=[];for(let h of d.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let g=Y(h.path,r,n);p.push(g!=null?String(g):"")}else{l=!1;break}if(!l)break;c[u]=p.join("")}else if(d.type===m.OBJECT&&d.properties.length<=5){let p={};for(let h of d.properties){let g=h.key,y=h.value;if(y.type===m.LITERAL)p[g]=y.value;else if(y.type===m.VARIABLE)p[g]=Y(y.path,r,n);else if(y.type===m.INTERPOLATION){let I=[];for(let w of y.parts)if(typeof w=="string")I.push(w);else if(w.type===m.VARIABLE){let x=Y(w.path,r,n);I.push(x!=null?String(x):"")}else{l=!1;break}if(!l)break;p[g]=I.join("")}else{l=!1;break}}if(!l)break;c[u]=p}else{l=!1;break}}if(l)return a[i]=c,a}}return null},Si=(e,t,r,n)=>{let o=t.functions||t;if(e.whenCondition&&!ye(e.whenCondition,o,r,n))return;let i=Ci(e,t,r,n);if(i!==null)return i;if(e.fast){let l={};for(let f of e.properties){let u=f.parsedKey?k(f.parsedKey,t,r,n):f.key,d=f.value;if(d.type===m.LITERAL)l[u]=d.value;else if(d.type===m.VARIABLE)l[u]=Y(d.path,r,n);else if(d.type===m.INTERPOLATION){let p=[];for(let h of d.parts)if(typeof h=="string")p.push(h);else if(h.type===m.VARIABLE){let g=Y(h.path,r,n);p.push(g!=null?String(g):"")}else{let g=k(h,t,r,n);p.push(g!=null?String(g):"")}l[u]=p.join("")}else l[u]=k(d,t,r,n)}return l}let s={},a=null,c=!1;for(let l of e.properties)if(!l.key.startsWith("$if ")&&!l.key.match(/^\$if\s+\w+.*:?$/)&&!l.key.startsWith("$elif")&&!l.key.startsWith("$else")&&!l.key.startsWith("$for ")){c=!0;break}for(let l of e.properties)if(l.key.startsWith("$if ")||l.key.match(/^\$if\s+\w+.*:?$/)){let f=k(l.value,t,r,n);if(!c&&f!==null&&f!==void 0)return Array.isArray(f)&&f.length===1?f[0]:f;typeof f=="object"&&f!==null&&!Array.isArray(f)&&Object.assign(s,f)}else if(l.key.startsWith("$for ")){if(e.properties.length===1)return k(l.value,t,r,n)}else{let f=l.value;if(f&&f.type===m.OBJECT&&f.properties){let u=f.properties.find(d=>d.key.startsWith("$for "));if(u){let d=k(u.value,t,r,n);d!==void 0&&(s[l.key]=d)}else{let d=k(l.value,t,r,n);d!==void 0&&(s[l.key]=d)}}else{let u=l.parsedKey?k(l.parsedKey,t,r,n):l.key,d=k(l.value,t,r,n);d!==void 0&&(s[u]=d)}}return s},bn={},_i=(e,t,r,n)=>{let o=[];for(let i of e.items)if(i.type===m.LOOP){let s=k(i,t,r,n);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=k(i,t,r,n);s!==bn&&s!==void 0&&o.push(s)}return o},$i=(e,t,r,n)=>{let{name:o,data:i,whenCondition:s}=e,a=t.partials||{},c=t.functions||t;if(s&&!ye(s,c,r,n))return;if(!a[o])throw new Q(`Partial '${o}' is not defined`);let l=n._partialStack||[];if(l.includes(o))throw new Q(`Circular partial reference detected: ${o}`);let f=a[o],u=r,d={...n,_partialStack:[...l,o]};if(n){u={...r};for(let p of Object.keys(n))p.startsWith("_")||(u[p]=n[p])}if(i){let p=k(i,t,r,n);u={...u,...p}}return k(f,t,u,d)},Ri=(e,t,r,n)=>{let{path:o}=e,i=o.split("."),s=i[0],a=i.slice(1);if(!n||!(s in n))throw new Q(`Path reference '#{${o}}' refers to '${s}' which is not a loop variable in the current scope`);if(n.__paths__||(n.__paths__={}),!(s in n.__paths__))throw new Q(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let c=n.__paths__[s];if(typeof c=="number"){if(a.length>0)throw new Q(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(c)}return a.length>0&&(c+="."+a.join(".")),c};var er=mi;var Oi=/\$\{([^}]*)\}/g,Li=/#\{([^}]*)\}/g,An=(e,t={})=>{let r=e.match(/^(\w+)\((.*)\)$/);if(!r)return{isFunction:!1};let[,n,o]=r,i=ki(o,t);return{isFunction:!0,type:m.FUNCTION,name:n,args:i}},ki=(e,t={})=>e.trim()?Pi(e).map(n=>Ti(n.trim(),t)):[],Pi=e=>{let t=[],r="",n=0,o=!1,i="";for(let s=0;s<e.length;s++){let a=e[s],c=s>0?e[s-1]:"";!o&&(a==='"'||a==="'")?(o=!0,i=a,r+=a):o&&a===i&&c!=="\\"?(o=!1,i="",r+=a):!o&&a==="("?(n++,r+=a):!o&&a===")"?(n--,r+=a):!o&&a===","&&n===0?(t.push(r),r=""):r+=a}return r&&t.push(r),t},Ti=(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=An(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:a,type:c}of o){let l=0;for(;l<n.length;){let f=Re(n.substring(l),a);if(f===-1)break;let u=l+f;u>i&&(i=u,s={op:a,type:c}),l=u+a.length}}if(i!==-1)try{return K(n,t)}catch{return{type:m.VARIABLE,path:n}}return{type:m.VARIABLE,path:n}},wn=/^\w+\(.*\)$/,Di=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,Ni=e=>{if(!(!e||e.trim()===""||wn.test(e))&&Di.test(e))throw e.includes("?")&&e.includes(":")?new v(`Complex expressions not supported in variable replacements - consider calculating the value in your data instead. Offending expression: "${e}"`):e.includes("||")||e.includes("&&")||e.includes("??")?new v(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new v(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},In=e=>{let t=e.trim();if(wn.test(t))throw new v(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new v(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new v(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new v(`Logical operators not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("?")&&t.includes(":"))throw new v(`Complex expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);return{type:m.PATH_REFERENCE,path:t}},Je=(e,t={})=>{let r=e.trim();Ni(r);let n=An(r,t);if(n.isFunction)return{type:n.type,name:n.name,args:n.args};if(r.includes("[")&&!/[\s+\-*/%|&?:]/.test(r)){let o=0;for(let i of r)i==="["?o++:i==="]"&&o--;if(o!==0)throw new Error("Invalid array index syntax")}return{type:m.VARIABLE,path:r}},tr=(e,t={})=>{let r=e,n=[];(e.includes("\\${")||e.includes("\\#{"))&&(r=e.replace(/\\\\(\$\{[^}]*\})/g,"\\DOUBLE_ESC_VAR$1"),r=r.replace(/\\\\(#\{[^}]*\})/g,"\\DOUBLE_ESC_PATH$1"),r=r.replace(/\\(\$\{[^}]*\})/g,(l,f)=>{let u=`__ESCAPED_${n.length}__`;return n.push(f),u}),r=r.replace(/\\(#\{[^}]*\})/g,(l,f)=>{let u=`__ESCAPED_${n.length}__`;return n.push(f),u}),r=r.replace(/\\DOUBLE_ESC_VAR/g,"\\"),r=r.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...r.matchAll(Oi)],i=[...r.matchAll(Li)],s=[...o.map(l=>({match:l,type:"variable"})),...i.map(l=>({match:l,type:"pathref"}))].sort((l,f)=>l.match.index-f.match.index);if(s.length===0){let l=r;for(let f=0;f<n.length;f++)l=l.replace(`__ESCAPED_${f}__`,n[f]);return{type:m.LITERAL,value:l}}if(s.length===1&&s[0].match[0]===r&&n.length===0){let{match:l,type:f}=s[0];try{return f==="variable"?Je(l[1],t):In(l[1])}catch(u){if(u.message==="Invalid array index syntax")return{type:m.LITERAL,value:r};throw u}}let a=[],c=0;for(let{match:l,type:f}of s){let[u,d]=l,p=l.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&&a.push(h)}try{let h;f==="variable"?h=Je(d.trim(),t):h=In(d.trim()),a.push(h)}catch(h){if(h.message==="Invalid array index syntax")a.push(u);else throw h}c=p+u.length}if(c<r.length){let l=r.substring(c);for(let f=0;f<n.length;f++)l=l.replace(`__ESCAPED_${f}__`,n[f]);l&&a.push(l)}return{type:m.INTERPOLATION,parts:a}};var or=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),xn=e=>Object.keys(e),G=e=>e.join("."),be=(e,t,r)=>{let n=xn(e).filter(o=>!t.has(o));if(n.length>0)throw new v(`Unexpected key '${n[0]}' in condition JSON at '${G(r)}'`)},Ie=(e,t)=>typeof e=="string"?tr(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?ji(e,t):Mi(e,t):{type:m.LITERAL,value:e},Vi=e=>{let{$each:t,...r}=e;if(typeof t!="string")throw new v("$each value must be a non-empty string");let n=t.trim();if(n==="")throw new v("$each value must be a non-empty string");if(Object.keys(r).length===0)throw new v("Empty $each body not allowed");if(r.$partial!==void 0)throw new v("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${n}`]:r}},ji=(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=Vi(i),l=Object.keys(c);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let f=En(l[0],c[l[0]],t,!0);r.push(f),n=!0;continue}}catch(c){throw c instanceof v?c:new v(c.message)}let a=Object.keys(i);if(a.length===1&&/^\$for(?::\w+)?\s/.test(a[0])){let c=En(a[0],i[a[0]],t);r.push(c),n=!0;continue}}let s=Ie(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}},Mi=(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 v("$partial value must be a string");if(e.$partial.trim()==="")throw new v("$partial value cannot be an empty string");let c=["$if","$elif","$else","$for"],l=[];for(let[I]of i)for(let w of c)if(I===w||I.startsWith(w+" ")||I.startsWith(w+"#")){l.push(w);break}if(l.length>0)throw new v(`Cannot use $partial with ${l.join(", ")} at the same level. Wrap $partial in a parent object if you need conditionals.`);let{$partial:f,$when:u,...d}=e,p={},h=!1;for(let[I,w]of Object.entries(d)){let x=I;(I.startsWith("\\$")||I.startsWith("$$"))&&(x=I.slice(1)),p[x]=w,h=!0}let g=null;if(h&&(g=Ie(p,t),g.type===m.OBJECT)){let I=!1;for(let w of g.properties)if(w.value.type===m.VARIABLE||w.value.type===m.INTERPOLATION||w.value.type===m.FUNCTION||w.value.type===m.CONDITIONAL||w.value.type===m.OBJECT&&!w.value.fast||w.value.type===m.ARRAY&&!w.value.fast){I=!0;break}I&&(g.fast=!1)}let y={type:m.PARTIAL,name:f,data:g};return u!==void 0&&(y.whenCondition=vn(u,t)),y}for(let[c,l]of i)if(c==="$when"){if(o!==null)throw new v("Multiple '$when' directives on the same object are not allowed");if(l==null)throw new v("Missing condition expression after '$when'");o=vn(l,t),n=!0}else if(c.startsWith("$when#")||c.startsWith("$when "))throw new v("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<i.length;){let[c,l]=i[s];if(c==="$when"){s++;continue}if(c==="$each")throw new v("$each can only be used inside arrays");if(c.startsWith("$if ")||c.match(/^\$if#\w+\s/)||c.match(/^\$if\s+\w+.*:$/)){let f=Fi(i,s,t);r.push({key:c,value:f.node}),n=!0,s=f.nextIndex}else if(/^\$for(?::\w+)?\s/.test(c)){let f=c.match(/^\$for(?::(\w+))?\s/)?.[1]||"",u=f?`:${f}`:"";throw new v(`$for loops must be inside arrays - use '- $for${u} item in items:' instead of '$for${u} item in items:'. For cleaner object generation syntax, consider using $each.`)}else{if(c.startsWith("$elif ")||c.startsWith("$else"))throw new v(`'${c.split(" ")[0]}' without matching '$if'`);if(c==="$if"||c==="$if:")throw new v("Missing condition expression after '$if'");{let f=Ie(l,t);(f.type===m.FUNCTION||f.type===m.CONDITIONAL||f.type===m.PARTIAL||f.type===m.OBJECT&&!f.fast||f.type===m.ARRAY&&!f.fast)&&(n=!0);let u=tr(c,t),d={key:c,value:f};(u.type!==m.LITERAL||u.value!==c)&&(d.parsedKey=u),r.push(d),s++}}}let a={type:m.OBJECT,properties:r,fast:!n};return o&&(a.whenCondition=o),a},Fi=(e,t,r={})=>{let n=[],o=[],i=t,[s,a]=e[i],c=null,l;if(s.startsWith("$if#")){let u=s.match(/^\$if#(\w+)\s+(.+)$/);if(u)c=u[1],l=u[2];else throw new v(`Invalid conditional syntax: ${s}`)}else l=s.substring(4),l.endsWith(":")&&(l=l.slice(0,-1).trim());Zt(l);let f=K(l,r);for(n.push(f),o.push(Ie(a,r)),i++;i<e.length;){let[u,d]=e[i],p=!1,h;if(c?u.startsWith(`$elif#${c} `)?(h=u.substring(`$elif#${c} `.length),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(u===`$else#${c}`||u===`$else#${c}:`)&&(p=!0,h=null):u.startsWith("$elif ")?(h=u.substring(6),h.endsWith(":")&&(h=h.slice(0,-1).trim()),p=!0):(u==="$else"||u==="$else:")&&(p=!0,h=null),p){if(h===null)n.push(null);else{Zt(h);let g=K(h,r);n.push(g)}if(o.push(Ie(d,r)),i++,h===null)break}else break}return{node:{type:m.CONDITIONAL,conditions:n,bodies:o,id:c},nextIndex:i}},rr={eq:R.EQ,neq:R.NEQ,gt:R.GT,gte:R.GTE,lt:R.LT,lte:R.LTE,in:R.IN,add:R.ADD,sub:R.SUBTRACT},nr={all:R.AND,any:R.OR},Ui=new Set(["var","literal","call","not",...Object.keys(rr),...Object.keys(nr)]),Bi=(e,t,r)=>{if(!Array.isArray(e))throw new v(`Condition JSON operator '${t}' at '${G(r)}' requires an array`);if(e.length!==2)throw new v(`Condition JSON operator '${t}' at '${G(r)}' requires exactly 2 operands`);return e},zi=(e,t,r,n,o)=>{if(!Array.isArray(e))throw new v(`Condition JSON operator '${t}' at '${G(o)}' requires an array`);if(e.length===0)throw new v(`Condition JSON operator '${t}' at '${G(o)}' requires at least 1 condition`);return e.map((s,a)=>fe(s,n,[...o,a])).reduce((s,a)=>({type:m.BINARY,op:r,left:s,right:a}))},Wi=(e,t,r)=>{let n,o;if(typeof e.call=="string")n=e.call,o=e.args??[],be(e,new Set(["call","args"]),r);else if(or(e.call))n=e.call.name,o=e.call.args??[],be(e,new Set(["call"]),r),be(e.call,new Set(["name","args"]),[...r,"call"]);else throw new v(`Condition JSON call at '${G(r)}' requires a function name`);if(typeof n!="string"||n.trim()==="")throw new v(`Condition JSON call at '${G(r)}' requires a non-empty function name`);if(!/^\w+$/.test(n))throw new v(`Invalid condition JSON function name '${n}' at '${G(r)}'`);if(!Array.isArray(o))throw new v(`Condition JSON call '${n}' at '${G(r)}' requires args to be an array`);return{type:m.FUNCTION,name:n,args:o.map((i,s)=>fe(i,t,[...r,"args",s]))}},fe=(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 v(`Condition JSON array at '${G(r)}' must be wrapped in an operator or { literal: [...] }`);if(!or(e))throw new v(`Invalid condition JSON value at '${G(r)}'`);let n=xn(e);if(n.length===0)throw new v(`Condition JSON object at '${G(r)}' must contain an operator`);let o=n.filter(s=>Ui.has(s));if(o.length===0)throw new v(`Unknown condition JSON operator '${n[0]}' at '${G(r)}'`);if(o.length>1)throw new v(`Condition JSON at '${G(r)}' must contain exactly one operator`);let i=o.includes("call")?"call":o[0];if(i==="var"){if(be(e,new Set(["var"]),r),typeof e.var!="string"||e.var.trim()==="")throw new v(`Condition JSON var at '${G(r)}' requires a non-empty path`);return{type:m.VARIABLE,path:e.var}}if(i==="literal")return be(e,new Set(["literal"]),r),{type:m.LITERAL,value:e.literal};if(i==="call")return Wi(e,t,r);if(i==="not")return be(e,new Set(["not"]),r),{type:m.UNARY,op:Ve.NOT,operand:fe(e.not,t,[...r,"not"])};if(i in nr)return be(e,new Set([i]),r),zi(e[i],i,nr[i],t,[...r,i]);if(i in rr){be(e,new Set([i]),r);let s=Bi(e[i],i,[...r,i]);return{type:m.BINARY,op:rr[i],left:fe(s[0],t,[...r,i,0]),right:fe(s[1],t,[...r,i,1])}}throw new v(`Unknown condition JSON operator '${i}' at '${G(r)}'`)},vn=(e,t={})=>{if(e==null)throw new v("Missing condition expression after '$when'");if(typeof e=="string"){if(e.trim()==="")throw new v("Empty condition expression after '$when'");return K(e,t)}return or(e)||Array.isArray(e)?fe(e,t):{type:m.LITERAL,value:e}},K=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let l=e.slice(1,-1),f=0,u=!0;for(let d=0;d<l.length;d++)if(l[d]==="("?f++:l[d]===")"&&f--,f<0){u=!1;break}if(u&&f===0)return K(l,t)}let r=Re(e,"||");if(r!==-1)return{type:m.BINARY,op:R.OR,left:K(e.substring(0,r).trim(),t),right:K(e.substring(r+2).trim(),t)};let n=Re(e,"&&");if(n!==-1)return{type:m.BINARY,op:R.AND,left:K(e.substring(0,n).trim(),t),right:K(e.substring(n+2).trim(),t)};let o=[{op:">=",type:R.GTE},{op:"<=",type:R.LTE},{op:"==",type:R.EQ},{op:"!=",type:R.NEQ},{op:">",type:R.GT},{op:"<",type:R.LT},{op:" in ",type:R.IN}];for(let{op:l,type:f}of o){let u=Re(e,l);if(u!==-1)return{type:m.BINARY,op:f,left:K(e.substring(0,u).trim(),t),right:K(e.substring(u+l.length).trim(),t)}}let i=-1,s=null,a=[{op:" + ",type:R.ADD},{op:" - ",type:R.SUBTRACT}];for(let{op:l,type:f}of a){let u=0;for(;u<e.length;){let d=Re(e.substring(u),l);if(d===-1)break;let p=u+d;p>i&&(i=p,s={op:l,type:f}),u=p+l.length}}if(i!==-1&&s)return{type:m.BINARY,op:s.type,left:K(e.substring(0,i).trim(),t),right:K(e.substring(i+s.op.length).trim(),t)};let c=[" * "," / "," % "];for(let l of c)if(Re(e,l)!==-1)throw new v(`Arithmetic operations are not allowed in conditionals: "${l}"`);return e.startsWith("!")?{type:m.UNARY,op:Ve.NOT,operand:K(e.substring(1).trim(),t)}:Cn(e,t)},Re=(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},qi=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}},Cn=(e,t)=>{let r=e.trim();if(r.match(/^(\w+)\((.*)\)$/))return Je(r,t);let o=qi(r);if(o.type===m.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(r))return{type:m.VARIABLE,path:r};try{return Je(r,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},Yi=(e,t=!1)=>{let r=t?"$each":"$for";try{fn(e)}catch(n){if(n instanceof v&&t){let o=n.message.replace(/\$for/g,"$each");throw new v(o.replace("Parse Error: ",""))}throw n}},En=(e,t,r,n=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let y=n?"$each":"$for";throw new v(`Invalid loop syntax (got: '${e.replace("$for",y)}')`)}let s=i[1],a=i[2].trim();Yi(a,n);let c=a.match(/^(.+?)\s+in\s+(.+)$/);if(!c){let y=n?"$each":"$for";throw new v(`Invalid loop syntax - missing 'in' keyword (got: '${y} ${a}')`)}let l=c[1].trim(),f=c[2].trim(),u,d=null;if(l.includes(",")){let y=l.split(",").map(I=>I.trim());if(y.length!==2)throw new v(`Invalid loop variables: ${l}. Expected format: "item" or "item, index"`);u=y[0],d=y[1]}else u=l;let p=["this","undefined","null","true","false"];if(p.includes(u))throw new v(`Reserved variable name: ${u}`);if(d&&p.includes(d))throw new v(`Reserved variable name: ${d}`);let h=Cn(f,r),g=Ie(t,r);return{type:m.LOOP,itemVar:u,indexVar:d,iterable:h,body:g,flatten:s!=="nested"}};var Ki=(e,t={})=>{let{functions:r={}}=t;return Ie(e,r)},It=Ki;var Ge={};ii(Ge,{now:()=>Hi});var Hi=()=>Date.now();var Ji=(e,t,r={})=>{let{functions:n={},partials:o={}}=r,i={...Ge,...n},s=It(e,{functions:i}),a={};for(let[c,l]of Object.entries(o))a[c]=It(l,{functions:i});return er(s,t,{functions:i,partials:a})},Z=Ji;var Gi=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",Xi=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,Qi=(e,t)=>{if(Gi(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new v("Empty condition expression");return K(e,t)}return fe(e,t)},Zi=(e,t={},r={})=>{let n=Xi(r),o={...Ge,...n},i=Qi(e,o);return!!ye(i,{functions:o,partials:{}},t,{})},Oe=Zi;var _n=(e,t,r={})=>{let n=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=c=>c,transformActionFirstArgument:a=c=>c}=r;for(let[c,l]of Object.entries(t))c!=="createInitialState"&&(c.startsWith("select")?o[c]=(...f)=>l(s(n),...f):i[c]=(...f)=>{let u;return n=Qt(n,p=>{let h=l(a(p),...f);u=h!==void 0&&!te(h)?h:void 0}),u});return{...o,...i}},wt=(e,t)=>r=>{let n=e(),o=Array.isArray(r)?r:[r];return Qt(n,i=>{o.forEach(s=>{t.forEach(a=>{a(i,s)})})})};var es=(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{}}},ae=(e,t)=>Object.prototype.hasOwnProperty.call(e??{},t),Xe=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),$n=e=>{let t=te(e)?$e(e):e;return structuredClone(t)},Ae=e=>ae(e,"computed"),je=(e={},t={})=>Object.fromEntries(Object.entries(e??{}).filter(([r])=>!Ae(t[r]))),ts=e=>String(e).replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean),ir=(e,t)=>{let r=e;for(let n of t){if(r==null)return;r=r[n]}return r},rs=(e,t={})=>{if(typeof e!="string"||e.trim()==="")throw new Error("Computed expression var requires a non-empty string path");let r=ts(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 ir(s,i)}return n==="runtime"?ir(t.runtime,r.slice(1)):ir(t,r)},ns=(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)`)},Sn=(e,t)=>{if(!Array.isArray(t))throw new Error(`Computed expression operator "${e}" requires an array`);if(t.length===0)throw new Error(`Computed expression operator "${e}" requires at least one operand`)},os=(e,t)=>{if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Computed expression operator "${e}" requires finite numeric operands`)},se=(e,t,r,n)=>(ns(e,t,n),t.map(o=>At(o,r))),oe=(e,t,r,n)=>{let o=se(e,t,r,n);return o.forEach(i=>os(e,i)),o},is=(e,t,r)=>{switch(e){case"var":return rs(t,r);case"add":{let[n,o]=oe(e,t,r,2);return n+o}case"sub":{let[n,o]=oe(e,t,r,2);return n-o}case"mul":{let[n,o]=oe(e,t,r,2);return n*o}case"div":{let[n,o]=oe(e,t,r,2);return n/o}case"mod":{let[n,o]=oe(e,t,r,2);return n%o}case"neg":{let[n]=oe(e,t,r,1);return-n}case"round":{let[n]=oe(e,t,r,1);return Math.round(n)}case"floor":{let[n]=oe(e,t,r,1);return Math.floor(n)}case"ceil":{let[n]=oe(e,t,r,1);return Math.ceil(n)}case"min":{let[n,o]=oe(e,t,r,2);return Math.min(n,o)}case"max":{let[n,o]=oe(e,t,r,2);return Math.max(n,o)}case"clamp":{let[n,o,i]=oe(e,t,r,3);return Math.min(i,Math.max(o,n))}case"eq":{let[n,o]=se(e,t,r,2);return n==o}case"neq":{let[n,o]=se(e,t,r,2);return n!=o}case"gt":{let[n,o]=se(e,t,r,2);return n>o}case"gte":{let[n,o]=se(e,t,r,2);return n>=o}case"lt":{let[n,o]=se(e,t,r,2);return n<o}case"lte":{let[n,o]=se(e,t,r,2);return n<=o}case"in":{let[n,o]=se(e,t,r,2);return Array.isArray(o)?o.includes(n):!1}case"and":case"all":return Sn(e,t),t.every(n=>!!At(n,r));case"or":case"any":return Sn(e,t),t.some(n=>!!At(n,r));case"not":{let[n]=se(e,t,r,1);return!n}case"length":{let[n]=se(e,t,r,1);return typeof n=="string"||Array.isArray(n)?n.length:Xe(n)?Object.keys(n).length:0}case"includes":{let[n,o]=se(e,t,r,2);return typeof n=="string"||Array.isArray(n)?n.includes(o):!1}case"literal":return $n(t);default:throw new Error(`Unknown computed expression operator: ${e}`)}},At=(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 is(n,o,t)},ss=(e,t={})=>Oe(e,{variables:t.variables,runtime:t.runtime}),as=(e,t)=>{if(!Xe(e))throw new Error(`${t} must be an object`);let r=ae(e,"expr"),n=ae(e,"value");if(r===n)throw new Error(`${t} must contain exactly one of expr or value`)},sr=(e,t,r)=>(as(e,t),ae(e,"value")?$n(e.value):At(e.expr,r)),cs=(e,t={},r="unknown")=>{if(!Xe(e))throw new Error(`Computed variable "${r}" computed must be an object`);let n=ae(e,"expr"),o=ae(e,"value");if(ae(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(!Xe(e.default))throw new Error(`Computed variable "${r}" requires default`);for(let s=0;s<e.branches.length;s+=1){let a=e.branches[s];if(!Xe(a))throw new Error(`Computed variable "${r}" branch ${s} must be an object`);if(!ae(a,"when"))throw new Error(`Computed variable "${r}" branch ${s} requires when`);if(ss(a.when,t))return sr(a,`Computed variable "${r}" branch ${s}`,t)}return sr(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 sr(e,`Computed variable "${r}"`,t)},ls=(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}`)}},vt=({variables:e={},runtime:t={},variableConfigs:r={},eager:n=!0}={})=>{let o=je(e,r),i=Object.entries(r).filter(([,u])=>Ae(u)).map(([u])=>u),s={},a=[],c=u=>{if(ae(s,u))return s[u];let d=r[u];if(!Ae(d))return o[u];let p=a.indexOf(u);if(p>=0){let h=[...a.slice(p),u].join(" -> ");throw new Error(`Computed variable cycle detected: ${h}`)}a.push(u);try{let h=cs(d.computed,f,u);return ls(u,d.type,h),s[u]=h,h}finally{a.pop()}},l=new Proxy({},{get:(u,d)=>{if(typeof d=="string")return c(d)},has:(u,d)=>typeof d=="string"&&(ae(o,d)||i.includes(d)),ownKeys:()=>[...new Set([...Object.keys(o),...i])],getOwnPropertyDescriptor:(u,d)=>{if(!(typeof d!="string"||!ae(o,d)&&!i.includes(d)))return{enumerable:!0,configurable:!0}}}),f={variables:l,runtime:t,resolveVariable:c};return n?(i.forEach(u=>{c(u)}),{...o,...s}):l},us=({variables:e={},runtime:t={},variableConfigs:r,projectData:n}={})=>vt({variables:e,runtime:t,variableConfigs:r??n?.resources?.variables??{},eager:!0}),lr=e=>{let t={},r={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([n,o])=>{if(Ae(o))return;let i=es(o,n);o.scope==="context"?t[n]=i:r[n]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:r}},Et=(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(", ")}`)},xt=(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(", ")}`)},Ct=(e,t,r)=>{switch(t){case"set":return r;case"multiply":return(e??1)*r;case"divide":return(e??0)/r;case"increment":return(e??0)+(r??1);case"decrement":return(e??0)-(r??1);case"toggle":return!e;default:throw new Error(`Unknown operation: ${t}`)}};var Rn=(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 a=i.character?.sprite;return a&&Object.keys(a).length>0&&(s.sprite=a),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},ur=(e={},t={})=>{let r={},n=["sfx","voice"],o=s=>{let a=e[s],c=t[s];c&&!a?r[s]={changeType:"add",data:c}:a&&!c?n.includes(s)||(r[s]={changeType:"delete",data:a}):a&&c&&JSON.stringify(a)!==JSON.stringify(c)&&(r[s]={changeType:"update",data:c})};o("background"),o("bgm"),o("voice");let i=fs(e.dialogue,t.dialogue);return i&&(r.dialogue=i),o("choice"),o("form"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),r},fr=(e={})=>{let t=structuredClone(e);t.background&&(t.background.animations?.playback?.continuity!=="persistent"&&delete t.background.animations,t.background.resourceId||delete t.background);let r=o=>{t[o]&&(delete t[o].animations,Object.keys(t[o]).length===0&&delete t[o])};r("layout"),r("choice"),r("form"),t.dialogue?.ui&&(delete t.dialogue.ui.animations,Object.keys(t.dialogue.ui).length===0&&delete t.dialogue.ui,Object.keys(t.dialogue).length===0&&delete t.dialogue),t.dialogue?.character?.sprite&&(delete t.dialogue.character.sprite.animations,Object.keys(t.dialogue.character.sprite).length===0&&delete t.dialogue.character.sprite,Object.keys(t.dialogue.character).length===0&&delete t.dialogue.character,Object.keys(t.dialogue).length===0&&delete t.dialogue);let n=(o,i)=>{let s=t[o]?.items;Array.isArray(s)&&(t[o].items=s.map(a=>{let c={...a};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},ds=(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},ps=(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=ds(t,r);if(n===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return n},hs={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"])},On=(e,t)=>{let r=e[e.length-1];return r?hs[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,On(r,n)?o:ar(o,t,[...r,n])])):ps(e,t),cr=(e,t,r=[])=>Array.isArray(e)?e.map(n=>cr(n,t,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,On(r,n)?o:cr(o,t,[...r,n])])):typeof e=="string"?Z(e,t):e,dr=(e,t)=>{if(!t)return e;if(Object.prototype.hasOwnProperty.call(t,"event"))throw new Error('Action template context key "event" is no longer supported. Use "_event".');let r=ar(e,t._event);return cr(r,t)};var de=e=>structuredClone(te(e)?$e(e):e),Qe=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:de(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},Pn=(e,t)=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let r=e.map(n=>de(n)).filter(n=>t(n)||n.animations);return{hasValidItems:r.length>0,processedItems:r}},Me=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Ln=e=>e?.animations?.playback?.continuity==="persistent",ms=e=>{if(e){if(e.character&&Me(e.character,"name"))return e.character.name;if(Me(e,"characterName"))return e.characterName}},Tn=e=>!!e?.character&&Me(e.character,"sprite"),gs=e=>{let t={},r=!1,n=ms(e);return n!==void 0&&(t.name=n,r=!0),Tn(e)&&(t.sprite=de(e.character.sprite),r=!0),r?t:void 0},kn=e=>{e?.character?.sprite?.animations&&(e.character.sprite.animations={})},ys=({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=>de(o)):delete e.initialRevealedContent,e.content=[...n,...t]},bs=()=>({}),Is=(e,t)=>{if(t.background){let{animationsOnly:r,state:n}=Qe(t.background,s=>!!s.resourceId);if(r){e.background=e.background?.resourceId?{...de(e.background),...n}:n;return}if(!t.background.resourceId){delete e.background;return}let o=de(t.background),i=e.background;i?.resourceId===o.resourceId&&i?.transformId===o.transformId&&!Me(o,"animations")&&Ln(i)&&(o.animations=de(i.animations)),e.background=o}else e.background?.animations&&!Ln(e.background)&&(e.background.animations={})},As=(e,t)=>{if(!t.dialogue){e.dialogue&&(kn(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:l,state:f}=Qe(t.dialogue.ui,u=>!!u.resourceId);l?e.dialogue.ui={...e.dialogue.ui,...f}:e.dialogue.ui={...t.dialogue.ui}}else e.dialogue?.ui?.animations&&(e.dialogue.ui.animations={});t.dialogue.mode==="adv"&&(e.dialogue.content=e.dialogue.content||void 0,e.dialogue.characterId=e.dialogue.characterId||void 0,e.dialogue.mode="adv"),t.dialogue.mode==="nvl"&&(e.dialogue?.mode!=="nvl"&&(e.dialogue.lines=[]),e.dialogue.mode="nvl");let n=t.dialogue.append===!0&&r!=="nvl"&&e.dialogue?.mode!=="nvl"&&Array.isArray(t.dialogue.content);t.dialogue.content!==void 0&&ys({dialogueState:e.dialogue,content:t.dialogue.content,append:n});let o=Me(t.dialogue,"persistCharacter")?t.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;o?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let i=Me(t.dialogue,"characterId"),s=gs(t.dialogue),a=s!==void 0,c=Tn(t.dialogue);if(i?t.dialogue.characterId?e.dialogue.characterId=t.dialogue.characterId:delete e.dialogue.characterId:!o&&!n&&delete e.dialogue.characterId,a?e.dialogue.character=!i&&o&&e.dialogue.character?{...de(e.dialogue.character),...s}:s:(i||!o&&!n)&&delete e.dialogue.character,c||kn(e.dialogue),t.dialogue.clear){delete e.dialogue;return}if(t.dialogue?.clearPage&&e.dialogue?.mode==="nvl"&&(e.dialogue.lines=[]),e.dialogue?.mode==="nvl"&&t.dialogue.content!==void 0){let l={content:t.dialogue.content,characterId:e.dialogue.characterId??null};e.dialogue.character&&(l.character=de(e.dialogue.character)),e.dialogue.lines.push(l)}},ws=(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},vs=(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}}},Es=(e,t)=>{if(t.visual){let{hasValidItems:r,processedItems:n}=Pn(t.visual.items,o=>!!o.resourceId);r?e.visual={items:n}:delete e.visual}else e.visual?.items&&(e.visual.items=e.visual.items.map(r=>r.animations?{...r,animations:{}}:r))},xs=(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}=Pn(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId);r?e.character={items:n}:delete e.character},Cs=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},Ss=(e,t)=>{if(t.layout){let{animationsOnly:r,state:n}=Qe(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},_s=(e,t)=>{if(t.choice){let{animationsOnly:r,state:n}=Qe(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},$s=(e,t)=>{if(t.form){let{animationsOnly:r,state:n}=Qe(t.form,o=>!!o.resourceId);if(r){e.form={...e.form,...n};return}if(!t.form.resourceId){delete e.form;return}e.form=de(t.form)}else e.form&&delete e.form},Rs=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},Os=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},Ls=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(r=>{delete e[r]})},Le=e=>wt(bs,[Ls,Is,ws,vs,Es,As,xs,Cs,Ss,_s,$s,Rs,Os])(e);var we={objectValues:e=>Object.entries(e).map(([t,r])=>({id:t,...r})),formatDate:Rn},ks=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,Ps=(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},$t=(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),a=ks.exec(s);if(a){let[,c,l,f]=a,u=Ps(t,f);if(!Array.isArray(u))continue;let d=Array.isArray(i[s])?i[s]:[];u.forEach((p,h)=>{let g={...t,[c]:p};l&&(g[l]=h),d.forEach(y=>{let I=$t(y,g,r),w=Z(I,g,r);Array.isArray(w)?o.push(...w):o.push(w)})});continue}}o.push($t(i,t,r))}return o}if(!e||typeof e!="object")return e;let n={};return Object.entries(e).forEach(([o,i])=>{n[o]=$t(i,t,r)}),n},_r=({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".`)},Ts=({id:e,targetId:t,animation:r,playback:n,animationPath:o="animation"})=>{let i=structuredClone(r);return _r({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},Ds=(e,{animationId:t="animation",animationPath:r="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return _r({animationType:e.type,animationId:t,animationPath:r}),e.type},Ns=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},Vs=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},js=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Yn=e=>e?.playback?.continuity==="persistent",br=e=>Array.isArray(e)?e.map(br):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((t,r)=>(t[r]=br(e[r]),t),{}),Rt=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let t=structuredClone(e);return delete t.playback,JSON.stringify(br(t))},Kn=(e=[])=>e.filter(t=>Yn(t)).map(t=>structuredClone(t)),Hn=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,pr=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((t,r)=>Math.max(t,Hn(r)),0),Jn=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max(pr(e.tween),pr(e.prev?.tween),pr(e.next?.tween),Hn(e.mask?.progress)),Dn=({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(Rt).filter(Boolean));return e.some(n=>{if(!Yn(n))return!1;let o=Rt(n);return o?r.has(o):!1})},pe=({animationInstances:e,isLineCompleted:t,skipTransitionsAndAnimations:r,activePersistentAnimations:n,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||r?!1:i&&!t||Dn({animationInstances:e,activePersistentAnimations:n})?!0:i?!1:Dn({animationInstances:e,activePersistentAnimations:o}),Ms=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),Fs=(e,t)=>{if(Ms(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},Us=({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?Ts({id:n,targetId:o,animation:s,playback:r,animationPath:i}):null},Bs=({hasPrevious:e,hasCurrent:t,previousResourceId:r,currentResourceId:n,sharedTarget:o})=>!e&&t?"enter":e&&!t?"exit":e&&t?r===n&&o?"update":"replace":"none",zs=({animationType:e,animationId:t,animationPath:r,lifecycle:n})=>{if(!(e!=="update"||n==="update"))throw new Error(`[${r}] Animation "${t}" has type "update", but update animations can only be used when the same target persists across the state change. Use type "transition" for enter, exit, and replace.`)},Ws=(e,{defaultTargetId:t,defaultId:r,animationPath:n="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return _r({animationType:o.type,animationId:o.id??r,animationPath:n}),o.id??=r,o.targetId??=t,o},$r=({animations:e,transitions:t,defaultTargetId:r,idPrefix:n,animationPathPrefix:o=n})=>{t.forEach((i,s)=>{e.push(Ws(i,{defaultTargetId:r,defaultId:`${n}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},Ir=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let r=Z(e,t);return r&&typeof r=="object"?e:r},Ar=(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},qs=({content:e,path:t,variables:r})=>Ar(e,t).reduce((n,o)=>{let i=Ir(o.text,{variables:r});return n+`${i??""}`.length},0),Nn=(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))},St=(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("-")}`},hr=(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},Ys=(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},Vn=(e={},t)=>{if(t){if(e.images?.[t])return"sprite";if(e.videos?.[t])return"video";if(e.layouts?.[t])return"container"}},_t=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},Ks=(e={})=>e.textStyles||{},Hs=(e={})=>e.images||{},Js=(e={})=>e.colors||{},Gs=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,Ze=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,Ue=(e,t,r)=>{if(typeof e!="string"||e.length===0)throw new Error(`${r} at "${t}" must resolve to a non-empty string`)},jn=(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},Gn=(e,t)=>{if(typeof e!="string"||!Gs.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},Mn=(e,t,r)=>{let n=Gn(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})`},Xs=(e={},t)=>{let r=Ks(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=jn(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:Mn(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 a=e.colors?.[r.strokeColorId];if(!a)throw new Error(`Stroke color "${r.strokeColorId}" not found for text style "${t}"`);let c=jn(r.strokeAlpha,"strokeAlpha",t);s.strokeColor=Mn(a.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},wr=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>wr(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]=wr(i,t,Ze(r,o)));return e.textStyleId!==void 0&&(Ue(e.textStyleId,r,"textStyleId"),n.textStyle=Xs(t,e.textStyleId)),n},Xn=(e={},t)=>{let r=Js(e)?.[t];if(!r)throw new Error(`Color "${t}" not found`);return Gn(r.hex,`Color "${t}"`)},Qn=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",mr=(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 ${Qn(`${t}.fill`)} instead`)},Qs=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>et(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]=et(i,t,Ze(r,o)));return e.colorId!==void 0&&(Ue(e.colorId,r,"colorId"),n.fill=Xn(t,e.colorId)),n},et=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>et(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 ${Qn("fill")} instead`);mr(e,"hover",r),mr(e,"click",r),mr(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]=Qs(i,t,Ze(r,o));continue}n[o]=et(i,t,Ze(r,o))}return e.type==="rect"&&e.colorId!==void 0&&(Ue(e.colorId,r,"colorId"),n.fill=Xn(t,e.colorId)),n},gr=(e={},t)=>{let r=Hs(e)?.[t];return r||null},Zn=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",Fn=(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 ${Zn(`${t}.${n}`)} instead`)},Un=(e,t,r)=>{let n=e[t];e[t]={...n&&typeof n=="object"&&!Array.isArray(n)?n:{},src:r}},vr=(e,t={},r="root")=>{if(Array.isArray(e))return e.map((o,i)=>vr(o,t,`${r}[${i}]`));if(!e||typeof e!="object")return e;if(e.type==="sprite"){for(let o of["url","src","hoverUrl","hoverSrc","clickUrl","clickSrc"])if(Object.prototype.hasOwnProperty.call(e,o))throw new Error(`Inline ${o} is not allowed in sprite layout elements at "${r}". Use ${Zn(o)} instead`);Fn(e,"hover",r,"src"),Fn(e,"click",r,"src")}let n={};for(let[o,i]of Object.entries(e))e.type==="sprite"&&(o==="imageId"||o==="hoverImageId"||o==="clickImageId")||(n[o]=vr(i,t,Ze(r,o)));if(e.type==="sprite"&&e.imageId!==void 0){Ue(e.imageId,r,"imageId");let o=gr(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&&(Ue(e.hoverImageId,r,"hoverImageId"),Un(n,"hover",gr(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(Ue(e.clickImageId,r,"clickImageId"),Un(n,"click",gr(t,e.clickImageId)?.fileId??e.clickImageId)),n},Rr=(e,t={},r="root")=>vr(et(wr(e,t,r),t,r),t,r),ve=Rr,Be=(e=[])=>e.find(t=>t.id==="story");var Zs=(e={})=>e?.muteAll?0:e?.musicVolume??50,ce=({variables:e,runtime:t,saveSlots:r=[],dialogueState:n,includeInactiveAdvDialogue:o=!1,isLineCompleted:i,autoMode:s,skipMode:a,isChoiceVisible:c,isFormVisible:l,canRollback:f,confirmDialog:u,form:d,historyDialogue:p=[],characters:h={},dialogueUIHidden:g,skipOnlyViewedLines:y,skipTransitionsAndAnimations:I}={})=>{let w={dialogueTextSpeed:t?.dialogueTextSpeed??50,autoForwardDelay:t?.autoForwardDelay??1e3,skipUnseenText:t?.skipUnseenText??!1,skipTransitionsAndAnimations:t?.skipTransitionsAndAnimations??!1,soundVolume:t?.soundVolume??50,musicVolume:t?.musicVolume??50,muteAll:t?.muteAll??!1,saveLoadPagination:t?.saveLoadPagination??1,menuPage:t?.menuPage??"",menuEntryPoint:t?.menuEntryPoint??"",autoMode:t?.autoMode??s??!1,skipMode:t?.skipMode??a??!1,dialogueUIHidden:t?.dialogueUIHidden??g??!1,isLineCompleted:t?.isLineCompleted??i??!1},x=oa({dialogueState:n,includeInactiveAdvDialogue:o,characters:h,variables:e}),b={variables:e,runtime:w,saveSlots:r,isChoiceVisible:c,isFormVisible:l,canRollback:f,confirmDialog:u,form:d,historyDialogue:p,characters:h};return x&&(b.dialogue=x,b.dialogueLines=x.lines),b},Bn=100,Ot=(e,t)=>{if(Array.isArray(e))return e.map(n=>Ot(n,t));if(!e||typeof e!="object")return e;let r={...e};return Object.keys(r).forEach(n=>{r[n]=Ot(r[n],t)}),r.type==="text-revealing"?t(r):r},ea=e=>Ot(e,t=>({...t,revealEffect:"none"})),ta=e=>Ot(e,t=>{let r=Number(t.speed??t.displaySpeed),n=Number.isFinite(r)?Math.max(r,Bn):Bn;return{...t,speed:n,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:n}:{}}}),Ee=(e,{isLineCompleted:t=!1,skipMode:r=!1,skipTransitionsAndAnimations:n=!1}={})=>t||n?ea(e):r?ta(e):e,eo=({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:{}}}}),Er=e=>{if(Array.isArray(e))return e.map(Er);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=Er(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,_interactionSource:"choice"}:void 0;return{...t,click:{...t.click,payload:{...r,_interactionSource:"choice",...o?{actions:{...n,nextLine:o}}:{}}}}},ra=new Set(["click","change","submit","focusEvent","blurEvent","selectionChange","compositionStart","compositionUpdate","compositionEnd"]),zn=(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}}}},xr=(e,t)=>{if(Array.isArray(e))return e.map(i=>xr(i,t));if(!e||typeof e!="object")return e;let r={};for(let[i,s]of Object.entries(e))r[i]=xr(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:zn(r.change,o),submit:zn(r.submit,t.submitActions)}},Cr=(e,t)=>{if(Array.isArray(e))return e.map(n=>Cr(n,t));if(!e||typeof e!="object")return e;let r={};for(let[n,o]of Object.entries(e))r[n]=Cr(o,t);for(let n of ra){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},Sr=({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}},to=(e=[],t={})=>e.map(r=>{let n=Sr({characterId:r.characterId,character:r.character,characterName:r.characterName,characters:t}),o=typeof r.text=="string"?r.text:Array.isArray(r.content)?r.content.map(i=>i?.text??"").join(""):"";return{...r,text:o,character:n,characterName:n.name}}),na=e=>!(!e||e.mode==="adv"&&e.content===void 0),oa=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:r={},variables:n}={})=>{if(!t&&!na(e))return;let o=e.content===void 0?[{text:""}]:Ar(e.content,"dialogue.content"),i=e.content===void 0?0:qs({content:e.initialRevealedContent,path:"dialogue.initialRevealedContent",variables:n}),s=(e.lines||[]).map((c,l)=>{let f=Ar(c.content,`dialogue.lines[${l}].content`),u=Sr({characterId:c.characterId,character:c.character,characterName:c.characterName,characters:r});return{...c,content:f.map(d=>({...d,text:Ir(d.text,{variables:n})})),character:u,characterName:u.name}}),a=Sr({characterId:e.characterId,character:e.character,characters:r});return{characterId:e.characterId,persistCharacter:e.persistCharacter,character:a,content:o.map(c=>({...c,text:Ir(c.text,{variables:n})})),initialRevealedCharacters:i,lines:s}},ro=({container:e,resources:t,templateData:r,isLineCompleted:n=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=Z(e,r,{functions:we});return ve(Ee(s,{isLineCompleted:n,skipMode:o,skipTransitionsAndAnimations:i}),t)},yr=(e,t={})=>e?.payload&&typeof e.payload=="object"?structuredClone(e.payload):e?.actions&&typeof e.actions=="object"?{actions:structuredClone(e.actions)}:structuredClone(t),Wn=({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:yr(s)}},o?.keyup&&typeof o.keyup=="object"&&(e[n].keyup={payload:yr(o.keyup)});return}e[n]={...i,[r]:{payload:yr(o)}}})},ia=(e={},t={})=>{let r={};return Wn({renderStateKeyboard:r,keyboard:e,phase:"keydown"}),Wn({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:a,allowIncomingUpdateFallback:c=!1})=>{if(!e)return[];let l=[],f=({instanceId:b,targetId:O})=>{let L=Us({resources:t,animationId:g,playback:y,instanceId:b,targetId:O,animationPath:s});L&&l.push(L)},u=r!=null&&r!==!1,d=n!=null&&n!==!1,p=o&&i&&o===i,h=Bs({hasPrevious:u,hasCurrent:d,previousResourceId:r,currentResourceId:n,sharedTarget:p});Fs(e,s);let g=Ns(e),y=Vs(e),I=t?.animations?.[g],w=Ds(I,{animationId:g,animationPath:s}),x=c&&w==="update"&&h!=="update"&&d&&i;if(x||zs({animationType:w,animationId:g,animationPath:s,lifecycle:h}),w==="update")return u&&d&&r===n&&p?f({instanceId:`${a}-animation-update`,targetId:i}):x&&f({instanceId:`${a}-animation-update`,targetId:i}),l;if(w==="transition"){let b=`${a}-animation-transition`,O=y?.continuity==="persistent"?b:`${a}-animation-in`;if(u&&d&&p)return f({instanceId:b,targetId:i}),l;u&&f({instanceId:`${a}-animation-out`,targetId:o}),d&&f({instanceId:O,targetId:i})}return l},sa=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),aa=(e,{presentationState:t,previousPresentationState:r,currentLineActions:n,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:a,variables:c,runtime:l,activePersistentAnimations:f,restoredPersistentAnimations:u,autoMode:d,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:I,saveSlots:w=[]})=>{let{elements:x,animations:b}=e;if(t.background){let O=n===void 0?!0:js(n?.background??{},"animations"),L=x.find(B=>B.id==="story");if(!L)return e;let V=Ys(o,t.background),D=r?.background?.resourceId,_=t.background.resourceId??(t.background.animations?D:void 0),U=Vn(o,D),M=Vn(o,_);if(_){let{images:B={},videos:E={}}=o,S=B[_]||E[_];if(S){let j=E[_]!==void 0,W={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...V},H={id:_t({resourceId:_,kind:j?"video":"sprite"}),type:j?"video":"sprite",x:W.x,y:W.y,src:S.fileId,width:S.width,height:S.height,alpha:1,anchorX:W.anchorX,anchorY:W.anchorY,rotation:W.rotation,scaleX:W.scaleX,scaleY:W.scaleY};j&&(H.loop=t.background.loop??!1,H.volume=S.volume??50),L.children.push(H)}}if(_){let{layouts:B={}}=o,E=B[_];if(E){let S={id:_t({resourceId:_,kind:"container"}),type:"container",children:E.elements};V&&Object.assign(S,{x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...V});let j=Z(S,ce({variables:c,runtime:l,saveSlots:w,dialogueState:t.dialogue,isLineCompleted:s,autoMode:d,skipMode:p,isChoiceVisible:h,isFormVisible:g,canRollback:y,form:I,characters:o.characters||{},skipTransitionsAndAnimations:a}),{functions:we});L.children.push(ve(Ee(j,{isLineCompleted:s,skipMode:p,skipTransitionsAndAnimations:a}),o))}}let P=xe({animationsDef:t.background.animations,resources:o,previousResourceId:D,currentResourceId:_,previousTargetId:_t({resourceId:D,kind:U}),currentTargetId:_t({resourceId:_,kind:M}),animationPath:"background.animations",idPrefix:"bg-cg",allowIncomingUpdateFallback:!0});pe({animationInstances:P,isLineCompleted:s,skipTransitionsAndAnimations:a,activePersistentAnimations:f,restoredPersistentAnimations:u,isAuthoredOnCurrentLine:O})&&b.push(...P)}return e},ca=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:a,animations:c}=e;if(t.character&&n){let l=a.find(h=>h.id==="story");if(!l)return e;let f=t.character.items||[],u=r?.character?.items||[],d=Nn(f),p=Nn(u);for(let h=0;h<f.length;h++){let g=f[h],{transformId:y,sprites:I}=g,w=u.find(M=>M.id===g.id),x=u.findIndex(M=>M.id===g.id),b=w?.sprites&&w.sprites.length>0,O=I&&I.length>0,L=x>=0?St(w,x,p):void 0,V=xe({animationsDef:g.animations,resources:n,previousResourceId:L,currentResourceId:O?St(g,h,d):void 0,previousTargetId:L,currentTargetId:O?St(g,h,d):void 0,animationPath:`character.items[${h}].animations`,idPrefix:"character"});if(g.animations&&!I&&!y&&b&&pe({animationInstances:V,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){c.push(...V);continue}if(g.animations&&!I&&!y)continue;if(!I||I.length===0||!y){console.warn("Character item missing sprites or transformId:",g);continue}let D=St(g,h,d),_=n.transforms[y];if(!_){console.warn("Transform not found:",y);continue}let U={type:"container",id:D,x:g.x??_.x,y:g.y??_.y,anchorX:_.anchorX,anchorY:_.anchorY,rotation:_.rotation,scaleX:_.scaleX,scaleY:_.scaleY,children:[]};for(let M of I){let P=n.images[M.resourceId];if(!P){console.warn(`Image resource not found: ${M.resourceId}`);continue}U.children.push({type:"sprite",id:`${D}-${M.id}`,src:P.fileId,width:P.width,height:P.height,x:0,y:0})}l.children.push(U),pe({animationInstances:V,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...V)}}return e},la=(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,runtime:a,activePersistentAnimations:c,autoMode:l,skipMode:f,isChoiceVisible:u,isFormVisible:d,canRollback:p,form:h,saveSlots:g=[]})=>{let{elements:y,animations:I}=e;if(t.visual&&n){let w=y.find(b=>b.id==="story");if(!w)return e;let x=t.visual.items;for(let b of x){if(b.resourceId){let{images:D={},videos:_={},spritesheets:U={}}=n,M=U[b.resourceId];if(M){let P=hr(n,b),B=b.animationName;if(B){let E=M.animations?.[B];if(!E)throw new Error(`Animation '${B}' not found in spritesheet resource '${b.resourceId}'`);let S={id:`visual-${b.id}`,type:"animated-sprite",x:b.x??P.x,y:b.y??P.y,width:b.width??M.width,height:b.height??M.height,alpha:b.alpha??1,anchorX:P.anchorX,anchorY:P.anchorY,rotation:P.rotation,scaleX:P.scaleX,scaleY:P.scaleY,spritesheetSrc:M.fileId,spritesheetData:M.jsonData,animation:{frames:E.frames,animationSpeed:b.animationSpeed??E.animationSpeed??.5,loop:b.loop??E.loop??!0}};w.children.push(structuredClone(S))}}else{let P=D[b.resourceId]||_[b.resourceId];if(P){let B=_[b.resourceId]!==void 0,E=hr(n,b),S={id:`visual-${b.id}`,type:B?"video":"sprite",src:P.fileId,width:P.width,height:P.height,x:E.x,y:E.y,anchorX:E.anchorX,anchorY:E.anchorY,rotation:E.rotation,scaleX:E.scaleX,scaleY:E.scaleY};B&&(S.loop=P.loop??!1,S.volume=P.volume??50),w.children.push(S)}}}if(b.resourceId){let{layouts:D={}}=n,_=D[b.resourceId];if(_){let U=hr(n,b),M={id:`visual-${b.id}`,type:"container",children:structuredClone(_.elements),x:U.x,y:U.y,anchorX:U.anchorX,anchorY:U.anchorY,rotation:U.rotation,scaleX:U.scaleX,scaleY:U.scaleY},P=Z(M,ce({variables:s,runtime:a,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:o,autoMode:l,skipMode:f,isChoiceVisible:u,isFormVisible:d,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:i}),{functions:we});w.children.push(ve(Ee(P,{isLineCompleted:o,skipMode:f,skipTransitionsAndAnimations:i}),n))}}let L=(r?.visual?.items||[]).find(D=>D.id===b.id),V=xe({animationsDef:b.animations,resources:n,previousResourceId:L?.resourceId,currentResourceId:b.resourceId,previousTargetId:L?.resourceId?`visual-${b.id}`:void 0,currentTargetId:b.resourceId?`visual-${b.id}`:void 0,animationPath:`visual.items[${b.id}].animations`,idPrefix:b.id});pe({animationInstances:V,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:c})&&I.push(...V)}}return e},Fe="dialogue-character-sprite",qn=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,ua=(e,{presentationState:t,previousPresentationState:r,resources:n={},isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{animations:a}=e,c=Be(e.elements);if(!c)return e;let l=t.dialogue?.character?.sprite,f=r?.dialogue?.character?.sprite,u=qn(l),d=qn(f),p=xe({animationsDef:l?.animations,resources:n,previousResourceId:d?Fe:void 0,currentResourceId:u?Fe:void 0,previousTargetId:d?Fe:void 0,currentTargetId:u?Fe:void 0,animationPath:"dialogue.character.sprite.animations",idPrefix:"dialogue-character-sprite"});if(!u)return l?.animations&&d&&pe({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...p),e;let h=n.transforms?.[l.transformId];if(!h)return console.warn("Transform not found:",l.transformId),e;let g={type:"container",id:Fe,x:h.x,y:h.y,anchorX:h.anchorX,anchorY:h.anchorY,rotation:h.rotation,scaleX:h.scaleX,scaleY:h.scaleY,children:[]};for(let y of l.items){let I=n.images?.[y.resourceId];if(!I){console.warn(`Image resource not found: ${y.resourceId}`);continue}g.children.push({type:"sprite",id:`${Fe}-${y.id}`,src:I.fileId,width:I.width,height:I.height,x:0,y:0})}return c.children.push(g),pe({animationInstances:p,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&a.push(...p),e},fa=(e,{presentationState:t,previousPresentationState:r,resources:n={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:a,isFormVisible:c,canRollback:l,form:f,skipOnlyViewedLines:u,isLineCompleted:d,skipTransitionsAndAnimations:p,variables:h,runtime:g,activePersistentAnimations:y,saveSlots:I=[]})=>{let{elements:w,animations:x}=e;if(!t.dialogue||o)return e;let b=w.find(L=>L.id==="story");if(!b)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:L={}}=n,V=L[t.dialogue.ui.resourceId];if(V){let D={elements:V.elements},_=ce({variables:h,runtime:g,saveSlots:I,dialogueState:t.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:d,autoMode:i,skipMode:s,isChoiceVisible:a,isFormVisible:c,canRollback:l,form:f,characters:n.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:u,skipTransitionsAndAnimations:p}),U={functions:we},M=$t(D,_,U),P=Z(M,_,U),B=ve(Ee(P?.elements,{isLineCompleted:d,skipMode:s,skipTransitionsAndAnimations:p}),n);if(Array.isArray(B))for(let E of B)b.children.push(E);else B&&b.children.push(B)}}ua(e,{presentationState:t,previousPresentationState:r,resources:n,isLineCompleted:d,skipTransitionsAndAnimations:p,activePersistentAnimations:y});let O=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 pe({animationInstances:O,isLineCompleted:d,skipTransitionsAndAnimations:p,activePersistentAnimations:y})&&x.push(...O),e},da=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:a,runtime:c,autoMode:l,skipMode:f,isChoiceVisible:u,isFormVisible:d,canRollback:p,form:h,activePersistentAnimations:g,saveSlots:y=[]})=>{let{elements:I,animations:w}=e;if(t.choice&&n){let x=Be(I);if(!x)return e;let b=n?.layouts[t.choice.resourceId];if(b&&b.elements){let L={elements:b.elements},V=Z(L,{...ce({variables:a,runtime:c,saveSlots:y,dialogueState:t.dialogue,isLineCompleted:i,autoMode:l,skipMode:f,isChoiceVisible:u??!!t.choice,isFormVisible:d,canRollback:p,form:h,characters:n.characters||{},skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}},{functions:we}),D=Er(ve(Ee(V?.elements,{isLineCompleted:i,skipMode:f,skipTransitionsAndAnimations:s}),n));if(Array.isArray(D))for(let _ of D)x.children.push(_);else D&&x.children.push(D)}let O=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"});pe({animationInstances:O,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:g})&&w.push(...O)}return e},pa=(e,{presentationState:t,previousPresentationState:r,resources:n,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:a,runtime:c,autoMode:l,skipMode:f,isChoiceVisible:u,isFormVisible:d,canRollback:p,activePersistentAnimations:h,saveSlots:g=[],form:y})=>{let{elements:I,animations:w}=e;if(!y?.resourceId||!n)return e;let x=Be(I);if(!x)return e;let b=n?.layouts?.[y.resourceId];if(!b)return console.warn(`Form layout not found: ${y.resourceId}`),e;let O={id:"form-container",type:"container",x:0,y:0,children:b.elements||[]},L={...ce({variables:a,runtime:c,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:i,autoMode:l,skipMode:f,isChoiceVisible:u,isFormVisible:d,canRollback:p,characters:n.characters||{},skipTransitionsAndAnimations:s,form:y}),form:y},V=Z(O,L,{functions:we}),D=Cr(ve(Ee(xr(V,y),{isLineCompleted:i,skipMode:f,skipTransitionsAndAnimations:s}),n),y);D&&x.children.push(D);let _=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 pe({animationInstances:_,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:h})&&w.push(..._),e},ha=(e,{presentationState:t,resources:r={},variables:n,runtime:o,isLineCompleted:i,autoMode:s,skipMode:a,isChoiceVisible:c,isFormVisible:l,canRollback:f,form:u,saveSlots:d=[],skipTransitionsAndAnimations:p})=>{if(!t.control?.resourceId)return e;let h=r.controls?.[t.control.resourceId];if(!h)return e;let g=ia(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=Be(e.elements);if(!y)return e;let I={id:`control-${t.control.resourceId}`,type:"container",x:0,y:0,children:h.elements};return y.children.push(ro({container:I,resources:r,templateData:ce({variables:n,runtime:o,saveSlots:d,dialogueState:t.dialogue,isLineCompleted:i,autoMode:s,skipMode:a,isChoiceVisible:c,isFormVisible:l,canRollback:f,form:u,characters:r.characters||{},skipTransitionsAndAnimations:p}),isLineCompleted:i,skipMode:a,skipTransitionsAndAnimations:p})),e},ma=(e,{presentationState:t,resources:r,runtime:n,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&r){if(!Be(i))return e;let c=r.sounds[t.bgm.resourceId];if(!c)return e;let l=ce({variables:o,runtime:n}).runtime;s.push({id:"bgm",type:"sound",src:c.fileId,loop:t.bgm.loop??!0,volume:Zs(l),startDelayMs:t.bgm.startDelayMs??null})}return e},ga=(e,{presentationState:t,resources:r})=>{let{audio:n}=e;if(t.sfx&&r){let o=t.sfx.items;for(let i of o){let s=r.sounds?.[i.resourceId];s&&n.push({id:i.id,type:"sound",src:s.fileId,loop:i.loop??s.loop??!1,volume:i.volume??s.volume??50,startDelayMs:i.startDelayMs??s.startDelayMs??null})}}return e},ya=(e,t,r)=>{if(!(!t||!r))return e?.voices?.[t]?.[r]},ba=(e={},t={})=>t.muteAll?0:e.volume??t.soundVolume??50,Ia=(e,{presentationState:t,resources:r,currentSceneId:n,runtime:o,variables:i})=>{let{audio:s}=e;if(!t?.voice)return e;let a=t.voice,{resourceId:c,loop:l,startDelayMs:f}=a,u=ya(r,n,c);if(!u)return e;let d=ce({variables:i,runtime:o}).runtime;return s.push({id:`voice-${n}-${c}`,type:"sound",src:u.fileId,volume:ba(a,d),loop:l??!1,startDelayMs:f??null}),e},Aa=(e,{presentationState:t,previousPresentationState:r,resources:n={},variables:o,runtime:i,autoMode:s,skipMode:a,isChoiceVisible:c,isFormVisible:l,canRollback:f,form:u,saveSlots:d=[],isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})=>{let{elements:y,animations:I}=e;if(t.layout){let O=Be(y);if(!O)return e;let L=n.layouts[t.layout.resourceId];if(!L)return e;Array.isArray(L.transitions)&&!p&&!h&&$r({animations:I,transitions:L.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let V={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:L.elements||[]};O.children.push(ro({container:V,resources:n,templateData:ce({variables:o,runtime:i,saveSlots:d,dialogueState:t.dialogue,isLineCompleted:p,autoMode:s,skipMode:a,isChoiceVisible:c,isFormVisible:l,canRollback:f,form:u,characters:n.characters||{},skipTransitionsAndAnimations:h}),isLineCompleted:p,skipMode:a,skipTransitionsAndAnimations:h}))}let w=r?.layout?.resourceId,x=t.layout?.resourceId,b=xe({animationsDef:t.layout?.animations,resources:n,previousResourceId:w,currentResourceId:x,previousTargetId:w?`layout-${w}`:void 0,currentTargetId:x?`layout-${x}`:void 0,animationPath:"layout.animations",idPrefix:"layout"});return pe({animationInstances:b,isLineCompleted:p,skipTransitionsAndAnimations:h,activePersistentAnimations:g})&&I.push(...b),e},wa=(e,{presentationState:t,resources:r={},variables:n,runtime:o,autoMode:i,skipMode:s,isChoiceVisible:a,isFormVisible:c,canRollback:l,form:f,overlayStack:u=[],dialogueHistory:d=[],saveSlots:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:I,animations:w}=e;return u&&u.length>0&&u.forEach((x,b)=>{let O=r.layouts[x.resourceId];if(!O){console.warn(`Overlay layout not found: ${x.resourceId}`);return}Array.isArray(O.transitions)&&(y||$r({animations:w,transitions:O.transitions,defaultTargetId:`overlayStack-${b}`,idPrefix:`overlayStack-${b}`,animationPathPrefix:`overlayStack[${b}]`}));let L={id:`overlayStack-${b}`,type:"container",x:0,y:0,children:[eo({id:`overlayStack-${b}-blocker`,screen:h}),...O.elements||[]]},V=to(d,r.characters),D=ce({variables:n,runtime:o,saveSlots:p,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:i,skipMode:s,isChoiceVisible:a,isFormVisible:c,canRollback:l,form:f,historyDialogue:V,characters:r.characters||{},skipTransitionsAndAnimations:y}),_=Z(L,D,{functions:we}),[U,...M]=_.children||[],P=ve(Ee({..._,children:M},{isLineCompleted:g,skipMode:s,skipTransitionsAndAnimations:y}),r);I.push({...P,children:U?[U,...P.children||[]]:P.children})}),e},va=(e,{presentationState:t,resources:r={},variables:n,runtime:o,saveSlots:i=[],autoMode:s,skipMode:a,isChoiceVisible:c,isFormVisible:l,canRollback:f,form:u,confirmDialog:d,dialogueHistory:p=[],screen:h,isLineCompleted:g,skipTransitionsAndAnimations:y})=>{let{elements:I,animations:w}=e;if(!d?.resourceId)return e;let x=r.layouts?.[d.resourceId];if(!x)return console.warn(`ConfirmDialog layout not found: ${d.resourceId}`),e;Array.isArray(x.transitions)&&!y&&$r({animations:w,transitions:x.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let b={id:"confirmDialog",type:"container",x:0,y:0,children:[eo({id:"confirmDialog-blocker",screen:h}),...x.elements||[]]},O=to(p,r.characters),L=Z(b,ce({variables:n,runtime:o,saveSlots:i,dialogueState:t?.dialogue,isLineCompleted:g,autoMode:s,skipMode:a,isChoiceVisible:c,isFormVisible:l,canRollback:f,form:u,confirmDialog:d,historyDialogue:O,characters:r.characters||{},skipTransitionsAndAnimations:y}),{functions:we}),[V,...D]=L.children||[],_=ve(Ee({...L,children:D},{isLineCompleted:g,skipMode:a,skipTransitionsAndAnimations:y}),r);return I.push({..._,children:V?[V,..._.children||[]]:_.children}),e},no=e=>wt(sa,[ha,aa,ca,la,fa,da,pa,Aa,ma,ga,Ia,wa,va])(e);var Ea=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"}}),Lt=Object.freeze({dialogueTextSpeed:50,autoForwardDelay:1e3,skipUnseenText:!1,skipTransitionsAndAnimations:!1,soundVolume:50,musicVolume:50,muteAll:!1,autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isLineCompleted:!1}),tt=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),oo=Object.freeze({dialogueTextSpeed:"number",autoForwardDelay:"number",skipUnseenText:"boolean",skipTransitionsAndAnimations:"boolean",soundVolume:"number",musicVolume:"number",muteAll:"boolean",saveLoadPagination:"number",menuPage:"string",menuEntryPoint:"string",autoMode:"boolean",skipMode:"boolean",dialogueUIHidden:"boolean",isLineCompleted:"boolean"}),Or=Object.freeze(["dialogueTextSpeed","autoForwardDelay","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),Lr=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),xa=(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]}},ze=e=>Object.fromEntries(Object.entries(Ea).map(([t,r])=>{let n=xa(e,r.source),o=n!==void 0?n:Lt[t]??tt[t];return[t,o]})),ge=(e,t)=>ze(e)[t],io=(e={})=>Object.fromEntries(Or.map(t=>[t,e[t]??Lt[t]]));var kt={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},uo=1,fo="choice",po="form",Dt=()=>({manual:{...kt.manual},auto:{...kt.auto},applyMode:kt.applyMode}),kr=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let r=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...Dt()},r&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},N=e=>{let t=te(e)?$e(e):e;return structuredClone(t)},T=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Nt=e=>String(e),ho=()=>({sections:[],resources:[]}),Ca=e=>T(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):ho(),Sa=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",_a=({sectionId:e,lineId:t,content:r,dialogueState:n,characterName:o})=>({sectionId:e,lineId:t,content:r,text:Sa(r),characterId:n.characterId,character:{...n.character||{},name:o},characterName:o}),$a=()=>({resourceId:void 0}),Ra=e=>{if(!T(e))return e;let t={...e};return Object.prototype.hasOwnProperty.call(t,"requireComplete")&&!Object.prototype.hasOwnProperty.call(t,"requireLineCompleted")&&(t.requireLineCompleted=t.requireComplete),delete t.requireComplete,t},Pr=(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}},mo=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 a=r.get(s);if(a!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${a}" and "${n}". Section IDs must be globally unique.`);r.set(s,n)}}},go=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!==uo)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},Oa=(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:go(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete n.slotKey,delete n.date,n},La=(e={})=>Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Oa(t,r)])),bo=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:r})=>Al(r));return t.length>0?t:void 0},ka=e=>{!T(e)||!Array.isArray(e.timeline)||e.timeline.forEach(t=>{if(!T(t))return;let r=bo(t.executedActions);if(r){t.executedActions=r;return}delete t.executedActions})},so=(e,t,r,n="viewedRegistry")=>{let o=t==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[o]:String(e)};if(!T(e))throw new Error(`Malformed ${n}.${t}[${r}] entry.`);if(typeof e[o]!="string"||e[o].length===0)throw new Error(`Malformed ${n}.${t}[${r}] entry: missing ${o}.`);if(t==="sections"){let i={sectionId:e.sectionId};if(e.lastLineId!==void 0&&e.lastLineId!==null&&typeof e.lastLineId!="string")throw new Error(`Malformed ${n}.sections[${r}] entry: invalid lastLineId.`);return typeof e.lastLineId=="string"&&e.lastLineId.length>0&&(i.lastLineId=e.lastLineId),i}return{resourceId:e.resourceId}},Pa=(e,t="viewedRegistry")=>{if(e===void 0)return ho();if(!T(e))throw new Error(`Malformed ${t}.`);if(e.sections!==void 0&&!Array.isArray(e.sections))throw new Error(`Malformed ${t}.sections.`);if(e.resources!==void 0&&!Array.isArray(e.resources))throw new Error(`Malformed ${t}.resources.`);let r=e.sections??[],n=e.resources??[];return{sections:Object.values(Object.fromEntries(r.map((o,i)=>{let s=so(o,"sections",i,t);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(n.map((o,i)=>{let s=so(o,"resources",i,t);return[s.resourceId,s]})))}},Io=(e,t,r)=>{if(!T(e))throw new Error(`Malformed save slot ${r}.`);let{sectionId:n,lineId:o}=e;if(typeof n!="string"||n.length===0)throw new Error(`Malformed save slot ${r}: missing sectionId.`);if(typeof o!="string"||o.length===0)throw new Error(`Malformed save slot ${r}: missing lineId.`);let{sceneId:i,section:s}=Pr(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}},Ta=(e,t,r)=>{if(!T(e)||!Array.isArray(e.timeline))return rt({pointer:t,replayStartIndex:1});let n=e.timeline.flatMap((a,c)=>{if(!T(a))return[];try{let l=Io(a,r,`rollback.timeline[${c}]`),f=Tt({sectionId:l.sectionId,lineId:l.lineId,rollbackPolicy:a.rollbackPolicy}),u=bo(N(a.executedActions));return u&&(f.executedActions=u),[f]}catch{return[]}});if(n.length===0)return rt({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 a=n.findLastIndex(c=>c.sectionId===t.sectionId&&c.lineId===t.lineId);a>=0?o=a:(n.push(Tt({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}},Da=(e,t,r)=>{if(!T(e))throw new Error(`Malformed save slot contexts[${r}] entry.`);let n=Nr(t),o=Io(e.pointers?.read,t,`contexts[${r}].pointers.read`);if(e.variables!==void 0&&!T(e.variables))throw new Error(`Malformed save slot contexts[${r}].variables entry.`);if(e.runtime!==void 0&&!T(e.runtime))throw new Error(`Malformed save slot contexts[${r}].runtime entry.`);let i=e.variables?je(N(e.variables),t.resources?.variables??{}):{},s=Ka({loadedContextRuntime:T(e.runtime)?N(e.runtime):{}}),a={currentPointerMode:"read",pointers:{read:o},configuration:T(e.configuration)?N(e.configuration):{},views:Array.isArray(e.views)?N(e.views):[],bgm:T(e.bgm)?N(e.bgm):{resourceId:void 0},variables:{...n,...i},rollback:Ta(e.rollback,o,t)};return s&&(a.runtime=s),a},Na=(e,t)=>{if(!T(e))throw new Error("Malformed save slot state.");if(!Array.isArray(e.contexts)||e.contexts.length===0)throw new Error("Malformed save slot state: contexts must be a non-empty array.");return{contexts:e.contexts.map((r,n)=>Da(r,t,n))}},Va=(e,t)=>{if(!T(e))throw new Error("Malformed save slot.");let r=yo(e.formatVersion);return{...e,formatVersion:r,state:Na(e.state,t)}},ao=(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=N(e);return Object.prototype.hasOwnProperty.call(n,"hideConfirmDialog")||(n.hideConfirmDialog={}),n},ja=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:ao(e.confirmActions,"confirmActions",{required:!0}),cancelActions:ao(e.cancelActions,"cancelActions")}},We=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},Ma=e=>(T(e.global.formDrafts)||(e.global.formDrafts={}),e.global.formDrafts),qe=e=>{Object.prototype.hasOwnProperty.call(e.global,"formDrafts")&&(e.global.formDrafts={})},Fa=e=>{let t=e?.id??e?.resourceId;return typeof t=="string"&&t.length>0?t:void 0},Ua=(e,t)=>{let r=e?.sectionId,n=e?.lineId;if(!(!r||!n||!t))return`${r}:${n}:${t}`},Pt=e=>String(e??""),Ao=(e,t)=>{let r=Pt(t);return e?.trim===!0?r.trim():r},Ba=e=>T(e?.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,t])=>T(t)).map(([t,r])=>[t,{id:t,...N(r)}])):{},za=(e,t)=>{if(!t||!T(e.global.formDrafts))return;let r=e.global.formDrafts[t];return T(r)?r:void 0},wo=(e,t)=>{let r=Ma(e);T(r[t])||(r[t]={values:{},touched:{},errors:{},submitted:!1});let n=r[t];return T(n.values)||(n.values={}),T(n.touched)||(n.touched={}),T(n.errors)||(n.errors={}),typeof n.submitted!="boolean"&&(n.submitted=!1),n},Tr=(e,t)=>{let r=Ao(e,t);return e?.required===!0&&r.length===0?"required":null},Wa=({state:e,pointer:t})=>{if(!t?.sectionId||!t?.lineId)return{};let n=X({state:e},{sectionId:t.sectionId})?.lines||[],o=n.findIndex(i=>i.id===t.lineId);return o<0?{}:Le(n.slice(0,o+1).map(i=>i.actions||{}))},qa=({state:e,form:t,pointer:r})=>{if(!t?.resourceId)return null;let n=Fa(t),o=Ua(r,n);if(!n||!o)return null;let i=za(e,o),s=Ba(t),a=Ur({state:e}),c={},l=[],f={},u=!0;return Object.entries(s).forEach(([d,p])=>{let h=Pt(a?.[p.variableId]),g=Object.prototype.hasOwnProperty.call(i?.values??{},d)?Pt(i.values[d]):h,y=i?.touched?.[d]===!0,I=Tr(p,g),w=i?.submitted||y?I:null,x=typeof p.maxLength=="number"?Math.max(0,Math.round(p.maxLength)):void 0,b={id:d,variableId:p.variableId,value:g,initialValue:h,valid:!I,error:w,touched:y,required:p.required===!0,trim:p.trim===!0,placeholder:p.placeholder===void 0?"":String(p.placeholder),multiline:p.multiline===!0,...x!==void 0?{maxLength:x}:{}};I&&(u=!1),c[d]=b,l.push(b),f[d]=g}),{id:n,key:o,resourceId:t.resourceId,animations:t.animations,valid:u,submitted:i?.submitted===!0,fields:c,fieldList:l,values:f,submitActions:{submitForm:{formId:n,formKey:o,actions:N(t.submitActions??{})}},cancelActions:{cancelForm:{formId:n,formKey:o,actions:N(t.cancelActions??{})}}}},ke=[],co="line",Dr="interaction",Tt=({sectionId:e,lineId:t,rollbackPolicy:r})=>({sectionId:e,lineId:t,rollbackPolicy:r??"free"}),Nr=e=>{let{contextVariableDefaultValues:t}=lr(e??{});return N(t)},vo=()=>({...N(tt)}),Eo=({loadedRuntime:e,runtimeIds:t,defaults:r={},path:n})=>{if(e===void 0)return{runtimeState:N(r),hasLoadedValues:!1};if(!T(e))throw new Error(`Malformed ${n}.`);let o=N(r),i=!1;return t.forEach(s=>{e[s]!==void 0&&(o[s]=xo(s,N(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},Ya=({loadedGlobalRuntime:e={}})=>Eo({loadedRuntime:e,runtimeIds:Or,defaults:Lt,path:"global.runtime"}).runtimeState,Ka=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:r}=Eo({loadedRuntime:e,runtimeIds:Lr,defaults:vo(),path:"context.runtime"});return r?t:void 0},Vr=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},Ha=e=>e.runtime?(Lr.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=N(tt[t]))}),e.runtime):(e.runtime=vo(),e.runtime),Ja=e=>io(e.global),Ga=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:Ja(e)}})},Xa=e=>oo[e],Qa=(e,t)=>{let r=Xa(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}"`)},xo=(e,t)=>(Qa(e,t),e==="saveLoadPagination"?Math.max(1,Math.trunc(t)):t),Co=(e,t,r)=>{let n=xo(t,r);if(t in tt){let o=Vr(e);if(!o)return n;let i=Ha(o);return i[t]=n,n}return e.global[t]=n,n},So=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:N(e)},configuration:{},views:[],bgm:$a(),variables:Nr(t),rollback:rt({pointer:e})}),Ye=e=>e?(e.currentPointerMode="read",T(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,Za=e=>{let t=e.contexts?.[e.contexts.length-1],r=t?.pointers?.read;if(!t||!r?.sectionId||!r?.lineId)return null;let n=So({pointer:r,projectData:e.projectData});return e.contexts[e.contexts.length-1]=n,ec(e),n},ec=e=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,We(e),qe(e),e.global.nextLineConfig=Dt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})},_o=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},rt=({pointer:e,replayStartIndex:t=0})=>{let r=e?.sectionId&&e?.lineId;return{currentIndex:r?0:-1,isRestoring:!1,replayStartIndex:t,timeline:r?[Tt({sectionId:e.sectionId,lineId:e.lineId})]:[]}},Te=(e,t={})=>{if(e?.rollback)return _o(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=rt({pointer:r,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},jr=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return;let n=Te(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(Tt(t)),n.currentIndex=n.timeline.length-1},tc=e=>{let r=e.contexts?.[e.contexts.length-1]?.rollback;if(!r||r.isRestoring||!Array.isArray(r.timeline)||typeof r.currentIndex!="number")return null;let n=ke[ke.length-1],o=typeof n?.checkpointIndex=="number"?n.checkpointIndex:r.currentIndex;return o<0||o>=r.timeline.length?null:(typeof n?.checkpointIndex!="number"&&o<r.timeline.length-1&&(r.timeline=r.timeline.slice(0,o+1)),r.timeline[o]??null)},rc=({state:e},t={})=>{let r=t?.source===co?co:Dr,o=e.contexts?.[e.contexts.length-1]?.rollback;return!o||o.isRestoring||!Array.isArray(o.timeline)||typeof o.currentIndex!="number"||o.currentIndex<0||o.currentIndex>=o.timeline.length?(ke.push({checkpointIndex:null,source:r}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),ke.push({checkpointIndex:o.currentIndex,source:r}),e)},nc=({state:e})=>(ke.pop(),e),he=(e,t,r)=>{let o=ke[ke.length-1]?.source??Dr;if(!wl(t,o))return;let i=tc(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:N(r)}))},lo=(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}of n){let a=e.projectData.resources?.variables?.[o],c=a?.scope,l=a?.type;if(Ae(a))throw new Error(`Cannot update computed variable: ${o}`);if(a?.readonly===!0)throw new Error(`Cannot update readonly variable: ${o}`);Et(c,o),xt(l,i,o),c==="context"&&(r.variables[o]=Ct(r.variables[o],i,s))}},oc=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:r,payload:n})=>{vl(e,r,n)})},ic=(e,t)=>{let{sectionId:r,lineId:n}=t,s=X({state:e},{sectionId:r})?.lines?.find(a=>a.id===n)?.actions;s&&Object.entries(s).forEach(([a,c])=>{Wo(e,a,c)})},$o=(e,t)=>{let r=e.contexts?.[e.contexts.length-1];if(!r)return e;let n=Te(r),o=n.timeline[t];if(!o)return e;e.global.autoMode&&it({state:e}),e.global.skipMode&&Pe({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),n.isRestoring=!0,n.currentIndex=t;try{r.variables=Nr(e.projectData),delete r.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=N(kt),e.global.overlayStack=[],We(e),qe(e),e.global.isLineCompleted=!0;let i=n.replayStartIndex??0;for(let a=i;a<=t;a++)a>i&&kr(e),ic(e,n.timeline[a]),oc(e,n.timeline[a]);let s=Ye(r);s.read={sectionId:o.sectionId,lineId:o.lineId},e.global.pendingEffects=e.global.pendingEffects.filter(a=>a?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{n.isRestoring=!1}return e},sc=e=>{let{projectData:t}=e,r=e.global??{},{saveSlots:n={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=r;mo(t);let a=t.story.initialSceneId,c=t.story.scenes[a],l=c.initialSectionId,f=c.sections[l],u={sceneId:a,sectionId:l,lineId:f.initialLineId??f.lines[0].id},{globalVariablesDefaultValues:d}=lr(t),p={...d,...je(o,t.resources?.variables??{})};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,formDrafts:{},accountViewedRegistry:Pa(s,"accountViewedRegistry"),nextLineConfig:Dt(),saveSlots:La(n),overlayStack:[],variables:p,...Ya({loadedGlobalRuntime:i})},contexts:[So({pointer:u,projectData:t})]}},ac=({state:e})=>e.global.overlayStack||[],cc=({state:e})=>e.global.pendingEffects,Ro=({state:e})=>e.global.skipMode,lc=({state:e})=>e.global.autoMode,Oo=({state:e})=>e.global.dialogueUIHidden,Lo=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],r=t[t.length-1];if(!r)return[];let{sectionId:n,lineId:o}=r.pointers.read,i=X({state:e},{sectionId:n});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(f=>f.id===o),a=i.lines.slice(0,s+1),c=[],l={};for(let f of a){let u=f.actions||{};if(l=Le([l,u]),!u.dialogue)continue;let d=l.dialogue||{},p="";d.character?.name!==void 0?p=d.character.name:d.characterId&&(p=e.projectData.resources?.characters?.[d.characterId]?.name||"");let h=_a({sectionId:n,lineId:f.id,content:u.dialogue.append===!0?d.content:u.dialogue.content,dialogueState:d,characterName:p});if(u.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},uc=({state:e})=>e.global.confirmDialog??null,ot=({state:e},{pointer:t}={})=>{let r=t??le({state:e})?.pointer,n=Wa({state:e,pointer:r});return qa({state:e,form:n.form,pointer:r})},fc=({state:e},{pointer:t}={})=>!!ot({state:e},{pointer:t}),me=({state:e},{pointer:t}={})=>{let r=ot({state:e},{pointer:t});if(r)return{source:po,formId:r.id,formKey:r.key};let n=ko({state:e,pointer:t});return n?{source:fo,resourceId:n}:null},dc=({state:e,registry:t},r)=>{let{sectionId:n,lineId:o}=r,s=(Array.isArray(t?.sections)?t.sections:[]).find(f=>f.sectionId===n);if(!s)return!1;if(s.lastLineId===void 0||o===void 0)return!0;let a=X({state:e},{sectionId:n});if(!a||!a.lines||!Array.isArray(a.lines))return s.lastLineId===o;let c=a.lines.findIndex(f=>f.id===s.lastLineId),l=a.lines.findIndex(f=>f.id===o);return c===-1||l===-1?s.lastLineId===o:l<=c},pc=({registry:e},t)=>{let{resourceId:r}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===r)},Mr=({state:e},t)=>dc({state:e,registry:e.global.accountViewedRegistry},t),hc=({state:e},t)=>pc({registry:e.global.accountViewedRegistry},t),mc=({state:e})=>e.global.nextLineConfig,ko=({state:e,pointer:t}={})=>{let r=t??le({state:e})?.pointer;if(!r)return;let n=r?.sectionId,o=r?.lineId,s=X({state:e},{sectionId:n})?.lines||[],a=s.findIndex(l=>l.id===o);if(a<0)return;let c;for(let l of s.slice(0,a+1)){let f=l?.actions;if(f?.cleanAll&&(c=void 0),!f||!Object.prototype.hasOwnProperty.call(f,"choice")){c=void 0;continue}let u=f.choice;if(u?.resourceId){c=u.resourceId;continue}u?.animations||(c=void 0)}return c},Po=({state:e})=>!!ko({state:e}),gc=({state:e})=>structuredClone(e),To=({state:e})=>e.global.saveSlots,yc=({state:e},t)=>{let r=t?.slotId,n=Nt(r);return e.global.saveSlots[n]},Fr=({state:e})=>ze(e),bc=({state:e},t)=>ge(e,t?.runtimeId),Ur=({state:e})=>{let t={...e.global?.variables??{},...Vr(e)?.variables??{}};return vt({variables:t,runtime:ze(e),variableConfigs:e.projectData.resources?.variables??{}})},le=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],r=t[t.length-1];if(r)return{currentPointerMode:"read",pointer:r.pointers?.read}},X=({state:e},t)=>{let{sectionId:r}=t;return Pr(e.projectData,r).section},Br=({state:e})=>{let t=le({state:e});if(!t?.pointer)return;let{sectionId:r,lineId:n}=t.pointer,o=X({state:e},{sectionId:r});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===n)},Do=({state:e})=>{let{sectionId:t,lineId:r}=le({state:e}).pointer,o=X({state:e},{sectionId:t})?.lines||[],i=o.findIndex(l=>l.id===r),a=o.slice(0,i+1).map(l=>{let f=l.actions||{},u={};return Object.keys(f).forEach(d=>{u[d]=f[d]}),u});return Le(a)},Ic=({state:e})=>{let t=No({state:e}),n=Br({state:e})?.actions??{},o=Le([t??{},n]);return ur(t??{},o??{})},Ac=({state:e},{sectionId:t})=>{let r=X({state:e},{sectionId:t});if(!r?.lines)return[];let n=[],o={};for(let i of r.lines){let s=i.actions||{},a=Le([o,s]),c=ur(o,a);n.push({id:i.id,changes:c,presentationState:a}),o=fr(a)}return n},wc=({state:e},{sectionId:t,includePresentationState:r=!1})=>{let n=Ac({state:e},{sectionId:t});return r?{lines:n}:{lines:n.map(({presentationState:o,...i})=>i)}},No=({state:e})=>{let{sectionId:t,lineId:r}=le({state:e}).pointer,o=X({state:e},{sectionId:t})?.lines||[],i=o.findIndex(c=>c.id===r);if(i<=0)return null;let a=o.slice(0,i).map(c=>{let l=c.actions||{},f={};return Object.keys(l).forEach(u=>{f[u]=l[u]}),f});return fr(Le(a))},zr=({state:e},{slotsPerPage:t=6}={})=>{let o=((Fr({state:e}).saveLoadPagination??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let a=o+s,c=e.global.saveSlots&&e.global.saveSlots[Nt(a)]||{};i.push({...c,slotId:a})}return{saveSlots:i}},vc=To,Ec=zr,xc=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},Cc=({state:e},t={})=>{let r=Do({state:e}),n=No({state:e}),o=Br({state:e})?.actions??{},{sectionId:i}=le({state:e}).pointer,{sceneId:s}=Pr(e.projectData,i),a=Fr({state:e}),c=t?.activePersistentAnimations??[],l=t?.restoredPersistentAnimations??[],f=ot({state:e}),u=Po({state:e}),d=Ur({state:e}),{saveSlots:p}=zr({state:e}),h=xc(e);return no({presentationState:r,previousPresentationState:n,currentLineActions:o,resources:e.projectData.resources,currentSceneId:s,screen:e.projectData.screen,dialogueUIHidden:a.dialogueUIHidden,autoMode:a.autoMode,skipMode:a.skipMode,isChoiceVisible:u,isFormVisible:!!f,canRollback:Yo({state:e}),skipOnlyViewedLines:!a.skipUnseenText,isLineCompleted:a.isLineCompleted,skipTransitionsAndAnimations:!!a.skipTransitionsAndAnimations||h,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,form:f,dialogueHistory:Lo({state:e}),saveSlots:p,variables:d,runtime:a,activePersistentAnimations:c,restoredPersistentAnimations:l})},Sc=({state:e},t)=>(e.global.confirmDialog=ja(t),e.global.pendingEffects.push({name:"render"}),e),_c=({state:e})=>(e.global.confirmDialog&&(We(e),e.global.pendingEffects.push({name:"render"})),e),$c=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),he(e,"pushOverlay",t),e),Rc=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),he(e,"popOverlay",void 0),e),Oc=({state:e},t)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=t),e.global.pendingEffects.push({name:"render"}),he(e,"replaceLastOverlay",t),e),Lc=({state:e})=>(e.global.overlayStack=[],We(e),qe(e),e.global.pendingEffects.push({name:"render"}),he(e,"clearOverlays",void 0),e),kc=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"})},Vt=(e,t)=>{e.global.isLineCompleted=!1,qe(e);let r=me({state:e},{pointer:t}),n=r?.source===fo,o=r?.source===po;return r&&kc(e),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:n,isFormVisible:o,activeInteraction:r}},Vo=({state:e})=>(me({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:ge(e,"autoForwardDelay")}}),e.global.pendingEffects.push({name:"render"})),e),it=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Pc=({state:e})=>{let t=e.global.autoMode;return me({state:e})&&!t||(t?it({state:e}):Vo({state:e})),e},jo=({state:e})=>(me({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),Pe=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Tc=({state:e})=>{let t=Ro({state:e});return me({state:e})&&!t||(t?Pe({state:e}):jo({state:e})),e},jt=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),he(e,"showDialogueUI",void 0),e),Mo=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),he(e,"hideDialogueUI",void 0),e),Dc=({state:e})=>(Oo({state:e})?jt({state:e}):Mo({state:e}),e),De=(e,t,r)=>(Co(e,t,r),Ga(e),e.global.pendingEffects.push({name:"render"}),e),st=(e,t,r,n)=>{let o=Co(e,t,r);return e.global.pendingEffects.push({name:"render"}),he(e,n,{value:o}),e},Nc=({state:e},t)=>De(e,"dialogueTextSpeed",t?.value),Vc=({state:e},t)=>De(e,"autoForwardDelay",t?.value),jc=({state:e},t)=>De(e,"skipUnseenText",t?.value),Mc=({state:e},t)=>De(e,"skipTransitionsAndAnimations",t?.value),Fc=({state:e},t)=>De(e,"soundVolume",t?.value),Uc=({state:e},t)=>De(e,"musicVolume",t?.value),Bc=({state:e},t)=>De(e,"muteAll",t?.value),zc=({state:e},t)=>st(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),Wc=({state:e})=>{let t=ge(e,"saveLoadPagination")+1;return st(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},qc=({state:e})=>{let t=ge(e,"saveLoadPagination")-1;return st(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},Yc=({state:e},t)=>st(e,"menuPage",t?.value,"setMenuPage"),Kc=({state:e},t)=>st(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),Hc=({state:e})=>(e.global.pendingEffects=[],e),Jc=({state:e},t)=>(e.global.pendingEffects.push(t),e),Fo=(e,{sectionId:t,resetStoryState:r=!1})=>{let n=X({state:e},{sectionId:t});if(!n)return console.warn(`Section not found: ${t}`),e;let o=n.lines?.[0];if(!o)return console.warn(`Section ${t} has no lines`),e;if(r&&!Za(e))return e;e.global.autoMode&&it({state:e}),e.global.skipMode&&Pe({state:e});let i=e.contexts?.[e.contexts.length-1];if(i){let s=Ye(i);i.rollback||Te(i,{compatibilityAnchor:!0}),s.read={sectionId:t,lineId:o.id},r?i.rollback=rt({pointer:s.read}):jr(e,{sectionId:t,lineId:o.id})}return Vt(e,i?.pointers?.read),e},Gc=({state:e},t)=>Fo(e,{sectionId:t?.sectionId,resetStoryState:!0}),Uo=e=>(e.global.accountViewedRegistry=Ca(e.global.accountViewedRegistry),e.global.accountViewedRegistry),Wr=(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:N(r.value)}))}})},Bo=(e,t)=>{Wr(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:[]}}])},Xc=(e,t,{sectionId:r,lineId:n})=>{if(!r||!n)return!1;let o=T(t)?t:{};Array.isArray(o.sections)||(o.sections=[]);let i=o.sections.find(s=>s.sectionId===r);if(i){if(i.lastLineId===void 0)return!1;let s=X({state:e},{sectionId:r});if(s?.lines){let a=s.lines.findIndex(l=>l.id===i.lastLineId),c=s.lines.findIndex(l=>l.id===n);if(a===-1||c>a)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},nt=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;Xc(e,Uo(e),t)&&Bo(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},Qc=({state:e},t)=>(nt(e,t),e.global.pendingEffects.push({name:"render"}),e),Zc=({state:e},t)=>{let{resourceId:r}=t;if(e.global.accountViewedRegistry!==void 0){let n=Uo(e);n.resources.find(i=>i.resourceId===r)||(n.resources.push({resourceId:r}),Bo(e,{sections:[],resources:[{resourceId:r}]}))}return e.global.pendingEffects.push({name:"render"}),e},zo=({state:e},t)=>{let r=Ra(t.manual),{auto:n,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,a=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,l=me({state:e});return!a&&!l&&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}}):!a&&c===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),he(e,"setNextLineConfig",t),e},el=({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=Nt(r),s=N(e.contexts);s?.forEach(l=>{Ye(l),_o(l.rollback),ka(l.rollback)});let a={contexts:s},c={formatVersion:uo,slotId:go(r),savedAt:typeof o=="number"?o:Date.now(),image:n,state:a};return e.global.saveSlots[i]=c,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},tl=({state:e},t)=>{let r=t?.slotId;if(r==null||r==="")throw new Error("loadSlot requires slotId");let n=Nt(r),o=e.global.saveSlots[n];if(o){let i=Va(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=Dt(),e.global.overlayStack=[],e.global.isLineCompleted=!0,We(e),qe(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},rl=({state:e},t)=>{let{projectData:r}=t;mo(r),e.projectData=r;let n=r?.resources?.variables??{};return Object.prototype.hasOwnProperty.call(e.global??{},"variables")&&(e.global.variables=je(e.global.variables,n)),e.contexts?.forEach(o=>{Object.prototype.hasOwnProperty.call(o??{},"variables")&&(o.variables=je(o.variables,n))}),We(e),qe(e),e.global.pendingEffects.push({name:"render"}),e},nl=({state:e},t)=>{let{sectionId:r,lineId:n}=t;if(!n)return console.warn("jumpToLine requires lineId parameter"),e;let o=e.contexts[e.contexts.length-1];if(!o)return console.warn("No context available for jumpToLine"),e;let i=r||o.pointers.read?.sectionId;if(r&&!X({state:e},{sectionId:r}))return console.warn(`Section not found: ${r}`),e;let s=X({state:e},{sectionId:i});if(!s?.lines||!Array.isArray(s.lines))return console.warn(`Section ${i} has no lines`),e;if(!s.lines.find(l=>l.id===n))return console.warn(`Line not found: ${n} in section ${i}`),e;let c=Ye(o);return c.read={sectionId:i,lineId:n},Vt(e,c.read),e},ol=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return jt({state:e}),e;let r=me({state:e});if(r&&t?._interactionSource!==r.source)return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0;let f=le({state:e})?.pointer,u=f?.sectionId,d=f?.lineId;u&&d&&nt(e,{sectionId:u,lineId:d}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:ge(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=le({state:e})?.pointer,o=n?.sectionId,i=X({state:e},{sectionId:o}),s=e.contexts[e.contexts.length-1],a=i?.lines||[],l=a.findIndex(f=>f.id===n?.lineId)+1;if(l<a.length){let f=a[l],u=!ge(e,"skipUnseenText");if(e.global.skipMode&&u&&!Mr({state:e},{sectionId:o,lineId:f.id}))return Pe({state:e}),e;if(s&&!s.rollback&&Te(s,{compatibilityAnchor:!0}),s){let h=Ye(s),g=h.read?.lineId;g&&o&&nt(e,{sectionId:o,lineId:g}),h.read={sectionId:o,lineId:f.id}}jr(e,{sectionId:o,lineId:f.id}),kr(e);let{activeInteraction:d}=Vt(e,{sectionId:o,lineId:f.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&&it({state:e}),e.global.skipMode&&Pe({state:e});return e},il=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0;let t=me({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:ge(e,"autoForwardDelay")}});let r=le({state:e})?.pointer,n=r?.sectionId,o=r?.lineId;n&&o&&nt(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},sl=({state:e},t)=>Fo(e,{sectionId:t?.sectionId}),al=({state:e})=>{if(e.global.dialogueUIHidden)return jt({state:e}),e;if(me({state:e}))return e;let t=le({state:e})?.pointer,r=t?.sectionId,n=X({state:e},{sectionId:r}),o=e.contexts[e.contexts.length-1],i=n?.lines||[],a=i.findIndex(c=>c.id===t?.lineId)+1;if(a<i.length){let c=i[a],l=!ge(e,"skipUnseenText");if(e.global.skipMode&&l&&!Mr({state:e},{sectionId:r,lineId:c.id}))return Pe({state:e}),e;if(o&&!o.rollback&&Te(o,{compatibilityAnchor:!0}),o){let u=Ye(o),d=u.read?.lineId;d&&r&&nt(e,{sectionId:r,lineId:d}),u.read={sectionId:r,lineId:c.id}}jr(e,{sectionId:r,lineId:c.id}),kr(e);let{activeInteraction:f}=Vt(e,{sectionId:r,lineId:c.id});e.global.nextLineConfig.auto?.enabled&&!f&&e.global.nextLineConfig.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}})}else e.global.nextLineConfig.auto?.enabled&&(e.global.nextLineConfig.auto.enabled=!1,e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}));return e},qr=(e,t={})=>{let r=ot({state:e});return!r||t.formKey&&t.formKey!==r.key||t.formId&&t.formId!==r.id?null:r},cl=(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(Ae(r))throw new Error(`Cannot update computed variable: ${t.variableId}`);if(r?.readonly===!0)throw new Error(`Cannot update readonly variable: ${t.variableId}`);return Et(n,t.variableId),xt(o,"set",t.variableId),{variableConfig:r,scope:n}},ll=(e,t)=>({id:e.id,key:e.key,valid:!0,values:N(t),fields:N(e.fields),fieldList:N(e.fieldList)}),ul=({state:e},t={})=>{let r=qr(e,t),n=t.field;if(!r?.fields?.[n])return e;let o=wo(e,r.key),i=Pt(t.value),s=r.fields[n],a=Tr(s,i);return o.values[n]=i,o.touched[n]=!0,a?o.errors[n]=a:delete o.errors[n],e.global.pendingEffects.push({name:"render"}),e},fl=({state:e},t={})=>{let r=qr(e,t);if(!r)return{submitted:!1,valid:!1,reason:"inactive"};let n=wo(e,r.key);n.submitted=!0;let o={},i={};if(Object.entries(r.fields).forEach(([u,d])=>{let p=Object.prototype.hasOwnProperty.call(n.values,u)?n.values[u]:d.value,h=Tr(d,p);n.touched[u]=!0,h&&(i[u]=h),o[u]=Ao(d,p)}),n.errors=i,Object.keys(i).length>0)return e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!1,errors:N(i),form:{id:r.id,key:r.key,values:N(o)}};let s=e.contexts[e.contexts.length-1];if(s?.rollback?.isRestoring)return{submitted:!1,valid:!1,reason:"restoring"};let a=!1,c=[],l=[];Object.entries(r.fields).forEach(([u,d])=>{let{scope:p}=cl(e,d),h=p==="context"?s.variables:e.global.variables,g=o[u];h[d.variableId]=Ct(h[d.variableId],"set",g),p==="context"&&(a=!0,l.push({variableId:d.variableId,op:"set",value:g})),(p==="device"||p==="account")&&c.push({scope:p,path:`variables.${d.variableId}`,op:"set",value:N(h[d.variableId])})}),a&&he(e,"updateVariable",{id:"submitForm",operations:l}),Wr(e,c);let f=ll(r,o);return delete e.global.formDrafts[r.key],e.global.pendingEffects.push({name:"render"}),{submitted:!0,valid:!0,form:f}},dl=({state:e},t={})=>{let r=qr(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:N(r.values),fields:N(r.fields),fieldList:N(r.fieldList)}}):{cancelled:!1,reason:"inactive"}},pl=({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=[],a=[];return n.forEach(({variableId:c,op:l,value:f})=>{let u=e.projectData.resources?.variables?.[c],d=u?.scope,p=u?.type;if(Ae(u))throw new Error(`Cannot update computed variable: ${c}`);if(u?.readonly===!0)throw new Error(`Cannot update readonly variable: ${c}`);Et(d,c),xt(p,l,c);let h=d==="context"?o.variables:e.global.variables;d==="context"&&(i=!0,a.push({variableId:c,op:l,value:f})),h[c]=Ct(h[c],l,f),(d==="device"||d==="account")&&s.push({scope:d,path:`variables.${c}`,op:"set",value:N(h[c])})}),i&&he(e,"updateVariable",{id:r,operations:a}),Wr(e,s),e.global.pendingEffects.push({name:"render"}),e},hl=e=>(t,r)=>e({state:t},r),ml=e=>({variables:vt({variables:{...e.global?.variables??{},...Vr(e)?.variables??{}},runtime:ze(e),variableConfigs:e.projectData.resources?.variables??{},eager:!1}),runtime:ze(e)}),gl=e=>{if(!T(e))throw new Error("conditional action payload must be an object");if(!Array.isArray(e.branches))throw new Error("conditional action requires branches array");if(e.branches.length===0)throw new Error("conditional action requires at least one branch")},yl=(e,t,r)=>{if(!T(e))throw new Error(`conditional branch at index ${t} must be an object`);if(!T(e.actions))throw new Error(`conditional branch at index ${t} requires actions object`);if(!Object.prototype.hasOwnProperty.call(e,"when")&&t!==r-1)throw new Error("conditional else branch must be the last branch")},bl=(e,t)=>{gl(t);for(let r=0;r<t.branches.length;r+=1){let n=t.branches[r];if(yl(n,r,t.branches.length),!(Object.prototype.hasOwnProperty.call(n,"when")&&!Oe(n.when,ml(e)))){Object.entries(n.actions).forEach(([i,s])=>{Wo(e,i,s)});return}}},Il={conditional:{replayLine:bl},updateVariable:{recordSources:[Dr],replayLine:lo,replayRecorded:lo,persistInSaveSlot:!0},setNextLineConfig:{replayLine:hl(zo)}},Mt=e=>Il[e]??null,Al=e=>Mt(e)?.persistInSaveSlot===!0,wl=(e,t)=>{let r=Mt(e)?.recordSources;return Array.isArray(r)&&r.includes(t)},vl=(e,t,r)=>{Mt(t)?.replayRecorded?.(e,r)},Wo=(e,t,r)=>{Mt(t)?.replayLine?.(e,r)},qo=({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}},Yo=({state:e})=>qo({state:e},{offset:-1})!==null,El=({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=Te(n,{compatibilityAnchor:!n.rollback}),i=o.currentIndex+r;return i<0||i>=o.timeline.length?e:$o(e,i)},xl=({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=Te(o,{compatibilityAnchor:!o.rollback}),a=i.timeline.slice(0,i.currentIndex+1).findLastIndex(c=>c.sectionId===r&&c.lineId===n);if(a===-1)throw new Error(`Line ${n} not found in section ${r} rollback timeline`);return a===i.currentIndex?e:$o(e,a)},Ko=e=>{let t=sc(e);return _n(t,{selectPendingEffects:cc,selectSkipMode:Ro,selectAutoMode:lc,selectIsChoiceVisible:Po,selectIsFormVisible:fc,selectActiveInteraction:me,selectActiveForm:ot,selectDialogueUIHidden:Oo,selectDialogueHistory:Lo,selectConfirmDialog:uc,selectIsLineAccountViewed:Mr,selectIsResourceAccountViewed:hc,selectNextLineConfig:mc,selectSystemState:gc,selectSaveSlotMap:To,selectSaveSlots:vc,selectSaveSlot:yc,selectRuntime:Fr,selectRuntimeValue:bc,selectAllVariables:Ur,selectCurrentPointer:le,selectSection:X,selectCurrentLine:Br,selectPresentationState:Do,selectPresentationChanges:Ic,selectSectionLineChanges:wc,selectSaveSlotPage:zr,selectCurrentPageSlots:Ec,selectRenderState:Cc,selectOverlayStack:ac,selectLineIdByOffset:qo,selectCanRollback:Yo,startAutoMode:Vo,stopAutoMode:it,toggleAutoMode:Pc,startSkipMode:jo,stopSkipMode:Pe,toggleSkipMode:Tc,showDialogueUI:jt,hideDialogueUI:Mo,toggleDialogueUI:Dc,setDialogueTextSpeed:Nc,setAutoForwardDelay:Vc,setSkipUnseenText:jc,setSkipTransitionsAndAnimations:Mc,setSoundVolume:Fc,setMusicVolume:Uc,setMuteAll:Bc,setSaveLoadPagination:zc,incrementSaveLoadPagination:Wc,decrementSaveLoadPagination:qc,setMenuPage:Yc,setMenuEntryPoint:Kc,showConfirmDialog:Sc,hideConfirmDialog:_c,resetStoryAtSection:Gc,clearPendingEffects:Hc,appendPendingEffect:Jc,beginRollbackActionBatch:rc,endRollbackActionBatch:nc,addViewedLine:Qc,addViewedResource:Zc,setNextLineConfig:zo,saveSlot:el,loadSlot:tl,updateProjectData:rl,sectionTransition:sl,jumpToLine:nl,nextLine:ol,markLineCompleted:il,rollbackToLine:xl,rollbackByOffset:El,pushOverlay:$c,popOverlay:Rc,replaceLastOverlay:Oc,clearOverlays:Lc,updateFormField:ul,submitForm:fl,cancelForm:dl,updateVariable:pl,nextLineFromSystem:al},{transformActionFirstArgument:n=>({state:n}),transformSelectorFirstArgument:n=>({state:n})})};var Cl="route-engine",Sl="projectPersistence";var Jo=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),J=e=>Object.prototype.toString.call(e)==="[object Object]",Ho="variables.",_l=(e={})=>{let t=J(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!J(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)}:!J(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},$l=(e={})=>{let t=J(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(r=>typeof r=="string"||typeof r=="number"?{sectionId:String(r)}:!J(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)}:!J(r)||typeof r.resourceId!="string"||r.resourceId.length===0?null:{resourceId:r.resourceId}).filter(Boolean)}},Rl=(e,t)=>{let r=$l(e),n=_l(t),o=r.sections.map(s=>({...s})),i=r.resources.map(s=>({...s}));return n.sections.forEach(s=>{let a=o.find(c=>c.sectionId===s.sectionId);if(!a){o.push({sectionId:s.sectionId,...s.lineId===void 0?{}:{lastLineId:s.lineId}});return}if(a.lastLineId!==void 0){if(s.lineId===void 0){delete a.lastLineId;return}a.lastLineId=s.lineId}}),n.resources.forEach(s=>{i.find(c=>c.resourceId===s.resourceId)||i.push({...s})}),{sections:o,resources:i}},Go=(e={})=>{let t=J(e)?e:{};return{saveSlots:J(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:J(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:J(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:J(t.globalRuntime)?t.globalRuntime:{},accountViewedRegistry:J(t.accountViewedRegistry)?t.accountViewedRegistry:{}}},Ol=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((t,r)=>{if(!J(t))throw new Error(`Malformed applyScopedDataUpdates.updates[${r}] entry.`);let n=t.path?.startsWith(Ho)?t.path.slice(Ho.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}].`)})},Ll=(e,t)=>{let r={};return Ol(t).forEach(n=>{if(n.path==="viewedRegistry"){r.accountViewedRegistry=Rl(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},Yr=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},kl=e=>{let t=Yr(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},Pl=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},Tl=({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}".`))}}),Dl=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.`))}})},at=async({databasePromise:e,objectStoreName:t,namespace:r,patch:n})=>{let o=await e;return new Promise((i,s)=>{let a=o.transaction(t,"readwrite"),c=a.objectStore(t),l=c.get(r),f=!1,u=p=>{f||(f=!0,s(p))},d=()=>{f||(f=!0,i())};l.onerror=()=>{u(l.error??new Error(`Failed to read persisted namespace "${r}" before updating IndexedDB.`))},l.onsuccess=()=>{let p=Go(l.result),h=typeof n=="function"?n(p):n,g={namespace:r,version:1,...Jo(),...p,...h},y=c.put(g);y.onerror=()=>{u(y.error??new Error(`Failed to persist namespace "${r}" to IndexedDB.`))}},a.oncomplete=()=>{d()},a.onerror=()=>{u(a.error??new Error(`IndexedDB transaction failed while updating namespace "${r}".`))},a.onabort=()=>{u(a.error??new Error(`IndexedDB transaction aborted while updating namespace "${r}".`))}})},Nl=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),l=!1,f=d=>{l||(l=!0,i(d))},u=()=>{l||(l=!0,o())};c.onerror=()=>{f(c.error??new Error(`Failed to clear persisted namespace "${r}" from IndexedDB.`))},s.oncomplete=()=>{u()},s.onerror=()=>{f(s.error??new Error(`IndexedDB transaction failed while clearing namespace "${r}".`))},s.onabort=()=>{f(s.error??new Error(`IndexedDB transaction aborted while clearing namespace "${r}".`))}})},Kr=(e={})=>{let{indexedDB:t,databaseName:r=Cl,objectStoreName:n=Sl,namespace:o}=e,i=Pl(t),s=kl(o),a=Tl({indexedDB:i,databaseName:r,objectStoreName:n});return{namespace:s,load:async()=>{let c=await Dl({databasePromise:a,objectStoreName:n,namespace:s});return{...Jo(),...Go(c)}},clear:async()=>Nl({databasePromise:a,objectStoreName:n,namespace:s}),saveSlots:async c=>at({databasePromise:a,objectStoreName:n,namespace:s,patch:{saveSlots:J(c)?c:{}}}),saveGlobalDeviceVariables:async c=>at({databasePromise:a,objectStoreName:n,namespace:s,patch:{globalDeviceVariables:J(c)?c:{}}}),saveGlobalAccountVariables:async c=>at({databasePromise:a,objectStoreName:n,namespace:s,patch:{globalAccountVariables:J(c)?c:{}}}),saveGlobalRuntime:async c=>at({databasePromise:a,objectStoreName:n,namespace:s,patch:{globalRuntime:J(c)?c:{}}}),applyScopedDataUpdates:async c=>at({databasePromise:a,objectStoreName:n,namespace:s,patch:l=>Ll(l,c)})}},Vl=Kr;var jl=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),Ml=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]),Xo="conditional",Fl="choice",Qo="form",Ul=new Set(["submitForm","cancelForm"]),ct=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function Hr(e){let t,r=0,n=null,o=new Map,i=new Map,s=new Map,{handlePendingEffects:a}=e,c=(A=new Map,C=Date.now())=>new Map(Array.from(A.entries()).filter(([,$])=>C<$.expiresAt).map(([$,F])=>[$,{animation:structuredClone(F.animation),startedAt:F.startedAt,expiresAt:F.expiresAt}])),l=(A=new Map)=>Array.from(A.values()).map(C=>structuredClone(C.animation)),f=(A=Date.now())=>{o=new Map(Array.from(o.entries()).filter(([,C])=>A<C.expiresAt))},u=()=>{for(;t.selectPendingEffects().length>0;){let A=[...t.selectPendingEffects()];t.clearPendingEffects();try{a(A)}catch(C){throw t.clearPendingEffects(),A.forEach($=>{t.appendPendingEffect($)}),C}}},d=({initialState:A,namespace:C})=>{t=Ko(A),r=0,n=Yr(C),o=new Map,i=new Map,s=new Map,t.appendPendingEffect({name:"handleLineActions"}),u()},p=()=>n,h=()=>t.selectPresentationState(),g=()=>t.selectPresentationChanges(),y=A=>t.selectSectionLineChanges(A),I=(A={})=>{r+=1;let C=Date.now();f(C);let $=i.size>0,F=c(o,C),z=$?c(i,C):new Map,ue={...t.selectRenderState({activePersistentAnimations:l(F),restoredPersistentAnimations:l(z)}),id:`render-${r}`};return s.set(ue.id,{builtAt:C,persistentAnimationSessions:new Map([...z.entries(),...F.entries()]),usedRestoredPersistentAnimationSessions:$}),ue},w=(A={})=>I(A),x=(A={})=>I(A),b=A=>{let C=typeof A?.id=="string"&&A.id.length>0?A.id:null,$=C?s.get(C):null;C&&s.delete(C);let F=new Map;Kn(A?.animations).forEach(z=>{let ne=Rt(z);if(!ne)return;let ue=$?.persistentAnimationSessions?.get(ne)??o.get(ne),ft=Math.max(0,Jn(z)),Qr=ue?.startedAt??$?.builtAt??Date.now();F.set(ne,{animation:structuredClone(z),startedAt:Qr,expiresAt:Qr+ft})}),o=F,$?.usedRestoredPersistentAnimationSessions&&(i=new Map)},O=()=>t.selectSystemState(),L=()=>t.selectSaveSlotMap(),V=A=>t.selectSaveSlot(A),D=A=>t.selectSaveSlotPage(A),_=()=>t.selectSkipMode(),U=()=>t.selectAutoMode(),M=()=>t.selectRuntime(),P=()=>t.selectIsChoiceVisible(),B=()=>t.selectIsFormVisible(),E=()=>t.selectActiveInteraction(),S=(A,C,$={})=>![Fl,Qo].includes($.interactionSource)||A!=="nextLine"||!ct(C)?C:{...C,_interactionSource:$.interactionSource},j=(A,C)=>{if(!t[A])return;jl.has(A)&&(Ml.has(A)?i=c(o):i=new Map,o=new Map);let $=t[A](C);return u(),$},W=(A,C,$,F={})=>{if(A===Xo){let z=q($),ne=dr({[A]:C},z);Gr(ne[A],$,F);return}j(A,C)},H=(A,C)=>{W(A,C)},q=A=>{if(!A)return{variables:t.selectAllVariables?t.selectAllVariables():void 0,runtime:t.selectRuntime?t.selectRuntime():{}};if(Object.prototype.hasOwnProperty.call(A,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:C,...$}=A,F=t.selectAllVariables?t.selectAllVariables():void 0;return{...$,_event:C,variables:F,runtime:t.selectRuntime?t.selectRuntime():{}}},lt=A=>{if(!ct(A))throw new Error("conditional action payload must be an object");if(!Array.isArray(A.branches))throw new Error("conditional action requires branches array");if(A.branches.length===0)throw new Error("conditional action requires at least one branch")},ut=(A,C,$)=>{if(!ct(A))throw new Error(`conditional branch at index ${C} must be an object`);if(!ct(A.actions))throw new Error(`conditional branch at index ${C} requires actions object`);if(!Object.prototype.hasOwnProperty.call(A,"when")&&C!==$-1)throw new Error("conditional else branch must be the last branch")},Gr=(A,C,$)=>{lt(A);for(let F=0;F<A.branches.length;F+=1){let z=A.branches[F];ut(z,F,A.branches.length);let ne=q(C);if(!(Object.prototype.hasOwnProperty.call(z,"when")&&!Oe(z.when,ne))){Ut(z.actions,C,$);return}}},ti=(A,C)=>({...A??{},_form:C}),ri=(A,C,$,F)=>{let z=j(A,C),ne=z?.submitted===!0&&z.valid===!0,ue=z?.cancelled===!0;!ne&&!ue||ct(C.actions)&&Ut(C.actions,ti($,z.form),{...F,interactionSource:Qo})},ni=(A,C,$,F)=>{let z=q($),ue=dr({[A]:C},z)[A];if(A===Xo){Gr(ue,$,F);return}let ft=S(A,ue,F);if(Ul.has(A)){ri(A,ft,$,F);return}j(A,ft)},Ut=(A,C,$)=>{Object.entries(A).forEach(([F,z])=>{ni(F,z,C,$)})},Xr=(A,C,$={})=>{t.beginRollbackActionBatch({source:$.rollbackSource});try{Ut(A,C,$)}finally{t.endRollbackActionBatch({})}};return{init:d,handleAction:W,handleInternalAction:H,handleActions:Xr,selectRenderState:w,prepareRenderState:x,commitRenderState:b,selectPresentationState:h,selectPresentationChanges:g,selectSectionLineChanges:y,selectSystemState:O,selectSaveSlotMap:L,selectSaveSlot:V,selectSaveSlotPage:D,selectSaveSlots:L,selectRuntime:M,selectIsChoiceVisible:P,selectIsFormVisible:B,selectActiveInteraction:E,handleLineActions:()=>{let A=t.selectCurrentLine();return A?.actions?(Xr(A.actions,void 0,{rollbackSource:"line"}),!0):!1},getNamespace:p}}var Jr=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:r=>{e=r},addElapsed:r=>{e+=r},getCallback:()=>t,setCallback:r=>{t=r}}},Bl=80,ei=({engine:e,routeGraphics:t,trackRenderDispatch:r},n)=>{let o=e.prepareRenderState?.(n)??e.selectRenderState(n);r?.(o),t.render(o),e.commitRenderState?.(o)},zl=({engine:e,routeGraphics:t,trackRenderDispatch:r,getRenderDispatchCount:n},o)=>{let i=n?.()??0,s=e.handleLineActions();(n?.()??0)===i&&ei({engine:e,routeGraphics:t,trackRenderDispatch:r},o)},Wl=({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 a=n.delay??1e3;r.getElapsed()>=a&&(t.remove(i),r.setCallback(null),r.setElapsed(0),Ft(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},ql=({ticker:e,autoTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},Yl=({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 a=n?.delay??Bl;r.getElapsed()>=a&&(r.setElapsed(0),Ft(e,"nextLineFromSystem",{}))};r.setCallback(i),t.add(i)},Kl=({ticker:e,skipTimer:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},Hl=({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 a=n.delay??1e3;r.getElapsed()>=a&&(r.setElapsed(0),Ft(e,"nextLineFromSystem",{}),t.remove(i),r.setCallback(null))};r.setCallback(i),t.add(i)},Jl=({ticker:e,nextLineConfigTimerState:t},r)=>{let n=t.getCallback();n&&(e.remove(n),t.setCallback(null)),t.setElapsed(0)},Gl=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveSlots(t?.saveSlots))},Xl=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalDeviceVariables(t?.globalDeviceVariables))},Ql=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalAccountVariables(t?.globalAccountVariables))},Zl=({enqueuePersistenceWrite:e},t)=>{e(r=>r.saveGlobalRuntime(t?.globalRuntime))},eu=({enqueuePersistenceWrite:e},t)=>{e(r=>{if(typeof r.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return r.applyScopedDataUpdates(t?.updates)})},Zo={render:ei,saveSlots:Gl,saveGlobalDeviceVariables:Xl,saveGlobalAccountVariables:Ql,saveGlobalRuntime:Zl,applyScopedDataUpdates:eu,handleLineActions:zl,startAutoNextTimer:Wl,clearAutoNextTimer:ql,startSkipNextTimer:Yl,clearSkipNextTimer:Kl,nextLineConfigTimer:Hl,clearNextLineConfigTimer:Jl},tu=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),Ft=(e,t,r)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,r)},ru=(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(!tu.has(o.name)){r.unshift(o);continue}t.has(o.name)||(t.add(o.name),r.unshift(o))}return r},nu=({getEngine:e,routeGraphics:t,ticker:r,handleUnhandledEffect:n,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:a})=>{let c=Jr(),l=Jr(),f=Jr(),u=s??null,d=Promise.resolve(),p=null,h=null,g=!1,y=0,I=E=>{if(o){o(E);return}console.error("RouteEngine persistence write failed.",E)},w=()=>{if(u)return u;let E=e();return u=Kr({indexedDB:i,namespace:a??E?.getNamespace?.()}),u},x=E=>{d=d.catch(()=>{}).then(()=>{let S=w();return E(S)}).catch(S=>{I(S)})},b=E=>{let S=typeof E?.id=="string"&&E.id.length>0?E.id:null;y+=1,p=S,g=!1},O=()=>y,L=(E={})=>{if(E?.aborted===!0)return!1;let S=typeof E?.id=="string"&&E.id.length>0?E.id:null;return S?S!==p||S===h?!1:(h=S,!0):p!==null||g?!1:(g=!0,!0)},V=(E,S={})=>{if(E!=="renderComplete"||!L(S))return!1;let j=e();return Ft(j,"markLineCompleted",{}),!0},D=E=>typeof E?.selectActiveInteraction=="function"?E.selectActiveInteraction():typeof E?.selectIsChoiceVisible=="function"&&E.selectIsChoiceVisible()?{source:"choice"}:null,_=(E,S)=>!(!E||typeof E!="object"||Array.isArray(E)||E._interactionSource!==S?.source||S.source==="form"&&E._formKey&&E._formKey!==S.formKey||S.source==="form"&&E.formKey&&E.formKey!==S.formKey),U=(E={},S)=>{if(_(E,S))return!0;let j=E?.actions;return!j||typeof j!="object"||Array.isArray(j)?!1:Object.values(j).some(W=>_(W,S))},M=(E,S={})=>{if(!S?.actions)return!1;let j=D(E);return j?!U(S,j):!1},P=({preprocessPayload:E,onEvent:S}={})=>async(j,W={})=>{let H=e();if(M(H,W))return S?.(j,W);let q=await E?.(j,W)??W;if(M(H,q))return S?.(j,q);if(V(j,q),q?.actions){let lt=q?._event?{_event:q._event}:q?.event?{_event:q.event}:void 0,ut=q?._interactionSource?{interactionSource:q._interactionSource}:void 0;ut?H.handleActions(q.actions,lt,ut):H.handleActions(q.actions,lt)}return S?.(j,q)},B=E=>{let S=e(),j=ru(E);j.forEach(H=>{if(!Zo[H.name]&&!n)throw new Error(`Unhandled pending effect "${H.name}".`)});let W={engine:S,routeGraphics:t,ticker:r,autoTimer:c,skipTimer:l,nextLineConfigTimerState:f,trackRenderDispatch:b,getRenderDispatchCount:O,enqueuePersistenceWrite:x};for(let H of j){let q=Zo[H.name];if(q){q(W,H.payload);continue}n(H,W)}};return B.handleRouteGraphicsEvent=V,B.createRouteGraphicsEventHandler=P,B},ou=nu;var iu=(e,t={})=>{let{resources:r={}}=t;return Rr(e,r)};var xf=Hr;export{ou as createEffectsHandler,Vl as createIndexedDbPersistence,xf as default,us as resolveComputedVariables,iu as resolveLayoutReferences};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "route-engine-js",
3
- "version": "1.12.1",
3
+ "version": "1.13.0",
4
4
  "description": "A lightweight Visual Novel engine built in JavaScript for creating interactive narrative games with branching storylines",
5
5
  "repository": {
6
6
  "type": "git",