route-engine-js 1.6.1 → 1.8.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.
- package/dist/RouteEngine.js +1 -1
- package/package.json +1 -1
package/dist/RouteEngine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var Zr=Object.defineProperty;var Qr=(e,t)=>{for(var n in t)Zr(e,n,{get:t[n],enumerable:!0})};var bn=Symbol.for("immer-nothing"),pn=Symbol.for("immer-draftable"),K=Symbol.for("immer-state");function J(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var xe=Object.getPrototypeOf;function ie(e){return!!e&&!!e[K]}function le(e){return e?In(e)||Array.isArray(e)||!!e[pn]||!!e.constructor?.[pn]||ze(e)||We(e):!1}var eo=Object.prototype.constructor.toString();function In(e){if(!e||typeof e!="object")return!1;let t=xe(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)===eo}function je(e,t){Ue(e)===0?Reflect.ownKeys(e).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function Ue(e){let t=e[K];return t?t.type_:Array.isArray(e)?1:ze(e)?2:We(e)?3:0}function ht(e,t){return Ue(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function An(e,t,n){let r=Ue(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function to(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function ze(e){return e instanceof Map}function We(e){return e instanceof Set}function ce(e){return e.copy_||e.base_}function gt(e,t){if(ze(e))return new Map(e);if(We(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let n=In(e);if(t===!0||t==="class_only"&&!n){let r=Object.getOwnPropertyDescriptors(e);delete r[K];let o=Reflect.ownKeys(r);for(let i=0;i<o.length;i++){let s=o[i],l=r[s];l.writable===!1&&(l.writable=!0,l.configurable=!0),(l.get||l.set)&&(r[s]={configurable:!0,writable:!0,enumerable:l.enumerable,value:e[s]})}return Object.create(xe(e),r)}else{let r=xe(e);if(r!==null&&n)return{...e};let o=Object.create(r);return Object.assign(o,e)}}function At(e,t=!1){return Ye(e)||ie(e)||!le(e)||(Ue(e)>1&&(e.set=e.add=e.clear=e.delete=no),Object.freeze(e),t&&Object.entries(e).forEach(([n,r])=>At(r,!0))),e}function no(){J(2)}function Ye(e){return Object.isFrozen(e)}var ro={};function ue(e){let t=ro[e];return t||J(0,e),t}var Ce;function xn(){return Ce}function oo(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function hn(e,t){t&&(ue("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function mt(e){yt(e),e.drafts_.forEach(io),e.drafts_=null}function yt(e){e===Ce&&(Ce=e.parent_)}function gn(e){return Ce=oo(Ce,e)}function io(e){let t=e[K];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function mn(e,t){t.unfinalizedDrafts_=t.drafts_.length;let n=t.drafts_[0];return e!==void 0&&e!==n?(n[K].modified_&&(mt(t),J(4)),le(e)&&(e=Be(t,e),t.parent_||Fe(t,e)),t.patches_&&ue("Patches").generateReplacementPatches_(n[K].base_,e,t.patches_,t.inversePatches_)):e=Be(t,n,[]),mt(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==bn?e:void 0}function Be(e,t,n){if(Ye(t))return t;let r=t[K];if(!r)return je(t,(o,i)=>yn(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Fe(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),je(i,(l,c)=>yn(e,r,o,l,c,n,s)),Fe(e,o,!1),n&&e.patches_&&ue("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function yn(e,t,n,r,o,i,s){if(ie(o)){let l=i&&t&&t.type_!==3&&!ht(t.assigned_,r)?i.concat(r):void 0,c=Be(e,o,l);if(An(n,r,c),ie(c))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if(le(o)&&!Ye(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Be(e,o),(!t||!t.scope_.parent_)&&typeof r!="symbol"&&Object.prototype.propertyIsEnumerable.call(n,r)&&Fe(e,o)}}function Fe(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&At(t,n)}function so(e,t){let n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:xn(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=r,i=xt;n&&(o=[r],i=Le);let{revoke:s,proxy:l}=Proxy.revocable(o,i);return r.draft_=l,r.revoke_=s,l}var xt={get(e,t){if(t===K)return e;let n=ce(e);if(!ht(n,t))return ao(e,n,t);let r=n[t];return e.finalized_||!le(r)?r:r===dt(e.base_,t)?(pt(e),e.copy_[t]=It(r,e)):r},has(e,t){return t in ce(e)},ownKeys(e){return Reflect.ownKeys(ce(e))},set(e,t,n){let r=wn(ce(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){let o=dt(ce(e),t),i=o?.[K];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(to(n,o)&&(n!==void 0||ht(e.base_,t)))return!0;pt(e),bt(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 dt(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,pt(e),bt(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let n=ce(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){J(11)},getPrototypeOf(e){return xe(e.base_)},setPrototypeOf(){J(12)}},Le={};je(xt,(e,t)=>{Le[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});Le.deleteProperty=function(e,t){return Le.set.call(this,e,t,void 0)};Le.set=function(e,t,n){return xt.set.call(this,e[0],t,n,e[0])};function dt(e,t){let n=e[K];return(n?ce(n):e)[t]}function ao(e,t,n){let r=wn(t,n);return r?"value"in r?r.value:r.get?.call(e.draft_):void 0}function wn(e,t){if(!(t in e))return;let n=xe(e);for(;n;){let r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=xe(n)}}function bt(e){e.modified_||(e.modified_=!0,e.parent_&&bt(e.parent_))}function pt(e){e.copy_||(e.copy_=gt(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var co=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,...a){return s.produce(c,u=>n.call(this,u,...a))}}typeof n!="function"&&J(6),r!==void 0&&typeof r!="function"&&J(7);let o;if(le(t)){let i=gn(this),s=It(t,void 0),l=!0;try{o=n(s),l=!1}finally{l?mt(i):yt(i)}return hn(i,r),mn(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===bn&&(o=void 0),this.autoFreeze_&&At(o,!0),r){let i=[],s=[];ue("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else J(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,c=>t(c,...l));let r,o;return[this.produce(t,n,(s,l)=>{r=s,o=l}),r,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){le(e)||J(8),ie(e)&&(e=wt(e));let t=gn(this),n=It(e,void 0);return n[K].isManual_=!0,yt(t),n}finishDraft(e,t){let n=e&&e[K];(!n||!n.isManual_)&&J(9);let{scope_:r}=n;return hn(r,t),mn(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=ue("Patches").applyPatches_;return ie(e)?r(e,t):this.produce(e,o=>r(o,t))}};function It(e,t){let n=ze(e)?ue("MapSet").proxyMap_(e,t):We(e)?ue("MapSet").proxySet_(e,t):so(e,t);return(t?t.scope_:xn()).drafts_.push(n),n}function wt(e){return ie(e)||J(10,e),vn(e)}function vn(e){if(!le(e)||Ye(e))return e;let t=e[K],n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=gt(e,t.scope_.immer_.useStrictShallowCopy_)}else n=gt(e,!0);return je(n,(r,o)=>{An(n,r,vn(o))}),t&&(t.finalized_=!1),n}var q=new co,vt=q.produce,nc=q.produceWithPatches.bind(q),rc=q.setAutoFreeze.bind(q),oc=q.setUseStrictShallowCopy.bind(q),ic=q.applyPatches.bind(q),sc=q.createDraft.bind(q),ac=q.finishDraft.bind(q);var h={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},T={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},Re={NOT:0};var w=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},Y=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var Et=e=>{if(!e||e.trim()==="")throw new w("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let n=e.includes("===")?"==":"!=";throw new w(`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 w(`Incomplete comparison expression - missing right operand (got: '${e}')`)},En=e=>{if(e.trim().endsWith(" in"))throw new w(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new w(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,n]=e.split(" in ");if(!n||n.trim()==="")throw new w(`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 w(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new w(`Invalid loop syntax (got: '$for ${e}')`)}};var _n=(e,t,n=!1)=>{if(t===null)return new Y(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new Y(`Cannot iterate over undefined value at '$for ${e}'`);let r=typeof t;return n?new Y(`Cannot iterate over non-array value in loop '${e}' - got ${r} instead`):new Y(`Cannot iterate over non-array value (got: ${r}) at '$for ${e}'`)},Sn=(e,t)=>{let n=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new Y(`Unknown function '${e}' (${n})`)};var lo=(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=C(e,{functions:r,partials:o},t,{});return s===void 0?{}:s},C=(e,t,n,r)=>{let o=t.functions||t;if(e.var&&!e.type)return V(e.var,n,r);if(e.type===h.LITERAL)return e.value;if(e.type===h.VARIABLE)return V(e.path,n,r);if(e.type===h.INTERPOLATION)return fo(e.parts,t,n,r);switch(e.type){case h.FUNCTION:return Ln(e,t,n,r);case h.BINARY:return Rn(e,t,n,r);case h.UNARY:return kn(e,t,n,r);case h.CONDITIONAL:return ho(e,t,n,r);case h.LOOP:return Io(e,t,n,r);case h.OBJECT:return xo(e,t,n,r);case h.ARRAY:return wo(e,t,n,r);case h.PARTIAL:return vo(e,t,n,r);case h.PATH_REFERENCE:return Eo(e,t,n,r);default:throw new Error(`Unknown node type: ${e.type}`)}},Cn=new Map,uo=e=>{let t=[],n="",r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(i==="[")n&&(t.push({type:"property",value:n}),n=""),r=!0;else if(i==="]"){if(r&&n){let s=n.trim();if(/^\d+$/.test(s))t.push({type:"index",value:parseInt(s,10)});else if(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'")){let l=s.slice(1,-1);t.push({type:"property",value:l})}else t.push({type:"property",value:s});n=""}r=!1}else n+=i}return n&&t.push({type:"property",value:n}),t},V=(e,t,n)=>{if(!e)return;if(e in n)return n[e];let r=Cn.get(e);if(!r){let i=[],s="",l=0;for(let c=0;c<e.length;c++){let a=e[c];a==="["?(l++,s+=a):a==="]"?(l--,s+=a):a==="."&&l===0?s&&(i.push(s),s=""):s+=a}s&&i.push(s),r=[];for(let c of i){let a=uo(c.trim());r.push(...a)}Cn.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},fo=(e,t,n,r)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=C(i,t,n,r);o.push(s!=null?String(s):"")}return o.join("")},Ln=(e,t,n,r)=>{let o=t.functions||t,i=o[e.name];if(!i)throw Sn(e.name,o);let s=e.args.map(l=>C(l,t,n,r));return i(...s)},we=(e,t,n,r)=>{if(e.var&&!e.type)return V(e.var,n,r);switch(e.type){case h.VARIABLE:return V(e.path,n,r);case h.LITERAL:return e.value;case h.BINARY:return Rn(e,t,n,r);case h.UNARY:return kn(e,t,n,r);case h.FUNCTION:return Ln(e,t,n,r);default:return C(e,t,n,r)}},Rn=(e,t,n,r)=>{if(e.op===T.AND||e.op===T.OR){let s=we(e.left,t,n,r),l=we(e.right,t,n,r);switch(e.op){case T.AND:return s&&l;case T.OR:return s||l}}let o=C(e.left,t,n,r),i=C(e.right,t,n,r);switch(e.op){case T.EQ:return o==i;case T.NEQ:return o!=i;case T.GT:return o>i;case T.LT:return o<i;case T.GTE:return o>=i;case T.LTE:return o<=i;case T.IN:return Array.isArray(i)?i.includes(o):!1;case T.ADD:if(typeof o!="number"||typeof i!="number")throw new Y(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case T.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new Y(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},kn=(e,t,n,r)=>{let o=e.op===Re.NOT?we(e.operand,t,n,r):C(e.operand,t,n,r);if(e.op===Re.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},po=(e,t,n,r)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===h.VARIABLE)if(V(o.path,n,r)){let s=e.bodies[0];if(s.type===h.OBJECT&&s.properties.length<=5){let l={};for(let c of s.properties){let a=c.parsedKey?C(c.parsedKey,t,n,r):c.key,u=c.value;if(u.type===h.LITERAL)l[a]=u.value;else if(u.type===h.VARIABLE)l[a]=V(u.path,n,r);else if(u.type===h.INTERPOLATION){let f=[];for(let d of u.parts)if(typeof d=="string")f.push(d);else if(d.type===h.VARIABLE){let p=V(d.path,n,r);f.push(p!=null?String(p):"")}else{let p=C(d,t,n,r);f.push(p!=null?String(p):"")}l[a]=f.join("")}else l[a]=C(u,t,n,r)}return l}}else{let s=e.bodies[1];if(s.type===h.OBJECT&&s.properties.length<=5){let l={};for(let c of s.properties){let a=c.parsedKey?C(c.parsedKey,t,n,r):c.key,u=c.value;if(u.type===h.LITERAL)l[a]=u.value;else if(u.type===h.VARIABLE)l[a]=V(u.path,n,r);else if(u.type===h.INTERPOLATION){let f=[];for(let d of u.parts)if(typeof d=="string")f.push(d);else if(d.type===h.VARIABLE){let p=V(d.path,n,r);f.push(p!=null?String(p):"")}else{let p=C(d,t,n,r);f.push(p!=null?String(p):"")}l[a]=f.join("")}else l[a]=C(u,t,n,r)}return l}}}return null},ho=(e,t,n,r)=>{let o=po(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||we(s,t,n,r))return C(e.bodies[i],t,n,r)}return $n},go=(e,t)=>{let n=e.body,r=e.itemVar;if(n.type===h.CONDITIONAL&&n.conditions.length===1&&n.conditions[0].type===h.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===h.OBJECT&&i.properties.length<=5){for(let c of i.properties)if(c.parsedKey)return null;let l=[];for(let c=0;c<t.length;c++){let a=t[c];if(a[s]){let u={};for(let f of i.properties){let d=f.key,p=f.value;if(p.type===h.LITERAL)u[d]=p.value;else if(p.type===h.VARIABLE){let g=p.path;if(g===r)u[d]=a;else if(g.startsWith(r+".")){let y=g.substring(r.length+1);u[d]=a[y]}else return null}else if(p.type===h.INTERPOLATION){let g=[],y=!0;for(let I of p.parts)if(typeof I=="string")g.push(I);else if(I.type===h.VARIABLE){let b=I.path;if(b===r)g.push(a!=null?String(a):"");else if(b.startsWith(r+".")){let m=b.substring(r.length+1),x=a[m];g.push(x!=null?String(x):"")}else{y=!1;break}}else{y=!1;break}if(!y)return null;u[d]=g.join("")}else return null}l.push(u)}}return l}}}return null},mo=(e,t)=>{let n=e.body,r=e.itemVar,o=go(e,t);if(o!==null)return o;if(n.type===h.OBJECT&&n.properties.length<=5&&!n.whenCondition){for(let l of n.properties)if(l.parsedKey)return null;let i=[],s=!0;for(let l of n.properties){let c=l.key,a=l.value;if(a.type===h.LITERAL)i.push({key:c,type:"literal",value:a.value});else if(a.type===h.VARIABLE){let u=a.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(a.type===h.INTERPOLATION&&a.parts.length===1){let u=a.parts[0];if(u.type===h.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 l=new Array(t.length);if(i.length===3&&i[0].type==="prop"&&i[0].key==="id"&&i[1].type==="prop_string"&&i[1].key==="title"&&i[2].type==="prop"&&i[2].key==="completed")for(let c=0;c<t.length;c++){let a=t[c];l[c]={id:a.id,title:a.title!=null?String(a.title):"",completed:a.completed}}else for(let c=0;c<t.length;c++){let a=t[c],u={};for(let f of i)if(f.type==="literal")u[f.key]=f.value;else if(f.type==="item")u[f.key]=a;else if(f.type==="prop")u[f.key]=a[f.prop];else if(f.type==="item_string")u[f.key]=a!=null?String(a):"";else if(f.type==="prop_string"){let d=a[f.prop];u[f.key]=d!=null?String(d):""}l[c]=u}return l}}return null},yo=(e,t,n,r,o)=>{let i=[],s=e.body;if(s.type===h.OBJECT&&s.fast!==!1){let l=e.itemVar,c=e.indexVar;for(let a=0;a<o.length;a++){let u=o[a],f={},d={...r,[l]:u,...c&&{[c]:a}};d.__paths__||(d.__paths__=r.__paths__||{});let p=e.iterable.path||"";if(r&&r.__paths__&&p){let g=p.split("."),y=g[0];y in r.__paths__&&(p=r.__paths__[y],g.length>1&&(p+="."+g.slice(1).join(".")))}d.__paths__={...d.__paths__,[l]:`${p}[${a}]`,...c&&{[c]:a}};for(let g of s.properties){let y=g.parsedKey?C(g.parsedKey,t,n,d):g.key,I=g.value;if(I.type===h.LITERAL)f[y]=I.value;else if(I.type===h.VARIABLE){let b=I.path;if(b===l)f[y]=u;else if(b===c)f[y]=a;else if(b.startsWith(l+".")){let m=b.substring(l.length+1);!m.includes(".")&&!m.includes("[")?f[y]=u[m]:f[y]=V(b,n,{...r,[l]:u,...c&&{[c]:a}})}else f[y]=V(b,n,{...r,[l]:u,...c&&{[c]:a}})}else if(I.type===h.INTERPOLATION){let b=[];for(let m of I.parts)if(typeof m=="string")b.push(m);else if(m.type===h.VARIABLE){let x=m.path,E;if(x===l)E=u;else if(x===c)E=a;else if(x.startsWith(l+".")){let L=x.substring(l.length+1);!L.includes(".")&&!L.includes("[")?E=u[L]:E=V(x,n,{...r,[l]:u,...c&&{[c]:a}})}else E=V(x,n,{...r,[l]:u,...c&&{[c]:a}});b.push(E!=null?String(E):"")}else{let x={...r,[l]:u,...c&&{[c]:a}},E=C(m,t,n,x);b.push(E!=null?String(E):"")}f[y]=b.join("")}else{let b={...r,[l]:u,...c&&{[c]:a}};f[y]=C(I,t,n,b)}}i.push(f)}return i}return null},bo=(e,t,n)=>{let r=e.body;if(r.type===h.OBJECT&&r.properties.length===1&&r.properties[0].key==="$if item.visible"){let i=r.properties[0].value;if(i.type===h.CONDITIONAL&&i.conditions.length===1&&i.conditions[0].type===h.VARIABLE&&i.conditions[0].path==="item.visible"){let s=i.bodies[0];if(s.type===h.OBJECT&&s.properties.length===2){let l=s.properties[0],c=s.properties[1];if(l.key==="id"&&l.value.type===h.VARIABLE&&l.value.path==="item.id"&&c.key==="$if item.highlighted"&&c.value.type===h.CONDITIONAL){let a=[];for(let u=0;u<t.length;u++){let f=t[u];if(f.visible){let d={id:f.id};f.highlighted?(d.highlight=!0,d.message=`This item is highlighted: ${f.name}`):(d.highlight=!1,d.message=f.name),a.push(d)}}return a}}}}return null},Io=(e,t,n,r)=>{let o=C(e.iterable,t,n,r);if(!Array.isArray(o)){let a,u=!1;if(e.iterable.type===h.FUNCTION){u=!0;let d=e.iterable.args.map(p=>p.type===h.LITERAL?typeof p.value=="string"?`'${p.value}'`:String(p.value):p.type===h.VARIABLE?p.path:p.type===h.FUNCTION?`${p.name}(...)`:"?").join(", ");a=`${e.iterable.name}(${d})`}else a=e.iterable.path||"undefined";let f=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${a}`;throw _n(f,o,u)}if(!e.indexVar){let a=bo(e,o,e.itemVar);if(a!==null)return a}if(!e.indexVar){let a=mo(e,o);if(a!==null)return a}let i=yo(e,t,n,r,o);if(i!==null)return i;let s=[],l=e.iterable.path||"";if(r&&r.__paths__&&l){let a=l.split("."),u=a[0];u in r.__paths__&&(l=r.__paths__[u],a.length>1&&(l+="."+a.slice(1).join(".")))}let c=!1;e.body.type===h.ARRAY&&(e.body.items.length<=1?c=!1:c=e.body._shouldPreserveArray??=e.body.items.some(a=>a.type===h.OBJECT&&a.properties.some(u=>u.key.startsWith("$if ")||u.key.startsWith("$when "))));for(let a=0;a<o.length;a++){let u=e.indexVar?{...r,[e.itemVar]:o[a],[e.indexVar]:a}:{...r,[e.itemVar]:o[a]};u.__paths__||(u.__paths__=r.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${l}[${a}]`},e.indexVar&&(u.__paths__[e.indexVar]=a);let f=C(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},Ao=(e,t,n,r)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?C(o.parsedKey,t,n,r):o.key,s=o.value;if(s.type===h.OBJECT&&s.properties.length<=10&&!s.whenCondition){let l={},c={},a=!0;for(let u of s.properties){let f=u.parsedKey?C(u.parsedKey,t,n,r):u.key,d=u.value;if(d.type===h.LITERAL)c[f]=d.value;else if(d.type===h.VARIABLE)c[f]=V(d.path,n,r);else if(d.type===h.INTERPOLATION){let p=[];for(let g of d.parts)if(typeof g=="string")p.push(g);else if(g.type===h.VARIABLE){let y=V(g.path,n,r);p.push(y!=null?String(y):"")}else{a=!1;break}if(!a)break;c[f]=p.join("")}else if(d.type===h.OBJECT&&d.properties.length<=5){let p={};for(let g of d.properties){let y=g.key,I=g.value;if(I.type===h.LITERAL)p[y]=I.value;else if(I.type===h.VARIABLE)p[y]=V(I.path,n,r);else if(I.type===h.INTERPOLATION){let b=[];for(let m of I.parts)if(typeof m=="string")b.push(m);else if(m.type===h.VARIABLE){let x=V(m.path,n,r);b.push(x!=null?String(x):"")}else{a=!1;break}if(!a)break;p[y]=b.join("")}else{a=!1;break}}if(!a)break;c[f]=p}else{a=!1;break}}if(a)return l[i]=c,l}}return null},xo=(e,t,n,r)=>{let o=t.functions||t;if(e.whenCondition&&!we(e.whenCondition,o,n,r))return;let i=Ao(e,t,n,r);if(i!==null)return i;if(e.fast){let a={};for(let u of e.properties){let f=u.parsedKey?C(u.parsedKey,t,n,r):u.key,d=u.value;if(d.type===h.LITERAL)a[f]=d.value;else if(d.type===h.VARIABLE)a[f]=V(d.path,n,r);else if(d.type===h.INTERPOLATION){let p=[];for(let g of d.parts)if(typeof g=="string")p.push(g);else if(g.type===h.VARIABLE){let y=V(g.path,n,r);p.push(y!=null?String(y):"")}else{let y=C(g,t,n,r);p.push(y!=null?String(y):"")}a[f]=p.join("")}else a[f]=C(d,t,n,r)}return a}let s={},l=null,c=!1;for(let a of e.properties)if(!a.key.startsWith("$if ")&&!a.key.match(/^\$if\s+\w+.*:?$/)&&!a.key.startsWith("$elif")&&!a.key.startsWith("$else")&&!a.key.startsWith("$for ")){c=!0;break}for(let a of e.properties)if(a.key.startsWith("$if ")||a.key.match(/^\$if\s+\w+.*:?$/)){let u=C(a.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(a.key.startsWith("$for ")){if(e.properties.length===1)return C(a.value,t,n,r)}else{let u=a.value;if(u&&u.type===h.OBJECT&&u.properties){let f=u.properties.find(d=>d.key.startsWith("$for "));if(f){let d=C(f.value,t,n,r);d!==void 0&&(s[a.key]=d)}else{let d=C(a.value,t,n,r);d!==void 0&&(s[a.key]=d)}}else{let f=a.parsedKey?C(a.parsedKey,t,n,r):a.key,d=C(a.value,t,n,r);d!==void 0&&(s[f]=d)}}return s},$n={},wo=(e,t,n,r)=>{let o=[];for(let i of e.items)if(i.type===h.LOOP){let s=C(i,t,n,r);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=C(i,t,n,r);s!==$n&&s!==void 0&&o.push(s)}return o},vo=(e,t,n,r)=>{let{name:o,data:i,whenCondition:s}=e,l=t.partials||{},c=t.functions||t;if(s&&!we(s,c,n,r))return;if(!l[o])throw new Y(`Partial '${o}' is not defined`);let a=r._partialStack||[];if(a.includes(o))throw new Y(`Circular partial reference detected: ${o}`);let u=l[o],f=n,d={...r,_partialStack:[...a,o]};if(r){f={...n};for(let p of Object.keys(r))p.startsWith("_")||(f[p]=r[p])}if(i){let p=C(i,t,n,r);f={...f,...p}}return C(u,t,f,d)},Eo=(e,t,n,r)=>{let{path:o}=e,i=o.split("."),s=i[0],l=i.slice(1);if(!r||!(s in r))throw new Y(`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 Y(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let c=r.__paths__[s];if(typeof c=="number"){if(l.length>0)throw new Y(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(c)}return l.length>0&&(c+="."+l.join(".")),c},_t=lo;var _o=/\$\{([^}]*)\}/g,So=/#\{([^}]*)\}/g,Pn=(e,t={})=>{let n=e.match(/^(\w+)\((.*)\)$/);if(!n)return{isFunction:!1};let[,r,o]=n,i=Co(o,t);return{isFunction:!0,type:h.FUNCTION,name:r,args:i}},Co=(e,t={})=>e.trim()?Lo(e).map(r=>Ro(r.trim(),t)):[],Lo=e=>{let t=[],n="",r=0,o=!1,i="";for(let s=0;s<e.length;s++){let l=e[s],c=s>0?e[s-1]:"";!o&&(l==='"'||l==="'")?(o=!0,i=l,n+=l):o&&l===i&&c!=="\\"?(o=!1,i="",n+=l):!o&&l==="("?(r++,n+=l):!o&&l===")"?(r--,n+=l):!o&&l===","&&r===0?(t.push(n),n=""):n+=l}return n&&t.push(n),t},Ro=(e,t={})=>{if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:h.LITERAL,value:e.slice(1,-1)};if(/^-?\d+(\.\d+)?$/.test(e))return{type:h.LITERAL,value:parseFloat(e)};if(e==="true")return{type:h.LITERAL,value:!0};if(e==="false")return{type:h.LITERAL,value:!1};if(e==="null")return{type:h.LITERAL,value:null};let n=Pn(e,t);if(n.isFunction)return{type:n.type,name:n.name,args:n.args};let r=e.trim(),o=[{op:" + ",type:"ADD"},{op:" - ",type:"SUBTRACT"}],i=-1,s=null;for(let{op:l,type:c}of o){let a=0;for(;a<r.length;){let u=fe(r.substring(a),l);if(u===-1)break;let f=a+u;f>i&&(i=f,s={op:l,type:c}),a=f+l.length}}if(i!==-1)try{return z(r,t)}catch{return{type:h.VARIABLE,path:r}}return{type:h.VARIABLE,path:r}},Tn=/^\w+\(.*\)$/,ko=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,$o=e=>{if(!(!e||e.trim()===""||Tn.test(e))&&ko.test(e))throw e.includes("?")&&e.includes(":")?new w(`Complex expressions not supported in variable replacements - consider calculating the value in your data instead. Offending expression: "${e}"`):e.includes("||")||e.includes("&&")||e.includes("??")?new w(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new w(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},On=e=>{let t=e.trim();if(Tn.test(t))throw new w(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new w(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new w(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new w(`Logical operators not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("?")&&t.includes(":"))throw new w(`Complex expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);return{type:h.PATH_REFERENCE,path:t}},ke=(e,t={})=>{let n=e.trim();$o(n);let r=Pn(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:h.VARIABLE,path:n}},St=(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,(a,u)=>{let f=`__ESCAPED_${r.length}__`;return r.push(u),f}),n=n.replace(/\\(#\{[^}]*\})/g,(a,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(_o)],i=[...n.matchAll(So)],s=[...o.map(a=>({match:a,type:"variable"})),...i.map(a=>({match:a,type:"pathref"}))].sort((a,u)=>a.match.index-u.match.index);if(s.length===0){let a=n;for(let u=0;u<r.length;u++)a=a.replace(`__ESCAPED_${u}__`,r[u]);return{type:h.LITERAL,value:a}}if(s.length===1&&s[0].match[0]===n&&r.length===0){let{match:a,type:u}=s[0];try{return u==="variable"?ke(a[1],t):On(a[1])}catch(f){if(f.message==="Invalid array index syntax")return{type:h.LITERAL,value:n};throw f}}let l=[],c=0;for(let{match:a,type:u}of s){let[f,d]=a,p=a.index;if(p>c){let g=n.substring(c,p);for(let y=0;y<r.length;y++)g=g.replace(`__ESCAPED_${y}__`,r[y]);g&&l.push(g)}try{let g;u==="variable"?g=ke(d.trim(),t):g=On(d.trim()),l.push(g)}catch(g){if(g.message==="Invalid array index syntax")l.push(f);else throw g}c=p+f.length}if(c<n.length){let a=n.substring(c);for(let u=0;u<r.length;u++)a=a.replace(`__ESCAPED_${u}__`,r[u]);a&&l.push(a)}return{type:h.INTERPOLATION,parts:l}};var se=(e,t)=>typeof e=="string"?St(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?Po(e,t):To(e,t):{type:h.LITERAL,value:e},Oo=e=>{let{$each:t,...n}=e;if(typeof t!="string")throw new w("$each value must be a non-empty string");let r=t.trim();if(r==="")throw new w("$each value must be a non-empty string");if(Object.keys(n).length===0)throw new w("Empty $each body not allowed");if(n.$partial!==void 0)throw new w("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${r}`]:n}},Po=(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=Oo(i),a=Object.keys(c);if(a.length===1&&/^\$for(?::\w+)?\s/.test(a[0])){let u=Nn(a[0],c[a[0]],t,!0);n.push(u),r=!0;continue}}catch(c){throw c instanceof w?c:new w(c.message)}let l=Object.keys(i);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let c=Nn(l[0],i[l[0]],t);n.push(c),r=!0;continue}}let s=se(i,t);n.push(s),(s.type===h.FUNCTION||s.type===h.CONDITIONAL||s.type===h.LOOP||s.type===h.PARTIAL||s.type===h.OBJECT&&!s.fast||s.type===h.ARRAY&&!s.fast)&&(r=!0)}return{type:h.ARRAY,items:n,fast:!r}},To=(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 w("$partial value must be a string");if(e.$partial.trim()==="")throw new w("$partial value cannot be an empty string");let c=["$if","$elif","$else","$for"],a=[];for(let[b]of i)for(let m of c)if(b===m||b.startsWith(m+" ")||b.startsWith(m+"#")){a.push(m);break}if(a.length>0)throw new w(`Cannot use $partial with ${a.join(", ")} at the same level. Wrap $partial in a parent object if you need conditionals.`);let{$partial:u,$when:f,...d}=e,p={},g=!1;for(let[b,m]of Object.entries(d)){let x=b;(b.startsWith("\\$")||b.startsWith("$$"))&&(x=b.slice(1)),p[x]=m,g=!0}let y=null;if(g&&(y=se(p,t),y.type===h.OBJECT)){let b=!1;for(let m of y.properties)if(m.value.type===h.VARIABLE||m.value.type===h.INTERPOLATION||m.value.type===h.FUNCTION||m.value.type===h.CONDITIONAL||m.value.type===h.OBJECT&&!m.value.fast||m.value.type===h.ARRAY&&!m.value.fast){b=!0;break}b&&(y.fast=!1)}let I={type:h.PARTIAL,name:u,data:y};if(f!==void 0){let b;if(typeof f=="string"){if(f.trim()==="")throw new w("Empty condition expression after '$when'");b=z(f,t)}else b={type:h.LITERAL,value:f};I.whenCondition=b}return I}for(let[c,a]of i)if(c==="$when"){if(o!==null)throw new w("Multiple '$when' directives on the same object are not allowed");if(a==null)throw new w("Missing condition expression after '$when'");let u=typeof a=="string"?a:JSON.stringify(a);if(u.trim()==="")throw new w("Empty condition expression after '$when'");o=z(u,t),r=!0}else if(c.startsWith("$when#")||c.startsWith("$when "))throw new w("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<i.length;){let[c,a]=i[s];if(c==="$when"){s++;continue}if(c==="$each")throw new w("$each can only be used inside arrays");if(c.startsWith("$if ")||c.match(/^\$if#\w+\s/)||c.match(/^\$if\s+\w+.*:$/)){let u=No(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 w(`$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 w(`'${c.split(" ")[0]}' without matching '$if'`);if(c==="$if"||c==="$if:")throw new w("Missing condition expression after '$if'");{let u=se(a,t);(u.type===h.FUNCTION||u.type===h.CONDITIONAL||u.type===h.PARTIAL||u.type===h.OBJECT&&!u.fast||u.type===h.ARRAY&&!u.fast)&&(r=!0);let f=St(c,t),d={key:c,value:u};(f.type!==h.LITERAL||f.value!==c)&&(d.parsedKey=f),n.push(d),s++}}}let l={type:h.OBJECT,properties:n,fast:!r};return o&&(l.whenCondition=o),l},No=(e,t,n={})=>{let r=[],o=[],i=t,[s,l]=e[i],c=null,a;if(s.startsWith("$if#")){let f=s.match(/^\$if#(\w+)\s+(.+)$/);if(f)c=f[1],a=f[2];else throw new w(`Invalid conditional syntax: ${s}`)}else a=s.substring(4),a.endsWith(":")&&(a=a.slice(0,-1).trim());Et(a);let u=z(a,n);for(r.push(u),o.push(se(l,n)),i++;i<e.length;){let[f,d]=e[i],p=!1,g;if(c?f.startsWith(`$elif#${c} `)?(g=f.substring(`$elif#${c} `.length),g.endsWith(":")&&(g=g.slice(0,-1).trim()),p=!0):(f===`$else#${c}`||f===`$else#${c}:`)&&(p=!0,g=null):f.startsWith("$elif ")?(g=f.substring(6),g.endsWith(":")&&(g=g.slice(0,-1).trim()),p=!0):(f==="$else"||f==="$else:")&&(p=!0,g=null),p){if(g===null)r.push(null);else{Et(g);let y=z(g,n);r.push(y)}if(o.push(se(d,n)),i++,g===null)break}else break}return{node:{type:h.CONDITIONAL,conditions:r,bodies:o,id:c},nextIndex:i}},z=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let a=e.slice(1,-1),u=0,f=!0;for(let d=0;d<a.length;d++)if(a[d]==="("?u++:a[d]===")"&&u--,u<0){f=!1;break}if(f&&u===0)return z(a,t)}let n=fe(e,"||");if(n!==-1)return{type:h.BINARY,op:T.OR,left:z(e.substring(0,n).trim(),t),right:z(e.substring(n+2).trim(),t)};let r=fe(e,"&&");if(r!==-1)return{type:h.BINARY,op:T.AND,left:z(e.substring(0,r).trim(),t),right:z(e.substring(r+2).trim(),t)};let o=[{op:">=",type:T.GTE},{op:"<=",type:T.LTE},{op:"==",type:T.EQ},{op:"!=",type:T.NEQ},{op:">",type:T.GT},{op:"<",type:T.LT},{op:" in ",type:T.IN}];for(let{op:a,type:u}of o){let f=fe(e,a);if(f!==-1)return{type:h.BINARY,op:u,left:z(e.substring(0,f).trim(),t),right:z(e.substring(f+a.length).trim(),t)}}let i=-1,s=null,l=[{op:" + ",type:T.ADD},{op:" - ",type:T.SUBTRACT}];for(let{op:a,type:u}of l){let f=0;for(;f<e.length;){let d=fe(e.substring(f),a);if(d===-1)break;let p=f+d;p>i&&(i=p,s={op:a,type:u}),f=p+a.length}}if(i!==-1&&s)return{type:h.BINARY,op:s.type,left:z(e.substring(0,i).trim(),t),right:z(e.substring(i+s.op.length).trim(),t)};let c=[" * "," / "," % "];for(let a of c)if(fe(e,a)!==-1)throw new w(`Arithmetic operations are not allowed in conditionals: "${a}"`);return e.startsWith("!")?{type:h.UNARY,op:Re.NOT,operand:z(e.substring(1).trim(),t)}:Dn(e,t)},fe=(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},Do=e=>{if(e=e.trim(),e==="true")return{type:h.LITERAL,value:!0};if(e==="false")return{type:h.LITERAL,value:!1};if(e==="null")return{type:h.LITERAL,value:null};if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:h.LITERAL,value:e.slice(1,-1)};if(e==='""'||e==="''")return{type:h.LITERAL,value:""};if(e==="{}")return{type:h.LITERAL,value:{}};if(e==="[]")return{type:h.LITERAL,value:[]};let t=Number(e);return!isNaN(t)&&isFinite(t)?{type:h.LITERAL,value:t}:{type:h.VARIABLE,path:e}},Dn=(e,t)=>{let n=e.trim();if(n.match(/^(\w+)\((.*)\)$/))return ke(n,t);let o=Do(n);if(o.type===h.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(n))return{type:h.VARIABLE,path:n};try{return ke(n,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},Vo=(e,t=!1)=>{let n=t?"$each":"$for";try{En(e)}catch(r){if(r instanceof w&&t){let o=r.message.replace(/\$for/g,"$each");throw new w(o.replace("Parse Error: ",""))}throw r}},Nn=(e,t,n,r=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let I=r?"$each":"$for";throw new w(`Invalid loop syntax (got: '${e.replace("$for",I)}')`)}let s=i[1],l=i[2].trim();Vo(l,r);let c=l.match(/^(.+?)\s+in\s+(.+)$/);if(!c){let I=r?"$each":"$for";throw new w(`Invalid loop syntax - missing 'in' keyword (got: '${I} ${l}')`)}let a=c[1].trim(),u=c[2].trim(),f,d=null;if(a.includes(",")){let I=a.split(",").map(b=>b.trim());if(I.length!==2)throw new w(`Invalid loop variables: ${a}. Expected format: "item" or "item, index"`);f=I[0],d=I[1]}else f=a;let p=["this","undefined","null","true","false"];if(p.includes(f))throw new w(`Reserved variable name: ${f}`);if(d&&p.includes(d))throw new w(`Reserved variable name: ${d}`);let g=Dn(u,n),y=se(t,n);return{type:h.LOOP,itemVar:f,indexVar:d,iterable:g,body:y,flatten:s!=="nested"}};var Mo=(e,t={})=>{let{functions:n={}}=t;return se(e,n)},He=Mo;var Ct={};Qr(Ct,{now:()=>jo});var jo=()=>Date.now();var Bo=(e,t,n={})=>{let{functions:r={},partials:o={}}=n,i={...Ct,...r},s=He(e,{functions:i}),l={};for(let[c,a]of Object.entries(o))l[c]=He(a,{functions:i});return _t(s,t,{functions:i,partials:l})},X=Bo;var Vn=(e,t,n={})=>{let r=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=c=>c,transformActionFirstArgument:l=c=>c}=n;for(let[c,a]of Object.entries(t))c!=="createInitialState"&&(c.startsWith("select")?o[c]=(...u)=>a(s(r),...u):i[c]=(...u)=>{r=vt(r,d=>a(l(d),...u))});return{...o,...i}},Ge=(e,t)=>n=>{let r=e(),o=Array.isArray(n)?n:[n];return vt(r,i=>{o.forEach(s=>{t.forEach(l=>{l(i,s)})})})};var Fo=(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{}}},kt=e=>{let t={},n={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([r,o])=>{let i=Fo(o,r);o.scope==="context"?t[r]=i:n[r]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}},$t=(e,t)=>{let n=["context","device","account"];if(!e)throw new Error(`Variable scope is required for variable: ${t}`);if(!n.includes(e))throw new Error(`Invalid variable scope: ${e} for variable ${t}. Expected one of: ${n.join(", ")}`)},Ot=(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(", ")}`)},Pt=(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}`)}},Tt=(e,t,n)=>Object.fromEntries(Object.entries(e).filter(([r])=>t?.[r]?.scope===n)),Mn=(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()))},Uo=(e,t)=>{let n=e?.ui,r=t?.ui;return JSON.stringify(n)===JSON.stringify(r)?null:n&&!r?{changeType:"delete",data:e}:r&&!e?{changeType:"add",data:t}:r&&e?{changeType:"update",data:t}:null},Nt=(e={},t={})=>{let n={},r=["sfx","voice"],o=s=>{let l=e[s],c=t[s];c&&!l?n[s]={changeType:"add",data:c}:l&&!c?r.includes(s)||(n[s]={changeType:"delete",data:l}):l&&c&&JSON.stringify(l)!==JSON.stringify(c)&&(n[s]={changeType:"update",data:c})};o("background"),o("bgm"),o("voice");let i=Uo(e.dialogue,t.dialogue);return i&&(n.dialogue=i),o("choice"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),n},Dt=(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);let r=(o,i)=>{let s=t[o]?.items;Array.isArray(s)&&(t[o].items=s.map(l=>{let c={...l};return delete c.animations,i(c)?c:null}).filter(Boolean),t[o].items.length===0&&delete t[o])};return r("character",o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId),r("visual",o=>o.resourceId||o.transformId),t},zo=(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},Wo=(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=zo(t,n);if(r===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return r},Yo={updateProjectData:new Set(["projectData"]),showConfirmDialog:new Set(["confirmActions","cancelActions"])},jn=(e,t)=>{let n=e[e.length-1];return n?Yo[n]?.has(t)===!0:!1},Lt=(e,t,n=[])=>Array.isArray(e)?e.map(r=>Lt(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,jn(n,r)?o:Lt(o,t,[...n,r])])):Wo(e,t),Rt=(e,t,n=[])=>Array.isArray(e)?e.map(r=>Rt(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,jn(n,r)?o:Rt(o,t,[...n,r])])):typeof e=="string"?X(e,t):e,Bn=(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=Lt(e,t._event);return Rt(n,t)};var Ke=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:structuredClone(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},Un=(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}},$e=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Fn=e=>e?.animations?.playback?.continuity==="persistent",Ho=e=>{if(e){if(e.character&&$e(e.character,"name"))return e.character.name;if($e(e,"characterName"))return e.characterName}},Go=()=>({}),Ko=(e,t)=>{if(t.background){let{animationsOnly:n,state:r}=Ke(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&&!$e(o,"animations")&&Fn(i)&&(o.animations=structuredClone(i.animations)),e.background=o}else e.background?.animations&&!Fn(e.background)&&(e.background.animations={})},qo=(e,t)=>{if(!t.dialogue){e.dialogue&&e.dialogue.mode==="adv"&&(e.dialogue.content=void 0,e.dialogue.persistCharacter!==!0&&(delete e.dialogue.characterId,delete e.dialogue.character));return}if(e.dialogue||(e.dialogue={}),t.dialogue.ui){let{animationsOnly:s,state:l}=Ke(t.dialogue.ui,c=>!!c.resourceId);s?e.dialogue.ui={...e.dialogue.ui,...l}: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"),t.dialogue.content!==void 0&&(e.dialogue.content=t.dialogue.content);let n=$e(t.dialogue,"persistCharacter")?t.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;n?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let r=$e(t.dialogue,"characterId"),o=Ho(t.dialogue),i=o!==void 0;if(r?t.dialogue.characterId?e.dialogue.characterId=t.dialogue.characterId:delete e.dialogue.characterId:n||delete e.dialogue.characterId,i?e.dialogue.character={name:o}:(r||!n)&&delete e.dialogue.character,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 s={content:t.dialogue.content,characterId:e.dialogue.characterId??null};e.dialogue.character&&(s.character={...e.dialogue.character}),e.dialogue.lines.push(s)}},Xo=(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},Jo=(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}}},Zo=(e,t)=>{if(t.visual){let{hasValidItems:n,processedItems:r}=Un(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))},Qo=(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}=Un(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId);n?e.character={items:r}:delete e.character},ei=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},ti=(e,t)=>{if(t.layout){let{animationsOnly:n,state:r}=Ke(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},ni=(e,t)=>{if(t.choice){let{animationsOnly:n,state:r}=Ke(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},ri=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},oi=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},ii=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(n=>{delete e[n]})},ve=e=>Ge(Go,[ii,Ko,Xo,Jo,Zo,qo,Qo,ei,ti,ni,ri,oi])(e);var pe={objectValues:e=>Object.entries(e).map(([t,n])=>({id:t,...n})),formatDate:Mn},si=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,ai=(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},Je=(e,t,n)=>{if(Array.isArray(e)){let o=[];for(let i of e){if(i&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===1){let[s]=Object.keys(i),l=si.exec(s);if(l){let[,c,a,u]=l,f=ai(t,u);if(!Array.isArray(f))continue;let d=Array.isArray(i[s])?i[s]:[];f.forEach((p,g)=>{let y={...t,[c]:p};a&&(y[a]=g),d.forEach(I=>{let b=Je(I,y,n),m=X(b,y,n);Array.isArray(m)?o.push(...m):o.push(m)})});continue}}o.push(Je(i,t,n))}return o}if(!e||typeof e!="object")return e;let r={};return Object.entries(e).forEach(([o,i])=>{r[o]=Je(i,t,n)}),r},Yt=({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".`)},ci=({id:e,targetId:t,animation:n,playback:r,animationPath:o="animation"})=>{let i=structuredClone(n);return Yt({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},li=(e,{animationId:t="animation",animationPath:n="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return Yt({animationType:e.type,animationId:t,animationPath:n}),e.type},ui=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},fi=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},di=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Qn=e=>e?.playback?.continuity==="persistent",Ft=e=>Array.isArray(e)?e.map(Ft):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((t,n)=>(t[n]=Ft(e[n]),t),{}),Ze=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let t=structuredClone(e);return delete t.playback,JSON.stringify(Ft(t))},er=(e=[])=>e.filter(t=>Qn(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,Vt=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(Vt(e.tween),Vt(e.prev?.tween),Vt(e.next?.tween),tr(e.mask?.progress)),zn=({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(Ze).filter(Boolean));return e.some(r=>{if(!Qn(r))return!1;let o=Ze(r);return o?n.has(o):!1})},de=({animationInstances:e,isLineCompleted:t,skipTransitionsAndAnimations:n,activePersistentAnimations:r,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||n?!1:i&&!t||zn({animationInstances:e,activePersistentAnimations:r})?!0:i?!1:zn({animationInstances:e,activePersistentAnimations:o}),pi=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),hi=(e,t)=>{if(pi(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},gi=({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?ci({id:r,targetId:o,animation:s,playback:n,animationPath:i}):null},mi=({hasPrevious:e,hasCurrent:t,previousResourceId:n,currentResourceId:r,sharedTarget:o})=>!e&&t?"enter":e&&!t?"exit":e&&t?n===r&&o?"update":"replace":"none",yi=({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.`)},bi=(e,{defaultTargetId:t,defaultId:n,animationPath:r="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return Yt({animationType:o.type,animationId:o.id??n,animationPath:r}),o.id??=n,o.targetId??=t,o},Ht=({animations:e,transitions:t,defaultTargetId:n,idPrefix:r,animationPathPrefix:o=r})=>{t.forEach((i,s)=>{e.push(bi(i,{defaultTargetId:n,defaultId:`${r}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},Wn=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let n=X(e,t);return n&&typeof n=="object"?e:n},Yn=(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},Hn=(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))},qe=(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("-")}`},Mt=(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},Ii=(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},Gn=(e={},t)=>{if(t){if(e.images?.[t])return"sprite";if(e.videos?.[t])return"video";if(e.layouts?.[t])return"container"}},Xe=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},Ai=(e={})=>e.textStyles||{},xi=(e={})=>e.images||{},wi=(e={})=>e.colors||{},vi=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,Oe=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,Ee=(e,t,n)=>{if(typeof e!="string"||e.length===0)throw new Error(`${n} at "${t}" must resolve to a non-empty string`)},Kn=(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},rr=(e,t)=>{if(typeof e!="string"||!vi.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},qn=(e,t,n)=>{let r=rr(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})`},Ei=(e={},t)=>{let n=Ai(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=Kn(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:qn(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 l=e.colors?.[n.strokeColorId];if(!l)throw new Error(`Stroke color "${n.strokeColorId}" not found for text style "${t}"`);let c=Kn(n.strokeAlpha,"strokeAlpha",t);s.strokeColor=qn(l.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},Ut=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>Ut(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]=Ut(i,t,Oe(n,o)));return e.textStyleId!==void 0&&(Ee(e.textStyleId,n,"textStyleId"),r.textStyle=Ei(t,e.textStyleId)),r},or=(e={},t)=>{let n=wi(e)?.[t];if(!n)throw new Error(`Color "${t}" not found`);return rr(n.hex,`Color "${t}"`)},ir=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",jt=(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 ${ir(`${t}.fill`)} instead`)},_i=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>Pe(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]=Pe(i,t,Oe(n,o)));return e.colorId!==void 0&&(Ee(e.colorId,n,"colorId"),r.fill=or(t,e.colorId)),r},Pe=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>Pe(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 ${ir("fill")} instead`);jt(e,"hover",n),jt(e,"click",n),jt(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]=_i(i,t,Oe(n,o));continue}r[o]=Pe(i,t,Oe(n,o))}return e.type==="rect"&&e.colorId!==void 0&&(Ee(e.colorId,n,"colorId"),r.fill=or(t,e.colorId)),r},Bt=(e={},t)=>{let n=xi(e)?.[t];return n||null},sr=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",Xn=(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 ${sr(`${t}.${r}`)} instead`)},Jn=(e,t,n)=>{let r=e[t];e[t]={...r&&typeof r=="object"&&!Array.isArray(r)?r:{},src:n}},zt=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>zt(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 ${sr(o)} instead`);Xn(e,"hover",n,"src"),Xn(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]=zt(i,t,Oe(n,o)));if(e.type==="sprite"&&e.imageId!==void 0){Ee(e.imageId,n,"imageId");let o=Bt(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&&(Ee(e.hoverImageId,n,"hoverImageId"),Jn(r,"hover",Bt(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(Ee(e.clickImageId,n,"clickImageId"),Jn(r,"click",Bt(t,e.clickImageId)?.fileId??e.clickImageId)),r},Gt=(e,t={},n="root")=>zt(Pe(Ut(e,t,n),t,n),t,n),he=Gt,et=(e=[])=>e.find(t=>t.id==="story");var Si=(e={})=>e?.muteAll?0:e?.musicVolume??50,ee=({variables:e,runtime:t,saveSlots:n=[],dialogueState:r,includeInactiveAdvDialogue:o=!1,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:c,canRollback:a,confirmDialog:u,historyDialogue:f=[],characters:d={},dialogueUIHidden:p,skipOnlyViewedLines:g,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??l??!1,dialogueUIHidden:t?.dialogueUIHidden??p??!1,isLineCompleted:t?.isLineCompleted??i??!1},b=ki({dialogueState:r,includeInactiveAdvDialogue:o,characters:d,variables:e}),m={variables:e,runtime:I,saveSlots:n,isChoiceVisible:c,canRollback:a,confirmDialog:u,historyDialogue:f,characters:d};return b&&(m.dialogue=b,m.dialogueLines=b.lines),m},Zn=100,Qe=(e,t)=>{if(Array.isArray(e))return e.map(r=>Qe(r,t));if(!e||typeof e!="object")return e;let n={...e};return Object.keys(n).forEach(r=>{n[r]=Qe(n[r],t)}),n.type==="text-revealing"?t(n):n},Ci=e=>Qe(e,t=>({...t,revealEffect:"none"})),Li=e=>Qe(e,t=>{let n=Number(t.speed??t.displaySpeed),r=Number.isFinite(n)?Math.max(n,Zn):Zn;return{...t,speed:r,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:r}:{}}}),ge=(e,{isLineCompleted:t=!1,skipMode:n=!1,skipTransitionsAndAnimations:r=!1}={})=>t||r?Ci(e):n?Li(e):e,ar=({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:{}}}}),Wt=e=>{if(Array.isArray(e))return e.map(Wt);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=Wt(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}}:{}}}}},cr=(e=[],t={})=>e.map(n=>{let r=t?.[n.characterId],o=n.character?.name!==void 0?n.character.name:n.characterName!==void 0?n.characterName:r?.name||"",i=typeof n.text=="string"?n.text:Array.isArray(n.content)?n.content.map(s=>s?.text??"").join(""):"";return{...n,text:i,character:{...n.character||{},name:o},characterName:o}}),Ri=e=>!(!e||e.mode==="adv"&&e.content===void 0),ki=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:n={},variables:r}={})=>{if(!t&&!Ri(e))return;let o;e.characterId&&(o=n?.[e.characterId]),e.character&&(o={...o,name:e.character.name});let i=e.content===void 0?[{text:""}]:Yn(e.content,"dialogue.content"),s=(e.lines||[]).map((l,c)=>{let a=Yn(l.content,`dialogue.lines[${c}].content`),u=l.character?.name!==void 0?l.character.name:l.characterName!==void 0?l.characterName:l.characterId&&n?.[l.characterId]?.name||"";return{...l,content:a.map(f=>({...f,text:Wn(f.text,{variables:r})})),character:{...l.character||{},name:u},characterName:u}});return{characterId:e.characterId,persistCharacter:e.persistCharacter,character:{...e.character||{},name:o?.name||""},content:i.map(l=>({...l,text:Wn(l.text,{variables:r})})),lines:s}},lr=({container:e,resources:t,templateData:n,isLineCompleted:r=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=X(e,n,{functions:pe});return he(ge(s,{isLineCompleted:r,skipMode:o,skipTransitionsAndAnimations:i}),t)},$i=(e={})=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,{payload:{actions:structuredClone(n?.actions||{})}}]))},_e=({animationsDef:e,resources:t,previousResourceId:n,currentResourceId:r,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:l,allowIncomingUpdateFallback:c=!1})=>{if(!e)return[];let a=[],u=({instanceId:E,targetId:L})=>{let R=gi({resources:t,animationId:y,playback:I,instanceId:E,targetId:L,animationPath:s});R&&a.push(R)},f=n!=null&&n!==!1,d=r!=null&&r!==!1,p=o&&i&&o===i,g=mi({hasPrevious:f,hasCurrent:d,previousResourceId:n,currentResourceId:r,sharedTarget:p});hi(e,s);let y=ui(e),I=fi(e),b=t?.animations?.[y],m=li(b,{animationId:y,animationPath:s}),x=c&&m==="update"&&g!=="update"&&d&&i;if(x||yi({animationType:m,animationId:y,animationPath:s,lifecycle:g}),m==="update")return f&&d&&n===r&&p?u({instanceId:`${l}-animation-update`,targetId:i}):x&&u({instanceId:`${l}-animation-update`,targetId:i}),a;if(m==="transition"){let E=`${l}-animation-transition`,L=I?.continuity==="persistent"?E:`${l}-animation-in`;if(f&&d&&p)return u({instanceId:E,targetId:i}),a;f&&u({instanceId:`${l}-animation-out`,targetId:o}),d&&u({instanceId:L,targetId:i})}return a},Oi=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),Pi=(e,{presentationState:t,previousPresentationState:n,currentLineActions:r,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:l,variables:c,runtime:a,activePersistentAnimations:u,restoredPersistentAnimations:f,autoMode:d,skipMode:p,isChoiceVisible:g,canRollback:y,saveSlots:I=[]})=>{let{elements:b,animations:m}=e;if(t.background){let x=r===void 0?!0:di(r?.background??{},"animations"),E=b.find($=>$.id==="story");if(!E)return e;let L=Ii(o,t.background),R=n?.background?.resourceId,S=t.background.resourceId??(t.background.animations?R:void 0),N=Gn(o,R),O=Gn(o,S);if(S){let{images:$={},videos:A={}}=o,v=$[S]||A[S];if(v){let D=A[S]!==void 0,B={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...L},F={id:Xe({resourceId:S,kind:D?"video":"sprite"}),type:D?"video":"sprite",x:B.x,y:B.y,src:v.fileId,width:v.width,height:v.height,alpha:1,anchorX:B.anchorX,anchorY:B.anchorY,rotation:B.rotation,scaleX:B.scaleX,scaleY:B.scaleY};D&&(F.loop=t.background.loop??!1,F.volume=v.volume??50),E.children.push(F)}}if(S){let{layouts:$={}}=o,A=$[S];if(A){let v={id:Xe({resourceId:S,kind:"container"}),type:"container",children:A.elements};L&&Object.assign(v,{x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...L});let D=X(v,ee({variables:c,runtime:a,saveSlots:I,dialogueState:t.dialogue,isLineCompleted:s,autoMode:d,skipMode:p,isChoiceVisible:g,canRollback:y,characters:o.characters||{},skipTransitionsAndAnimations:l}),{functions:pe});E.children.push(he(ge(D,{isLineCompleted:s,skipMode:p,skipTransitionsAndAnimations:l}),o))}}let k=_e({animationsDef:t.background.animations,resources:o,previousResourceId:R,currentResourceId:S,previousTargetId:Xe({resourceId:R,kind:N}),currentTargetId:Xe({resourceId:S,kind:O}),animationPath:"background.animations",idPrefix:"bg-cg",allowIncomingUpdateFallback:!0});de({animationInstances:k,isLineCompleted:s,skipTransitionsAndAnimations:l,activePersistentAnimations:u,restoredPersistentAnimations:f,isAuthoredOnCurrentLine:x})&&m.push(...k)}return e},Ti=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:l,animations:c}=e;if(t.character&&r){let a=l.find(g=>g.id==="story");if(!a)return e;let u=t.character.items||[],f=n?.character?.items||[],d=Hn(u),p=Hn(f);for(let g=0;g<u.length;g++){let y=u[g],{transformId:I,sprites:b}=y,m=f.find($=>$.id===y.id),x=f.findIndex($=>$.id===y.id),E=m?.sprites&&m.sprites.length>0,L=b&&b.length>0,R=x>=0?qe(m,x,p):void 0,S=_e({animationsDef:y.animations,resources:r,previousResourceId:R,currentResourceId:L?qe(y,g,d):void 0,previousTargetId:R,currentTargetId:L?qe(y,g,d):void 0,animationPath:`character.items[${g}].animations`,idPrefix:"character"});if(y.animations&&!b&&!I&&E&&de({animationInstances:S,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){c.push(...S);continue}if(y.animations&&!b&&!I)continue;if(!b||b.length===0||!I){console.warn("Character item missing sprites or transformId:",y);continue}let N=qe(y,g,d),O=r.transforms[I];if(!O){console.warn("Transform not found:",I);continue}let k={type:"container",id:N,x:y.x??O.x,y:y.y??O.y,anchorX:O.anchorX,anchorY:O.anchorY,rotation:O.rotation,scaleX:O.scaleX,scaleY:O.scaleY,children:[]};for(let $ of b){let A=r.images[$.resourceId];if(!A){console.warn(`Image resource not found: ${$.resourceId}`);continue}k.children.push({type:"sprite",id:`${N}-${$.id}`,src:A.fileId,width:A.width,height:A.height,x:0,y:0})}a.children.push(k),de({animationInstances:S,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&c.push(...S)}}return e},Ni=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,runtime:l,activePersistentAnimations:c,autoMode:a,skipMode:u,isChoiceVisible:f,canRollback:d,saveSlots:p=[]})=>{let{elements:g,animations:y}=e;if(t.visual&&r){let I=g.find(m=>m.id==="story");if(!I)return e;let b=t.visual.items;for(let m of b){if(m.resourceId){let{images:R={},videos:S={},spritesheets:N={}}=r,O=N[m.resourceId];if(O){let k=Mt(r,m),$=m.animationName;if($){let A=O.animations?.[$];if(!A)throw new Error(`Animation '${$}' not found in spritesheet resource '${m.resourceId}'`);let v={id:`visual-${m.id}`,type:"animated-sprite",x:m.x??k.x,y:m.y??k.y,width:m.width??O.width,height:m.height??O.height,alpha:m.alpha??1,anchorX:k.anchorX,anchorY:k.anchorY,rotation:k.rotation,scaleX:k.scaleX,scaleY:k.scaleY,spritesheetSrc:O.fileId,spritesheetData:O.jsonData,animation:{frames:A.frames,animationSpeed:m.animationSpeed??A.animationSpeed??.5,loop:m.loop??A.loop??!0}};I.children.push(structuredClone(v))}}else{let k=R[m.resourceId]||S[m.resourceId];if(k){let $=S[m.resourceId]!==void 0,A=Mt(r,m),v={id:`visual-${m.id}`,type:$?"video":"sprite",src:k.fileId,width:k.width,height:k.height,x:A.x,y:A.y,anchorX:A.anchorX,anchorY:A.anchorY,rotation:A.rotation,scaleX:A.scaleX,scaleY:A.scaleY};$&&(v.loop=k.loop??!1,v.volume=k.volume??50),I.children.push(v)}}}if(m.resourceId){let{layouts:R={}}=r,S=R[m.resourceId];if(S){let N=Mt(r,m),O={id:`visual-${m.id}`,type:"container",children:structuredClone(S.elements),x:N.x,y:N.y,anchorX:N.anchorX,anchorY:N.anchorY,rotation:N.rotation,scaleX:N.scaleX,scaleY:N.scaleY},k=X(O,ee({variables:s,runtime:l,saveSlots:p,dialogueState:t.dialogue,isLineCompleted:o,autoMode:a,skipMode:u,isChoiceVisible:f,canRollback:d,characters:r.characters||{},skipTransitionsAndAnimations:i}),{functions:pe});I.children.push(he(ge(k,{isLineCompleted:o,skipMode:u,skipTransitionsAndAnimations:i}),r))}}let E=(n?.visual?.items||[]).find(R=>R.id===m.id),L=_e({animationsDef:m.animations,resources:r,previousResourceId:E?.resourceId,currentResourceId:m.resourceId,previousTargetId:E?.resourceId?`visual-${m.id}`:void 0,currentTargetId:m.resourceId?`visual-${m.id}`:void 0,animationPath:`visual.items[${m.id}].animations`,idPrefix:m.id});de({animationInstances:L,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:c})&&y.push(...L)}}return e},Di=(e,{presentationState:t,previousPresentationState:n,resources:r={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:l,canRollback:c,skipOnlyViewedLines:a,isLineCompleted:u,skipTransitionsAndAnimations:f,variables:d,runtime:p,activePersistentAnimations:g,saveSlots:y=[]})=>{let{elements:I,animations:b}=e;if(!t.dialogue||o)return e;let m=I.find(E=>E.id==="story");if(!m)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:E={}}=r,L=E[t.dialogue.ui.resourceId];if(L){let R={elements:L.elements},S=ee({variables:d,runtime:p,saveSlots:y,dialogueState:t.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:u,autoMode:i,skipMode:s,isChoiceVisible:l,canRollback:c,characters:r.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:a,skipTransitionsAndAnimations:f}),N={functions:pe},O=Je(R,S,N),k=X(O,S,N),$=he(ge(k?.elements,{isLineCompleted:u,skipMode:s,skipTransitionsAndAnimations:f}),r);if(Array.isArray($))for(let A of $)m.children.push(A);else $&&m.children.push($)}}let x=_e({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 de({animationInstances:x,isLineCompleted:u,skipTransitionsAndAnimations:f,activePersistentAnimations:g})&&b.push(...x),e},Vi=(e,{presentationState:t,previousPresentationState:n,resources:r,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:l,runtime:c,autoMode:a,skipMode:u,isChoiceVisible:f,canRollback:d,activePersistentAnimations:p,saveSlots:g=[]})=>{let{elements:y,animations:I}=e;if(t.choice&&r){let b=et(y);if(!b)return e;let m=r?.layouts[t.choice.resourceId];if(m&&m.elements){let E={elements:m.elements},L=X(E,{...ee({variables:l,runtime:c,saveSlots:g,dialogueState:t.dialogue,isLineCompleted:i,autoMode:a,skipMode:u,isChoiceVisible:f??!!t.choice,canRollback:d,characters:r.characters||{},skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}},{functions:pe}),R=Wt(he(ge(L?.elements,{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),r));if(Array.isArray(R))for(let S of R)b.children.push(S);else R&&b.children.push(R)}let x=_e({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"});de({animationInstances:x,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:p})&&I.push(...x)}return e},Mi=(e,{presentationState:t,resources:n={},variables:r,runtime:o,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:c,canRollback:a,saveSlots:u=[],skipTransitionsAndAnimations:f})=>{if(!t.control?.resourceId)return e;let d=n.controls?.[t.control.resourceId];if(!d)return e;let p=$i(d.keyboard);if(p&&Object.keys(p).length>0&&(e.global.keyboard=p),!Array.isArray(d.elements)||d.elements.length===0)return e;let g=et(e.elements);if(!g)return e;let y={id:`control-${t.control.resourceId}`,type:"container",x:0,y:0,children:d.elements};return g.children.push(lr({container:y,resources:n,templateData:ee({variables:r,runtime:o,saveSlots:u,dialogueState:t.dialogue,isLineCompleted:i,autoMode:s,skipMode:l,isChoiceVisible:c,canRollback:a,characters:n.characters||{},skipTransitionsAndAnimations:f}),isLineCompleted:i,skipMode:l,skipTransitionsAndAnimations:f})),e},ji=(e,{presentationState:t,resources:n,runtime:r,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&n){if(!et(i))return e;let c=n.sounds[t.bgm.resourceId];if(!c)return e;let a=ee({variables:o,runtime:r}).runtime;s.push({id:"bgm",type:"sound",src:c.fileId,loop:t.bgm.loop??!0,volume:Si(a),delay:t.bgm.delay??null})}return e},Bi=(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,delay:i.delay??s.delay??null})}}return e},Fi=(e,{presentationState:t,resources:n})=>{let{audio:r}=e;if(!t?.voice)return e;let{fileId:o,volume:i,loop:s}=t.voice;return r.push({id:`voice-${o}`,type:"sound",src:o,volume:i??50,loop:s??!1}),e},Ui=(e,{presentationState:t,previousPresentationState:n,resources:r={},variables:o,runtime:i,autoMode:s,skipMode:l,isChoiceVisible:c,canRollback:a,saveSlots:u=[],isLineCompleted:f,skipTransitionsAndAnimations:d,activePersistentAnimations:p})=>{let{elements:g,animations:y}=e;if(t.layout){let x=et(g);if(!x)return e;let E=r.layouts[t.layout.resourceId];if(!E)return e;Array.isArray(E.transitions)&&!f&&!d&&Ht({animations:y,transitions:E.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let L={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:E.elements||[]};x.children.push(lr({container:L,resources:r,templateData:ee({variables:o,runtime:i,saveSlots:u,dialogueState:t.dialogue,isLineCompleted:f,autoMode:s,skipMode:l,isChoiceVisible:c,canRollback:a,characters:r.characters||{},skipTransitionsAndAnimations:d}),isLineCompleted:f,skipMode:l,skipTransitionsAndAnimations:d}))}let I=n?.layout?.resourceId,b=t.layout?.resourceId,m=_e({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 de({animationInstances:m,isLineCompleted:f,skipTransitionsAndAnimations:d,activePersistentAnimations:p})&&y.push(...m),e},zi=(e,{presentationState:t,resources:n={},variables:r,runtime:o,autoMode:i,skipMode:s,isChoiceVisible:l,canRollback:c,overlayStack:a=[],dialogueHistory:u=[],saveSlots:f=[],screen:d,isLineCompleted:p,skipTransitionsAndAnimations:g})=>{let{elements:y,animations:I}=e;return a&&a.length>0&&a.forEach((b,m)=>{let x=n.layouts[b.resourceId];if(!x){console.warn(`Overlay layout not found: ${b.resourceId}`);return}Array.isArray(x.transitions)&&(g||Ht({animations:I,transitions:x.transitions,defaultTargetId:`overlayStack-${m}`,idPrefix:`overlayStack-${m}`,animationPathPrefix:`overlayStack[${m}]`}));let E={id:`overlayStack-${m}`,type:"container",x:0,y:0,children:[ar({id:`overlayStack-${m}-blocker`,screen:d}),...x.elements||[]]},L=cr(u,n.characters),R=ee({variables:r,runtime:o,saveSlots:f,dialogueState:t?.dialogue,isLineCompleted:p,autoMode:i,skipMode:s,isChoiceVisible:l,canRollback:c,historyDialogue:L,characters:n.characters||{},skipTransitionsAndAnimations:g}),S=X(E,R,{functions:pe}),[N,...O]=S.children||[],k=he(ge({...S,children:O},{isLineCompleted:p,skipMode:s,skipTransitionsAndAnimations:g}),n);y.push({...k,children:N?[N,...k.children||[]]:k.children})}),e},Wi=(e,{presentationState:t,resources:n={},variables:r,runtime:o,saveSlots:i=[],autoMode:s,skipMode:l,isChoiceVisible:c,canRollback:a,confirmDialog:u,dialogueHistory:f=[],screen:d,isLineCompleted:p,skipTransitionsAndAnimations:g})=>{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)&&!g&&Ht({animations:I,transitions:b.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let m={id:"confirmDialog",type:"container",x:0,y:0,children:[ar({id:"confirmDialog-blocker",screen:d}),...b.elements||[]]},x=cr(f,n.characters),E=X(m,ee({variables:r,runtime:o,saveSlots:i,dialogueState:t?.dialogue,isLineCompleted:p,autoMode:s,skipMode:l,isChoiceVisible:c,canRollback:a,confirmDialog:u,historyDialogue:x,characters:n.characters||{},skipTransitionsAndAnimations:g}),{functions:pe}),[L,...R]=E.children||[],S=he(ge({...E,children:R},{isLineCompleted:p,skipMode:l,skipTransitionsAndAnimations:g}),n);return y.push({...S,children:L?[L,...S.children||[]]:S.children}),e},ur=e=>Ge(Oi,[Mi,Pi,Ti,Ni,Di,Vi,Ui,ji,Bi,Fi,zi,Wi])(e);var Yi=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"}}),tt=Object.freeze({dialogueTextSpeed:50,autoForwardDelay:1e3,skipUnseenText:!1,skipTransitionsAndAnimations:!1,soundVolume:50,musicVolume:50,muteAll:!1,autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isLineCompleted:!1}),Te=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),fr=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"}),Kt=Object.freeze(["dialogueTextSpeed","autoForwardDelay","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),qt=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),Hi=(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]}},Xt=e=>Object.fromEntries(Object.entries(Yi).map(([t,n])=>{let r=Hi(e,n.source),o=r!==void 0?r:tt[t]??Te[t];return[t,o]})),te=(e,t)=>Xt(e)[t],dr=(e={})=>Object.fromEntries(Kt.map(t=>[t,e[t]??tt[t]]));var nt={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},yr=1,it=()=>({manual:{...nt.manual},auto:{...nt.auto},applyMode:nt.applyMode}),Jt=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let n=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...it()},n&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},j=e=>{let t=ie(e)?wt(e):e;return structuredClone(t)},M=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),st=e=>String(e),Zt=()=>({sections:[],resources:[]}),rt=()=>({sectionId:void 0,lineId:void 0}),Gi=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",Ki=()=>({resourceId:void 0}),qi=e=>{if(!M(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},br=(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}},Ir=e=>{let t=e?.story?.scenes??{},n=new Map;for(let[r,o]of Object.entries(t)){let i=o?.sections??{};for(let s of Object.keys(i)){let l=n.get(s);if(l!==void 0)throw new Error(`Duplicate sectionId "${s}" found in scenes "${l}" and "${r}". Section IDs must be globally unique.`);n.set(s,r)}}},Ar=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},xr=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==yr)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},Xi=(e,t={})=>{let n;try{n=xr(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let r={...t,formatVersion:n,slotId:Ar(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete r.slotKey,delete r.date,r},Ji=(e={})=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Xi(t,n)])),wr=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:n})=>wa(n));return t.length>0?t:void 0},Zi=e=>{!M(e)||!Array.isArray(e.timeline)||e.timeline.forEach(t=>{if(!M(t))return;let n=wr(t.executedActions);if(n){t.executedActions=n;return}delete t.executedActions})},pr=(e,t,n)=>{let r=t==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[r]:String(e)};if(!M(e))throw new Error(`Malformed save slot viewedRegistry.${t}[${n}] entry.`);if(typeof e[r]!="string"||e[r].length===0)throw new Error(`Malformed save slot viewedRegistry.${t}[${n}] entry: missing ${r}.`);if(t==="sections"){let o={sectionId:e.sectionId};if(e.lastLineId!==void 0&&e.lastLineId!==null&&typeof e.lastLineId!="string")throw new Error(`Malformed save slot viewedRegistry.sections[${n}] entry: invalid lastLineId.`);return typeof e.lastLineId=="string"&&e.lastLineId.length>0&&(o.lastLineId=e.lastLineId),o}return{resourceId:e.resourceId}},Qi=e=>{if(e===void 0)return Zt();if(!M(e))throw new Error("Malformed save slot viewedRegistry.");if(e.sections!==void 0&&!Array.isArray(e.sections))throw new Error("Malformed save slot viewedRegistry.sections.");if(e.resources!==void 0&&!Array.isArray(e.resources))throw new Error("Malformed save slot viewedRegistry.resources.");let t=e.sections??[],n=e.resources??[];return{sections:Object.values(Object.fromEntries(t.map((r,o)=>{let i=pr(r,"sections",o);return[i.sectionId,i]}))),resources:Object.values(Object.fromEntries(n.map((r,o)=>{let i=pr(r,"resources",o);return[i.resourceId,i]})))}},Qt=(e,t,n)=>{if(!M(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}=br(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}},es=(e,t)=>{if(!M(e)||typeof e.sectionId!="string"||e.sectionId.length===0||typeof e.lineId!="string"||e.lineId.length===0)return rt();try{let n=Qt(e,t,"contexts[*].pointers.history");return{sectionId:n.sectionId,lineId:n.lineId}}catch{return rt()}},ts=(e,t,n)=>{if(!M(e)||!Array.isArray(e.timeline))return Ne({pointer:t,replayStartIndex:1});let r=e.timeline.flatMap((l,c)=>{if(!M(l))return[];try{let a=Qt(l,n,`rollback.timeline[${c}]`),u=ot({sectionId:a.sectionId,lineId:a.lineId,rollbackPolicy:l.rollbackPolicy}),f=wr(j(l.executedActions));return f&&(u.executedActions=f),[u]}catch{return[]}});if(r.length===0)return Ne({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 l=r.findLastIndex(c=>c.sectionId===t.sectionId&&c.lineId===t.lineId);l>=0?o=l:(r.push(ot({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}},ns=(e,t,n)=>{if(!M(e))throw new Error(`Malformed save slot contexts[${n}] entry.`);let r=tn(t),o=Qt(e.pointers?.read,t,`contexts[${n}].pointers.read`);if(e.variables!==void 0&&!M(e.variables))throw new Error(`Malformed save slot contexts[${n}].variables entry.`);if(e.runtime!==void 0&&!M(e.runtime))throw new Error(`Malformed save slot contexts[${n}].runtime entry.`);let i=es(e.pointers?.history,t),s=e.variables?j(e.variables):{},l=as({loadedContextRuntime:M(e.runtime)?j(e.runtime):{}}),c={currentPointerMode:e.currentPointerMode==="history"&&i.lineId?"history":"read",pointers:{read:o,history:i},configuration:M(e.configuration)?j(e.configuration):{},views:Array.isArray(e.views)?j(e.views):[],bgm:M(e.bgm)?j(e.bgm):{resourceId:void 0},variables:{...r,...s},rollback:ts(e.rollback,o,t)};return l&&(c.runtime=l),c},rs=(e,t)=>{if(!M(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{viewedRegistry:Qi(e.viewedRegistry),contexts:e.contexts.map((n,r)=>ns(n,t,r))}},os=(e,t)=>{if(!M(e))throw new Error("Malformed save slot.");let n=xr(e.formatVersion);return{...e,formatVersion:n,state:rs(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=j(e);return Object.prototype.hasOwnProperty.call(r,"hideConfirmDialog")||(r.hideConfirmDialog={}),r},is=(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")}},Se=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},me=[],gr="line",en="interaction",ot=({sectionId:e,lineId:t,rollbackPolicy:n})=>({sectionId:e,lineId:t,rollbackPolicy:n??"free"}),tn=e=>{let{contextVariableDefaultValues:t}=kt(e??{});return j(t)},vr=()=>({...j(Te)}),Er=({loadedRuntime:e,runtimeIds:t,defaults:n={},path:r})=>{if(e===void 0)return{runtimeState:j(n),hasLoadedValues:!1};if(!M(e))throw new Error(`Malformed ${r}.`);let o=j(n),i=!1;return t.forEach(s=>{e[s]!==void 0&&(o[s]=Sr(s,j(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},ss=({loadedGlobalRuntime:e={}})=>Er({loadedRuntime:e,runtimeIds:Kt,defaults:tt,path:"global.runtime"}).runtimeState,as=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:n}=Er({loadedRuntime:e,runtimeIds:qt,defaults:vr(),path:"context.runtime"});return n?t:void 0},_r=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},cs=e=>e.runtime?(qt.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=j(Te[t]))}),e.runtime):(e.runtime=vr(),e.runtime),ls=e=>dr(e.global),us=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:ls(e)}})},fs=e=>fr[e],ds=(e,t)=>{let n=fs(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}"`)},Sr=(e,t)=>(ds(e,t),e==="saveLoadPagination"?Math.max(1,Math.trunc(t)):t),Cr=(e,t,n)=>{let r=Sr(t,n);if(t in Te){let o=_r(e);if(!o)return r;let i=cs(o);return i[t]=r,r}return e.global[t]=r,r},Lr=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:j(e),history:rt()},configuration:{},views:[],bgm:Ki(),variables:tn(t),rollback:Ne({pointer:e})}),ps=e=>{let t=e.contexts?.[e.contexts.length-1],n=t?.pointers?.read;if(!t||!n?.sectionId||!n?.lineId)return null;let r=Lr({pointer:n,projectData:e.projectData});return e.contexts[e.contexts.length-1]=r,hs(e),r},hs=e=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,Se(e),e.global.viewedRegistry=Zt(),e.global.nextLineConfig=it(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})},Rr=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},Ne=({pointer:e,replayStartIndex:t=0})=>{let n=e?.sectionId&&e?.lineId;return{currentIndex:n?0:-1,isRestoring:!1,replayStartIndex:t,timeline:n?[ot({sectionId:e.sectionId,lineId:e.lineId})]:[]}},be=(e,t={})=>{if(e?.rollback)return Rr(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=Ne({pointer:n,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},nn=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return;let r=be(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(ot(t)),r.currentIndex=r.timeline.length-1},gs=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=me[me.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)},ms=({state:e},t={})=>{let n=t?.source===gr?gr:en,o=e.contexts?.[e.contexts.length-1]?.rollback;return!o||o.isRestoring||!Array.isArray(o.timeline)||typeof o.currentIndex!="number"||o.currentIndex<0||o.currentIndex>=o.timeline.length?(me.push({checkpointIndex:null,source:n}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),me.push({checkpointIndex:o.currentIndex,source:n}),e)},ys=({state:e})=>(me.pop(),e),ne=(e,t,n)=>{let o=me[me.length-1]?.source??en;if(!va(t,o))return;let i=gs(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:j(n)}))},mr=(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 l=e.projectData.resources?.variables?.[o],c=l?.scope,a=l?.type;$t(c,o),Ot(a,i,o),c==="context"&&(n.variables[o]=Pt(n.variables[o],i,s))}},bs=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:n,payload:r})=>{Ea(e,n,r)})},Is=(e,t)=>{let{sectionId:n,lineId:r}=t,s=W({state:e},{sectionId:n})?.lines?.find(l=>l.id===r)?.actions;s&&Object.entries(s).forEach(([l,c])=>{_a(e,l,c)})},kr=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return e;let r=be(n),o=r.timeline[t];if(!o)return e;e.global.autoMode&&Ve({state:e}),e.global.skipMode&&ye({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),r.isRestoring=!0,r.currentIndex=t;try{n.variables=tn(e.projectData),delete n.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=j(nt),e.global.overlayStack=[],Se(e),e.global.isLineCompleted=!0;let i=r.replayStartIndex??0;for(let s=i;s<=t;s++)s>i&&Jt(e),Is(e,r.timeline[s]),bs(e,r.timeline[s]);n.pointers.read={sectionId:o.sectionId,lineId:o.lineId},n.currentPointerMode="read",n.pointers?.history&&(n.pointers.history={sectionId:null,lineId:null}),e.global.pendingEffects=e.global.pendingEffects.filter(s=>s?.name!=="render"),e.global.pendingEffects.push({name:"render"})}finally{r.isRestoring=!1}return e},As=e=>{let{projectData:t}=e,n=e.global??{},{saveSlots:r={},variables:o={},runtime:i={}}=n;Ir(t);let s=t.story.initialSceneId,l=t.story.scenes[s],c=l.initialSectionId,a=l.sections[c],u={sceneId:s,sectionId:c,lineId:a.initialLineId??a.lines[0].id},{globalVariablesDefaultValues:f}=kt(t),d={...f,...o};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,viewedRegistry:Zt(),nextLineConfig:it(),saveSlots:Ji(r),overlayStack:[],variables:d,...ss({loadedGlobalRuntime:i})},contexts:[Lr({pointer:u,projectData:t})]}},xs=({state:e})=>e.global.overlayStack||[],ws=({state:e})=>e.global.pendingEffects,$r=({state:e})=>e.global.skipMode,vs=({state:e})=>e.global.autoMode,Or=({state:e})=>e.global.dialogueUIHidden,Pr=({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=W({state:e},{sectionId:r});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(u=>u.id===o),l=i.lines.slice(0,s+1),c=[],a={};for(let u of l){let f=u.actions||{};if(a=ve([a,f]),!f.dialogue)continue;let d=a.dialogue||{},p="";d.character?.name!==void 0?p=d.character.name:d.characterId&&(p=e.projectData.resources?.characters?.[d.characterId]?.name||""),c.push({sectionId:r,lineId:u.id,content:f.dialogue.content,text:Gi(f.dialogue.content),characterId:d.characterId,character:{name:p},characterName:p})}return c},Es=({state:e})=>e.global.confirmDialog??null,rn=({state:e},t)=>{let{sectionId:n,lineId:r}=t,o=e.global.viewedRegistry.sections.find(c=>c.sectionId===n);if(!o)return!1;if(o.lastLineId===void 0||r===void 0)return!0;let i=W({state:e},{sectionId:n});if(!i||!i.lines||!Array.isArray(i.lines))return o.lastLineId===r;let s=i.lines.findIndex(c=>c.id===o.lastLineId),l=i.lines.findIndex(c=>c.id===r);return s===-1||l===-1?o.lastLineId===r:l<=s},_s=({state:e},t)=>{let{resourceId:n}=t;return!!e.global.viewedRegistry.resources.find(o=>o.resourceId===n)},Ss=({state:e})=>e.global.nextLineConfig,Tr=({state:e,pointer:t}={})=>{let n=t??Z({state:e})?.pointer;if(!n)return;let r=n?.sectionId,o=n?.lineId,s=W({state:e},{sectionId:r})?.lines||[],l=s.findIndex(a=>a.id===o);if(l<0)return;let c;for(let a of s.slice(0,l+1)){let u=a?.actions;if(u?.cleanAll&&(c=void 0),!u||!Object.prototype.hasOwnProperty.call(u,"choice")){c=void 0;continue}let f=u.choice;if(f?.resourceId){c=f.resourceId;continue}f?.animations||(c=void 0)}return c},Q=({state:e})=>!!Tr({state:e}),Cs=({state:e})=>structuredClone(e),Nr=({state:e})=>e.global.saveSlots,Ls=({state:e},t)=>{let n=t?.slotId,r=st(n);return e.global.saveSlots[r]},on=({state:e})=>Xt(e),Rs=({state:e},t)=>te(e,t?.runtimeId),Dr=({state:e})=>({...e.global?.variables??{},..._r(e)?.variables??{}}),Z=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],n=t[t.length-1];if(!n)return;let r=n.pointers?.[n.currentPointerMode];return{currentPointerMode:n.currentPointerMode,pointer:r}},W=({state:e},t)=>{let{sectionId:n}=t;return br(e.projectData,n).section},sn=({state:e})=>{let t=Z({state:e});if(!t?.pointer)return;let{sectionId:n,lineId:r}=t.pointer,o=W({state:e},{sectionId:n});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===r)},Vr=({state:e})=>{let{sectionId:t,lineId:n}=Z({state:e}).pointer,o=W({state:e},{sectionId:t})?.lines||[],i=o.findIndex(a=>a.id===n),l=o.slice(0,i+1).map(a=>{let u=a.actions||{},f={};return Object.keys(u).forEach(d=>{f[d]=u[d]}),f});return ve(l)},ks=({state:e})=>{let t=Mr({state:e}),r=sn({state:e})?.actions??{},o=ve([t??{},r]);return Nt(t??{},o??{})},$s=({state:e},{sectionId:t})=>{let n=W({state:e},{sectionId:t});if(!n?.lines)return[];let r=[],o={};for(let i of n.lines){let s=i.actions||{},l=ve([o,s]),c=Nt(o,l);r.push({id:i.id,changes:c,presentationState:l}),o=Dt(l)}return r},Os=({state:e},{sectionId:t,includePresentationState:n=!1})=>{let r=$s({state:e},{sectionId:t});return n?{lines:r}:{lines:r.map(({presentationState:o,...i})=>i)}},Mr=({state:e})=>{let{sectionId:t,lineId:n}=Z({state:e}).pointer,o=W({state:e},{sectionId:t})?.lines||[],i=o.findIndex(c=>c.id===n);if(i<=0)return null;let l=o.slice(0,i).map(c=>{let a=c.actions||{},u={};return Object.keys(a).forEach(f=>{u[f]=a[f]}),u});return Dt(ve(l))},an=({state:e},{slotsPerPage:t=6}={})=>{let o=((on({state:e}).saveLoadPagination??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let l=o+s,c=e.global.saveSlots&&e.global.saveSlots[st(l)]||{};i.push({...c,slotId:l})}return{saveSlots:i}},Ps=Nr,Ts=an,Ns=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},Ds=({state:e},t={})=>{let n=Vr({state:e}),r=Mr({state:e}),o=sn({state:e})?.actions??{},i=on({state:e}),s=t?.activePersistentAnimations??[],l=t?.restoredPersistentAnimations??[],c=Dr({state:e}),{saveSlots:a}=an({state:e}),u=Ns(e);return ur({presentationState:n,previousPresentationState:r,currentLineActions:o,resources:e.projectData.resources,screen:e.projectData.screen,dialogueUIHidden:i.dialogueUIHidden,autoMode:i.autoMode,skipMode:i.skipMode,isChoiceVisible:Q({state:e}),canRollback:Yr({state:e}),skipOnlyViewedLines:!i.skipUnseenText,isLineCompleted:i.isLineCompleted,skipTransitionsAndAnimations:!!i.skipTransitionsAndAnimations||u,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,dialogueHistory:Pr({state:e}),saveSlots:a,variables:c,runtime:i,activePersistentAnimations:s,restoredPersistentAnimations:l})},Vs=({state:e},t)=>(e.global.confirmDialog=is(t),e.global.pendingEffects.push({name:"render"}),e),Ms=({state:e})=>(e.global.confirmDialog&&(Se(e),e.global.pendingEffects.push({name:"render"})),e),js=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),ne(e,"pushOverlay",t),e),Bs=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),ne(e,"popOverlay",void 0),e),Fs=({state:e},t)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=t),e.global.pendingEffects.push({name:"render"}),ne(e,"replaceLastOverlay",t),e),Us=({state:e})=>(e.global.overlayStack=[],Se(e),e.global.pendingEffects.push({name:"render"}),ne(e,"clearOverlays",void 0),e),zs=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"})},at=(e,t)=>{e.global.isLineCompleted=!1;let n=!!Tr({state:e,pointer:t});return n&&zs(e),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:n}},jr=({state:e})=>(Q({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:te(e,"autoForwardDelay")}}),e.global.pendingEffects.push({name:"render"})),e),Ve=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Ws=({state:e})=>{let t=e.global.autoMode;return Q({state:e})&&!t||(t?Ve({state:e}):jr({state:e})),e},Br=({state:e})=>(Q({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),ye=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Ys=({state:e})=>{let t=$r({state:e});return Q({state:e})&&!t||(t?ye({state:e}):Br({state:e})),e},ct=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),ne(e,"showDialogueUI",void 0),e),Fr=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),ne(e,"hideDialogueUI",void 0),e),Hs=({state:e})=>(Or({state:e})?ct({state:e}):Fr({state:e}),e),Ie=(e,t,n)=>(Cr(e,t,n),us(e),e.global.pendingEffects.push({name:"render"}),e),Me=(e,t,n,r)=>{let o=Cr(e,t,n);return e.global.pendingEffects.push({name:"render"}),ne(e,r,{value:o}),e},Gs=({state:e},t)=>Ie(e,"dialogueTextSpeed",t?.value),Ks=({state:e},t)=>Ie(e,"autoForwardDelay",t?.value),qs=({state:e},t)=>Ie(e,"skipUnseenText",t?.value),Xs=({state:e},t)=>Ie(e,"skipTransitionsAndAnimations",t?.value),Js=({state:e},t)=>Ie(e,"soundVolume",t?.value),Zs=({state:e},t)=>Ie(e,"musicVolume",t?.value),Qs=({state:e},t)=>Ie(e,"muteAll",t?.value),ea=({state:e},t)=>Me(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),ta=({state:e})=>{let t=te(e,"saveLoadPagination")+1;return Me(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},na=({state:e})=>{let t=te(e,"saveLoadPagination")-1;return Me(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},ra=({state:e},t)=>Me(e,"menuPage",t?.value,"setMenuPage"),oa=({state:e},t)=>Me(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),ia=({state:e})=>(e.global.pendingEffects=[],e),sa=({state:e},t)=>(e.global.pendingEffects.push(t),e),Ur=(e,{sectionId:t,resetStoryState:n=!1})=>{let r=W({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&&!ps(e))return e;e.global.autoMode&&Ve({state:e}),e.global.skipMode&&ye({state:e});let i=e.contexts?.[e.contexts.length-1];return i&&(i.rollback||be(i,{compatibilityAnchor:!0}),i.pointers.read={sectionId:t,lineId:o.id},n?i.rollback=Ne({pointer:i.pointers.read}):nn(e,{sectionId:t,lineId:o.id})),at(e,i?.pointers?.read),e},aa=({state:e},t)=>Ur(e,{sectionId:t?.sectionId,resetStoryState:!0}),De=(e,{sectionId:t,lineId:n})=>{e.global.viewedRegistry||(e.global.viewedRegistry={}),Array.isArray(e.global.viewedRegistry.sections)||(e.global.viewedRegistry.sections=[]);let r=e.global.viewedRegistry.sections.find(o=>o.sectionId===t);if(r){let o=W({state:e},{sectionId:t});if(o?.lines&&r.lastLineId!==void 0){let i=o.lines.findIndex(l=>l.id===r.lastLineId),s=o.lines.findIndex(l=>l.id===n);(i===-1||s>i)&&(r.lastLineId=n)}else r.lastLineId=n}else e.global.viewedRegistry.sections.push({sectionId:t,lastLineId:n})},ca=({state:e},t)=>(De(e,t),e.global.pendingEffects.push({name:"render"}),e),la=({state:e},t)=>{let{resourceId:n}=t;return e.global.viewedRegistry.resources.find(o=>o.resourceId===n)||e.global.viewedRegistry.resources.push({resourceId:n}),e.global.pendingEffects.push({name:"render"}),e},zr=({state:e},t)=>{let n=qi(t.manual),{auto:r,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,l=e.contexts?.[e.contexts.length-1]?.rollback?.isRestoring===!0;n&&r?(e.global.nextLineConfig={manual:n,auto:r},o!==void 0?e.global.nextLineConfig.applyMode=o:s!==void 0&&(e.global.nextLineConfig.applyMode=s)):(n&&(e.global.nextLineConfig.manual=n),r&&(e.global.nextLineConfig.auto=r),o!==void 0&&(e.global.nextLineConfig.applyMode=o));let c=e.global.nextLineConfig.auto?.enabled,a=Q({state:e});return!l&&!a&&c===!0&&!i?e.global.nextLineConfig.auto?.trigger==="fromStart"?e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):e.global.isLineCompleted&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):!l&&c===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),ne(e,"setNextLineConfig",t),e},ua=({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=st(n),s=j(e.contexts);s?.forEach(a=>{Rr(a.rollback),Zi(a.rollback)});let l={contexts:s,viewedRegistry:j(e.global.viewedRegistry)},c={formatVersion:yr,slotId:Ar(n),savedAt:typeof o=="number"?o:Date.now(),image:r,state:l};return e.global.saveSlots[i]=c,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},fa=({state:e},t)=>{let n=t?.slotId;if(n==null||n==="")throw new Error("loadSlot requires slotId");let r=st(n),o=e.global.saveSlots[r];if(o){let i=os(o,e.projectData);e.global.viewedRegistry=i.state.viewedRegistry,e.contexts=i.state.contexts,e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=it(),e.global.overlayStack=[],e.global.isLineCompleted=!0,Se(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},da=({state:e},t)=>{let{projectData:n}=t;return Ir(n),e.projectData=n,Se(e),e.global.pendingEffects.push({name:"render"}),e},pa=({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&&!W({state:e},{sectionId:n}))return console.warn(`Section not found: ${n}`),e;let s=W({state:e},{sectionId:i});return!s?.lines||!Array.isArray(s.lines)?(console.warn(`Section ${i} has no lines`),e):s.lines.find(c=>c.id===r)?(o.pointers.read={sectionId:i,lineId:r},at(e,o.pointers.read),e):(console.warn(`Line not found: ${r} in section ${i}`),e)},ha=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return ct({state:e}),e;if(Q({state:e})&&t?._interactionSource!=="choice")return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0;let a=Z({state:e})?.pointer,u=a?.sectionId,f=a?.lineId;u&&f&&De(e,{sectionId:u,lineId:f}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:te(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=Z({state:e})?.pointer,r=n?.sectionId,o=W({state:e},{sectionId:r}),i=e.contexts[e.contexts.length-1],s=o?.lines||[],c=s.findIndex(a=>a.id===n?.lineId)+1;if(c<s.length){let a=s[c],u=!te(e,"skipUnseenText");if(e.global.skipMode&&u&&!rn({state:e},{sectionId:r,lineId:a.id}))return ye({state:e}),e;if(i&&!i.rollback&&be(i,{compatibilityAnchor:!0}),i){let p=i.pointers.read.lineId;p&&r&&De(e,{sectionId:r,lineId:p}),i.pointers.read={sectionId:r,lineId:a.id}}nn(e,{sectionId:r,lineId:a.id}),Jt(e);let{isChoiceVisible:f}=at(e,{sectionId:r,lineId:a.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&&Ve({state:e}),e.global.skipMode&&ye({state:e});return e},ga=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0;let t=Q({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:te(e,"autoForwardDelay")}});let n=Z({state:e})?.pointer,r=n?.sectionId,o=n?.lineId;r&&o&&De(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},ma=({state:e},t)=>{let n=t?.sectionId??Z({state:e})?.pointer?.sectionId,r=W({state:e},{sectionId:n});if(!r||!r.lines||r.lines.length===0)return e;let o=r.lines,i=e.contexts[e.contexts.length-1];if(!i||!i.pointers)return e;let s=i.currentPointerMode==="history"&&i.pointers.history?.lineId?i.pointers.history:i.pointers.read;if(i.currentPointerMode!=="history"||!i.pointers.history){if(!s)return e;i.currentPointerMode="history",i.pointers.history={sectionId:n,lineId:s?.lineId};let u=o.findIndex(f=>f.id===s.lineId)-1;if(u>=0&&u<o.length){let f=o[u];i.pointers.history={sectionId:n,lineId:f.id}}return e.global.pendingEffects.push({name:"render"}),e}let c=o.findIndex(a=>a.id===i.pointers.history.lineId)-1;if(c>=0&&c<o.length){let a=o[c];i.pointers.history={sectionId:n,lineId:a.id},e.global.pendingEffects.push({name:"render"})}return e},ya=({state:e},t)=>Ur(e,{sectionId:t?.sectionId}),ba=({state:e})=>{if(e.global.dialogueUIHidden)return ct({state:e}),e;if(Q({state:e}))return e;let t=Z({state:e})?.pointer,n=t?.sectionId,r=W({state:e},{sectionId:n}),o=e.contexts[e.contexts.length-1],i=r?.lines||[],l=i.findIndex(c=>c.id===t?.lineId)+1;if(l<i.length){let c=i[l],a=!te(e,"skipUnseenText");if(e.global.skipMode&&a&&!rn({state:e},{sectionId:n,lineId:c.id}))return ye({state:e}),e;if(o&&!o.rollback&&be(o,{compatibilityAnchor:!0}),o){let f=o.pointers.read.lineId;f&&n&&De(e,{sectionId:n,lineId:f}),o.pointers.read={sectionId:n,lineId:c.id}}nn(e,{sectionId:n,lineId:c.id}),Jt(e);let{isChoiceVisible:u}=at(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},Ia=({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=!1,l=!1,c=[];if(r.forEach(({variableId:a,op:u,value:f})=>{let d=e.projectData.resources?.variables?.[a],p=d?.scope,g=d?.type;$t(p,a),Ot(g,u,a);let y=p==="context"?o.variables:e.global.variables;p==="context"?(i=!0,c.push({variableId:a,op:u,value:f})):p==="device"?s=!0:p==="account"&&(l=!0),y[a]=Pt(y[a],u,f)}),i&&ne(e,"updateVariable",{id:n,operations:c}),s){let a=Tt(e.global.variables,e.projectData.resources?.variables,"device");e.global.pendingEffects.push({name:"saveGlobalDeviceVariables",payload:{globalDeviceVariables:a}})}if(l){let a=Tt(e.global.variables,e.projectData.resources?.variables,"account");e.global.pendingEffects.push({name:"saveGlobalAccountVariables",payload:{globalAccountVariables:a}})}return e.global.pendingEffects.push({name:"render"}),e},Aa=e=>(t,n)=>e({state:t},n),xa={updateVariable:{recordSources:[en],replayLine:mr,replayRecorded:mr,persistInSaveSlot:!0},setNextLineConfig:{replayLine:Aa(zr)}},lt=e=>xa[e]??null,wa=e=>lt(e)?.persistInSaveSlot===!0,va=(e,t)=>{let n=lt(e)?.recordSources;return Array.isArray(n)&&n.includes(t)},Ea=(e,t,n)=>{lt(t)?.replayRecorded?.(e,n)},_a=(e,t,n)=>{lt(t)?.replayLine?.(e,n)},Wr=({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}},Yr=({state:e})=>Wr({state:e},{offset:-1})!==null,Sa=({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=be(r,{compatibilityAnchor:!r.rollback}),i=o.currentIndex+n;return i<0||i>=o.timeline.length?e:kr(e,i)},Ca=({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=be(o,{compatibilityAnchor:!o.rollback}),l=i.timeline.slice(0,i.currentIndex+1).findLastIndex(c=>c.sectionId===n&&c.lineId===r);if(l===-1)throw new Error(`Line ${r} not found in section ${n} rollback timeline`);return l===i.currentIndex?e:kr(e,l)},Hr=e=>{let t=As(e);return Vn(t,{selectPendingEffects:ws,selectSkipMode:$r,selectAutoMode:vs,selectIsChoiceVisible:Q,selectDialogueUIHidden:Or,selectDialogueHistory:Pr,selectConfirmDialog:Es,selectIsLineViewed:rn,selectIsResourceViewed:_s,selectNextLineConfig:Ss,selectSystemState:Cs,selectSaveSlotMap:Nr,selectSaveSlots:Ps,selectSaveSlot:Ls,selectRuntime:on,selectRuntimeValue:Rs,selectAllVariables:Dr,selectCurrentPointer:Z,selectSection:W,selectCurrentLine:sn,selectPresentationState:Vr,selectPresentationChanges:ks,selectSectionLineChanges:Os,selectSaveSlotPage:an,selectCurrentPageSlots:Ts,selectRenderState:Ds,selectOverlayStack:xs,selectLineIdByOffset:Wr,selectCanRollback:Yr,startAutoMode:jr,stopAutoMode:Ve,toggleAutoMode:Ws,startSkipMode:Br,stopSkipMode:ye,toggleSkipMode:Ys,showDialogueUI:ct,hideDialogueUI:Fr,toggleDialogueUI:Hs,setDialogueTextSpeed:Gs,setAutoForwardDelay:Ks,setSkipUnseenText:qs,setSkipTransitionsAndAnimations:Xs,setSoundVolume:Js,setMusicVolume:Zs,setMuteAll:Qs,setSaveLoadPagination:ea,incrementSaveLoadPagination:ta,decrementSaveLoadPagination:na,setMenuPage:ra,setMenuEntryPoint:oa,showConfirmDialog:Vs,hideConfirmDialog:Ms,resetStoryAtSection:aa,clearPendingEffects:ia,appendPendingEffect:sa,beginRollbackActionBatch:ms,endRollbackActionBatch:ys,addViewedLine:ca,addViewedResource:la,setNextLineConfig:zr,saveSlot:ua,loadSlot:fa,updateProjectData:da,sectionTransition:ya,jumpToLine:pa,nextLine:ha,markLineCompleted:ga,prevLine:ma,rollbackToLine:Ca,rollbackByOffset:Sa,pushOverlay:js,popOverlay:Bs,replaceLastOverlay:Fs,clearOverlays:Us,updateVariable:Ia,nextLineFromSystem:ba},{transformActionFirstArgument:r=>({state:r}),transformSelectorFirstArgument:r=>({state:r})})};var La="route-engine",Ra="projectPersistence";var Gr=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{}}),re=e=>Object.prototype.toString.call(e)==="[object Object]",Kr=(e={})=>{let t=re(e)?e:{};return{saveSlots:re(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:re(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:re(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:re(t.globalRuntime)?t.globalRuntime:{}}},cn=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},ka=e=>{let t=cn(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},$a=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},Oa=({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}".`))}}),Pa=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.`))}})},ut=async({databasePromise:e,objectStoreName:t,namespace:n,patch:r})=>{let o=await e;return new Promise((i,s)=>{let l=o.transaction(t,"readwrite"),c=l.objectStore(t),a=c.get(n),u=!1,f=p=>{u||(u=!0,s(p))},d=()=>{u||(u=!0,i())};a.onerror=()=>{f(a.error??new Error(`Failed to read persisted namespace "${n}" before updating IndexedDB.`))},a.onsuccess=()=>{let p=Kr(a.result),g={namespace:n,version:1,...Gr(),...p,...r},y=c.put(g);y.onerror=()=>{f(y.error??new Error(`Failed to persist namespace "${n}" to IndexedDB.`))}},l.oncomplete=()=>{d()},l.onerror=()=>{f(l.error??new Error(`IndexedDB transaction failed while updating namespace "${n}".`))},l.onabort=()=>{f(l.error??new Error(`IndexedDB transaction aborted while updating namespace "${n}".`))}})},Ta=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),a=!1,u=d=>{a||(a=!0,i(d))},f=()=>{a||(a=!0,o())};c.onerror=()=>{u(c.error??new Error(`Failed to clear persisted namespace "${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}".`))}})},ln=(e={})=>{let{indexedDB:t,databaseName:n=La,objectStoreName:r=Ra,namespace:o}=e,i=$a(t),s=ka(o),l=Oa({indexedDB:i,databaseName:n,objectStoreName:r});return{namespace:s,load:async()=>{let c=await Pa({databasePromise:l,objectStoreName:r,namespace:s});return{...Gr(),...Kr(c)}},clear:async()=>Ta({databasePromise:l,objectStoreName:r,namespace:s}),saveSlots:async c=>ut({databasePromise:l,objectStoreName:r,namespace:s,patch:{saveSlots:re(c)?c:{}}}),saveGlobalDeviceVariables:async c=>ut({databasePromise:l,objectStoreName:r,namespace:s,patch:{globalDeviceVariables:re(c)?c:{}}}),saveGlobalAccountVariables:async c=>ut({databasePromise:l,objectStoreName:r,namespace:s,patch:{globalAccountVariables:re(c)?c:{}}}),saveGlobalRuntime:async c=>ut({databasePromise:l,objectStoreName:r,namespace:s,patch:{globalRuntime:re(c)?c:{}}})}},Na=ln;var Da=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","prevLine","updateProjectData"]),Va=new Set(["loadSlot","rollbackByOffset","rollbackToLine","prevLine"]);function un(e){let t,n=0,r=null,o=new Map,i=new Map,s=new Map,{handlePendingEffects:l}=e,c=(_=new Map,P=Date.now())=>new Map(Array.from(_.entries()).filter(([,U])=>P<U.expiresAt).map(([U,G])=>[U,{animation:structuredClone(G.animation),startedAt:G.startedAt,expiresAt:G.expiresAt}])),a=(_=new Map)=>Array.from(_.values()).map(P=>structuredClone(P.animation)),u=(_=Date.now())=>{o=new Map(Array.from(o.entries()).filter(([,P])=>_<P.expiresAt))},f=()=>{for(;t.selectPendingEffects().length>0;){let _=[...t.selectPendingEffects()];t.clearPendingEffects();try{l(_)}catch(P){throw t.clearPendingEffects(),_.forEach(U=>{t.appendPendingEffect(U)}),P}}},d=({initialState:_,namespace:P})=>{t=Hr(_),n=0,r=cn(P),o=new Map,i=new Map,s=new Map,t.appendPendingEffect({name:"handleLineActions"}),f()},p=()=>r,g=()=>t.selectPresentationState(),y=()=>t.selectPresentationChanges(),I=_=>t.selectSectionLineChanges(_),b=(_={})=>{n+=1;let P=Date.now();u(P);let U=i.size>0,G=c(o,P),oe=U?c(i,P):new Map,Ae={...t.selectRenderState({activePersistentAnimations:a(G),restoredPersistentAnimations:a(oe)}),id:`render-${n}`};return s.set(Ae.id,{builtAt:P,persistentAnimationSessions:new Map([...oe.entries(),...G.entries()]),usedRestoredPersistentAnimationSessions:U}),Ae},m=(_={})=>b(_),x=(_={})=>b(_),E=_=>{let P=typeof _?.id=="string"&&_.id.length>0?_.id:null,U=P?s.get(P):null;P&&s.delete(P);let G=new Map;er(_?.animations).forEach(oe=>{let ae=Ze(oe);if(!ae)return;let Ae=U?.persistentAnimationSessions?.get(ae)??o.get(ae),Jr=Math.max(0,nr(oe)),dn=Ae?.startedAt??U?.builtAt??Date.now();G.set(ae,{animation:structuredClone(oe),startedAt:dn,expiresAt:dn+Jr})}),o=G,U?.usedRestoredPersistentAnimationSessions&&(i=new Map)},L=()=>t.selectSystemState(),R=()=>t.selectSaveSlotMap(),S=_=>t.selectSaveSlot(_),N=_=>t.selectSaveSlotPage(_),O=()=>t.selectSkipMode(),k=()=>t.selectAutoMode(),$=()=>t.selectRuntime(),A=()=>t.selectIsChoiceVisible(),v=(_,P)=>{t[_]&&(Da.has(_)&&(Va.has(_)?i=c(o):i=new Map,o=new Map),t[_](P),f())},D=(_,P)=>{v(_,P)},B=_=>{if(!_)return{variables:t.selectAllVariables?t.selectAllVariables():void 0,runtime:t.selectRuntime?t.selectRuntime():{}};if(Object.prototype.hasOwnProperty.call(_,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:P,...U}=_,G=t.selectAllVariables?t.selectAllVariables():void 0;return{...U,_event:P,variables:G,runtime:t.selectRuntime?t.selectRuntime():{}}},F=(_,P,U={})=>{let G=B(P),oe=Bn(_,G);t.beginRollbackActionBatch({source:U.rollbackSource});try{Object.entries(oe).forEach(([ae,Ae])=>{v(ae,Ae)})}finally{t.endRollbackActionBatch({})}};return{init:d,handleAction:v,handleInternalAction:D,handleActions:F,selectRenderState:m,prepareRenderState:x,commitRenderState:E,selectPresentationState:g,selectPresentationChanges:y,selectSectionLineChanges:I,selectSystemState:L,selectSaveSlotMap:R,selectSaveSlot:S,selectSaveSlotPage:N,selectSaveSlots:R,selectRuntime:$,selectIsChoiceVisible:A,handleLineActions:()=>{let _=t.selectCurrentLine();return _?.actions?(F(_.actions,void 0,{rollbackSource:"line"}),!0):!1},getNamespace:p}}var fn=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:n=>{e=n},addElapsed:n=>{e+=n},getCallback:()=>t,setCallback:n=>{t=n}}},Ma=80,Xr=({engine:e,routeGraphics:t,trackRenderDispatch:n},r)=>{let o=e.prepareRenderState?.(r)??e.selectRenderState(r);n?.(o),t.render(o),e.commitRenderState?.(o)},ja=({engine:e,routeGraphics:t,trackRenderDispatch:n,getRenderDispatchCount:r},o)=>{let i=r?.()??0,s=e.handleLineActions();(r?.()??0)===i&&Xr({engine:e,routeGraphics:t,trackRenderDispatch:n},o)},Ba=({engine:e,ticker:t,autoTimer:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let l=r.delay??1e3;n.getElapsed()>=l&&(t.remove(i),n.setCallback(null),n.setElapsed(0),ft(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},Fa=({ticker:e,autoTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Ua=({engine:e,ticker:t,skipTimer:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let l=r?.delay??Ma;n.getElapsed()>=l&&(n.setElapsed(0),ft(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},za=({ticker:e,skipTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Wa=({engine:e,ticker:t,nextLineConfigTimerState:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=s=>{n.addElapsed(s.deltaMS);let l=r.delay??1e3;n.getElapsed()>=l&&(n.setElapsed(0),ft(e,"nextLineFromSystem",{}),t.remove(i),n.setCallback(null))};n.setCallback(i),t.add(i)},Ya=({ticker:e,nextLineConfigTimerState:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Ha=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveSlots(t?.saveSlots))},Ga=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalDeviceVariables(t?.globalDeviceVariables))},Ka=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalAccountVariables(t?.globalAccountVariables))},qa=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalRuntime(t?.globalRuntime))},qr={render:Xr,saveSlots:Ha,saveGlobalDeviceVariables:Ga,saveGlobalAccountVariables:Ka,saveGlobalRuntime:qa,handleLineActions:ja,startAutoNextTimer:Ba,clearAutoNextTimer:Fa,startSkipNextTimer:Ua,clearSkipNextTimer:za,nextLineConfigTimer:Wa,clearNextLineConfigTimer:Ya},Xa=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),ft=(e,t,n)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,n)},Ja=(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(!Xa.has(o.name)){n.unshift(o);continue}t.has(o.name)||(t.add(o.name),n.unshift(o))}return n},Za=({getEngine:e,routeGraphics:t,ticker:n,handleUnhandledEffect:r,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:l})=>{let c=fn(),a=fn(),u=fn(),f=s??null,d=Promise.resolve(),p=null,g=null,y=!1,I=0,b=A=>{if(o){o(A);return}console.error("RouteEngine persistence write failed.",A)},m=()=>{if(f)return f;let A=e();return f=ln({indexedDB:i,namespace:l??A?.getNamespace?.()}),f},x=A=>{d=d.catch(()=>{}).then(()=>{let v=m();return A(v)}).catch(v=>{b(v)})},E=A=>{let v=typeof A?.id=="string"&&A.id.length>0?A.id:null;I+=1,p=v,y=!1},L=()=>I,R=(A={})=>{if(A?.aborted===!0)return!1;let v=typeof A?.id=="string"&&A.id.length>0?A.id:null;return v?v!==p||v===g?!1:(g=v,!0):p!==null||y?!1:(y=!0,!0)},S=(A,v={})=>{if(A!=="renderComplete"||!R(v))return!1;let D=e();return ft(D,"markLineCompleted",{}),!0},N=(A={})=>{if(A?._interactionSource==="choice")return!0;let v=A?.actions;return!v||typeof v!="object"||Array.isArray(v)?!1:Object.values(v).some(D=>D?._interactionSource==="choice")},O=(A,v={})=>!v?.actions||typeof A?.selectIsChoiceVisible!="function"||!A.selectIsChoiceVisible()?!1:!N(v),k=({preprocessPayload:A,onEvent:v}={})=>async(D,B={})=>{let F=e();if(O(F,B))return v?.(D,B);let H=await A?.(D,B)??B;if(O(F,H))return v?.(D,H);if(S(D,H),H?.actions){let _=H?._event?{_event:H._event}:H?.event?{_event:H.event}:void 0;F.handleActions(H.actions,_)}return v?.(D,H)},$=A=>{let v=e(),D=Ja(A);D.forEach(F=>{if(!qr[F.name]&&!r)throw new Error(`Unhandled pending effect "${F.name}".`)});let B={engine:v,routeGraphics:t,ticker:n,autoTimer:c,skipTimer:a,nextLineConfigTimerState:u,trackRenderDispatch:E,getRenderDispatchCount:L,enqueuePersistenceWrite:x};for(let F of D){let H=qr[F.name];if(H){H(B,F.payload);continue}r(F,B)}};return $.handleRouteGraphicsEvent=S,$.createRouteGraphicsEventHandler=k,$},Qa=Za;var ec=(e,t={})=>{let{resources:n={}}=t;return Gt(e,n)};var al=un;export{Qa as createEffectsHandler,Na as createIndexedDbPersistence,al as default,ec as resolveLayoutReferences};
|
|
1
|
+
var to=Object.defineProperty;var no=(e,t)=>{for(var n in t)to(e,n,{get:t[n],enumerable:!0})};var gn=Symbol.for("immer-nothing"),fn=Symbol.for("immer-draftable"),G=Symbol.for("immer-state");function Z(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var we=Object.getPrototypeOf;function ie(e){return!!e&&!!e[G]}function le(e){return e?yn(e)||Array.isArray(e)||!!e[fn]||!!e.constructor?.[fn]||Ye(e)||He(e):!1}var ro=Object.prototype.constructor.toString();function yn(e){if(!e||typeof e!="object")return!1;let t=we(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)===ro}function Be(e,t){We(e)===0?Reflect.ownKeys(e).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function We(e){let t=e[G];return t?t.type_:Array.isArray(e)?1:Ye(e)?2:He(e)?3:0}function ht(e,t){return We(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function bn(e,t,n){let r=We(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function oo(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Ye(e){return e instanceof Map}function He(e){return e instanceof Set}function ce(e){return e.copy_||e.base_}function mt(e,t){if(Ye(e))return new Map(e);if(He(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let n=yn(e);if(t===!0||t==="class_only"&&!n){let r=Object.getOwnPropertyDescriptors(e);delete r[G];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(we(e),r)}else{let r=we(e);if(r!==null&&n)return{...e};let o=Object.create(r);return Object.assign(o,e)}}function At(e,t=!1){return qe(e)||ie(e)||!le(e)||(We(e)>1&&(e.set=e.add=e.clear=e.delete=io),Object.freeze(e),t&&Object.entries(e).forEach(([n,r])=>At(r,!0))),e}function io(){Z(2)}function qe(e){return Object.isFrozen(e)}var so={};function ue(e){let t=so[e];return t||Z(0,e),t}var Le;function In(){return Le}function ao(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function dn(e,t){t&&(ue("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function gt(e){yt(e),e.drafts_.forEach(co),e.drafts_=null}function yt(e){e===Le&&(Le=e.parent_)}function pn(e){return Le=ao(Le,e)}function co(e){let t=e[G];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function hn(e,t){t.unfinalizedDrafts_=t.drafts_.length;let n=t.drafts_[0];return e!==void 0&&e!==n?(n[G].modified_&&(gt(t),Z(4)),le(e)&&(e=Fe(t,e),t.parent_||ze(t,e)),t.patches_&&ue("Patches").generateReplacementPatches_(n[G].base_,e,t.patches_,t.inversePatches_)):e=Fe(t,n,[]),gt(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==gn?e:void 0}function Fe(e,t,n){if(qe(t))return t;let r=t[G];if(!r)return Be(t,(o,i)=>mn(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return ze(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),Be(i,(a,l)=>mn(e,r,o,a,l,n,s)),ze(e,o,!1),n&&e.patches_&&ue("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function mn(e,t,n,r,o,i,s){if(ie(o)){let a=i&&t&&t.type_!==3&&!ht(t.assigned_,r)?i.concat(r):void 0,l=Fe(e,o,a);if(bn(n,r,l),ie(l))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if(le(o)&&!qe(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Fe(e,o),(!t||!t.scope_.parent_)&&typeof r!="symbol"&&Object.prototype.propertyIsEnumerable.call(n,r)&&ze(e,o)}}function ze(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&At(t,n)}function lo(e,t){let n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:In(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=r,i=wt;n&&(o=[r],i=Re);let{revoke:s,proxy:a}=Proxy.revocable(o,i);return r.draft_=a,r.revoke_=s,a}var wt={get(e,t){if(t===G)return e;let n=ce(e);if(!ht(n,t))return uo(e,n,t);let r=n[t];return e.finalized_||!le(r)?r:r===dt(e.base_,t)?(pt(e),e.copy_[t]=It(r,e)):r},has(e,t){return t in ce(e)},ownKeys(e){return Reflect.ownKeys(ce(e))},set(e,t,n){let r=An(ce(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){let o=dt(ce(e),t),i=o?.[G];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(oo(n,o)&&(n!==void 0||ht(e.base_,t)))return!0;pt(e),bt(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 dt(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,pt(e),bt(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let n=ce(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){Z(11)},getPrototypeOf(e){return we(e.base_)},setPrototypeOf(){Z(12)}},Re={};Be(wt,(e,t)=>{Re[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});Re.deleteProperty=function(e,t){return Re.set.call(this,e,t,void 0)};Re.set=function(e,t,n){return wt.set.call(this,e[0],t,n,e[0])};function dt(e,t){let n=e[G];return(n?ce(n):e)[t]}function uo(e,t,n){let r=An(t,n);return r?"value"in r?r.value:r.get?.call(e.draft_):void 0}function An(e,t){if(!(t in e))return;let n=we(e);for(;n;){let r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=we(n)}}function bt(e){e.modified_||(e.modified_=!0,e.parent_&&bt(e.parent_))}function pt(e){e.copy_||(e.copy_=mt(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var fo=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(l=i,...c){return s.produce(l,u=>n.call(this,u,...c))}}typeof n!="function"&&Z(6),r!==void 0&&typeof r!="function"&&Z(7);let o;if(le(t)){let i=pn(this),s=It(t,void 0),a=!0;try{o=n(s),a=!1}finally{a?gt(i):yt(i)}return dn(i,r),hn(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===gn&&(o=void 0),this.autoFreeze_&&At(o,!0),r){let i=[],s=[];ue("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else Z(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...a)=>this.produceWithPatches(s,l=>t(l,...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){le(e)||Z(8),ie(e)&&(e=xt(e));let t=pn(this),n=It(e,void 0);return n[G].isManual_=!0,yt(t),n}finishDraft(e,t){let n=e&&e[G];(!n||!n.isManual_)&&Z(9);let{scope_:r}=n;return dn(r,t),hn(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=ue("Patches").applyPatches_;return ie(e)?r(e,t):this.produce(e,o=>r(o,t))}};function It(e,t){let n=Ye(e)?ue("MapSet").proxyMap_(e,t):He(e)?ue("MapSet").proxySet_(e,t):lo(e,t);return(t?t.scope_:In()).drafts_.push(n),n}function xt(e){return ie(e)||Z(10,e),wn(e)}function wn(e){if(!le(e)||qe(e))return e;let t=e[G],n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=mt(e,t.scope_.immer_.useStrictShallowCopy_)}else n=mt(e,!0);return Be(n,(r,o)=>{bn(n,r,wn(o))}),t&&(t.finalized_=!1),n}var X=new fo,Et=X.produce,mc=X.produceWithPatches.bind(X),gc=X.setAutoFreeze.bind(X),yc=X.setUseStrictShallowCopy.bind(X),bc=X.applyPatches.bind(X),Ic=X.createDraft.bind(X),Ac=X.finishDraft.bind(X);var h={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},T={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},$e={NOT:0};var x=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},Y=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var vt=e=>{if(!e||e.trim()==="")throw new x("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let n=e.includes("===")?"==":"!=";throw new x(`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 x(`Incomplete comparison expression - missing right operand (got: '${e}')`)},xn=e=>{if(e.trim().endsWith(" in"))throw new x(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new x(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,n]=e.split(" in ");if(!n||n.trim()==="")throw new x(`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 x(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new x(`Invalid loop syntax (got: '$for ${e}')`)}};var En=(e,t,n=!1)=>{if(t===null)return new Y(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new Y(`Cannot iterate over undefined value at '$for ${e}'`);let r=typeof t;return n?new Y(`Cannot iterate over non-array value in loop '${e}' - got ${r} instead`):new Y(`Cannot iterate over non-array value (got: ${r}) at '$for ${e}'`)},vn=(e,t)=>{let n=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new Y(`Unknown function '${e}' (${n})`)};var po=(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=C(e,{functions:r,partials:o},t,{});return s===void 0?{}:s},C=(e,t,n,r)=>{let o=t.functions||t;if(e.var&&!e.type)return M(e.var,n,r);if(e.type===h.LITERAL)return e.value;if(e.type===h.VARIABLE)return M(e.path,n,r);if(e.type===h.INTERPOLATION)return mo(e.parts,t,n,r);switch(e.type){case h.FUNCTION:return _n(e,t,n,r);case h.BINARY:return Cn(e,t,n,r);case h.UNARY:return Ln(e,t,n,r);case h.CONDITIONAL:return yo(e,t,n,r);case h.LOOP:return xo(e,t,n,r);case h.OBJECT:return vo(e,t,n,r);case h.ARRAY:return So(e,t,n,r);case h.PARTIAL:return _o(e,t,n,r);case h.PATH_REFERENCE:return Co(e,t,n,r);default:throw new Error(`Unknown node type: ${e.type}`)}},Sn=new Map,ho=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},M=(e,t,n)=>{if(!e)return;if(e in n)return n[e];let r=Sn.get(e);if(!r){let i=[],s="",a=0;for(let l=0;l<e.length;l++){let c=e[l];c==="["?(a++,s+=c):c==="]"?(a--,s+=c):c==="."&&a===0?s&&(i.push(s),s=""):s+=c}s&&i.push(s),r=[];for(let l of i){let c=ho(l.trim());r.push(...c)}Sn.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},mo=(e,t,n,r)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=C(i,t,n,r);o.push(s!=null?String(s):"")}return o.join("")},_n=(e,t,n,r)=>{let o=t.functions||t,i=o[e.name];if(!i)throw vn(e.name,o);let s=e.args.map(a=>C(a,t,n,r));return i(...s)},xe=(e,t,n,r)=>{if(e.var&&!e.type)return M(e.var,n,r);switch(e.type){case h.VARIABLE:return M(e.path,n,r);case h.LITERAL:return e.value;case h.BINARY:return Cn(e,t,n,r);case h.UNARY:return Ln(e,t,n,r);case h.FUNCTION:return _n(e,t,n,r);default:return C(e,t,n,r)}},Cn=(e,t,n,r)=>{if(e.op===T.AND||e.op===T.OR){let s=xe(e.left,t,n,r),a=xe(e.right,t,n,r);switch(e.op){case T.AND:return s&&a;case T.OR:return s||a}}let o=C(e.left,t,n,r),i=C(e.right,t,n,r);switch(e.op){case T.EQ:return o==i;case T.NEQ:return o!=i;case T.GT:return o>i;case T.LT:return o<i;case T.GTE:return o>=i;case T.LTE:return o<=i;case T.IN:return Array.isArray(i)?i.includes(o):!1;case T.ADD:if(typeof o!="number"||typeof i!="number")throw new Y(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case T.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new Y(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},Ln=(e,t,n,r)=>{let o=e.op===$e.NOT?xe(e.operand,t,n,r):C(e.operand,t,n,r);if(e.op===$e.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},go=(e,t,n,r)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===h.VARIABLE)if(M(o.path,n,r)){let s=e.bodies[0];if(s.type===h.OBJECT&&s.properties.length<=5){let a={};for(let l of s.properties){let c=l.parsedKey?C(l.parsedKey,t,n,r):l.key,u=l.value;if(u.type===h.LITERAL)a[c]=u.value;else if(u.type===h.VARIABLE)a[c]=M(u.path,n,r);else if(u.type===h.INTERPOLATION){let f=[];for(let d of u.parts)if(typeof d=="string")f.push(d);else if(d.type===h.VARIABLE){let p=M(d.path,n,r);f.push(p!=null?String(p):"")}else{let p=C(d,t,n,r);f.push(p!=null?String(p):"")}a[c]=f.join("")}else a[c]=C(u,t,n,r)}return a}}else{let s=e.bodies[1];if(s.type===h.OBJECT&&s.properties.length<=5){let a={};for(let l of s.properties){let c=l.parsedKey?C(l.parsedKey,t,n,r):l.key,u=l.value;if(u.type===h.LITERAL)a[c]=u.value;else if(u.type===h.VARIABLE)a[c]=M(u.path,n,r);else if(u.type===h.INTERPOLATION){let f=[];for(let d of u.parts)if(typeof d=="string")f.push(d);else if(d.type===h.VARIABLE){let p=M(d.path,n,r);f.push(p!=null?String(p):"")}else{let p=C(d,t,n,r);f.push(p!=null?String(p):"")}a[c]=f.join("")}else a[c]=C(u,t,n,r)}return a}}}return null},yo=(e,t,n,r)=>{let o=go(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||xe(s,t,n,r))return C(e.bodies[i],t,n,r)}return Rn},bo=(e,t)=>{let n=e.body,r=e.itemVar;if(n.type===h.CONDITIONAL&&n.conditions.length===1&&n.conditions[0].type===h.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===h.OBJECT&&i.properties.length<=5){for(let l of i.properties)if(l.parsedKey)return null;let a=[];for(let l=0;l<t.length;l++){let c=t[l];if(c[s]){let u={};for(let f of i.properties){let d=f.key,p=f.value;if(p.type===h.LITERAL)u[d]=p.value;else if(p.type===h.VARIABLE){let m=p.path;if(m===r)u[d]=c;else if(m.startsWith(r+".")){let y=m.substring(r.length+1);u[d]=c[y]}else return null}else if(p.type===h.INTERPOLATION){let m=[],y=!0;for(let I of p.parts)if(typeof I=="string")m.push(I);else if(I.type===h.VARIABLE){let b=I.path;if(b===r)m.push(c!=null?String(c):"");else if(b.startsWith(r+".")){let g=b.substring(r.length+1),w=c[g];m.push(w!=null?String(w):"")}else{y=!1;break}}else{y=!1;break}if(!y)return null;u[d]=m.join("")}else return null}a.push(u)}}return a}}}return null},Io=(e,t)=>{let n=e.body,r=e.itemVar,o=bo(e,t);if(o!==null)return o;if(n.type===h.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 l=a.key,c=a.value;if(c.type===h.LITERAL)i.push({key:l,type:"literal",value:c.value});else if(c.type===h.VARIABLE){let u=c.path;if(u===r)i.push({key:l,type:"item"});else if(u.startsWith(r+".")){let f=u.substring(r.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:l,type:"prop",prop:f});else{s=!1;break}}else{s=!1;break}}else if(c.type===h.INTERPOLATION&&c.parts.length===1){let u=c.parts[0];if(u.type===h.VARIABLE){let f=u.path;if(f===r)i.push({key:l,type:"item_string"});else if(f.startsWith(r+".")){let d=f.substring(r.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:l,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 l=0;l<t.length;l++){let c=t[l];a[l]={id:c.id,title:c.title!=null?String(c.title):"",completed:c.completed}}else for(let l=0;l<t.length;l++){let c=t[l],u={};for(let f of i)if(f.type==="literal")u[f.key]=f.value;else if(f.type==="item")u[f.key]=c;else if(f.type==="prop")u[f.key]=c[f.prop];else if(f.type==="item_string")u[f.key]=c!=null?String(c):"";else if(f.type==="prop_string"){let d=c[f.prop];u[f.key]=d!=null?String(d):""}a[l]=u}return a}}return null},Ao=(e,t,n,r,o)=>{let i=[],s=e.body;if(s.type===h.OBJECT&&s.fast!==!1){let a=e.itemVar,l=e.indexVar;for(let c=0;c<o.length;c++){let u=o[c],f={},d={...r,[a]:u,...l&&{[l]:c}};d.__paths__||(d.__paths__=r.__paths__||{});let p=e.iterable.path||"";if(r&&r.__paths__&&p){let m=p.split("."),y=m[0];y in r.__paths__&&(p=r.__paths__[y],m.length>1&&(p+="."+m.slice(1).join(".")))}d.__paths__={...d.__paths__,[a]:`${p}[${c}]`,...l&&{[l]:c}};for(let m of s.properties){let y=m.parsedKey?C(m.parsedKey,t,n,d):m.key,I=m.value;if(I.type===h.LITERAL)f[y]=I.value;else if(I.type===h.VARIABLE){let b=I.path;if(b===a)f[y]=u;else if(b===l)f[y]=c;else if(b.startsWith(a+".")){let g=b.substring(a.length+1);!g.includes(".")&&!g.includes("[")?f[y]=u[g]:f[y]=M(b,n,{...r,[a]:u,...l&&{[l]:c}})}else f[y]=M(b,n,{...r,[a]:u,...l&&{[l]:c}})}else if(I.type===h.INTERPOLATION){let b=[];for(let g of I.parts)if(typeof g=="string")b.push(g);else if(g.type===h.VARIABLE){let w=g.path,v;if(w===a)v=u;else if(w===l)v=c;else if(w.startsWith(a+".")){let L=w.substring(a.length+1);!L.includes(".")&&!L.includes("[")?v=u[L]:v=M(w,n,{...r,[a]:u,...l&&{[l]:c}})}else v=M(w,n,{...r,[a]:u,...l&&{[l]:c}});b.push(v!=null?String(v):"")}else{let w={...r,[a]:u,...l&&{[l]:c}},v=C(g,t,n,w);b.push(v!=null?String(v):"")}f[y]=b.join("")}else{let b={...r,[a]:u,...l&&{[l]:c}};f[y]=C(I,t,n,b)}}i.push(f)}return i}return null},wo=(e,t,n)=>{let r=e.body;if(r.type===h.OBJECT&&r.properties.length===1&&r.properties[0].key==="$if item.visible"){let i=r.properties[0].value;if(i.type===h.CONDITIONAL&&i.conditions.length===1&&i.conditions[0].type===h.VARIABLE&&i.conditions[0].path==="item.visible"){let s=i.bodies[0];if(s.type===h.OBJECT&&s.properties.length===2){let a=s.properties[0],l=s.properties[1];if(a.key==="id"&&a.value.type===h.VARIABLE&&a.value.path==="item.id"&&l.key==="$if item.highlighted"&&l.value.type===h.CONDITIONAL){let c=[];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),c.push(d)}}return c}}}}return null},xo=(e,t,n,r)=>{let o=C(e.iterable,t,n,r);if(!Array.isArray(o)){let c,u=!1;if(e.iterable.type===h.FUNCTION){u=!0;let d=e.iterable.args.map(p=>p.type===h.LITERAL?typeof p.value=="string"?`'${p.value}'`:String(p.value):p.type===h.VARIABLE?p.path:p.type===h.FUNCTION?`${p.name}(...)`:"?").join(", ");c=`${e.iterable.name}(${d})`}else c=e.iterable.path||"undefined";let f=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${c}`;throw En(f,o,u)}if(!e.indexVar){let c=wo(e,o,e.itemVar);if(c!==null)return c}if(!e.indexVar){let c=Io(e,o);if(c!==null)return c}let i=Ao(e,t,n,r,o);if(i!==null)return i;let s=[],a=e.iterable.path||"";if(r&&r.__paths__&&a){let c=a.split("."),u=c[0];u in r.__paths__&&(a=r.__paths__[u],c.length>1&&(a+="."+c.slice(1).join(".")))}let l=!1;e.body.type===h.ARRAY&&(e.body.items.length<=1?l=!1:l=e.body._shouldPreserveArray??=e.body.items.some(c=>c.type===h.OBJECT&&c.properties.some(u=>u.key.startsWith("$if ")||u.key.startsWith("$when "))));for(let c=0;c<o.length;c++){let u=e.indexVar?{...r,[e.itemVar]:o[c],[e.indexVar]:c}:{...r,[e.itemVar]:o[c]};u.__paths__||(u.__paths__=r.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${a}[${c}]`},e.indexVar&&(u.__paths__[e.indexVar]=c);let f=C(e.body,t,n,u);if(Array.isArray(f)&&f.length===1&&!l){let d=f[0];s.push(d===void 0?{}:d)}else s.push(f===void 0?{}:f)}return s},Eo=(e,t,n,r)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?C(o.parsedKey,t,n,r):o.key,s=o.value;if(s.type===h.OBJECT&&s.properties.length<=10&&!s.whenCondition){let a={},l={},c=!0;for(let u of s.properties){let f=u.parsedKey?C(u.parsedKey,t,n,r):u.key,d=u.value;if(d.type===h.LITERAL)l[f]=d.value;else if(d.type===h.VARIABLE)l[f]=M(d.path,n,r);else if(d.type===h.INTERPOLATION){let p=[];for(let m of d.parts)if(typeof m=="string")p.push(m);else if(m.type===h.VARIABLE){let y=M(m.path,n,r);p.push(y!=null?String(y):"")}else{c=!1;break}if(!c)break;l[f]=p.join("")}else if(d.type===h.OBJECT&&d.properties.length<=5){let p={};for(let m of d.properties){let y=m.key,I=m.value;if(I.type===h.LITERAL)p[y]=I.value;else if(I.type===h.VARIABLE)p[y]=M(I.path,n,r);else if(I.type===h.INTERPOLATION){let b=[];for(let g of I.parts)if(typeof g=="string")b.push(g);else if(g.type===h.VARIABLE){let w=M(g.path,n,r);b.push(w!=null?String(w):"")}else{c=!1;break}if(!c)break;p[y]=b.join("")}else{c=!1;break}}if(!c)break;l[f]=p}else{c=!1;break}}if(c)return a[i]=l,a}}return null},vo=(e,t,n,r)=>{let o=t.functions||t;if(e.whenCondition&&!xe(e.whenCondition,o,n,r))return;let i=Eo(e,t,n,r);if(i!==null)return i;if(e.fast){let c={};for(let u of e.properties){let f=u.parsedKey?C(u.parsedKey,t,n,r):u.key,d=u.value;if(d.type===h.LITERAL)c[f]=d.value;else if(d.type===h.VARIABLE)c[f]=M(d.path,n,r);else if(d.type===h.INTERPOLATION){let p=[];for(let m of d.parts)if(typeof m=="string")p.push(m);else if(m.type===h.VARIABLE){let y=M(m.path,n,r);p.push(y!=null?String(y):"")}else{let y=C(m,t,n,r);p.push(y!=null?String(y):"")}c[f]=p.join("")}else c[f]=C(d,t,n,r)}return c}let s={},a=null,l=!1;for(let c of e.properties)if(!c.key.startsWith("$if ")&&!c.key.match(/^\$if\s+\w+.*:?$/)&&!c.key.startsWith("$elif")&&!c.key.startsWith("$else")&&!c.key.startsWith("$for ")){l=!0;break}for(let c of e.properties)if(c.key.startsWith("$if ")||c.key.match(/^\$if\s+\w+.*:?$/)){let u=C(c.value,t,n,r);if(!l&&u!==null&&u!==void 0)return Array.isArray(u)&&u.length===1?u[0]:u;typeof u=="object"&&u!==null&&!Array.isArray(u)&&Object.assign(s,u)}else if(c.key.startsWith("$for ")){if(e.properties.length===1)return C(c.value,t,n,r)}else{let u=c.value;if(u&&u.type===h.OBJECT&&u.properties){let f=u.properties.find(d=>d.key.startsWith("$for "));if(f){let d=C(f.value,t,n,r);d!==void 0&&(s[c.key]=d)}else{let d=C(c.value,t,n,r);d!==void 0&&(s[c.key]=d)}}else{let f=c.parsedKey?C(c.parsedKey,t,n,r):c.key,d=C(c.value,t,n,r);d!==void 0&&(s[f]=d)}}return s},Rn={},So=(e,t,n,r)=>{let o=[];for(let i of e.items)if(i.type===h.LOOP){let s=C(i,t,n,r);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=C(i,t,n,r);s!==Rn&&s!==void 0&&o.push(s)}return o},_o=(e,t,n,r)=>{let{name:o,data:i,whenCondition:s}=e,a=t.partials||{},l=t.functions||t;if(s&&!xe(s,l,n,r))return;if(!a[o])throw new Y(`Partial '${o}' is not defined`);let c=r._partialStack||[];if(c.includes(o))throw new Y(`Circular partial reference detected: ${o}`);let u=a[o],f=n,d={...r,_partialStack:[...c,o]};if(r){f={...n};for(let p of Object.keys(r))p.startsWith("_")||(f[p]=r[p])}if(i){let p=C(i,t,n,r);f={...f,...p}}return C(u,t,f,d)},Co=(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 Y(`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 Y(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let l=r.__paths__[s];if(typeof l=="number"){if(a.length>0)throw new Y(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(l)}return a.length>0&&(l+="."+a.join(".")),l},St=po;var Lo=/\$\{([^}]*)\}/g,Ro=/#\{([^}]*)\}/g,kn=(e,t={})=>{let n=e.match(/^(\w+)\((.*)\)$/);if(!n)return{isFunction:!1};let[,r,o]=n,i=$o(o,t);return{isFunction:!0,type:h.FUNCTION,name:r,args:i}},$o=(e,t={})=>e.trim()?ko(e).map(r=>Oo(r.trim(),t)):[],ko=e=>{let t=[],n="",r=0,o=!1,i="";for(let s=0;s<e.length;s++){let a=e[s],l=s>0?e[s-1]:"";!o&&(a==='"'||a==="'")?(o=!0,i=a,n+=a):o&&a===i&&l!=="\\"?(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},Oo=(e,t={})=>{if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:h.LITERAL,value:e.slice(1,-1)};if(/^-?\d+(\.\d+)?$/.test(e))return{type:h.LITERAL,value:parseFloat(e)};if(e==="true")return{type:h.LITERAL,value:!0};if(e==="false")return{type:h.LITERAL,value:!1};if(e==="null")return{type:h.LITERAL,value:null};let n=kn(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:l}of o){let c=0;for(;c<r.length;){let u=fe(r.substring(c),a);if(u===-1)break;let f=c+u;f>i&&(i=f,s={op:a,type:l}),c=f+a.length}}if(i!==-1)try{return W(r,t)}catch{return{type:h.VARIABLE,path:r}}return{type:h.VARIABLE,path:r}},On=/^\w+\(.*\)$/,Po=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,To=e=>{if(!(!e||e.trim()===""||On.test(e))&&Po.test(e))throw e.includes("?")&&e.includes(":")?new x(`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 x(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new x(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},$n=e=>{let t=e.trim();if(On.test(t))throw new x(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new x(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new x(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new x(`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 x(`Complex expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);return{type:h.PATH_REFERENCE,path:t}},ke=(e,t={})=>{let n=e.trim();To(n);let r=kn(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:h.VARIABLE,path:n}},_t=(e,t={})=>{let n=e,r=[];(e.includes("\\${")||e.includes("\\#{"))&&(n=e.replace(/\\\\(\$\{[^}]*\})/g,"\\DOUBLE_ESC_VAR$1"),n=n.replace(/\\\\(#\{[^}]*\})/g,"\\DOUBLE_ESC_PATH$1"),n=n.replace(/\\(\$\{[^}]*\})/g,(c,u)=>{let f=`__ESCAPED_${r.length}__`;return r.push(u),f}),n=n.replace(/\\(#\{[^}]*\})/g,(c,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(Lo)],i=[...n.matchAll(Ro)],s=[...o.map(c=>({match:c,type:"variable"})),...i.map(c=>({match:c,type:"pathref"}))].sort((c,u)=>c.match.index-u.match.index);if(s.length===0){let c=n;for(let u=0;u<r.length;u++)c=c.replace(`__ESCAPED_${u}__`,r[u]);return{type:h.LITERAL,value:c}}if(s.length===1&&s[0].match[0]===n&&r.length===0){let{match:c,type:u}=s[0];try{return u==="variable"?ke(c[1],t):$n(c[1])}catch(f){if(f.message==="Invalid array index syntax")return{type:h.LITERAL,value:n};throw f}}let a=[],l=0;for(let{match:c,type:u}of s){let[f,d]=c,p=c.index;if(p>l){let m=n.substring(l,p);for(let y=0;y<r.length;y++)m=m.replace(`__ESCAPED_${y}__`,r[y]);m&&a.push(m)}try{let m;u==="variable"?m=ke(d.trim(),t):m=$n(d.trim()),a.push(m)}catch(m){if(m.message==="Invalid array index syntax")a.push(f);else throw m}l=p+f.length}if(l<n.length){let c=n.substring(l);for(let u=0;u<r.length;u++)c=c.replace(`__ESCAPED_${u}__`,r[u]);c&&a.push(c)}return{type:h.INTERPOLATION,parts:a}};var se=(e,t)=>typeof e=="string"?_t(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?No(e,t):Vo(e,t):{type:h.LITERAL,value:e},Do=e=>{let{$each:t,...n}=e;if(typeof t!="string")throw new x("$each value must be a non-empty string");let r=t.trim();if(r==="")throw new x("$each value must be a non-empty string");if(Object.keys(n).length===0)throw new x("Empty $each body not allowed");if(n.$partial!==void 0)throw new x("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${r}`]:n}},No=(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 l=Do(i),c=Object.keys(l);if(c.length===1&&/^\$for(?::\w+)?\s/.test(c[0])){let u=Pn(c[0],l[c[0]],t,!0);n.push(u),r=!0;continue}}catch(l){throw l instanceof x?l:new x(l.message)}let a=Object.keys(i);if(a.length===1&&/^\$for(?::\w+)?\s/.test(a[0])){let l=Pn(a[0],i[a[0]],t);n.push(l),r=!0;continue}}let s=se(i,t);n.push(s),(s.type===h.FUNCTION||s.type===h.CONDITIONAL||s.type===h.LOOP||s.type===h.PARTIAL||s.type===h.OBJECT&&!s.fast||s.type===h.ARRAY&&!s.fast)&&(r=!0)}return{type:h.ARRAY,items:n,fast:!r}},Vo=(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 x("$partial value must be a string");if(e.$partial.trim()==="")throw new x("$partial value cannot be an empty string");let l=["$if","$elif","$else","$for"],c=[];for(let[b]of i)for(let g of l)if(b===g||b.startsWith(g+" ")||b.startsWith(g+"#")){c.push(g);break}if(c.length>0)throw new x(`Cannot use $partial with ${c.join(", ")} at the same level. Wrap $partial in a parent object if you need conditionals.`);let{$partial:u,$when:f,...d}=e,p={},m=!1;for(let[b,g]of Object.entries(d)){let w=b;(b.startsWith("\\$")||b.startsWith("$$"))&&(w=b.slice(1)),p[w]=g,m=!0}let y=null;if(m&&(y=se(p,t),y.type===h.OBJECT)){let b=!1;for(let g of y.properties)if(g.value.type===h.VARIABLE||g.value.type===h.INTERPOLATION||g.value.type===h.FUNCTION||g.value.type===h.CONDITIONAL||g.value.type===h.OBJECT&&!g.value.fast||g.value.type===h.ARRAY&&!g.value.fast){b=!0;break}b&&(y.fast=!1)}let I={type:h.PARTIAL,name:u,data:y};if(f!==void 0){let b;if(typeof f=="string"){if(f.trim()==="")throw new x("Empty condition expression after '$when'");b=W(f,t)}else b={type:h.LITERAL,value:f};I.whenCondition=b}return I}for(let[l,c]of i)if(l==="$when"){if(o!==null)throw new x("Multiple '$when' directives on the same object are not allowed");if(c==null)throw new x("Missing condition expression after '$when'");let u=typeof c=="string"?c:JSON.stringify(c);if(u.trim()==="")throw new x("Empty condition expression after '$when'");o=W(u,t),r=!0}else if(l.startsWith("$when#")||l.startsWith("$when "))throw new x("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<i.length;){let[l,c]=i[s];if(l==="$when"){s++;continue}if(l==="$each")throw new x("$each can only be used inside arrays");if(l.startsWith("$if ")||l.match(/^\$if#\w+\s/)||l.match(/^\$if\s+\w+.*:$/)){let u=Mo(i,s,t);n.push({key:l,value:u.node}),r=!0,s=u.nextIndex}else if(/^\$for(?::\w+)?\s/.test(l)){let u=l.match(/^\$for(?::(\w+))?\s/)?.[1]||"",f=u?`:${u}`:"";throw new x(`$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(l.startsWith("$elif ")||l.startsWith("$else"))throw new x(`'${l.split(" ")[0]}' without matching '$if'`);if(l==="$if"||l==="$if:")throw new x("Missing condition expression after '$if'");{let u=se(c,t);(u.type===h.FUNCTION||u.type===h.CONDITIONAL||u.type===h.PARTIAL||u.type===h.OBJECT&&!u.fast||u.type===h.ARRAY&&!u.fast)&&(r=!0);let f=_t(l,t),d={key:l,value:u};(f.type!==h.LITERAL||f.value!==l)&&(d.parsedKey=f),n.push(d),s++}}}let a={type:h.OBJECT,properties:n,fast:!r};return o&&(a.whenCondition=o),a},Mo=(e,t,n={})=>{let r=[],o=[],i=t,[s,a]=e[i],l=null,c;if(s.startsWith("$if#")){let f=s.match(/^\$if#(\w+)\s+(.+)$/);if(f)l=f[1],c=f[2];else throw new x(`Invalid conditional syntax: ${s}`)}else c=s.substring(4),c.endsWith(":")&&(c=c.slice(0,-1).trim());vt(c);let u=W(c,n);for(r.push(u),o.push(se(a,n)),i++;i<e.length;){let[f,d]=e[i],p=!1,m;if(l?f.startsWith(`$elif#${l} `)?(m=f.substring(`$elif#${l} `.length),m.endsWith(":")&&(m=m.slice(0,-1).trim()),p=!0):(f===`$else#${l}`||f===`$else#${l}:`)&&(p=!0,m=null):f.startsWith("$elif ")?(m=f.substring(6),m.endsWith(":")&&(m=m.slice(0,-1).trim()),p=!0):(f==="$else"||f==="$else:")&&(p=!0,m=null),p){if(m===null)r.push(null);else{vt(m);let y=W(m,n);r.push(y)}if(o.push(se(d,n)),i++,m===null)break}else break}return{node:{type:h.CONDITIONAL,conditions:r,bodies:o,id:l},nextIndex:i}},W=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let c=e.slice(1,-1),u=0,f=!0;for(let d=0;d<c.length;d++)if(c[d]==="("?u++:c[d]===")"&&u--,u<0){f=!1;break}if(f&&u===0)return W(c,t)}let n=fe(e,"||");if(n!==-1)return{type:h.BINARY,op:T.OR,left:W(e.substring(0,n).trim(),t),right:W(e.substring(n+2).trim(),t)};let r=fe(e,"&&");if(r!==-1)return{type:h.BINARY,op:T.AND,left:W(e.substring(0,r).trim(),t),right:W(e.substring(r+2).trim(),t)};let o=[{op:">=",type:T.GTE},{op:"<=",type:T.LTE},{op:"==",type:T.EQ},{op:"!=",type:T.NEQ},{op:">",type:T.GT},{op:"<",type:T.LT},{op:" in ",type:T.IN}];for(let{op:c,type:u}of o){let f=fe(e,c);if(f!==-1)return{type:h.BINARY,op:u,left:W(e.substring(0,f).trim(),t),right:W(e.substring(f+c.length).trim(),t)}}let i=-1,s=null,a=[{op:" + ",type:T.ADD},{op:" - ",type:T.SUBTRACT}];for(let{op:c,type:u}of a){let f=0;for(;f<e.length;){let d=fe(e.substring(f),c);if(d===-1)break;let p=f+d;p>i&&(i=p,s={op:c,type:u}),f=p+c.length}}if(i!==-1&&s)return{type:h.BINARY,op:s.type,left:W(e.substring(0,i).trim(),t),right:W(e.substring(i+s.op.length).trim(),t)};let l=[" * "," / "," % "];for(let c of l)if(fe(e,c)!==-1)throw new x(`Arithmetic operations are not allowed in conditionals: "${c}"`);return e.startsWith("!")?{type:h.UNARY,op:$e.NOT,operand:W(e.substring(1).trim(),t)}:Tn(e,t)},fe=(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},jo=e=>{if(e=e.trim(),e==="true")return{type:h.LITERAL,value:!0};if(e==="false")return{type:h.LITERAL,value:!1};if(e==="null")return{type:h.LITERAL,value:null};if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:h.LITERAL,value:e.slice(1,-1)};if(e==='""'||e==="''")return{type:h.LITERAL,value:""};if(e==="{}")return{type:h.LITERAL,value:{}};if(e==="[]")return{type:h.LITERAL,value:[]};let t=Number(e);return!isNaN(t)&&isFinite(t)?{type:h.LITERAL,value:t}:{type:h.VARIABLE,path:e}},Tn=(e,t)=>{let n=e.trim();if(n.match(/^(\w+)\((.*)\)$/))return ke(n,t);let o=jo(n);if(o.type===h.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(n))return{type:h.VARIABLE,path:n};try{return ke(n,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},Uo=(e,t=!1)=>{let n=t?"$each":"$for";try{xn(e)}catch(r){if(r instanceof x&&t){let o=r.message.replace(/\$for/g,"$each");throw new x(o.replace("Parse Error: ",""))}throw r}},Pn=(e,t,n,r=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let I=r?"$each":"$for";throw new x(`Invalid loop syntax (got: '${e.replace("$for",I)}')`)}let s=i[1],a=i[2].trim();Uo(a,r);let l=a.match(/^(.+?)\s+in\s+(.+)$/);if(!l){let I=r?"$each":"$for";throw new x(`Invalid loop syntax - missing 'in' keyword (got: '${I} ${a}')`)}let c=l[1].trim(),u=l[2].trim(),f,d=null;if(c.includes(",")){let I=c.split(",").map(b=>b.trim());if(I.length!==2)throw new x(`Invalid loop variables: ${c}. Expected format: "item" or "item, index"`);f=I[0],d=I[1]}else f=c;let p=["this","undefined","null","true","false"];if(p.includes(f))throw new x(`Reserved variable name: ${f}`);if(d&&p.includes(d))throw new x(`Reserved variable name: ${d}`);let m=Tn(u,n),y=se(t,n);return{type:h.LOOP,itemVar:f,indexVar:d,iterable:m,body:y,flatten:s!=="nested"}};var Bo=(e,t={})=>{let{functions:n={}}=t;return se(e,n)},Ke=Bo;var Ct={};no(Ct,{now:()=>Fo});var Fo=()=>Date.now();var zo=(e,t,n={})=>{let{functions:r={},partials:o={}}=n,i={...Ct,...r},s=Ke(e,{functions:i}),a={};for(let[l,c]of Object.entries(o))a[l]=Ke(c,{functions:i});return St(s,t,{functions:i,partials:a})},J=zo;var Dn=(e,t,n={})=>{let r=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=l=>l,transformActionFirstArgument:a=l=>l}=n;for(let[l,c]of Object.entries(t))l!=="createInitialState"&&(l.startsWith("select")?o[l]=(...u)=>c(s(r),...u):i[l]=(...u)=>{r=Et(r,d=>c(a(d),...u))});return{...o,...i}},Ge=(e,t)=>n=>{let r=e(),o=Array.isArray(n)?n:[n];return Et(r,i=>{o.forEach(s=>{t.forEach(a=>{a(i,s)})})})};var Wo=(e,t)=>{if(e.default!==void 0)return e.default;let n=["number","boolean","string","object"];if(!n.includes(e.type))throw new Error(`Invalid variable type: ${e.type} for variable ${t}. Expected one of: ${n.join(", ")}`);switch(e.type){case"number":return 0;case"boolean":return!1;case"string":return"";case"object":return{}}},$t=e=>{let t={},n={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([r,o])=>{let i=Wo(o,r);o.scope==="context"?t[r]=i:n[r]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}},kt=(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(", ")}`)},Ot=(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(", ")}`)},Pt=(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 Nn=(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()))},Yo=(e,t)=>{let n=e?.ui,r=t?.ui;return JSON.stringify(n)===JSON.stringify(r)?null:n&&!r?{changeType:"delete",data:e}:r&&!e?{changeType:"add",data:t}:r&&e?{changeType:"update",data:t}:null},Tt=(e={},t={})=>{let n={},r=["sfx","voice"],o=s=>{let a=e[s],l=t[s];l&&!a?n[s]={changeType:"add",data:l}:a&&!l?r.includes(s)||(n[s]={changeType:"delete",data:a}):a&&l&&JSON.stringify(a)!==JSON.stringify(l)&&(n[s]={changeType:"update",data:l})};o("background"),o("bgm"),o("voice");let i=Yo(e.dialogue,t.dialogue);return i&&(n.dialogue=i),o("choice"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),n},Dt=(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);let r=(o,i)=>{let s=t[o]?.items;Array.isArray(s)&&(t[o].items=s.map(a=>{let l={...a};return delete l.animations,i(l)?l: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},Ho=(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},qo=(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=Ho(t,n);if(r===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return r},Ko={updateProjectData:new Set(["projectData"]),showConfirmDialog:new Set(["confirmActions","cancelActions"])},Vn=(e,t)=>{let n=e[e.length-1];return n?Ko[n]?.has(t)===!0:!1},Lt=(e,t,n=[])=>Array.isArray(e)?e.map(r=>Lt(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,Vn(n,r)?o:Lt(o,t,[...n,r])])):qo(e,t),Rt=(e,t,n=[])=>Array.isArray(e)?e.map(r=>Rt(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,Vn(n,r)?o:Rt(o,t,[...n,r])])):typeof e=="string"?J(e,t):e,Mn=(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=Lt(e,t._event);return Rt(n,t)};var Xe=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:structuredClone(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},Un=(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}},Oe=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),jn=e=>e?.animations?.playback?.continuity==="persistent",Go=e=>{if(e){if(e.character&&Oe(e.character,"name"))return e.character.name;if(Oe(e,"characterName"))return e.characterName}},Xo=()=>({}),Jo=(e,t)=>{if(t.background){let{animationsOnly:n,state:r}=Xe(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&&!Oe(o,"animations")&&jn(i)&&(o.animations=structuredClone(i.animations)),e.background=o}else e.background?.animations&&!jn(e.background)&&(e.background.animations={})},Zo=(e,t)=>{if(!t.dialogue){e.dialogue&&e.dialogue.mode==="adv"&&(e.dialogue.content=void 0,e.dialogue.persistCharacter!==!0&&(delete e.dialogue.characterId,delete e.dialogue.character));return}if(e.dialogue||(e.dialogue={}),t.dialogue.ui){let{animationsOnly:s,state:a}=Xe(t.dialogue.ui,l=>!!l.resourceId);s?e.dialogue.ui={...e.dialogue.ui,...a}: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"),t.dialogue.content!==void 0&&(e.dialogue.content=t.dialogue.content);let n=Oe(t.dialogue,"persistCharacter")?t.dialogue.persistCharacter===!0:e.dialogue.persistCharacter===!0;n?e.dialogue.persistCharacter=!0:delete e.dialogue.persistCharacter;let r=Oe(t.dialogue,"characterId"),o=Go(t.dialogue),i=o!==void 0;if(r?t.dialogue.characterId?e.dialogue.characterId=t.dialogue.characterId:delete e.dialogue.characterId:n||delete e.dialogue.characterId,i?e.dialogue.character={name:o}:(r||!n)&&delete e.dialogue.character,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 s={content:t.dialogue.content,characterId:e.dialogue.characterId??null};e.dialogue.character&&(s.character={...e.dialogue.character}),e.dialogue.lines.push(s)}},Qo=(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},ei=(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}}},ti=(e,t)=>{if(t.visual){let{hasValidItems:n,processedItems:r}=Un(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))},ni=(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}=Un(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId);n?e.character={items:r}:delete e.character},ri=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},oi=(e,t)=>{if(t.layout){let{animationsOnly:n,state:r}=Xe(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},ii=(e,t)=>{if(t.choice){let{animationsOnly:n,state:r}=Xe(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},si=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},ai=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},ci=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(n=>{delete e[n]})},Ee=e=>Ge(Xo,[ci,Jo,Qo,ei,ti,Zo,ni,ri,oi,ii,si,ai])(e);var pe={objectValues:e=>Object.entries(e).map(([t,n])=>({id:t,...n})),formatDate:Nn},li=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,ui=(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},Qe=(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=li.exec(s);if(a){let[,l,c,u]=a,f=ui(t,u);if(!Array.isArray(f))continue;let d=Array.isArray(i[s])?i[s]:[];f.forEach((p,m)=>{let y={...t,[l]:p};c&&(y[c]=m),d.forEach(I=>{let b=Qe(I,y,n),g=J(b,y,n);Array.isArray(g)?o.push(...g):o.push(g)})});continue}}o.push(Qe(i,t,n))}return o}if(!e||typeof e!="object")return e;let r={};return Object.entries(e).forEach(([o,i])=>{r[o]=Qe(i,t,n)}),r},Wt=({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".`)},fi=({id:e,targetId:t,animation:n,playback:r,animationPath:o="animation"})=>{let i=structuredClone(n);return Wt({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},di=(e,{animationId:t="animation",animationPath:n="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return Wt({animationType:e.type,animationId:t,animationPath:n}),e.type},pi=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},hi=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e.playback},mi=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Jn=e=>e?.playback?.continuity==="persistent",Ut=e=>Array.isArray(e)?e.map(Ut):!e||typeof e!="object"?e:Object.keys(e).sort().reduce((t,n)=>(t[n]=Ut(e[n]),t),{}),et=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let t=structuredClone(e);return delete t.playback,JSON.stringify(Ut(t))},Zn=(e=[])=>e.filter(t=>Jn(t)).map(t=>structuredClone(t)),Qn=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,Nt=e=>!e||typeof e!="object"||Array.isArray(e)?0:Object.values(e).reduce((t,n)=>Math.max(t,Qn(n)),0),er=e=>!e||typeof e!="object"||Array.isArray(e)?0:Math.max(Nt(e.tween),Nt(e.prev?.tween),Nt(e.next?.tween),Qn(e.mask?.progress)),Bn=({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(et).filter(Boolean));return e.some(r=>{if(!Jn(r))return!1;let o=et(r);return o?n.has(o):!1})},de=({animationInstances:e,isLineCompleted:t,skipTransitionsAndAnimations:n,activePersistentAnimations:r,restoredPersistentAnimations:o,isAuthoredOnCurrentLine:i=!0})=>!Array.isArray(e)||e.length===0||n?!1:i&&!t||Bn({animationInstances:e,activePersistentAnimations:r})?!0:i?!1:Bn({animationInstances:e,activePersistentAnimations:o}),gi=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),yi=(e,t)=>{if(gi(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},bi=({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?fi({id:r,targetId:o,animation:s,playback:n,animationPath:i}):null},Ii=({hasPrevious:e,hasCurrent:t,previousResourceId:n,currentResourceId:r,sharedTarget:o})=>!e&&t?"enter":e&&!t?"exit":e&&t?n===r&&o?"update":"replace":"none",Ai=({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.`)},wi=(e,{defaultTargetId:t,defaultId:n,animationPath:r="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return Wt({animationType:o.type,animationId:o.id??n,animationPath:r}),o.id??=n,o.targetId??=t,o},Yt=({animations:e,transitions:t,defaultTargetId:n,idPrefix:r,animationPathPrefix:o=r})=>{t.forEach((i,s)=>{e.push(wi(i,{defaultTargetId:n,defaultId:`${r}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},Fn=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let n=J(e,t);return n&&typeof n=="object"?e:n},zn=(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},Wn=(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))},Je=(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("-")}`},Vt=(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},xi=(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},Yn=(e={},t)=>{if(t){if(e.images?.[t])return"sprite";if(e.videos?.[t])return"video";if(e.layouts?.[t])return"container"}},Ze=({resourceId:e,kind:t})=>{if(e)return t?`bg-cg-background-${t}`:`bg-cg-${e}`},Ei=(e={})=>e.textStyles||{},vi=(e={})=>e.images||{},Si=(e={})=>e.colors||{},_i=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,Pe=(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`)},Hn=(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},tr=(e,t)=>{if(typeof e!="string"||!_i.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},qn=(e,t,n)=>{let r=tr(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})`},Ci=(e={},t)=>{let n=Ei(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=Hn(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:qn(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 l=Hn(n.strokeAlpha,"strokeAlpha",t);s.strokeColor=qn(a.hex,l,`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},Bt=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>Bt(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]=Bt(i,t,Pe(n,o)));return e.textStyleId!==void 0&&(ve(e.textStyleId,n,"textStyleId"),r.textStyle=Ci(t,e.textStyleId)),r},nr=(e={},t)=>{let n=Si(e)?.[t];if(!n)throw new Error(`Color "${t}" not found`);return tr(n.hex,`Color "${t}"`)},rr=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",Mt=(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 ${rr(`${t}.fill`)} instead`)},Li=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>Te(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]=Te(i,t,Pe(n,o)));return e.colorId!==void 0&&(ve(e.colorId,n,"colorId"),r.fill=nr(t,e.colorId)),r},Te=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>Te(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 ${rr("fill")} instead`);Mt(e,"hover",n),Mt(e,"click",n),Mt(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]=Li(i,t,Pe(n,o));continue}r[o]=Te(i,t,Pe(n,o))}return e.type==="rect"&&e.colorId!==void 0&&(ve(e.colorId,n,"colorId"),r.fill=nr(t,e.colorId)),r},jt=(e={},t)=>{let n=vi(e)?.[t];return n||null},or=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",Kn=(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 ${or(`${t}.${r}`)} instead`)},Gn=(e,t,n)=>{let r=e[t];e[t]={...r&&typeof r=="object"&&!Array.isArray(r)?r:{},src:n}},Ft=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>Ft(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 ${or(o)} instead`);Kn(e,"hover",n,"src"),Kn(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]=Ft(i,t,Pe(n,o)));if(e.type==="sprite"&&e.imageId!==void 0){ve(e.imageId,n,"imageId");let o=jt(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"),Gn(r,"hover",jt(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(ve(e.clickImageId,n,"clickImageId"),Gn(r,"click",jt(t,e.clickImageId)?.fileId??e.clickImageId)),r},Ht=(e,t={},n="root")=>Ft(Te(Bt(e,t,n),t,n),t,n),he=Ht,nt=(e=[])=>e.find(t=>t.id==="story");var Ri=(e={})=>e?.muteAll?0:e?.musicVolume??50,Q=({variables:e,runtime:t,saveSlots:n=[],dialogueState:r,includeInactiveAdvDialogue:o=!1,isLineCompleted:i,autoMode:s,skipMode:a,isChoiceVisible:l,canRollback:c,confirmDialog:u,historyDialogue:f=[],characters:d={},dialogueUIHidden:p,skipOnlyViewedLines:m,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=Pi({dialogueState:r,includeInactiveAdvDialogue:o,characters:d,variables:e}),g={variables:e,runtime:I,saveSlots:n,isChoiceVisible:l,canRollback:c,confirmDialog:u,historyDialogue:f,characters:d};return b&&(g.dialogue=b,g.dialogueLines=b.lines),g},Xn=100,tt=(e,t)=>{if(Array.isArray(e))return e.map(r=>tt(r,t));if(!e||typeof e!="object")return e;let n={...e};return Object.keys(n).forEach(r=>{n[r]=tt(n[r],t)}),n.type==="text-revealing"?t(n):n},$i=e=>tt(e,t=>({...t,revealEffect:"none"})),ki=e=>tt(e,t=>{let n=Number(t.speed??t.displaySpeed),r=Number.isFinite(n)?Math.max(n,Xn):Xn;return{...t,speed:r,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:r}:{}}}),me=(e,{isLineCompleted:t=!1,skipMode:n=!1,skipTransitionsAndAnimations:r=!1}={})=>t||r?$i(e):n?ki(e):e,ir=({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:{}}}}),zt=e=>{if(Array.isArray(e))return e.map(zt);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=zt(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}}:{}}}}},sr=(e=[],t={})=>e.map(n=>{let r=t?.[n.characterId],o=n.character?.name!==void 0?n.character.name:n.characterName!==void 0?n.characterName:r?.name||"",i=typeof n.text=="string"?n.text:Array.isArray(n.content)?n.content.map(s=>s?.text??"").join(""):"";return{...n,text:i,character:{...n.character||{},name:o},characterName:o}}),Oi=e=>!(!e||e.mode==="adv"&&e.content===void 0),Pi=({dialogueState:e,includeInactiveAdvDialogue:t=!1,characters:n={},variables:r}={})=>{if(!t&&!Oi(e))return;let o;e.characterId&&(o=n?.[e.characterId]),e.character&&(o={...o,name:e.character.name});let i=e.content===void 0?[{text:""}]:zn(e.content,"dialogue.content"),s=(e.lines||[]).map((a,l)=>{let c=zn(a.content,`dialogue.lines[${l}].content`),u=a.character?.name!==void 0?a.character.name:a.characterName!==void 0?a.characterName:a.characterId&&n?.[a.characterId]?.name||"";return{...a,content:c.map(f=>({...f,text:Fn(f.text,{variables:r})})),character:{...a.character||{},name:u},characterName:u}});return{characterId:e.characterId,persistCharacter:e.persistCharacter,character:{...e.character||{},name:o?.name||""},content:i.map(a=>({...a,text:Fn(a.text,{variables:r})})),lines:s}},ar=({container:e,resources:t,templateData:n,isLineCompleted:r=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=J(e,n,{functions:pe});return he(me(s,{isLineCompleted:r,skipMode:o,skipTransitionsAndAnimations:i}),t)},Ti=(e={})=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,{payload:{actions:structuredClone(n?.actions||{})}}]))},Se=({animationsDef:e,resources:t,previousResourceId:n,currentResourceId:r,previousTargetId:o,currentTargetId:i,animationPath:s,idPrefix:a,allowIncomingUpdateFallback:l=!1})=>{if(!e)return[];let c=[],u=({instanceId:v,targetId:L})=>{let R=bi({resources:t,animationId:y,playback:I,instanceId:v,targetId:L,animationPath:s});R&&c.push(R)},f=n!=null&&n!==!1,d=r!=null&&r!==!1,p=o&&i&&o===i,m=Ii({hasPrevious:f,hasCurrent:d,previousResourceId:n,currentResourceId:r,sharedTarget:p});yi(e,s);let y=pi(e),I=hi(e),b=t?.animations?.[y],g=di(b,{animationId:y,animationPath:s}),w=l&&g==="update"&&m!=="update"&&d&&i;if(w||Ai({animationType:g,animationId:y,animationPath:s,lifecycle:m}),g==="update")return f&&d&&n===r&&p?u({instanceId:`${a}-animation-update`,targetId:i}):w&&u({instanceId:`${a}-animation-update`,targetId:i}),c;if(g==="transition"){let v=`${a}-animation-transition`,L=I?.continuity==="persistent"?v:`${a}-animation-in`;if(f&&d&&p)return u({instanceId:v,targetId:i}),c;f&&u({instanceId:`${a}-animation-out`,targetId:o}),d&&u({instanceId:L,targetId:i})}return c},Di=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),Ni=(e,{presentationState:t,previousPresentationState:n,currentLineActions:r,resources:o={},screen:i={width:1920,height:1080},isLineCompleted:s,skipTransitionsAndAnimations:a,variables:l,runtime:c,activePersistentAnimations:u,restoredPersistentAnimations:f,autoMode:d,skipMode:p,isChoiceVisible:m,canRollback:y,saveSlots:I=[]})=>{let{elements:b,animations:g}=e;if(t.background){let w=r===void 0?!0:mi(r?.background??{},"animations"),v=b.find(k=>k.id==="story");if(!v)return e;let L=xi(o,t.background),R=n?.background?.resourceId,_=t.background.resourceId??(t.background.animations?R:void 0),D=Yn(o,R),O=Yn(o,_);if(_){let{images:k={},videos:A={}}=o,E=k[_]||A[_];if(E){let N=A[_]!==void 0,U={x:(i?.width??1920)/2,y:(i?.height??1080)/2,anchorX:.5,anchorY:.5,rotation:0,scaleX:1,scaleY:1,...L},B={id:Ze({resourceId:_,kind:N?"video":"sprite"}),type:N?"video":"sprite",x:U.x,y:U.y,src:E.fileId,width:E.width,height:E.height,alpha:1,anchorX:U.anchorX,anchorY:U.anchorY,rotation:U.rotation,scaleX:U.scaleX,scaleY:U.scaleY};N&&(B.loop=t.background.loop??!1,B.volume=E.volume??50),v.children.push(B)}}if(_){let{layouts:k={}}=o,A=k[_];if(A){let E={id:Ze({resourceId:_,kind:"container"}),type:"container",children:A.elements};L&&Object.assign(E,{x:0,y:0,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1,...L});let N=J(E,Q({variables:l,runtime:c,saveSlots:I,dialogueState:t.dialogue,isLineCompleted:s,autoMode:d,skipMode:p,isChoiceVisible:m,canRollback:y,characters:o.characters||{},skipTransitionsAndAnimations:a}),{functions:pe});v.children.push(he(me(N,{isLineCompleted:s,skipMode:p,skipTransitionsAndAnimations:a}),o))}}let $=Se({animationsDef:t.background.animations,resources:o,previousResourceId:R,currentResourceId:_,previousTargetId:Ze({resourceId:R,kind:D}),currentTargetId:Ze({resourceId:_,kind:O}),animationPath:"background.animations",idPrefix:"bg-cg",allowIncomingUpdateFallback:!0});de({animationInstances:$,isLineCompleted:s,skipTransitionsAndAnimations:a,activePersistentAnimations:u,restoredPersistentAnimations:f,isAuthoredOnCurrentLine:w})&&g.push(...$)}return e},Vi=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})=>{let{elements:a,animations:l}=e;if(t.character&&r){let c=a.find(m=>m.id==="story");if(!c)return e;let u=t.character.items||[],f=n?.character?.items||[],d=Wn(u),p=Wn(f);for(let m=0;m<u.length;m++){let y=u[m],{transformId:I,sprites:b}=y,g=f.find(k=>k.id===y.id),w=f.findIndex(k=>k.id===y.id),v=g?.sprites&&g.sprites.length>0,L=b&&b.length>0,R=w>=0?Je(g,w,p):void 0,_=Se({animationsDef:y.animations,resources:r,previousResourceId:R,currentResourceId:L?Je(y,m,d):void 0,previousTargetId:R,currentTargetId:L?Je(y,m,d):void 0,animationPath:`character.items[${m}].animations`,idPrefix:"character"});if(y.animations&&!b&&!I&&v&&de({animationInstances:_,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})){l.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=Je(y,m,d),O=r.transforms[I];if(!O){console.warn("Transform not found:",I);continue}let $={type:"container",id:D,x:y.x??O.x,y:y.y??O.y,anchorX:O.anchorX,anchorY:O.anchorY,rotation:O.rotation,scaleX:O.scaleX,scaleY:O.scaleY,children:[]};for(let k of b){let A=r.images[k.resourceId];if(!A){console.warn(`Image resource not found: ${k.resourceId}`);continue}$.children.push({type:"sprite",id:`${D}-${k.id}`,src:A.fileId,width:A.width,height:A.height,x:0,y:0})}c.children.push($),de({animationInstances:_,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:s})&&l.push(..._)}}return e},Mi=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,runtime:a,activePersistentAnimations:l,autoMode:c,skipMode:u,isChoiceVisible:f,canRollback:d,saveSlots:p=[]})=>{let{elements:m,animations:y}=e;if(t.visual&&r){let I=m.find(g=>g.id==="story");if(!I)return e;let b=t.visual.items;for(let g of b){if(g.resourceId){let{images:R={},videos:_={},spritesheets:D={}}=r,O=D[g.resourceId];if(O){let $=Vt(r,g),k=g.animationName;if(k){let A=O.animations?.[k];if(!A)throw new Error(`Animation '${k}' not found in spritesheet resource '${g.resourceId}'`);let E={id:`visual-${g.id}`,type:"animated-sprite",x:g.x??$.x,y:g.y??$.y,width:g.width??O.width,height:g.height??O.height,alpha:g.alpha??1,anchorX:$.anchorX,anchorY:$.anchorY,rotation:$.rotation,scaleX:$.scaleX,scaleY:$.scaleY,spritesheetSrc:O.fileId,spritesheetData:O.jsonData,animation:{frames:A.frames,animationSpeed:g.animationSpeed??A.animationSpeed??.5,loop:g.loop??A.loop??!0}};I.children.push(structuredClone(E))}}else{let $=R[g.resourceId]||_[g.resourceId];if($){let k=_[g.resourceId]!==void 0,A=Vt(r,g),E={id:`visual-${g.id}`,type:k?"video":"sprite",src:$.fileId,width:$.width,height:$.height,x:A.x,y:A.y,anchorX:A.anchorX,anchorY:A.anchorY,rotation:A.rotation,scaleX:A.scaleX,scaleY:A.scaleY};k&&(E.loop=$.loop??!1,E.volume=$.volume??50),I.children.push(E)}}}if(g.resourceId){let{layouts:R={}}=r,_=R[g.resourceId];if(_){let D=Vt(r,g),O={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},$=J(O,Q({variables:s,runtime:a,saveSlots:p,dialogueState:t.dialogue,isLineCompleted:o,autoMode:c,skipMode:u,isChoiceVisible:f,canRollback:d,characters:r.characters||{},skipTransitionsAndAnimations:i}),{functions:pe});I.children.push(he(me($,{isLineCompleted:o,skipMode:u,skipTransitionsAndAnimations:i}),r))}}let v=(n?.visual?.items||[]).find(R=>R.id===g.id),L=Se({animationsDef:g.animations,resources:r,previousResourceId:v?.resourceId,currentResourceId:g.resourceId,previousTargetId:v?.resourceId?`visual-${g.id}`:void 0,currentTargetId:g.resourceId?`visual-${g.id}`:void 0,animationPath:`visual.items[${g.id}].animations`,idPrefix:g.id});de({animationInstances:L,isLineCompleted:o,skipTransitionsAndAnimations:i,activePersistentAnimations:l})&&y.push(...L)}}return e},ji=(e,{presentationState:t,previousPresentationState:n,resources:r={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:l,skipOnlyViewedLines:c,isLineCompleted:u,skipTransitionsAndAnimations:f,variables:d,runtime:p,activePersistentAnimations:m,saveSlots:y=[]})=>{let{elements:I,animations:b}=e;if(!t.dialogue||o)return e;let g=I.find(v=>v.id==="story");if(!g)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:v={}}=r,L=v[t.dialogue.ui.resourceId];if(L){let R={elements:L.elements},_=Q({variables:d,runtime:p,saveSlots:y,dialogueState:t.dialogue,includeInactiveAdvDialogue:!0,isLineCompleted:u,autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:l,characters:r.characters||{},dialogueUIHidden:o,skipOnlyViewedLines:c,skipTransitionsAndAnimations:f}),D={functions:pe},O=Qe(R,_,D),$=J(O,_,D),k=he(me($?.elements,{isLineCompleted:u,skipMode:s,skipTransitionsAndAnimations:f}),r);if(Array.isArray(k))for(let A of k)g.children.push(A);else k&&g.children.push(k)}}let w=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 de({animationInstances:w,isLineCompleted:u,skipTransitionsAndAnimations:f,activePersistentAnimations:m})&&b.push(...w),e},Ui=(e,{presentationState:t,previousPresentationState:n,resources:r,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:a,runtime:l,autoMode:c,skipMode:u,isChoiceVisible:f,canRollback:d,activePersistentAnimations:p,saveSlots:m=[]})=>{let{elements:y,animations:I}=e;if(t.choice&&r){let b=nt(y);if(!b)return e;let g=r?.layouts[t.choice.resourceId];if(g&&g.elements){let v={elements:g.elements},L=J(v,{...Q({variables:a,runtime:l,saveSlots:m,dialogueState:t.dialogue,isLineCompleted:i,autoMode:c,skipMode:u,isChoiceVisible:f??!!t.choice,canRollback:d,characters:r.characters||{},skipTransitionsAndAnimations:s}),choice:{items:t.choice?.items??[]}},{functions:pe}),R=zt(he(me(L?.elements,{isLineCompleted:i,skipMode:u,skipTransitionsAndAnimations:s}),r));if(Array.isArray(R))for(let _ of R)b.children.push(_);else R&&b.children.push(R)}let w=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"});de({animationInstances:w,isLineCompleted:i,skipTransitionsAndAnimations:s,activePersistentAnimations:p})&&I.push(...w)}return e},Bi=(e,{presentationState:t,resources:n={},variables:r,runtime:o,isLineCompleted:i,autoMode:s,skipMode:a,isChoiceVisible:l,canRollback:c,saveSlots:u=[],skipTransitionsAndAnimations:f})=>{if(!t.control?.resourceId)return e;let d=n.controls?.[t.control.resourceId];if(!d)return e;let p=Ti(d.keyboard);if(p&&Object.keys(p).length>0&&(e.global.keyboard=p),!Array.isArray(d.elements)||d.elements.length===0)return e;let m=nt(e.elements);if(!m)return e;let y={id:`control-${t.control.resourceId}`,type:"container",x:0,y:0,children:d.elements};return m.children.push(ar({container:y,resources:n,templateData:Q({variables:r,runtime:o,saveSlots:u,dialogueState:t.dialogue,isLineCompleted:i,autoMode:s,skipMode:a,isChoiceVisible:l,canRollback:c,characters:n.characters||{},skipTransitionsAndAnimations:f}),isLineCompleted:i,skipMode:a,skipTransitionsAndAnimations:f})),e},Fi=(e,{presentationState:t,resources:n,runtime:r,variables:o})=>{let{elements:i,audio:s}=e;if(t.bgm&&n){if(!nt(i))return e;let l=n.sounds[t.bgm.resourceId];if(!l)return e;let c=Q({variables:o,runtime:r}).runtime;s.push({id:"bgm",type:"sound",src:l.fileId,loop:t.bgm.loop??!0,volume:Ri(c),delay:t.bgm.delay??null})}return e},zi=(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,delay:i.delay??s.delay??null})}}return e},Wi=(e,t,n)=>{if(!(!t||!n))return e?.voices?.[t]?.[n]},Yi=(e={},t={})=>t.muteAll?0:e.volume??t.soundVolume??50,Hi=(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:l,loop:c,delay:u}=a,f=Wi(n,r,l);if(!f)return e;let d=Q({variables:i,runtime:o}).runtime;return s.push({id:`voice-${r}-${l}`,type:"sound",src:f.fileId,volume:Yi(a,d),loop:c??!1,delay:u??null}),e},qi=(e,{presentationState:t,previousPresentationState:n,resources:r={},variables:o,runtime:i,autoMode:s,skipMode:a,isChoiceVisible:l,canRollback:c,saveSlots:u=[],isLineCompleted:f,skipTransitionsAndAnimations:d,activePersistentAnimations:p})=>{let{elements:m,animations:y}=e;if(t.layout){let w=nt(m);if(!w)return e;let v=r.layouts[t.layout.resourceId];if(!v)return e;Array.isArray(v.transitions)&&!f&&!d&&Yt({animations:y,transitions:v.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let L={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:v.elements||[]};w.children.push(ar({container:L,resources:r,templateData:Q({variables:o,runtime:i,saveSlots:u,dialogueState:t.dialogue,isLineCompleted:f,autoMode:s,skipMode:a,isChoiceVisible:l,canRollback:c,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 de({animationInstances:g,isLineCompleted:f,skipTransitionsAndAnimations:d,activePersistentAnimations:p})&&y.push(...g),e},Ki=(e,{presentationState:t,resources:n={},variables:r,runtime:o,autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:l,overlayStack:c=[],dialogueHistory:u=[],saveSlots:f=[],screen:d,isLineCompleted:p,skipTransitionsAndAnimations:m})=>{let{elements:y,animations:I}=e;return c&&c.length>0&&c.forEach((b,g)=>{let w=n.layouts[b.resourceId];if(!w){console.warn(`Overlay layout not found: ${b.resourceId}`);return}Array.isArray(w.transitions)&&(m||Yt({animations:I,transitions:w.transitions,defaultTargetId:`overlayStack-${g}`,idPrefix:`overlayStack-${g}`,animationPathPrefix:`overlayStack[${g}]`}));let v={id:`overlayStack-${g}`,type:"container",x:0,y:0,children:[ir({id:`overlayStack-${g}-blocker`,screen:d}),...w.elements||[]]},L=sr(u,n.characters),R=Q({variables:r,runtime:o,saveSlots:f,dialogueState:t?.dialogue,isLineCompleted:p,autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:l,historyDialogue:L,characters:n.characters||{},skipTransitionsAndAnimations:m}),_=J(v,R,{functions:pe}),[D,...O]=_.children||[],$=he(me({..._,children:O},{isLineCompleted:p,skipMode:s,skipTransitionsAndAnimations:m}),n);y.push({...$,children:D?[D,...$.children||[]]:$.children})}),e},Gi=(e,{presentationState:t,resources:n={},variables:r,runtime:o,saveSlots:i=[],autoMode:s,skipMode:a,isChoiceVisible:l,canRollback:c,confirmDialog:u,dialogueHistory:f=[],screen:d,isLineCompleted:p,skipTransitionsAndAnimations:m})=>{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)&&!m&&Yt({animations:I,transitions:b.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let g={id:"confirmDialog",type:"container",x:0,y:0,children:[ir({id:"confirmDialog-blocker",screen:d}),...b.elements||[]]},w=sr(f,n.characters),v=J(g,Q({variables:r,runtime:o,saveSlots:i,dialogueState:t?.dialogue,isLineCompleted:p,autoMode:s,skipMode:a,isChoiceVisible:l,canRollback:c,confirmDialog:u,historyDialogue:w,characters:n.characters||{},skipTransitionsAndAnimations:m}),{functions:pe}),[L,...R]=v.children||[],_=he(me({...v,children:R},{isLineCompleted:p,skipMode:a,skipTransitionsAndAnimations:m}),n);return y.push({..._,children:L?[L,..._.children||[]]:_.children}),e},cr=e=>Ge(Di,[Bi,Ni,Vi,Mi,ji,Ui,qi,Fi,zi,Hi,Ki,Gi])(e);var Xi=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"}}),rt=Object.freeze({dialogueTextSpeed:50,autoForwardDelay:1e3,skipUnseenText:!1,skipTransitionsAndAnimations:!1,soundVolume:50,musicVolume:50,muteAll:!1,autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isLineCompleted:!1}),De=Object.freeze({saveLoadPagination:1,menuPage:"",menuEntryPoint:""}),lr=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"}),qt=Object.freeze(["dialogueTextSpeed","autoForwardDelay","skipUnseenText","skipTransitionsAndAnimations","soundVolume","musicVolume","muteAll"]),Kt=Object.freeze(["saveLoadPagination","menuPage","menuEntryPoint"]),Ji=(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]}},Gt=e=>Object.fromEntries(Object.entries(Xi).map(([t,n])=>{let r=Ji(e,n.source),o=r!==void 0?r:rt[t]??De[t];return[t,o]})),ne=(e,t)=>Gt(e)[t],ur=(e={})=>Object.fromEntries(qt.map(t=>[t,e[t]??rt[t]]));var ot={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},mr=1,st=()=>({manual:{...ot.manual},auto:{...ot.auto},applyMode:ot.applyMode}),Xt=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let n=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...st()},n&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},j=e=>{let t=ie(e)?xt(e):e;return structuredClone(t)},V=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),at=e=>String(e),gr=()=>({sections:[],resources:[]}),Zi=e=>V(e)?(Array.isArray(e.sections)||(e.sections=[]),Array.isArray(e.resources)||(e.resources=[]),e):gr(),Qi=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",es=()=>({resourceId:void 0}),ts=e=>{if(!V(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},Jt=(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}},yr=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)}}},br=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},Ir=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==mr)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},ns=(e,t={})=>{let n;try{n=Ir(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let r={...t,formatVersion:n,slotId:br(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete r.slotKey,delete r.date,r},rs=(e={})=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,ns(t,n)])),Ar=e=>{if(!Array.isArray(e))return;let t=e.filter(({type:n})=>Ra(n));return t.length>0?t:void 0},os=e=>{!V(e)||!Array.isArray(e.timeline)||e.timeline.forEach(t=>{if(!V(t))return;let n=Ar(t.executedActions);if(n){t.executedActions=n;return}delete t.executedActions})},fr=(e,t,n,r="viewedRegistry")=>{let o=t==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[o]:String(e)};if(!V(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}},is=(e,t="viewedRegistry")=>{if(e===void 0)return gr();if(!V(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=fr(o,"sections",i,t);return[s.sectionId,s]}))),resources:Object.values(Object.fromEntries(r.map((o,i)=>{let s=fr(o,"resources",i,t);return[s.resourceId,s]})))}},wr=(e,t,n)=>{if(!V(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}=Jt(t,r);if(!s)throw new Error(`Malformed save slot ${n}: section "${r}" does not exist in projectData.`);if(!s.lines?.some(l=>l.id===o))throw new Error(`Malformed save slot ${n}: line "${o}" does not exist in section "${r}".`);return{sceneId:i,sectionId:r,lineId:o}},ss=(e,t,n)=>{if(!V(e)||!Array.isArray(e.timeline))return Ne({pointer:t,replayStartIndex:1});let r=e.timeline.flatMap((a,l)=>{if(!V(a))return[];try{let c=wr(a,n,`rollback.timeline[${l}]`),u=it({sectionId:c.sectionId,lineId:c.lineId,rollbackPolicy:a.rollbackPolicy}),f=Ar(j(a.executedActions));return f&&(u.executedActions=f),[u]}catch{return[]}});if(r.length===0)return Ne({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(l=>l.sectionId===t.sectionId&&l.lineId===t.lineId);a>=0?o=a:(r.push(it({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}},as=(e,t,n)=>{if(!V(e))throw new Error(`Malformed save slot contexts[${n}] entry.`);let r=Qt(t),o=wr(e.pointers?.read,t,`contexts[${n}].pointers.read`);if(e.variables!==void 0&&!V(e.variables))throw new Error(`Malformed save slot contexts[${n}].variables entry.`);if(e.runtime!==void 0&&!V(e.runtime))throw new Error(`Malformed save slot contexts[${n}].runtime entry.`);let i=e.variables?j(e.variables):{},s=ds({loadedContextRuntime:V(e.runtime)?j(e.runtime):{}}),a={currentPointerMode:"read",pointers:{read:o},configuration:V(e.configuration)?j(e.configuration):{},views:Array.isArray(e.views)?j(e.views):[],bgm:V(e.bgm)?j(e.bgm):{resourceId:void 0},variables:{...r,...i},rollback:ss(e.rollback,o,t)};return s&&(a.runtime=s),a},cs=(e,t)=>{if(!V(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)=>as(n,t,r))}},ls=(e,t)=>{if(!V(e))throw new Error("Malformed save slot.");let n=Ir(e.formatVersion);return{...e,formatVersion:n,state:cs(e.state,t)}},dr=(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=j(e);return Object.prototype.hasOwnProperty.call(r,"hideConfirmDialog")||(r.hideConfirmDialog={}),r},us=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:dr(e.confirmActions,"confirmActions",{required:!0}),cancelActions:dr(e.cancelActions,"cancelActions")}},_e=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},ge=[],pr="line",Zt="interaction",it=({sectionId:e,lineId:t,rollbackPolicy:n})=>({sectionId:e,lineId:t,rollbackPolicy:n??"free"}),Qt=e=>{let{contextVariableDefaultValues:t}=$t(e??{});return j(t)},xr=()=>({...j(De)}),Er=({loadedRuntime:e,runtimeIds:t,defaults:n={},path:r})=>{if(e===void 0)return{runtimeState:j(n),hasLoadedValues:!1};if(!V(e))throw new Error(`Malformed ${r}.`);let o=j(n),i=!1;return t.forEach(s=>{e[s]!==void 0&&(o[s]=Sr(s,j(e[s])),i=!0)}),{runtimeState:o,hasLoadedValues:i}},fs=({loadedGlobalRuntime:e={}})=>Er({loadedRuntime:e,runtimeIds:qt,defaults:rt,path:"global.runtime"}).runtimeState,ds=({loadedContextRuntime:e={}})=>{let{runtimeState:t,hasLoadedValues:n}=Er({loadedRuntime:e,runtimeIds:Kt,defaults:xr(),path:"context.runtime"});return n?t:void 0},vr=e=>{let t=Array.isArray(e?.contexts)?e.contexts:[];return t[t.length-1]},ps=e=>e.runtime?(Kt.forEach(t=>{e.runtime[t]===void 0&&(e.runtime[t]=j(De[t]))}),e.runtime):(e.runtime=xr(),e.runtime),hs=e=>ur(e.global),ms=e=>{e.global.pendingEffects.push({name:"saveGlobalRuntime",payload:{globalRuntime:hs(e)}})},gs=e=>lr[e],ys=(e,t)=>{let n=gs(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}"`)},Sr=(e,t)=>(ys(e,t),e==="saveLoadPagination"?Math.max(1,Math.trunc(t)):t),_r=(e,t,n)=>{let r=Sr(t,n);if(t in De){let o=vr(e);if(!o)return r;let i=ps(o);return i[t]=r,r}return e.global[t]=r,r},Cr=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:j(e)},configuration:{},views:[],bgm:es(),variables:Qt(t),rollback:Ne({pointer:e})}),Ce=e=>e?(e.currentPointerMode="read",V(e.pointers)||(e.pointers={}),Object.prototype.hasOwnProperty.call(e.pointers,"history")&&delete e.pointers.history,e.pointers):null,bs=e=>{let t=e.contexts?.[e.contexts.length-1],n=t?.pointers?.read;if(!t||!n?.sectionId||!n?.lineId)return null;let r=Cr({pointer:n,projectData:e.projectData});return e.contexts[e.contexts.length-1]=r,Is(e),r},Is=e=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,_e(e),e.global.nextLineConfig=st(),e.global.overlayStack=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})},Lr=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},Ne=({pointer:e,replayStartIndex:t=0})=>{let n=e?.sectionId&&e?.lineId;return{currentIndex:n?0:-1,isRestoring:!1,replayStartIndex:t,timeline:n?[it({sectionId:e.sectionId,lineId:e.lineId})]:[]}},be=(e,t={})=>{if(e?.rollback)return Lr(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=Ne({pointer:n,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},en=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return;let r=be(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(it(t)),r.currentIndex=r.timeline.length-1},As=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=ge[ge.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)},ws=({state:e},t={})=>{let n=t?.source===pr?pr:Zt,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?(ge.push({checkpointIndex:null,source:n}),e):(o.currentIndex<o.timeline.length-1&&(o.timeline=o.timeline.slice(0,o.currentIndex+1)),ge.push({checkpointIndex:o.currentIndex,source:n}),e)},xs=({state:e})=>(ge.pop(),e),re=(e,t,n)=>{let o=ge[ge.length-1]?.source??Zt;if(!$a(t,o))return;let i=As(e);i&&(Array.isArray(i.executedActions)||(i.executedActions=[]),i.executedActions.push({type:t,payload:j(n)}))},hr=(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],l=a?.scope,c=a?.type;kt(l,o),Ot(c,i,o),l==="context"&&(n.variables[o]=Pt(n.variables[o],i,s))}},Es=(e,t)=>{Array.isArray(t?.executedActions)&&t.executedActions.forEach(({type:n,payload:r})=>{ka(e,n,r)})},vs=(e,t)=>{let{sectionId:n,lineId:r}=t,s=H({state:e},{sectionId:n})?.lines?.find(a=>a.id===r)?.actions;s&&Object.entries(s).forEach(([a,l])=>{Oa(e,a,l)})},Rr=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return e;let r=be(n),o=r.timeline[t];if(!o)return e;e.global.autoMode&&Me({state:e}),e.global.skipMode&&ye({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),r.isRestoring=!0,r.currentIndex=t;try{n.variables=Qt(e.projectData),delete n.runtime,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=j(ot),e.global.overlayStack=[],_e(e),e.global.isLineCompleted=!0;let i=r.replayStartIndex??0;for(let a=i;a<=t;a++)a>i&&Xt(e),vs(e,r.timeline[a]),Es(e,r.timeline[a]);let s=Ce(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},Ss=e=>{let{projectData:t}=e,n=e.global??{},{saveSlots:r={},variables:o={},runtime:i={},accountViewedRegistry:s={}}=n;yr(t);let a=t.story.initialSceneId,l=t.story.scenes[a],c=l.initialSectionId,u=l.sections[c],f={sceneId:a,sectionId:c,lineId:u.initialLineId??u.lines[0].id},{globalVariablesDefaultValues:d}=$t(t),p={...d,...o};return{projectData:t,global:{pendingEffects:[],confirmDialog:null,accountViewedRegistry:is(s,"accountViewedRegistry"),nextLineConfig:st(),saveSlots:rs(r),overlayStack:[],variables:p,...fs({loadedGlobalRuntime:i})},contexts:[Cr({pointer:f,projectData:t})]}},_s=({state:e})=>e.global.overlayStack||[],Cs=({state:e})=>e.global.pendingEffects,$r=({state:e})=>e.global.skipMode,Ls=({state:e})=>e.global.autoMode,kr=({state:e})=>e.global.dialogueUIHidden,Or=({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=H({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),l=[],c={};for(let u of a){let f=u.actions||{};if(c=Ee([c,f]),!f.dialogue)continue;let d=c.dialogue||{},p="";d.character?.name!==void 0?p=d.character.name:d.characterId&&(p=e.projectData.resources?.characters?.[d.characterId]?.name||""),l.push({sectionId:r,lineId:u.id,content:f.dialogue.content,text:Qi(f.dialogue.content),characterId:d.characterId,character:{name:p},characterName:p})}return l},Rs=({state:e})=>e.global.confirmDialog??null,$s=({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=H({state:e},{sectionId:r});if(!a||!a.lines||!Array.isArray(a.lines))return s.lastLineId===o;let l=a.lines.findIndex(u=>u.id===s.lastLineId),c=a.lines.findIndex(u=>u.id===o);return l===-1||c===-1?s.lastLineId===o:c<=l},ks=({registry:e},t)=>{let{resourceId:n}=t;return!!(Array.isArray(e?.resources)?e.resources:[]).find(i=>i.resourceId===n)},tn=({state:e},t)=>$s({state:e,registry:e.global.accountViewedRegistry},t),Os=({state:e},t)=>ks({registry:e.global.accountViewedRegistry},t),Ps=({state:e})=>e.global.nextLineConfig,Pr=({state:e,pointer:t}={})=>{let n=t??ee({state:e})?.pointer;if(!n)return;let r=n?.sectionId,o=n?.lineId,s=H({state:e},{sectionId:r})?.lines||[],a=s.findIndex(c=>c.id===o);if(a<0)return;let l;for(let c of s.slice(0,a+1)){let u=c?.actions;if(u?.cleanAll&&(l=void 0),!u||!Object.prototype.hasOwnProperty.call(u,"choice")){l=void 0;continue}let f=u.choice;if(f?.resourceId){l=f.resourceId;continue}f?.animations||(l=void 0)}return l},te=({state:e})=>!!Pr({state:e}),Ts=({state:e})=>structuredClone(e),Tr=({state:e})=>e.global.saveSlots,Ds=({state:e},t)=>{let n=t?.slotId,r=at(n);return e.global.saveSlots[r]},nn=({state:e})=>Gt(e),Ns=({state:e},t)=>ne(e,t?.runtimeId),Dr=({state:e})=>({...e.global?.variables??{},...vr(e)?.variables??{}}),ee=({state:e})=>{let t=Array.isArray(e.contexts)?e.contexts:[],n=t[t.length-1];if(n)return{currentPointerMode:"read",pointer:n.pointers?.read}},H=({state:e},t)=>{let{sectionId:n}=t;return Jt(e.projectData,n).section},rn=({state:e})=>{let t=ee({state:e});if(!t?.pointer)return;let{sectionId:n,lineId:r}=t.pointer,o=H({state:e},{sectionId:n});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===r)},Nr=({state:e})=>{let{sectionId:t,lineId:n}=ee({state:e}).pointer,o=H({state:e},{sectionId:t})?.lines||[],i=o.findIndex(c=>c.id===n),a=o.slice(0,i+1).map(c=>{let u=c.actions||{},f={};return Object.keys(u).forEach(d=>{f[d]=u[d]}),f});return Ee(a)},Vs=({state:e})=>{let t=Vr({state:e}),r=rn({state:e})?.actions??{},o=Ee([t??{},r]);return Tt(t??{},o??{})},Ms=({state:e},{sectionId:t})=>{let n=H({state:e},{sectionId:t});if(!n?.lines)return[];let r=[],o={};for(let i of n.lines){let s=i.actions||{},a=Ee([o,s]),l=Tt(o,a);r.push({id:i.id,changes:l,presentationState:a}),o=Dt(a)}return r},js=({state:e},{sectionId:t,includePresentationState:n=!1})=>{let r=Ms({state:e},{sectionId:t});return n?{lines:r}:{lines:r.map(({presentationState:o,...i})=>i)}},Vr=({state:e})=>{let{sectionId:t,lineId:n}=ee({state:e}).pointer,o=H({state:e},{sectionId:t})?.lines||[],i=o.findIndex(l=>l.id===n);if(i<=0)return null;let a=o.slice(0,i).map(l=>{let c=l.actions||{},u={};return Object.keys(c).forEach(f=>{u[f]=c[f]}),u});return Dt(Ee(a))},on=({state:e},{slotsPerPage:t=6}={})=>{let o=((nn({state:e}).saveLoadPagination??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let a=o+s,l=e.global.saveSlots&&e.global.saveSlots[at(a)]||{};i.push({...l,slotId:a})}return{saveSlots:i}},Us=Tr,Bs=on,Fs=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},zs=({state:e},t={})=>{let n=Nr({state:e}),r=Vr({state:e}),o=rn({state:e})?.actions??{},{sectionId:i}=ee({state:e}).pointer,{sceneId:s}=Jt(e.projectData,i),a=nn({state:e}),l=t?.activePersistentAnimations??[],c=t?.restoredPersistentAnimations??[],u=Dr({state:e}),{saveSlots:f}=on({state:e}),d=Fs(e);return cr({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:te({state:e}),canRollback:qr({state:e}),skipOnlyViewedLines:!a.skipUnseenText,isLineCompleted:a.isLineCompleted,skipTransitionsAndAnimations:!!a.skipTransitionsAndAnimations||d,overlayStack:e.global.overlayStack,confirmDialog:e.global.confirmDialog,dialogueHistory:Or({state:e}),saveSlots:f,variables:u,runtime:a,activePersistentAnimations:l,restoredPersistentAnimations:c})},Ws=({state:e},t)=>(e.global.confirmDialog=us(t),e.global.pendingEffects.push({name:"render"}),e),Ys=({state:e})=>(e.global.confirmDialog&&(_e(e),e.global.pendingEffects.push({name:"render"})),e),Hs=({state:e},t)=>(e.global.overlayStack.push(t),e.global.pendingEffects.push({name:"render"}),re(e,"pushOverlay",t),e),qs=({state:e})=>(e.global.overlayStack.pop(),e.global.pendingEffects.push({name:"render"}),re(e,"popOverlay",void 0),e),Ks=({state:e},t)=>(e.global.overlayStack.length>0&&(e.global.overlayStack[e.global.overlayStack.length-1]=t),e.global.pendingEffects.push({name:"render"}),re(e,"replaceLastOverlay",t),e),Gs=({state:e})=>(e.global.overlayStack=[],_e(e),e.global.pendingEffects.push({name:"render"}),re(e,"clearOverlays",void 0),e),Xs=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"})},ct=(e,t)=>{e.global.isLineCompleted=!1;let n=!!Pr({state:e,pointer:t});return n&&Xs(e),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:n}},Mr=({state:e})=>(te({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:ne(e,"autoForwardDelay")}}),e.global.pendingEffects.push({name:"render"})),e),Me=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Js=({state:e})=>{let t=e.global.autoMode;return te({state:e})&&!t||(t?Me({state:e}):Mr({state:e})),e},jr=({state:e})=>(te({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),ye=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Zs=({state:e})=>{let t=$r({state:e});return te({state:e})&&!t||(t?ye({state:e}):jr({state:e})),e},lt=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),re(e,"showDialogueUI",void 0),e),Ur=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),re(e,"hideDialogueUI",void 0),e),Qs=({state:e})=>(kr({state:e})?lt({state:e}):Ur({state:e}),e),Ie=(e,t,n)=>(_r(e,t,n),ms(e),e.global.pendingEffects.push({name:"render"}),e),je=(e,t,n,r)=>{let o=_r(e,t,n);return e.global.pendingEffects.push({name:"render"}),re(e,r,{value:o}),e},ea=({state:e},t)=>Ie(e,"dialogueTextSpeed",t?.value),ta=({state:e},t)=>Ie(e,"autoForwardDelay",t?.value),na=({state:e},t)=>Ie(e,"skipUnseenText",t?.value),ra=({state:e},t)=>Ie(e,"skipTransitionsAndAnimations",t?.value),oa=({state:e},t)=>Ie(e,"soundVolume",t?.value),ia=({state:e},t)=>Ie(e,"musicVolume",t?.value),sa=({state:e},t)=>Ie(e,"muteAll",t?.value),aa=({state:e},t)=>je(e,"saveLoadPagination",t?.value,"setSaveLoadPagination"),ca=({state:e})=>{let t=ne(e,"saveLoadPagination")+1;return je(e,"saveLoadPagination",t,"incrementSaveLoadPagination"),e},la=({state:e})=>{let t=ne(e,"saveLoadPagination")-1;return je(e,"saveLoadPagination",t,"decrementSaveLoadPagination"),e},ua=({state:e},t)=>je(e,"menuPage",t?.value,"setMenuPage"),fa=({state:e},t)=>je(e,"menuEntryPoint",t?.value,"setMenuEntryPoint"),da=({state:e})=>(e.global.pendingEffects=[],e),pa=({state:e},t)=>(e.global.pendingEffects.push(t),e),Br=(e,{sectionId:t,resetStoryState:n=!1})=>{let r=H({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&&!bs(e))return e;e.global.autoMode&&Me({state:e}),e.global.skipMode&&ye({state:e});let i=e.contexts?.[e.contexts.length-1];if(i){let s=Ce(i);i.rollback||be(i,{compatibilityAnchor:!0}),s.read={sectionId:t,lineId:o.id},n?i.rollback=Ne({pointer:s.read}):en(e,{sectionId:t,lineId:o.id})}return ct(e,i?.pointers?.read),e},ha=({state:e},t)=>Br(e,{sectionId:t?.sectionId,resetStoryState:!0}),Fr=e=>(e.global.accountViewedRegistry=Zi(e.global.accountViewedRegistry),e.global.accountViewedRegistry),zr=(e,t)=>{!Array.isArray(t)||t.length===0||e.global.pendingEffects.push({name:"applyScopedDataUpdates",payload:{updates:t.map(n=>({scope:n.scope,path:n.path,op:n.op,value:j(n.value)}))}})},Wr=(e,t)=>{zr(e,[{scope:"account",path:"viewedRegistry",op:"markViewed",value:{sections:(Array.isArray(t?.sections)?t.sections:[]).map(n=>({sectionId:n.sectionId,...n.lastLineId===void 0?{}:{lineId:n.lastLineId}})),resources:Array.isArray(t?.resources)?t.resources:[]}}])},ma=(e,t,{sectionId:n,lineId:r})=>{if(!n||!r)return!1;let o=V(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=H({state:e},{sectionId:n});if(s?.lines){let a=s.lines.findIndex(c=>c.id===i.lastLineId),l=s.lines.findIndex(c=>c.id===r);if(a===-1||l>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},Ve=(e,t)=>{if(e.global.accountViewedRegistry===void 0)return;ma(e,Fr(e),t)&&Wr(e,{sections:[{sectionId:t.sectionId,lastLineId:t.lineId}],resources:[]})},ga=({state:e},t)=>(Ve(e,t),e.global.pendingEffects.push({name:"render"}),e),ya=({state:e},t)=>{let{resourceId:n}=t;if(e.global.accountViewedRegistry!==void 0){let r=Fr(e);r.resources.find(i=>i.resourceId===n)||(r.resources.push({resourceId:n}),Wr(e,{sections:[],resources:[{resourceId:n}]}))}return e.global.pendingEffects.push({name:"render"}),e},Yr=({state:e},t)=>{let n=ts(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 l=e.global.nextLineConfig.auto?.enabled,c=te({state:e});return!a&&!c&&l===!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&&l===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),re(e,"setNextLineConfig",t),e},ba=({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=at(n),s=j(e.contexts);s?.forEach(c=>{Ce(c),Lr(c.rollback),os(c.rollback)});let a={contexts:s},l={formatVersion:mr,slotId:br(n),savedAt:typeof o=="number"?o:Date.now(),image:r,state:a};return e.global.saveSlots[i]=l,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},Ia=({state:e},t)=>{let n=t?.slotId;if(n==null||n==="")throw new Error("loadSlot requires slotId");let r=at(n),o=e.global.saveSlots[r];if(o){let i=ls(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=st(),e.global.overlayStack=[],e.global.isLineCompleted=!0,_e(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},Aa=({state:e},t)=>{let{projectData:n}=t;return yr(n),e.projectData=n,_e(e),e.global.pendingEffects.push({name:"render"}),e},wa=({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&&!H({state:e},{sectionId:n}))return console.warn(`Section not found: ${n}`),e;let s=H({state:e},{sectionId:i});if(!s?.lines||!Array.isArray(s.lines))return console.warn(`Section ${i} has no lines`),e;if(!s.lines.find(c=>c.id===r))return console.warn(`Line not found: ${r} in section ${i}`),e;let l=Ce(o);return l.read={sectionId:i,lineId:r},ct(e,l.read),e},xa=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return lt({state:e}),e;if(te({state:e})&&t?._interactionSource!=="choice")return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0;let c=ee({state:e})?.pointer,u=c?.sectionId,f=c?.lineId;u&&f&&Ve(e,{sectionId:u,lineId:f}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:ne(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=ee({state:e})?.pointer,r=n?.sectionId,o=H({state:e},{sectionId:r}),i=e.contexts[e.contexts.length-1],s=o?.lines||[],l=s.findIndex(c=>c.id===n?.lineId)+1;if(l<s.length){let c=s[l],u=!ne(e,"skipUnseenText");if(e.global.skipMode&&u&&!tn({state:e},{sectionId:r,lineId:c.id}))return ye({state:e}),e;if(i&&!i.rollback&&be(i,{compatibilityAnchor:!0}),i){let p=Ce(i),m=p.read?.lineId;m&&r&&Ve(e,{sectionId:r,lineId:m}),p.read={sectionId:r,lineId:c.id}}en(e,{sectionId:r,lineId:c.id}),Xt(e);let{isChoiceVisible:f}=ct(e,{sectionId:r,lineId:c.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&&Me({state:e}),e.global.skipMode&&ye({state:e});return e},Ea=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0;let t=te({state:e});e.global.autoMode&&!t&&e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:ne(e,"autoForwardDelay")}});let n=ee({state:e})?.pointer,r=n?.sectionId,o=n?.lineId;r&&o&&Ve(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},va=({state:e},t)=>Br(e,{sectionId:t?.sectionId}),Sa=({state:e})=>{if(e.global.dialogueUIHidden)return lt({state:e}),e;if(te({state:e}))return e;let t=ee({state:e})?.pointer,n=t?.sectionId,r=H({state:e},{sectionId:n}),o=e.contexts[e.contexts.length-1],i=r?.lines||[],a=i.findIndex(l=>l.id===t?.lineId)+1;if(a<i.length){let l=i[a],c=!ne(e,"skipUnseenText");if(e.global.skipMode&&c&&!tn({state:e},{sectionId:n,lineId:l.id}))return ye({state:e}),e;if(o&&!o.rollback&&be(o,{compatibilityAnchor:!0}),o){let f=Ce(o),d=f.read?.lineId;d&&n&&Ve(e,{sectionId:n,lineId:d}),f.read={sectionId:n,lineId:l.id}}en(e,{sectionId:n,lineId:l.id}),Xt(e);let{isChoiceVisible:u}=ct(e,{sectionId:n,lineId:l.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},_a=({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:l,op:c,value:u})=>{let f=e.projectData.resources?.variables?.[l],d=f?.scope,p=f?.type;kt(d,l),Ot(p,c,l);let m=d==="context"?o.variables:e.global.variables;d==="context"&&(i=!0,a.push({variableId:l,op:c,value:u})),m[l]=Pt(m[l],c,u),(d==="device"||d==="account")&&s.push({scope:d,path:`variables.${l}`,op:"set",value:j(m[l])})}),i&&re(e,"updateVariable",{id:n,operations:a}),zr(e,s),e.global.pendingEffects.push({name:"render"}),e},Ca=e=>(t,n)=>e({state:t},n),La={updateVariable:{recordSources:[Zt],replayLine:hr,replayRecorded:hr,persistInSaveSlot:!0},setNextLineConfig:{replayLine:Ca(Yr)}},ut=e=>La[e]??null,Ra=e=>ut(e)?.persistInSaveSlot===!0,$a=(e,t)=>{let n=ut(e)?.recordSources;return Array.isArray(n)&&n.includes(t)},ka=(e,t,n)=>{ut(t)?.replayRecorded?.(e,n)},Oa=(e,t,n)=>{ut(t)?.replayLine?.(e,n)},Hr=({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}},qr=({state:e})=>Hr({state:e},{offset:-1})!==null,Pa=({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=be(r,{compatibilityAnchor:!r.rollback}),i=o.currentIndex+n;return i<0||i>=o.timeline.length?e:Rr(e,i)},Ta=({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=be(o,{compatibilityAnchor:!o.rollback}),a=i.timeline.slice(0,i.currentIndex+1).findLastIndex(l=>l.sectionId===n&&l.lineId===r);if(a===-1)throw new Error(`Line ${r} not found in section ${n} rollback timeline`);return a===i.currentIndex?e:Rr(e,a)},Kr=e=>{let t=Ss(e);return Dn(t,{selectPendingEffects:Cs,selectSkipMode:$r,selectAutoMode:Ls,selectIsChoiceVisible:te,selectDialogueUIHidden:kr,selectDialogueHistory:Or,selectConfirmDialog:Rs,selectIsLineAccountViewed:tn,selectIsResourceAccountViewed:Os,selectNextLineConfig:Ps,selectSystemState:Ts,selectSaveSlotMap:Tr,selectSaveSlots:Us,selectSaveSlot:Ds,selectRuntime:nn,selectRuntimeValue:Ns,selectAllVariables:Dr,selectCurrentPointer:ee,selectSection:H,selectCurrentLine:rn,selectPresentationState:Nr,selectPresentationChanges:Vs,selectSectionLineChanges:js,selectSaveSlotPage:on,selectCurrentPageSlots:Bs,selectRenderState:zs,selectOverlayStack:_s,selectLineIdByOffset:Hr,selectCanRollback:qr,startAutoMode:Mr,stopAutoMode:Me,toggleAutoMode:Js,startSkipMode:jr,stopSkipMode:ye,toggleSkipMode:Zs,showDialogueUI:lt,hideDialogueUI:Ur,toggleDialogueUI:Qs,setDialogueTextSpeed:ea,setAutoForwardDelay:ta,setSkipUnseenText:na,setSkipTransitionsAndAnimations:ra,setSoundVolume:oa,setMusicVolume:ia,setMuteAll:sa,setSaveLoadPagination:aa,incrementSaveLoadPagination:ca,decrementSaveLoadPagination:la,setMenuPage:ua,setMenuEntryPoint:fa,showConfirmDialog:Ws,hideConfirmDialog:Ys,resetStoryAtSection:ha,clearPendingEffects:da,appendPendingEffect:pa,beginRollbackActionBatch:ws,endRollbackActionBatch:xs,addViewedLine:ga,addViewedResource:ya,setNextLineConfig:Yr,saveSlot:ba,loadSlot:Ia,updateProjectData:Aa,sectionTransition:va,jumpToLine:wa,nextLine:xa,markLineCompleted:Ea,rollbackToLine:Ta,rollbackByOffset:Pa,pushOverlay:Hs,popOverlay:qs,replaceLastOverlay:Ks,clearOverlays:Gs,updateVariable:_a,nextLineFromSystem:Sa},{transformActionFirstArgument:r=>({state:r}),transformSelectorFirstArgument:r=>({state:r})})};var Da="route-engine",Na="projectPersistence";var Xr=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{},globalRuntime:{},accountViewedRegistry:{}}),F=e=>Object.prototype.toString.call(e)==="[object Object]",Gr="variables.",Va=(e={})=>{let t=F(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(n=>typeof n=="string"||typeof n=="number"?{sectionId:String(n)}:!F(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)}:!F(n)||typeof n.resourceId!="string"||n.resourceId.length===0?null:{resourceId:n.resourceId}).filter(Boolean)}},Ma=(e={})=>{let t=F(e)?e:{};return{sections:(Array.isArray(t.sections)?t.sections:[]).map(n=>typeof n=="string"||typeof n=="number"?{sectionId:String(n)}:!F(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)}:!F(n)||typeof n.resourceId!="string"||n.resourceId.length===0?null:{resourceId:n.resourceId}).filter(Boolean)}},ja=(e,t)=>{let n=Ma(e),r=Va(t),o=n.sections.map(s=>({...s})),i=n.resources.map(s=>({...s}));return r.sections.forEach(s=>{let a=o.find(l=>l.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(l=>l.resourceId===s.resourceId)||i.push({...s})}),{sections:o,resources:i}},Jr=(e={})=>{let t=F(e)?e:{};return{saveSlots:F(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:F(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:F(t.globalAccountVariables)?t.globalAccountVariables:{},globalRuntime:F(t.globalRuntime)?t.globalRuntime:{},accountViewedRegistry:F(t.accountViewedRegistry)?t.accountViewedRegistry:{}}},Ua=(e=[])=>{if(e===void 0)return[];if(!Array.isArray(e))throw new Error("applyScopedDataUpdates requires an updates array.");return e.map((t,n)=>{if(!F(t))throw new Error(`Malformed applyScopedDataUpdates.updates[${n}] entry.`);let r=t.path?.startsWith(Gr)?t.path.slice(Gr.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}].`)})},Ba=(e,t)=>{let n={};return Ua(t).forEach(r=>{if(r.path==="viewedRegistry"){n.accountViewedRegistry=ja(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},sn=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},Fa=e=>{let t=sn(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},za=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},Wa=({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}".`))}}),Ya=async({databasePromise:e,objectStoreName:t,namespace:n})=>{let r=await e;return new Promise((o,i)=>{let l=r.transaction(t,"readonly").objectStore(t).get(n);l.onsuccess=()=>{o(l.result??null)},l.onerror=()=>{i(l.error??new Error(`Failed to read persisted namespace "${n}" from IndexedDB.`))}})},Ue=async({databasePromise:e,objectStoreName:t,namespace:n,patch:r})=>{let o=await e;return new Promise((i,s)=>{let a=o.transaction(t,"readwrite"),l=a.objectStore(t),c=l.get(n),u=!1,f=p=>{u||(u=!0,s(p))},d=()=>{u||(u=!0,i())};c.onerror=()=>{f(c.error??new Error(`Failed to read persisted namespace "${n}" before updating IndexedDB.`))},c.onsuccess=()=>{let p=Jr(c.result),m=typeof r=="function"?r(p):r,y={namespace:n,version:1,...Xr(),...p,...m},I=l.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}".`))}})},Ha=async({databasePromise:e,objectStoreName:t,namespace:n})=>{let r=await e;return new Promise((o,i)=>{let s=r.transaction(t,"readwrite"),l=s.objectStore(t).delete(n),c=!1,u=d=>{c||(c=!0,i(d))},f=()=>{c||(c=!0,o())};l.onerror=()=>{u(l.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}".`))}})},an=(e={})=>{let{indexedDB:t,databaseName:n=Da,objectStoreName:r=Na,namespace:o}=e,i=za(t),s=Fa(o),a=Wa({indexedDB:i,databaseName:n,objectStoreName:r});return{namespace:s,load:async()=>{let l=await Ya({databasePromise:a,objectStoreName:r,namespace:s});return{...Xr(),...Jr(l)}},clear:async()=>Ha({databasePromise:a,objectStoreName:r,namespace:s}),saveSlots:async l=>Ue({databasePromise:a,objectStoreName:r,namespace:s,patch:{saveSlots:F(l)?l:{}}}),saveGlobalDeviceVariables:async l=>Ue({databasePromise:a,objectStoreName:r,namespace:s,patch:{globalDeviceVariables:F(l)?l:{}}}),saveGlobalAccountVariables:async l=>Ue({databasePromise:a,objectStoreName:r,namespace:s,patch:{globalAccountVariables:F(l)?l:{}}}),saveGlobalRuntime:async l=>Ue({databasePromise:a,objectStoreName:r,namespace:s,patch:{globalRuntime:F(l)?l:{}}}),applyScopedDataUpdates:async l=>Ue({databasePromise:a,objectStoreName:r,namespace:s,patch:c=>Ba(c,l)})}},qa=an;var Ka=new Set(["loadSlot","resetStoryAtSection","rollbackByOffset","rollbackToLine","updateProjectData"]),Ga=new Set(["loadSlot","rollbackByOffset","rollbackToLine"]);function cn(e){let t,n=0,r=null,o=new Map,i=new Map,s=new Map,{handlePendingEffects:a}=e,l=(S=new Map,P=Date.now())=>new Map(Array.from(S.entries()).filter(([,z])=>P<z.expiresAt).map(([z,K])=>[z,{animation:structuredClone(K.animation),startedAt:K.startedAt,expiresAt:K.expiresAt}])),c=(S=new Map)=>Array.from(S.values()).map(P=>structuredClone(P.animation)),u=(S=Date.now())=>{o=new Map(Array.from(o.entries()).filter(([,P])=>S<P.expiresAt))},f=()=>{for(;t.selectPendingEffects().length>0;){let S=[...t.selectPendingEffects()];t.clearPendingEffects();try{a(S)}catch(P){throw t.clearPendingEffects(),S.forEach(z=>{t.appendPendingEffect(z)}),P}}},d=({initialState:S,namespace:P})=>{t=Kr(S),n=0,r=sn(P),o=new Map,i=new Map,s=new Map,t.appendPendingEffect({name:"handleLineActions"}),f()},p=()=>r,m=()=>t.selectPresentationState(),y=()=>t.selectPresentationChanges(),I=S=>t.selectSectionLineChanges(S),b=(S={})=>{n+=1;let P=Date.now();u(P);let z=i.size>0,K=l(o,P),oe=z?l(i,P):new Map,Ae={...t.selectRenderState({activePersistentAnimations:c(K),restoredPersistentAnimations:c(oe)}),id:`render-${n}`};return s.set(Ae.id,{builtAt:P,persistentAnimationSessions:new Map([...oe.entries(),...K.entries()]),usedRestoredPersistentAnimationSessions:z}),Ae},g=(S={})=>b(S),w=(S={})=>b(S),v=S=>{let P=typeof S?.id=="string"&&S.id.length>0?S.id:null,z=P?s.get(P):null;P&&s.delete(P);let K=new Map;Zn(S?.animations).forEach(oe=>{let ae=et(oe);if(!ae)return;let Ae=z?.persistentAnimationSessions?.get(ae)??o.get(ae),eo=Math.max(0,er(oe)),un=Ae?.startedAt??z?.builtAt??Date.now();K.set(ae,{animation:structuredClone(oe),startedAt:un,expiresAt:un+eo})}),o=K,z?.usedRestoredPersistentAnimationSessions&&(i=new Map)},L=()=>t.selectSystemState(),R=()=>t.selectSaveSlotMap(),_=S=>t.selectSaveSlot(S),D=S=>t.selectSaveSlotPage(S),O=()=>t.selectSkipMode(),$=()=>t.selectAutoMode(),k=()=>t.selectRuntime(),A=()=>t.selectIsChoiceVisible(),E=(S,P)=>{t[S]&&(Ka.has(S)&&(Ga.has(S)?i=l(o):i=new Map,o=new Map),t[S](P),f())},N=(S,P)=>{E(S,P)},U=S=>{if(!S)return{variables:t.selectAllVariables?t.selectAllVariables():void 0,runtime:t.selectRuntime?t.selectRuntime():{}};if(Object.prototype.hasOwnProperty.call(S,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:P,...z}=S,K=t.selectAllVariables?t.selectAllVariables():void 0;return{...z,_event:P,variables:K,runtime:t.selectRuntime?t.selectRuntime():{}}},B=(S,P,z={})=>{let K=U(P),oe=Mn(S,K);t.beginRollbackActionBatch({source:z.rollbackSource});try{Object.entries(oe).forEach(([ae,Ae])=>{E(ae,Ae)})}finally{t.endRollbackActionBatch({})}};return{init:d,handleAction:E,handleInternalAction:N,handleActions:B,selectRenderState:g,prepareRenderState:w,commitRenderState:v,selectPresentationState:m,selectPresentationChanges:y,selectSectionLineChanges:I,selectSystemState:L,selectSaveSlotMap:R,selectSaveSlot:_,selectSaveSlotPage:D,selectSaveSlots:R,selectRuntime:k,selectIsChoiceVisible:A,handleLineActions:()=>{let S=t.selectCurrentLine();return S?.actions?(B(S.actions,void 0,{rollbackSource:"line"}),!0):!1},getNamespace:p}}var ln=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:n=>{e=n},addElapsed:n=>{e+=n},getCallback:()=>t,setCallback:n=>{t=n}}},Xa=80,Qr=({engine:e,routeGraphics:t,trackRenderDispatch:n},r)=>{let o=e.prepareRenderState?.(r)??e.selectRenderState(r);n?.(o),t.render(o),e.commitRenderState?.(o)},Ja=({engine:e,routeGraphics:t,trackRenderDispatch:n,getRenderDispatchCount:r},o)=>{let i=r?.()??0,s=e.handleLineActions();(r?.()??0)===i&&Qr({engine:e,routeGraphics:t,trackRenderDispatch:n},o)},Za=({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),ft(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},Qa=({ticker:e,autoTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},ec=({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??Xa;n.getElapsed()>=a&&(n.setElapsed(0),ft(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},tc=({ticker:e,skipTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},nc=({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),ft(e,"nextLineFromSystem",{}),t.remove(i),n.setCallback(null))};n.setCallback(i),t.add(i)},rc=({ticker:e,nextLineConfigTimerState:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},oc=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveSlots(t?.saveSlots))},ic=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalDeviceVariables(t?.globalDeviceVariables))},sc=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalAccountVariables(t?.globalAccountVariables))},ac=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalRuntime(t?.globalRuntime))},cc=({enqueuePersistenceWrite:e},t)=>{e(n=>{if(typeof n.applyScopedDataUpdates!="function")throw new Error("RouteEngine persistence adapter must implement applyScopedDataUpdates.");return n.applyScopedDataUpdates(t?.updates)})},Zr={render:Qr,saveSlots:oc,saveGlobalDeviceVariables:ic,saveGlobalAccountVariables:sc,saveGlobalRuntime:ac,applyScopedDataUpdates:cc,handleLineActions:Ja,startAutoNextTimer:Za,clearAutoNextTimer:Qa,startSkipNextTimer:ec,clearSkipNextTimer:tc,nextLineConfigTimer:nc,clearNextLineConfigTimer:rc},lc=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","saveGlobalRuntime","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),ft=(e,t,n)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,n)},uc=(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(!lc.has(o.name)){n.unshift(o);continue}t.has(o.name)||(t.add(o.name),n.unshift(o))}return n},fc=({getEngine:e,routeGraphics:t,ticker:n,handleUnhandledEffect:r,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:a})=>{let l=ln(),c=ln(),u=ln(),f=s??null,d=Promise.resolve(),p=null,m=null,y=!1,I=0,b=A=>{if(o){o(A);return}console.error("RouteEngine persistence write failed.",A)},g=()=>{if(f)return f;let A=e();return f=an({indexedDB:i,namespace:a??A?.getNamespace?.()}),f},w=A=>{d=d.catch(()=>{}).then(()=>{let E=g();return A(E)}).catch(E=>{b(E)})},v=A=>{let E=typeof A?.id=="string"&&A.id.length>0?A.id:null;I+=1,p=E,y=!1},L=()=>I,R=(A={})=>{if(A?.aborted===!0)return!1;let E=typeof A?.id=="string"&&A.id.length>0?A.id:null;return E?E!==p||E===m?!1:(m=E,!0):p!==null||y?!1:(y=!0,!0)},_=(A,E={})=>{if(A!=="renderComplete"||!R(E))return!1;let N=e();return ft(N,"markLineCompleted",{}),!0},D=(A={})=>{if(A?._interactionSource==="choice")return!0;let E=A?.actions;return!E||typeof E!="object"||Array.isArray(E)?!1:Object.values(E).some(N=>N?._interactionSource==="choice")},O=(A,E={})=>!E?.actions||typeof A?.selectIsChoiceVisible!="function"||!A.selectIsChoiceVisible()?!1:!D(E),$=({preprocessPayload:A,onEvent:E}={})=>async(N,U={})=>{let B=e();if(O(B,U))return E?.(N,U);let q=await A?.(N,U)??U;if(O(B,q))return E?.(N,q);if(_(N,q),q?.actions){let S=q?._event?{_event:q._event}:q?.event?{_event:q.event}:void 0;B.handleActions(q.actions,S)}return E?.(N,q)},k=A=>{let E=e(),N=uc(A);N.forEach(B=>{if(!Zr[B.name]&&!r)throw new Error(`Unhandled pending effect "${B.name}".`)});let U={engine:E,routeGraphics:t,ticker:n,autoTimer:l,skipTimer:c,nextLineConfigTimerState:u,trackRenderDispatch:v,getRenderDispatchCount:L,enqueuePersistenceWrite:w};for(let B of N){let q=Zr[B.name];if(q){q(U,B.payload);continue}r(B,U)}};return k.handleRouteGraphicsEvent=_,k.createRouteGraphicsEventHandler=$,k},dc=fc;var pc=(e,t={})=>{let{resources:n={}}=t;return Ht(e,n)};var Al=cn;export{dc as createEffectsHandler,qa as createIndexedDbPersistence,Al as default,pc as resolveLayoutReferences};
|
package/package.json
CHANGED