route-engine-js 0.7.4 → 0.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 +5 -5
package/dist/RouteEngine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var ur=Object.defineProperty;var fr=(e,t)=>{for(var n in t)ur(e,n,{get:t[n],enumerable:!0})};var qt=Symbol.for("immer-nothing"),Ut=Symbol.for("immer-draftable"),T=Symbol.for("immer-state");function M(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var se=Object.getPrototypeOf;function F(e){return!!e&&!!e[T]}function K(e){return e?Jt(e)||Array.isArray(e)||!!e[Ut]||!!e.constructor?.[Ut]||_e(e)||Ce(e):!1}var dr=Object.prototype.constructor.toString();function Jt(e){if(!e||typeof e!="object")return!1;let t=se(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)===dr}function xe(e,t){Ee(e)===0?Reflect.ownKeys(e).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function Ee(e){let t=e[T];return t?t.type_:Array.isArray(e)?1:_e(e)?2:Ce(e)?3:0}function Je(e,t){return Ee(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Xt(e,t,n){let r=Ee(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function pr(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function _e(e){return e instanceof Map}function Ce(e){return e instanceof Set}function H(e){return e.copy_||e.base_}function Xe(e,t){if(_e(e))return new Map(e);if(Ce(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let n=Jt(e);if(t===!0||t==="class_only"&&!n){let r=Object.getOwnPropertyDescriptors(e);delete r[T];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(se(e),r)}else{let r=se(e);if(r!==null&&n)return{...e};let o=Object.create(r);return Object.assign(o,e)}}function tt(e,t=!1){return $e(e)||F(e)||!K(e)||(Ee(e)>1&&(e.set=e.add=e.clear=e.delete=hr),Object.freeze(e),t&&Object.entries(e).forEach(([n,r])=>tt(r,!0))),e}function hr(){M(2)}function $e(e){return Object.isFrozen(e)}var gr={};function q(e){let t=gr[e];return t||M(0,e),t}var de;function Gt(){return de}function yr(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function Wt(e,t){t&&(q("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Ge(e){Ze(e),e.drafts_.forEach(mr),e.drafts_=null}function Ze(e){e===de&&(de=e.parent_)}function Yt(e){return de=yr(de,e)}function mr(e){let t=e[T];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function Ht(e,t){t.unfinalizedDrafts_=t.drafts_.length;let n=t.drafts_[0];return e!==void 0&&e!==n?(n[T].modified_&&(Ge(t),M(4)),K(e)&&(e=we(t,e),t.parent_||ve(t,e)),t.patches_&&q("Patches").generateReplacementPatches_(n[T].base_,e,t.patches_,t.inversePatches_)):e=we(t,n,[]),Ge(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==qt?e:void 0}function we(e,t,n){if($e(t))return t;let r=t[T];if(!r)return xe(t,(o,i)=>Kt(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return ve(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),xe(i,(a,c)=>Kt(e,r,o,a,c,n,s)),ve(e,o,!1),n&&e.patches_&&q("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function Kt(e,t,n,r,o,i,s){if(F(o)){let a=i&&t&&t.type_!==3&&!Je(t.assigned_,r)?i.concat(r):void 0,c=we(e,o,a);if(Xt(n,r,c),F(c))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if(K(o)&&!$e(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;we(e,o),(!t||!t.scope_.parent_)&&typeof r!="symbol"&&Object.prototype.propertyIsEnumerable.call(n,r)&&ve(e,o)}}function ve(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&tt(t,n)}function br(e,t){let n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:Gt(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=r,i=nt;n&&(o=[r],i=pe);let{revoke:s,proxy:a}=Proxy.revocable(o,i);return r.draft_=a,r.revoke_=s,a}var nt={get(e,t){if(t===T)return e;let n=H(e);if(!Je(n,t))return Ir(e,n,t);let r=n[t];return e.finalized_||!K(r)?r:r===Ke(e.base_,t)?(qe(e),e.copy_[t]=et(r,e)):r},has(e,t){return t in H(e)},ownKeys(e){return Reflect.ownKeys(H(e))},set(e,t,n){let r=Zt(H(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){let o=Ke(H(e),t),i=o?.[T];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(pr(n,o)&&(n!==void 0||Je(e.base_,t)))return!0;qe(e),Qe(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 Ke(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,qe(e),Qe(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let n=H(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){M(11)},getPrototypeOf(e){return se(e.base_)},setPrototypeOf(){M(12)}},pe={};xe(nt,(e,t)=>{pe[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});pe.deleteProperty=function(e,t){return pe.set.call(this,e,t,void 0)};pe.set=function(e,t,n){return nt.set.call(this,e[0],t,n,e[0])};function Ke(e,t){let n=e[T];return(n?H(n):e)[t]}function Ir(e,t,n){let r=Zt(t,n);return r?"value"in r?r.value:r.get?.call(e.draft_):void 0}function Zt(e,t){if(!(t in e))return;let n=se(e);for(;n;){let r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=se(n)}}function Qe(e){e.modified_||(e.modified_=!0,e.parent_&&Qe(e.parent_))}function qe(e){e.copy_||(e.copy_=Xe(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Ar=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){let i=n;n=t;let s=this;return function(c=i,...l){return s.produce(c,u=>n.call(this,u,...l))}}typeof n!="function"&&M(6),r!==void 0&&typeof r!="function"&&M(7);let o;if(K(t)){let i=Yt(this),s=et(t,void 0),a=!0;try{o=n(s),a=!1}finally{a?Ge(i):Ze(i)}return Wt(i,r),Ht(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===qt&&(o=void 0),this.autoFreeze_&&tt(o,!0),r){let i=[],s=[];q("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else M(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...a)=>this.produceWithPatches(s,c=>t(c,...a));let r,o;return[this.produce(t,n,(s,a)=>{r=s,o=a}),r,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){K(e)||M(8),F(e)&&(e=rt(e));let t=Yt(this),n=et(e,void 0);return n[T].isManual_=!0,Ze(t),n}finishDraft(e,t){let n=e&&e[T];(!n||!n.isManual_)&&M(9);let{scope_:r}=n;return Wt(r,t),Ht(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=q("Patches").applyPatches_;return F(e)?r(e,t):this.produce(e,o=>r(o,t))}};function et(e,t){let n=_e(e)?q("MapSet").proxyMap_(e,t):Ce(e)?q("MapSet").proxySet_(e,t):br(e,t);return(t?t.scope_:Gt()).drafts_.push(n),n}function rt(e){return F(e)||M(10,e),Qt(e)}function Qt(e){if(!K(e)||$e(e))return e;let t=e[T],n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=Xe(e,t.scope_.immer_.useStrictShallowCopy_)}else n=Xe(e,!0);return xe(n,(r,o)=>{Xt(n,r,Qt(o))}),t&&(t.finalized_=!1),n}var P=new Ar,ot=P.produce,ps=P.produceWithPatches.bind(P),hs=P.setAutoFreeze.bind(P),gs=P.setUseStrictShallowCopy.bind(P),ys=P.applyPatches.bind(P),ms=P.createDraft.bind(P),bs=P.finishDraft.bind(P);var p={LITERAL:0,VARIABLE:1,INTERPOLATION:2,FUNCTION:3,BINARY:4,UNARY:5,CONDITIONAL:6,LOOP:7,OBJECT:8,ARRAY:9,PARTIAL:10,PATH_REFERENCE:11},L={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},he={NOT:0};var E=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},O=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var it=e=>{if(!e||e.trim()==="")throw new E("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let n=e.includes("===")?"==":"!=";throw new E(`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 E(`Incomplete comparison expression - missing right operand (got: '${e}')`)},en=e=>{if(e.trim().endsWith(" in"))throw new E(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new E(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,n]=e.split(" in ");if(!n||n.trim()==="")throw new E(`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 E(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new E(`Invalid loop syntax (got: '$for ${e}')`)}};var tn=(e,t,n=!1)=>{if(t===null)return new O(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new O(`Cannot iterate over undefined value at '$for ${e}'`);let r=typeof t;return n?new O(`Cannot iterate over non-array value in loop '${e}' - got ${r} instead`):new O(`Cannot iterate over non-array value (got: ${r}) at '$for ${e}'`)},nn=(e,t)=>{let n=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new O(`Unknown function '${e}' (${n})`)};var xr=(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=$(e,{functions:r,partials:o},t,{});return s===void 0?{}:s},$=(e,t,n,r)=>{let o=t.functions||t;if(e.var&&!e.type)return S(e.var,n,r);if(e.type===p.LITERAL)return e.value;if(e.type===p.VARIABLE)return S(e.path,n,r);if(e.type===p.INTERPOLATION)return vr(e.parts,t,n,r);switch(e.type){case p.FUNCTION:return on(e,t,n,r);case p.BINARY:return sn(e,t,n,r);case p.UNARY:return ln(e,t,n,r);case p.CONDITIONAL:return _r(e,t,n,r);case p.LOOP:return kr(e,t,n,r);case p.OBJECT:return Or(e,t,n,r);case p.ARRAY:return Tr(e,t,n,r);case p.PARTIAL:return Pr(e,t,n,r);case p.PATH_REFERENCE:return Nr(e,t,n,r);default:throw new Error(`Unknown node type: ${e.type}`)}},rn=new Map,wr=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},S=(e,t,n)=>{if(!e)return;if(e in n)return n[e];let r=rn.get(e);if(!r){let i=[],s="",a=0;for(let c=0;c<e.length;c++){let l=e[c];l==="["?(a++,s+=l):l==="]"?(a--,s+=l):l==="."&&a===0?s&&(i.push(s),s=""):s+=l}s&&i.push(s),r=[];for(let c of i){let l=wr(c.trim());r.push(...l)}rn.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},vr=(e,t,n,r)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=$(i,t,n,r);o.push(s!=null?String(s):"")}return o.join("")},on=(e,t,n,r)=>{let o=t.functions||t,i=o[e.name];if(!i)throw nn(e.name,o);let s=e.args.map(a=>$(a,t,n,r));return i(...s)},le=(e,t,n,r)=>{if(e.var&&!e.type)return S(e.var,n,r);switch(e.type){case p.VARIABLE:return S(e.path,n,r);case p.LITERAL:return e.value;case p.BINARY:return sn(e,t,n,r);case p.UNARY:return ln(e,t,n,r);case p.FUNCTION:return on(e,t,n,r);default:return $(e,t,n,r)}},sn=(e,t,n,r)=>{if(e.op===L.AND||e.op===L.OR){let s=le(e.left,t,n,r),a=le(e.right,t,n,r);switch(e.op){case L.AND:return s&&a;case L.OR:return s||a}}let o=$(e.left,t,n,r),i=$(e.right,t,n,r);switch(e.op){case L.EQ:return o==i;case L.NEQ:return o!=i;case L.GT:return o>i;case L.LT:return o<i;case L.GTE:return o>=i;case L.LTE:return o<=i;case L.IN:return Array.isArray(i)?i.includes(o):!1;case L.ADD:if(typeof o!="number"||typeof i!="number")throw new O(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case L.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new O(`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===he.NOT?le(e.operand,t,n,r):$(e.operand,t,n,r);if(e.op===he.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},Er=(e,t,n,r)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===p.VARIABLE)if(S(o.path,n,r)){let s=e.bodies[0];if(s.type===p.OBJECT&&s.properties.length<=5){let a={};for(let c of s.properties){let l=c.parsedKey?$(c.parsedKey,t,n,r):c.key,u=c.value;if(u.type===p.LITERAL)a[l]=u.value;else if(u.type===p.VARIABLE)a[l]=S(u.path,n,r);else if(u.type===p.INTERPOLATION){let f=[];for(let d of u.parts)if(typeof d=="string")f.push(d);else if(d.type===p.VARIABLE){let h=S(d.path,n,r);f.push(h!=null?String(h):"")}else{let h=$(d,t,n,r);f.push(h!=null?String(h):"")}a[l]=f.join("")}else a[l]=$(u,t,n,r)}return a}}else{let s=e.bodies[1];if(s.type===p.OBJECT&&s.properties.length<=5){let a={};for(let c of s.properties){let l=c.parsedKey?$(c.parsedKey,t,n,r):c.key,u=c.value;if(u.type===p.LITERAL)a[l]=u.value;else if(u.type===p.VARIABLE)a[l]=S(u.path,n,r);else if(u.type===p.INTERPOLATION){let f=[];for(let d of u.parts)if(typeof d=="string")f.push(d);else if(d.type===p.VARIABLE){let h=S(d.path,n,r);f.push(h!=null?String(h):"")}else{let h=$(d,t,n,r);f.push(h!=null?String(h):"")}a[l]=f.join("")}else a[l]=$(u,t,n,r)}return a}}}return null},_r=(e,t,n,r)=>{let o=Er(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||le(s,t,n,r))return $(e.bodies[i],t,n,r)}return cn},Cr=(e,t)=>{let n=e.body,r=e.itemVar;if(n.type===p.CONDITIONAL&&n.conditions.length===1&&n.conditions[0].type===p.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===p.OBJECT&&i.properties.length<=5){for(let c of i.properties)if(c.parsedKey)return null;let a=[];for(let c=0;c<t.length;c++){let l=t[c];if(l[s]){let u={};for(let f of i.properties){let d=f.key,h=f.value;if(h.type===p.LITERAL)u[d]=h.value;else if(h.type===p.VARIABLE){let g=h.path;if(g===r)u[d]=l;else if(g.startsWith(r+".")){let m=g.substring(r.length+1);u[d]=l[m]}else return null}else if(h.type===p.INTERPOLATION){let g=[],m=!0;for(let y of h.parts)if(typeof y=="string")g.push(y);else if(y.type===p.VARIABLE){let I=y.path;if(I===r)g.push(l!=null?String(l):"");else if(I.startsWith(r+".")){let A=I.substring(r.length+1),b=l[A];g.push(b!=null?String(b):"")}else{m=!1;break}}else{m=!1;break}if(!m)return null;u[d]=g.join("")}else return null}a.push(u)}}return a}}}return null},$r=(e,t)=>{let n=e.body,r=e.itemVar,o=Cr(e,t);if(o!==null)return o;if(n.type===p.OBJECT&&n.properties.length<=5&&!n.whenCondition){for(let a of n.properties)if(a.parsedKey)return null;let i=[],s=!0;for(let a of n.properties){let c=a.key,l=a.value;if(l.type===p.LITERAL)i.push({key:c,type:"literal",value:l.value});else if(l.type===p.VARIABLE){let u=l.path;if(u===r)i.push({key:c,type:"item"});else if(u.startsWith(r+".")){let f=u.substring(r.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:c,type:"prop",prop:f});else{s=!1;break}}else{s=!1;break}}else if(l.type===p.INTERPOLATION&&l.parts.length===1){let u=l.parts[0];if(u.type===p.VARIABLE){let f=u.path;if(f===r)i.push({key:c,type:"item_string"});else if(f.startsWith(r+".")){let d=f.substring(r.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:c,type:"prop_string",prop:d});else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}if(s){let a=new Array(t.length);if(i.length===3&&i[0].type==="prop"&&i[0].key==="id"&&i[1].type==="prop_string"&&i[1].key==="title"&&i[2].type==="prop"&&i[2].key==="completed")for(let c=0;c<t.length;c++){let l=t[c];a[c]={id:l.id,title:l.title!=null?String(l.title):"",completed:l.completed}}else for(let c=0;c<t.length;c++){let l=t[c],u={};for(let f of i)if(f.type==="literal")u[f.key]=f.value;else if(f.type==="item")u[f.key]=l;else if(f.type==="prop")u[f.key]=l[f.prop];else if(f.type==="item_string")u[f.key]=l!=null?String(l):"";else if(f.type==="prop_string"){let d=l[f.prop];u[f.key]=d!=null?String(d):""}a[c]=u}return a}}return null},Lr=(e,t,n,r,o)=>{let i=[],s=e.body;if(s.type===p.OBJECT&&s.fast!==!1){let a=e.itemVar,c=e.indexVar;for(let l=0;l<o.length;l++){let u=o[l],f={},d={...r,[a]:u,...c&&{[c]:l}};d.__paths__||(d.__paths__=r.__paths__||{});let h=e.iterable.path||"";if(r&&r.__paths__&&h){let g=h.split("."),m=g[0];m in r.__paths__&&(h=r.__paths__[m],g.length>1&&(h+="."+g.slice(1).join(".")))}d.__paths__={...d.__paths__,[a]:`${h}[${l}]`,...c&&{[c]:l}};for(let g of s.properties){let m=g.parsedKey?$(g.parsedKey,t,n,d):g.key,y=g.value;if(y.type===p.LITERAL)f[m]=y.value;else if(y.type===p.VARIABLE){let I=y.path;if(I===a)f[m]=u;else if(I===c)f[m]=l;else if(I.startsWith(a+".")){let A=I.substring(a.length+1);!A.includes(".")&&!A.includes("[")?f[m]=u[A]:f[m]=S(I,n,{...r,[a]:u,...c&&{[c]:l}})}else f[m]=S(I,n,{...r,[a]:u,...c&&{[c]:l}})}else if(y.type===p.INTERPOLATION){let I=[];for(let A of y.parts)if(typeof A=="string")I.push(A);else if(A.type===p.VARIABLE){let b=A.path,x;if(b===a)x=u;else if(b===c)x=l;else if(b.startsWith(a+".")){let w=b.substring(a.length+1);!w.includes(".")&&!w.includes("[")?x=u[w]:x=S(b,n,{...r,[a]:u,...c&&{[c]:l}})}else x=S(b,n,{...r,[a]:u,...c&&{[c]:l}});I.push(x!=null?String(x):"")}else{let b={...r,[a]:u,...c&&{[c]:l}},x=$(A,t,n,b);I.push(x!=null?String(x):"")}f[m]=I.join("")}else{let I={...r,[a]:u,...c&&{[c]:l}};f[m]=$(y,t,n,I)}}i.push(f)}return i}return null},Sr=(e,t,n)=>{let r=e.body;if(r.type===p.OBJECT&&r.properties.length===1&&r.properties[0].key==="$if item.visible"){let i=r.properties[0].value;if(i.type===p.CONDITIONAL&&i.conditions.length===1&&i.conditions[0].type===p.VARIABLE&&i.conditions[0].path==="item.visible"){let s=i.bodies[0];if(s.type===p.OBJECT&&s.properties.length===2){let a=s.properties[0],c=s.properties[1];if(a.key==="id"&&a.value.type===p.VARIABLE&&a.value.path==="item.id"&&c.key==="$if item.highlighted"&&c.value.type===p.CONDITIONAL){let l=[];for(let u=0;u<t.length;u++){let f=t[u];if(f.visible){let d={id:f.id};f.highlighted?(d.highlight=!0,d.message=`This item is highlighted: ${f.name}`):(d.highlight=!1,d.message=f.name),l.push(d)}}return l}}}}return null},kr=(e,t,n,r)=>{let o=$(e.iterable,t,n,r);if(!Array.isArray(o)){let l,u=!1;if(e.iterable.type===p.FUNCTION){u=!0;let d=e.iterable.args.map(h=>h.type===p.LITERAL?typeof h.value=="string"?`'${h.value}'`:String(h.value):h.type===p.VARIABLE?h.path:h.type===p.FUNCTION?`${h.name}(...)`:"?").join(", ");l=`${e.iterable.name}(${d})`}else l=e.iterable.path||"undefined";let f=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${l}`;throw tn(f,o,u)}if(!e.indexVar){let l=Sr(e,o,e.itemVar);if(l!==null)return l}if(!e.indexVar){let l=$r(e,o);if(l!==null)return l}let i=Lr(e,t,n,r,o);if(i!==null)return i;let s=[],a=e.iterable.path||"";if(r&&r.__paths__&&a){let l=a.split("."),u=l[0];u in r.__paths__&&(a=r.__paths__[u],l.length>1&&(a+="."+l.slice(1).join(".")))}let c=!1;e.body.type===p.ARRAY&&(e.body.items.length<=1?c=!1:c=e.body._shouldPreserveArray??=e.body.items.some(l=>l.type===p.OBJECT&&l.properties.some(u=>u.key.startsWith("$if ")||u.key.startsWith("$when "))));for(let l=0;l<o.length;l++){let u=e.indexVar?{...r,[e.itemVar]:o[l],[e.indexVar]:l}:{...r,[e.itemVar]:o[l]};u.__paths__||(u.__paths__=r.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${a}[${l}]`},e.indexVar&&(u.__paths__[e.indexVar]=l);let f=$(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},Rr=(e,t,n,r)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?$(o.parsedKey,t,n,r):o.key,s=o.value;if(s.type===p.OBJECT&&s.properties.length<=10&&!s.whenCondition){let a={},c={},l=!0;for(let u of s.properties){let f=u.parsedKey?$(u.parsedKey,t,n,r):u.key,d=u.value;if(d.type===p.LITERAL)c[f]=d.value;else if(d.type===p.VARIABLE)c[f]=S(d.path,n,r);else if(d.type===p.INTERPOLATION){let h=[];for(let g of d.parts)if(typeof g=="string")h.push(g);else if(g.type===p.VARIABLE){let m=S(g.path,n,r);h.push(m!=null?String(m):"")}else{l=!1;break}if(!l)break;c[f]=h.join("")}else if(d.type===p.OBJECT&&d.properties.length<=5){let h={};for(let g of d.properties){let m=g.key,y=g.value;if(y.type===p.LITERAL)h[m]=y.value;else if(y.type===p.VARIABLE)h[m]=S(y.path,n,r);else if(y.type===p.INTERPOLATION){let I=[];for(let A of y.parts)if(typeof A=="string")I.push(A);else if(A.type===p.VARIABLE){let b=S(A.path,n,r);I.push(b!=null?String(b):"")}else{l=!1;break}if(!l)break;h[m]=I.join("")}else{l=!1;break}}if(!l)break;c[f]=h}else{l=!1;break}}if(l)return a[i]=c,a}}return null},Or=(e,t,n,r)=>{let o=t.functions||t;if(e.whenCondition&&!le(e.whenCondition,o,n,r))return;let i=Rr(e,t,n,r);if(i!==null)return i;if(e.fast){let l={};for(let u of e.properties){let f=u.parsedKey?$(u.parsedKey,t,n,r):u.key,d=u.value;if(d.type===p.LITERAL)l[f]=d.value;else if(d.type===p.VARIABLE)l[f]=S(d.path,n,r);else if(d.type===p.INTERPOLATION){let h=[];for(let g of d.parts)if(typeof g=="string")h.push(g);else if(g.type===p.VARIABLE){let m=S(g.path,n,r);h.push(m!=null?String(m):"")}else{let m=$(g,t,n,r);h.push(m!=null?String(m):"")}l[f]=h.join("")}else l[f]=$(d,t,n,r)}return l}let s={},a=null,c=!1;for(let l of e.properties)if(!l.key.startsWith("$if ")&&!l.key.match(/^\$if\s+\w+.*:?$/)&&!l.key.startsWith("$elif")&&!l.key.startsWith("$else")&&!l.key.startsWith("$for ")){c=!0;break}for(let l of e.properties)if(l.key.startsWith("$if ")||l.key.match(/^\$if\s+\w+.*:?$/)){let u=$(l.value,t,n,r);if(!c&&u!==null&&u!==void 0)return Array.isArray(u)&&u.length===1?u[0]:u;typeof u=="object"&&u!==null&&!Array.isArray(u)&&Object.assign(s,u)}else if(l.key.startsWith("$for ")){if(e.properties.length===1)return $(l.value,t,n,r)}else{let u=l.value;if(u&&u.type===p.OBJECT&&u.properties){let f=u.properties.find(d=>d.key.startsWith("$for "));if(f){let d=$(f.value,t,n,r);d!==void 0&&(s[l.key]=d)}else{let d=$(l.value,t,n,r);d!==void 0&&(s[l.key]=d)}}else{let f=l.parsedKey?$(l.parsedKey,t,n,r):l.key,d=$(l.value,t,n,r);d!==void 0&&(s[f]=d)}}return s},cn={},Tr=(e,t,n,r)=>{let o=[];for(let i of e.items)if(i.type===p.LOOP){let s=$(i,t,n,r);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=$(i,t,n,r);s!==cn&&s!==void 0&&o.push(s)}return o},Pr=(e,t,n,r)=>{let{name:o,data:i,whenCondition:s}=e,a=t.partials||{},c=t.functions||t;if(s&&!le(s,c,n,r))return;if(!a[o])throw new O(`Partial '${o}' is not defined`);let l=r._partialStack||[];if(l.includes(o))throw new O(`Circular partial reference detected: ${o}`);let u=a[o],f=n,d={...r,_partialStack:[...l,o]};if(r){f={...n};for(let h of Object.keys(r))h.startsWith("_")||(f[h]=r[h])}if(i){let h=$(i,t,n,r);f={...f,...h}}return $(u,t,f,d)},Nr=(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 O(`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 O(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let c=r.__paths__[s];if(typeof c=="number"){if(a.length>0)throw new O(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(c)}return a.length>0&&(c+="."+a.join(".")),c},st=xr;var Vr=/\$\{([^}]*)\}/g,Dr=/#\{([^}]*)\}/g,un=(e,t={})=>{let n=e.match(/^(\w+)\((.*)\)$/);if(!n)return{isFunction:!1};let[,r,o]=n,i=Mr(o,t);return{isFunction:!0,type:p.FUNCTION,name:r,args:i}},Mr=(e,t={})=>e.trim()?jr(e).map(r=>Br(r.trim(),t)):[],jr=e=>{let t=[],n="",r=0,o=!1,i="";for(let s=0;s<e.length;s++){let a=e[s],c=s>0?e[s-1]:"";!o&&(a==='"'||a==="'")?(o=!0,i=a,n+=a):o&&a===i&&c!=="\\"?(o=!1,i="",n+=a):!o&&a==="("?(r++,n+=a):!o&&a===")"?(r--,n+=a):!o&&a===","&&r===0?(t.push(n),n=""):n+=a}return n&&t.push(n),t},Br=(e,t={})=>{if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:p.LITERAL,value:e.slice(1,-1)};if(/^-?\d+(\.\d+)?$/.test(e))return{type:p.LITERAL,value:parseFloat(e)};if(e==="true")return{type:p.LITERAL,value:!0};if(e==="false")return{type:p.LITERAL,value:!1};if(e==="null")return{type:p.LITERAL,value:null};let n=un(e,t);if(n.isFunction)return{type:n.type,name:n.name,args:n.args};let r=e.trim(),o=[{op:" + ",type:"ADD"},{op:" - ",type:"SUBTRACT"}],i=-1,s=null;for(let{op:a,type:c}of o){let l=0;for(;l<r.length;){let u=J(r.substring(l),a);if(u===-1)break;let f=l+u;f>i&&(i=f,s={op:a,type:c}),l=f+a.length}}if(i!==-1)try{return R(r,t)}catch{return{type:p.VARIABLE,path:r}}return{type:p.VARIABLE,path:r}},fn=/^\w+\(.*\)$/,zr=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,Fr=e=>{if(!(!e||e.trim()===""||fn.test(e))&&zr.test(e))throw e.includes("?")&&e.includes(":")?new E(`Complex expressions not supported in variable replacements - consider calculating the value in your data instead. Offending expression: "${e}"`):e.includes("||")||e.includes("&&")||e.includes("??")?new E(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new E(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},an=e=>{let t=e.trim();if(fn.test(t))throw new E(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new E(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new E(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new E(`Logical operators not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("?")&&t.includes(":"))throw new E(`Complex expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);return{type:p.PATH_REFERENCE,path:t}},ge=(e,t={})=>{let n=e.trim();Fr(n);let r=un(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:p.VARIABLE,path:n}},lt=(e,t={})=>{let n=e,r=[];(e.includes("\\${")||e.includes("\\#{"))&&(n=e.replace(/\\\\(\$\{[^}]*\})/g,"\\DOUBLE_ESC_VAR$1"),n=n.replace(/\\\\(#\{[^}]*\})/g,"\\DOUBLE_ESC_PATH$1"),n=n.replace(/\\(\$\{[^}]*\})/g,(l,u)=>{let f=`__ESCAPED_${r.length}__`;return r.push(u),f}),n=n.replace(/\\(#\{[^}]*\})/g,(l,u)=>{let f=`__ESCAPED_${r.length}__`;return r.push(u),f}),n=n.replace(/\\DOUBLE_ESC_VAR/g,"\\"),n=n.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...n.matchAll(Vr)],i=[...n.matchAll(Dr)],s=[...o.map(l=>({match:l,type:"variable"})),...i.map(l=>({match:l,type:"pathref"}))].sort((l,u)=>l.match.index-u.match.index);if(s.length===0){let l=n;for(let u=0;u<r.length;u++)l=l.replace(`__ESCAPED_${u}__`,r[u]);return{type:p.LITERAL,value:l}}if(s.length===1&&s[0].match[0]===n&&r.length===0){let{match:l,type:u}=s[0];try{return u==="variable"?ge(l[1],t):an(l[1])}catch(f){if(f.message==="Invalid array index syntax")return{type:p.LITERAL,value:n};throw f}}let a=[],c=0;for(let{match:l,type:u}of s){let[f,d]=l,h=l.index;if(h>c){let g=n.substring(c,h);for(let m=0;m<r.length;m++)g=g.replace(`__ESCAPED_${m}__`,r[m]);g&&a.push(g)}try{let g;u==="variable"?g=ge(d.trim(),t):g=an(d.trim()),a.push(g)}catch(g){if(g.message==="Invalid array index syntax")a.push(f);else throw g}c=h+f.length}if(c<n.length){let l=n.substring(c);for(let u=0;u<r.length;u++)l=l.replace(`__ESCAPED_${u}__`,r[u]);l&&a.push(l)}return{type:p.INTERPOLATION,parts:a}};var U=(e,t)=>typeof e=="string"?lt(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?Wr(e,t):Yr(e,t):{type:p.LITERAL,value:e},Ur=e=>{let{$each:t,...n}=e;if(typeof t!="string")throw new E("$each value must be a non-empty string");let r=t.trim();if(r==="")throw new E("$each value must be a non-empty string");if(Object.keys(n).length===0)throw new E("Empty $each body not allowed");if(n.$partial!==void 0)throw new E("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${r}`]:n}},Wr=(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=Ur(i),l=Object.keys(c);if(l.length===1&&/^\$for(?::\w+)?\s/.test(l[0])){let u=dn(l[0],c[l[0]],t,!0);n.push(u),r=!0;continue}}catch(c){throw c instanceof E?c:new E(c.message)}let a=Object.keys(i);if(a.length===1&&/^\$for(?::\w+)?\s/.test(a[0])){let c=dn(a[0],i[a[0]],t);n.push(c),r=!0;continue}}let s=U(i,t);n.push(s),(s.type===p.FUNCTION||s.type===p.CONDITIONAL||s.type===p.LOOP||s.type===p.PARTIAL||s.type===p.OBJECT&&!s.fast||s.type===p.ARRAY&&!s.fast)&&(r=!0)}return{type:p.ARRAY,items:n,fast:!r}},Yr=(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 E("$partial value must be a string");if(e.$partial.trim()==="")throw new E("$partial value cannot be an empty string");let c=["$if","$elif","$else","$for"],l=[];for(let[I]of i)for(let A of c)if(I===A||I.startsWith(A+" ")||I.startsWith(A+"#")){l.push(A);break}if(l.length>0)throw new E(`Cannot use $partial with ${l.join(", ")} at the same level. Wrap $partial in a parent object if you need conditionals.`);let{$partial:u,$when:f,...d}=e,h={},g=!1;for(let[I,A]of Object.entries(d)){let b=I;(I.startsWith("\\$")||I.startsWith("$$"))&&(b=I.slice(1)),h[b]=A,g=!0}let m=null;if(g&&(m=U(h,t),m.type===p.OBJECT)){let I=!1;for(let A of m.properties)if(A.value.type===p.VARIABLE||A.value.type===p.INTERPOLATION||A.value.type===p.FUNCTION||A.value.type===p.CONDITIONAL||A.value.type===p.OBJECT&&!A.value.fast||A.value.type===p.ARRAY&&!A.value.fast){I=!0;break}I&&(m.fast=!1)}let y={type:p.PARTIAL,name:u,data:m};if(f!==void 0){let I;if(typeof f=="string"){if(f.trim()==="")throw new E("Empty condition expression after '$when'");I=R(f,t)}else I={type:p.LITERAL,value:f};y.whenCondition=I}return y}for(let[c,l]of i)if(c==="$when"){if(o!==null)throw new E("Multiple '$when' directives on the same object are not allowed");if(l==null)throw new E("Missing condition expression after '$when'");let u=typeof l=="string"?l:JSON.stringify(l);if(u.trim()==="")throw new E("Empty condition expression after '$when'");o=R(u,t),r=!0}else if(c.startsWith("$when#")||c.startsWith("$when "))throw new E("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<i.length;){let[c,l]=i[s];if(c==="$when"){s++;continue}if(c==="$each")throw new E("$each can only be used inside arrays");if(c.startsWith("$if ")||c.match(/^\$if#\w+\s/)||c.match(/^\$if\s+\w+.*:$/)){let u=Hr(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 E(`$for loops must be inside arrays - use '- $for${f} item in items:' instead of '$for${f} item in items:'. For cleaner object generation syntax, consider using $each.`)}else{if(c.startsWith("$elif ")||c.startsWith("$else"))throw new E(`'${c.split(" ")[0]}' without matching '$if'`);if(c==="$if"||c==="$if:")throw new E("Missing condition expression after '$if'");{let u=U(l,t);(u.type===p.FUNCTION||u.type===p.CONDITIONAL||u.type===p.PARTIAL||u.type===p.OBJECT&&!u.fast||u.type===p.ARRAY&&!u.fast)&&(r=!0);let f=lt(c,t),d={key:c,value:u};(f.type!==p.LITERAL||f.value!==c)&&(d.parsedKey=f),n.push(d),s++}}}let a={type:p.OBJECT,properties:n,fast:!r};return o&&(a.whenCondition=o),a},Hr=(e,t,n={})=>{let r=[],o=[],i=t,[s,a]=e[i],c=null,l;if(s.startsWith("$if#")){let f=s.match(/^\$if#(\w+)\s+(.+)$/);if(f)c=f[1],l=f[2];else throw new E(`Invalid conditional syntax: ${s}`)}else l=s.substring(4),l.endsWith(":")&&(l=l.slice(0,-1).trim());it(l);let u=R(l,n);for(r.push(u),o.push(U(a,n)),i++;i<e.length;){let[f,d]=e[i],h=!1,g;if(c?f.startsWith(`$elif#${c} `)?(g=f.substring(`$elif#${c} `.length),g.endsWith(":")&&(g=g.slice(0,-1).trim()),h=!0):(f===`$else#${c}`||f===`$else#${c}:`)&&(h=!0,g=null):f.startsWith("$elif ")?(g=f.substring(6),g.endsWith(":")&&(g=g.slice(0,-1).trim()),h=!0):(f==="$else"||f==="$else:")&&(h=!0,g=null),h){if(g===null)r.push(null);else{it(g);let m=R(g,n);r.push(m)}if(o.push(U(d,n)),i++,g===null)break}else break}return{node:{type:p.CONDITIONAL,conditions:r,bodies:o,id:c},nextIndex:i}},R=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let l=e.slice(1,-1),u=0,f=!0;for(let d=0;d<l.length;d++)if(l[d]==="("?u++:l[d]===")"&&u--,u<0){f=!1;break}if(f&&u===0)return R(l,t)}let n=J(e,"||");if(n!==-1)return{type:p.BINARY,op:L.OR,left:R(e.substring(0,n).trim(),t),right:R(e.substring(n+2).trim(),t)};let r=J(e,"&&");if(r!==-1)return{type:p.BINARY,op:L.AND,left:R(e.substring(0,r).trim(),t),right:R(e.substring(r+2).trim(),t)};let o=[{op:">=",type:L.GTE},{op:"<=",type:L.LTE},{op:"==",type:L.EQ},{op:"!=",type:L.NEQ},{op:">",type:L.GT},{op:"<",type:L.LT},{op:" in ",type:L.IN}];for(let{op:l,type:u}of o){let f=J(e,l);if(f!==-1)return{type:p.BINARY,op:u,left:R(e.substring(0,f).trim(),t),right:R(e.substring(f+l.length).trim(),t)}}let i=-1,s=null,a=[{op:" + ",type:L.ADD},{op:" - ",type:L.SUBTRACT}];for(let{op:l,type:u}of a){let f=0;for(;f<e.length;){let d=J(e.substring(f),l);if(d===-1)break;let h=f+d;h>i&&(i=h,s={op:l,type:u}),f=h+l.length}}if(i!==-1&&s)return{type:p.BINARY,op:s.type,left:R(e.substring(0,i).trim(),t),right:R(e.substring(i+s.op.length).trim(),t)};let c=[" * "," / "," % "];for(let l of c)if(J(e,l)!==-1)throw new E(`Arithmetic operations are not allowed in conditionals: "${l}"`);return e.startsWith("!")?{type:p.UNARY,op:he.NOT,operand:R(e.substring(1).trim(),t)}:pn(e,t)},J=(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},Kr=e=>{if(e=e.trim(),e==="true")return{type:p.LITERAL,value:!0};if(e==="false")return{type:p.LITERAL,value:!1};if(e==="null")return{type:p.LITERAL,value:null};if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:p.LITERAL,value:e.slice(1,-1)};if(e==='""'||e==="''")return{type:p.LITERAL,value:""};if(e==="{}")return{type:p.LITERAL,value:{}};if(e==="[]")return{type:p.LITERAL,value:[]};let t=Number(e);return!isNaN(t)&&isFinite(t)?{type:p.LITERAL,value:t}:{type:p.VARIABLE,path:e}},pn=(e,t)=>{let n=e.trim();if(n.match(/^(\w+)\((.*)\)$/))return ge(n,t);let o=Kr(n);if(o.type===p.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(n))return{type:p.VARIABLE,path:n};try{return ge(n,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},qr=(e,t=!1)=>{let n=t?"$each":"$for";try{en(e)}catch(r){if(r instanceof E&&t){let o=r.message.replace(/\$for/g,"$each");throw new E(o.replace("Parse Error: ",""))}throw r}},dn=(e,t,n,r=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let y=r?"$each":"$for";throw new E(`Invalid loop syntax (got: '${e.replace("$for",y)}')`)}let s=i[1],a=i[2].trim();qr(a,r);let c=a.match(/^(.+?)\s+in\s+(.+)$/);if(!c){let y=r?"$each":"$for";throw new E(`Invalid loop syntax - missing 'in' keyword (got: '${y} ${a}')`)}let l=c[1].trim(),u=c[2].trim(),f,d=null;if(l.includes(",")){let y=l.split(",").map(I=>I.trim());if(y.length!==2)throw new E(`Invalid loop variables: ${l}. Expected format: "item" or "item, index"`);f=y[0],d=y[1]}else f=l;let h=["this","undefined","null","true","false"];if(h.includes(f))throw new E(`Reserved variable name: ${f}`);if(d&&h.includes(d))throw new E(`Reserved variable name: ${d}`);let g=pn(u,n),m=U(t,n);return{type:p.LOOP,itemVar:f,indexVar:d,iterable:g,body:m,flatten:s!=="nested"}};var Jr=(e,t={})=>{let{functions:n={}}=t;return U(e,n)},Le=Jr;var ct={};fr(ct,{now:()=>Xr});var Xr=()=>Date.now();var Gr=(e,t,n={})=>{let{functions:r={},partials:o={}}=n,i={...ct,...r},s=Le(e,{functions:i}),a={};for(let[c,l]of Object.entries(o))a[c]=Le(l,{functions:i});return st(s,t,{functions:i,partials:a})},N=Gr;var hn=(e,t,n={})=>{let r=structuredClone(e),o={},i={},{transformSelectorFirstArgument:s=c=>c,transformActionFirstArgument:a=c=>c}=n;for(let[c,l]of Object.entries(t))c!=="createInitialState"&&(c.startsWith("select")?o[c]=(...u)=>l(s(r),...u):i[c]=(...u)=>{r=ot(r,d=>l(a(d),...u))});return{...o,...i}},Se=(e,t)=>n=>{let r=e(),o=Array.isArray(n)?n:[n];return ot(r,i=>{o.forEach(s=>{t.forEach(a=>{a(i,s)})})})};var Zr=(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{}}},ft=e=>{let t={},n={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([r,o])=>{let i=Zr(o,r);o.scope==="context"?t[r]=i:n[r]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}},ke=(e,t)=>{let n=["context","global-device","global-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(", ")}`)},Re=(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(", ")}`)},Oe=(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}`)}},dt=(e,t,n)=>Object.fromEntries(Object.entries(e).filter(([r])=>t?.[r]?.scope===n)),gn=(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()))},Qr=(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},pt=(e={},t={})=>{let n={},r=["sfx","voice"],o=s=>{let a=e[s],c=t[s];c&&!a?n[s]={changeType:"add",data:c}:a&&!c?r.includes(s)||(n[s]={changeType:"delete",data:a}):a&&c&&JSON.stringify(a)!==JSON.stringify(c)&&(n[s]={changeType:"update",data:c})};o("background"),o("bgm"),o("voice");let i=Qr(e.dialogue,t.dialogue);return i&&(n.dialogue=i),o("choice"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),n},ht=(e={})=>{let t=structuredClone(e),n=o=>{t[o]&&(delete t[o].animations,Object.keys(t[o]).length===0&&delete t[o])};n("background"),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 c={...a};return delete c.animations,i(c)?c:null}).filter(Boolean),t[o].items.length===0&&delete t[o])};return r("character",o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId),r("visual",o=>o.resourceId||o.transformId),t},eo=(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},to=(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=eo(t,n);if(r===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return r},no={updateProjectData:new Set(["projectData"]),showConfirmDialog:new Set(["confirmActions","cancelActions"])},yn=(e,t)=>{let n=e[e.length-1];return n?no[n]?.has(t)===!0:!1},at=(e,t,n=[])=>Array.isArray(e)?e.map(r=>at(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,yn(n,r)?o:at(o,t,[...n,r])])):to(e,t),ut=(e,t,n=[])=>Array.isArray(e)?e.map(r=>ut(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,yn(n,r)?o:ut(o,t,[...n,r])])):typeof e=="string"?N(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=at(e,t._event);return ut(n,t)};var Te=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:structuredClone(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},bn=(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}},ro=()=>({}),oo=(e,t)=>{if(t.background){let{animationsOnly:n,state:r}=Te(t.background,o=>!!o.resourceId);if(n){e.background=r;return}if(!t.background.resourceId){delete e.background;return}e.background=structuredClone(t.background)}else e.background?.animations&&(e.background.animations={})},io=(e,t)=>{if(!t.dialogue){e.dialogue&&e.dialogue.mode==="adv"&&(e.dialogue.content=void 0,e.dialogue.characterId=void 0);return}if(e.dialogue||(e.dialogue={}),t.dialogue.ui){let{animationsOnly:n,state:r}=Te(t.dialogue.ui,o=>!!o.resourceId);n?e.dialogue.ui={...e.dialogue.ui,...r}:e.dialogue.ui={...t.dialogue.ui}}else e.dialogue?.ui?.animations&&(e.dialogue.ui.animations={});if(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),delete e.dialogue.characterId,t.dialogue.characterId&&(e.dialogue.characterId=t.dialogue.characterId),t.dialogue.character?e.dialogue.character={...t.dialogue.character}:delete e.dialogue.character,t.dialogue.clear){delete e.dialogue;return}t.dialogue?.clearPage&&e.dialogue?.mode==="nvl"&&(e.dialogue.lines=[]),e.dialogue?.mode==="nvl"&&t.dialogue.content!==void 0&&e.dialogue.lines.push({content:t.dialogue.content,characterId:t.dialogue.characterId||null})},so=(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},lo=(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}}},co=(e,t)=>{if(t.visual){let{hasValidItems:n,processedItems:r}=bn(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))},ao=(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}=bn(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId);n?e.character={items:r}:delete e.character},uo=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},fo=(e,t)=>{if(t.layout){let{animationsOnly:n,state:r}=Te(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},po=(e,t)=>{if(t.choice){let{animationsOnly:n,state:r}=Te(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},ho=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},go=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},yo=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(n=>{delete e[n]})},ye=e=>Se(ro,[yo,oo,so,lo,co,io,ao,uo,fo,po,ho,go])(e);var Z={objectValues:e=>Object.entries(e).map(([t,n])=>({id:t,...n})),formatDate:gn},mo=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,bo=(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},Ne=(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=mo.exec(s);if(a){let[,c,l,u]=a,f=bo(t,u);if(!Array.isArray(f))continue;let d=Array.isArray(i[s])?i[s]:[];f.forEach((h,g)=>{let m={...t,[c]:h};l&&(m[l]=g),d.forEach(y=>{let I=Ne(y,m,n),A=N(I,m,n);Array.isArray(A)?o.push(...A):o.push(A)})});continue}}o.push(Ne(i,t,n))}return o}if(!e||typeof e!="object")return e;let r={};return Object.entries(e).forEach(([o,i])=>{r[o]=Ne(i,t,n)}),r},$n={live:"update",replace:"transition"},Ln=e=>{let t=structuredClone(e);return typeof t.type=="string"&&(t.type=$n[t.type]||t.type),t},Io=({id:e,targetId:t,animation:n})=>{let r=Ln(n);return delete r.name,r.id=e,r.targetId=t,r},gt=e=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return $n[e.type]||e.type},Pe=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},Ao=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),X=({animations:e,resources:t,animationId:n,instanceId:r,targetId:o})=>{if(!n||!o)return!1;let i=t?.animations?.[n];return i?(e.push(Io({id:r,targetId:o,animation:i})),!0):!1},xo=({hasPrevious:e,hasCurrent:t,previousResourceId:n,currentResourceId:r,sharedTarget:o})=>!e&&t?"enter":e&&!t?"exit":e&&t?n===r&&o?"update":"replace":"none",yt=({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.`)},wo=(e,{defaultTargetId:t,defaultId:n}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let r=Ln(e);return r.id??=n,r.targetId??=t,r},vt=({animations:e,transitions:t,defaultTargetId:n,idPrefix:r})=>{t.forEach((o,i)=>{e.push(wo(o,{defaultTargetId:n,defaultId:`${r}-transition-${i}`}))})},In=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let n=N(e,t);return n&&typeof n=="object"?e:n},An=(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},xn=(e,t=0)=>{let n=e?.sprites?.map(({resourceId:r})=>r)||[];return n.length===0?`character-container-${e.id}`:`character-container-${e.id}-${t}-${n.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},vo=(e={})=>e.textStyles||{},Eo=(e={})=>e.images||{},_o=(e={})=>e.colors||{},Co=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,me=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,ce=(e,t,n)=>{if(typeof e!="string"||e.length===0)throw new Error(`${n} at "${t}" must resolve to a non-empty string`)},wn=(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},Sn=(e,t)=>{if(typeof e!="string"||!Co.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},vn=(e,t,n)=>{let r=Sn(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})`},$o=(e={},t)=>{let n=vo(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=wn(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:vn(o.hex,i,`Color "${n.colorId}" for text style "${t}"`)};if(n.align!==void 0&&(s.align=n.align),n.wordWrap!==void 0&&(s.wordWrap=n.wordWrap),n.breakWords!==void 0&&(s.breakWords=n.breakWords),n.wordWrapWidth!==void 0&&(s.wordWrapWidth=n.wordWrapWidth),n.strokeColorId){let a=e.colors?.[n.strokeColorId];if(!a)throw new Error(`Stroke color "${n.strokeColorId}" not found for text style "${t}"`);let c=wn(n.strokeAlpha,"strokeAlpha",t);s.strokeColor=vn(a.hex,c,`Stroke color "${n.strokeColorId}" for text style "${t}"`)}else if(n.strokeAlpha!==void 0)throw new Error(`strokeAlpha for text style "${t}" requires strokeColorId`);return n.strokeWidth!==void 0&&(s.strokeWidth=n.strokeWidth),s},At=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>At(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]=At(i,t,me(n,o)));return e.textStyleId!==void 0&&(ce(e.textStyleId,n,"textStyleId"),r.textStyle=$o(t,e.textStyleId)),r},kn=(e={},t)=>{let n=_o(e)?.[t];if(!n)throw new Error(`Color "${t}" not found`);return Sn(n.hex,`Color "${t}"`)},Rn=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",bt=(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 ${Rn(`${t}.fill`)} instead`)},Lo=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>be(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]=be(i,t,me(n,o)));return e.colorId!==void 0&&(ce(e.colorId,n,"colorId"),r.fill=kn(t,e.colorId)),r},be=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>be(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 ${Rn("fill")} instead`);bt(e,"hover",n),bt(e,"click",n),bt(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]=Lo(i,t,me(n,o));continue}r[o]=be(i,t,me(n,o))}return e.type==="rect"&&e.colorId!==void 0&&(ce(e.colorId,n,"colorId"),r.fill=kn(t,e.colorId)),r},It=(e={},t)=>{let n=Eo(e)?.[t];return n||null},On=e=>e==="hoverUrl"||e==="hoverSrc"||e==="hover.src"?"hoverImageId":e==="clickUrl"||e==="clickSrc"||e==="click.src"?"clickImageId":"imageId",En=(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 ${On(`${t}.${r}`)} instead`)},_n=(e,t,n)=>{let r=e[t];e[t]={...r&&typeof r=="object"&&!Array.isArray(r)?r:{},src:n}},xt=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>xt(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 ${On(o)} instead`);En(e,"hover",n,"src"),En(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]=xt(i,t,me(n,o)));if(e.type==="sprite"&&e.imageId!==void 0){ce(e.imageId,n,"imageId");let o=It(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&&(ce(e.hoverImageId,n,"hoverImageId"),_n(r,"hover",It(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(ce(e.clickImageId,n,"clickImageId"),_n(r,"click",It(t,e.clickImageId)?.fileId??e.clickImageId)),r},Et=(e,t={},n="root")=>xt(be(At(e,t,n),t,n),t,n),Q=Et,De=(e=[])=>e.find(t=>t.id==="story"),ee=({variables:e,saveSlots:t=[],isLineCompleted:n,autoMode:r,skipMode:o,isChoiceVisible:i,canRollback:s,confirmDialog:a,historyDialogue:c=[],characters:l={}}={})=>({variables:e,saveSlots:t,isLineCompleted:n,autoMode:r,skipMode:o,isChoiceVisible:i,canRollback:s,confirmDialog:a,historyDialogue:c,characters:l,effectiveSoundVolume:e?._muteAll?0:e?._soundVolume??500,textSpeed:e?._textSpeed??50}),Cn=100,Ve=(e,t)=>{if(Array.isArray(e))return e.map(r=>Ve(r,t));if(!e||typeof e!="object")return e;let n={...e};return Object.keys(n).forEach(r=>{n[r]=Ve(n[r],t)}),n.type==="text-revealing"?t(n):n},So=e=>Ve(e,t=>({...t,revealEffect:"none"})),ko=e=>Ve(e,t=>{let n=Number(t.speed??t.displaySpeed),r=Number.isFinite(n)?Math.max(n,Cn):Cn;return{...t,speed:r,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:r}:{}}}),te=(e,{isLineCompleted:t=!1,skipMode:n=!1,skipTransitionsAndAnimations:r=!1}={})=>t||r?So(e):n?ko(e):e,Tn=({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}}:{}}}}},Pn=(e=[],t={})=>e.map(n=>{let r=t?.[n.characterId],o=typeof n.text=="string"?n.text:Array.isArray(n.content)?n.content.map(i=>i?.text??"").join(""):"";return{...n,text:o,characterName:r?.name||""}}),Nn=({container:e,resources:t,templateData:n,isLineCompleted:r=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=N(e,n,{functions:Z});return Q(te(s,{isLineCompleted:r,skipMode:o,skipTransitionsAndAnimations:i}),t)},Ro=(e={})=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,{payload:{actions:structuredClone(n?.actions||{})}}]))},G=({animations:e,animationsDef:t,resources:n,previousResourceId:r,currentResourceId:o,previousTargetId:i,currentTargetId:s,animationPath:a,idPrefix:c})=>{if(!t)return;let l=r!=null&&r!==!1,u=o!=null&&o!==!1,f=i&&s&&i===s,d=xo({hasPrevious:l,hasCurrent:u,previousResourceId:r,currentResourceId:o,sharedTarget:f});if(Ao(t)){if(t.in&&!l){let y=Pe(t.in);yt({animationType:gt(n?.animations?.[y]),animationId:y,animationPath:`${a}.in`,lifecycle:"enter"}),X({animations:e,resources:n,animationId:y,instanceId:`${c}-animation-in`,targetId:s})}if(t.out&&l&&r!==o){let y=Pe(t.out);yt({animationType:gt(n?.animations?.[y]),animationId:y,animationPath:`${a}.out`,lifecycle:"exit"}),X({animations:e,resources:n,animationId:y,instanceId:`${c}-animation-out`,targetId:i})}t.update&&l&&u&&r===o&&f&&X({animations:e,resources:n,animationId:Pe(t.update),instanceId:`${c}-animation-update`,targetId:s});return}let h=Pe(t),g=n?.animations?.[h],m=gt(g);if(yt({animationType:m,animationId:h,animationPath:a,lifecycle:d}),m==="update"){l&&u&&r===o&&f&&X({animations:e,resources:n,animationId:h,instanceId:`${c}-animation-update`,targetId:s});return}if(m==="transition"){if(l&&u&&f){X({animations:e,resources:n,animationId:h,instanceId:`${c}-animation-transition`,targetId:s});return}l&&X({animations:e,resources:n,animationId:h,instanceId:`${c}-animation-out`,targetId:i}),u&&X({animations:e,resources:n,animationId:h,instanceId:`${c}-animation-in`,targetId:s})}},Oo=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),To=(e,{presentationState:t,previousPresentationState:n,resources:r={},isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,autoMode:a,skipMode:c,isChoiceVisible:l,canRollback:u,saveSlots:f=[]})=>{let{elements:d,animations:h}=e;if(t.background){let g=d.find(m=>m.id==="story");if(!g)return e;if(t.background.resourceId){let{images:m={},videos:y={}}=r,I=m[t.background.resourceId]||y[t.background.resourceId];if(I){let A=y[t.background.resourceId]!==void 0,b={id:`bg-cg-${t.background.resourceId}`,type:A?"video":"sprite",x:0,y:0,src:I.fileId,width:I.width,height:I.height,alpha:1,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1};A&&(b.loop=t.background.loop??!1,b.volume=I.volume??500),g.children.push(b)}}if(t.background.resourceId){let{layouts:m={}}=r,y=m[t.background.resourceId];if(y){let I={id:`bg-cg-${t.background.resourceId}`,type:"container",children:y.elements},A=N(I,ee({variables:s,saveSlots:f,isLineCompleted:o,autoMode:a,skipMode:c,isChoiceVisible:l,canRollback:u}),{functions:Z});g.children.push(Q(te(A,{isLineCompleted:o,skipMode:c,skipTransitionsAndAnimations:i}),r))}}if(t.background.animations&&!o&&!i){let m=n?.background?.resourceId,y=t.background.resourceId;G({animations:h,animationsDef:t.background.animations,resources:r,previousResourceId:m,currentResourceId:y,previousTargetId:m?`bg-cg-${m}`:void 0,currentTargetId:y?`bg-cg-${y}`:void 0,animationPath:"background.animations",idPrefix:"bg-cg"})}}return e},Po=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i})=>{let{elements:s,animations:a}=e;if(t.character&&r){let c=s.find(f=>f.id==="story");if(!c)return e;let l=t.character.items||[],u=n?.character?.items||[];for(let f=0;f<l.length;f++){let d=l[f],{transformId:h,sprites:g}=d,m=u.find(_=>_.id===d.id),y=u.findIndex(_=>_.id===d.id),I=m?.sprites&&m.sprites.length>0,A=g&&g.length>0,b=y>=0?xn(m,y):void 0;if(d.animations&&!g&&!h&&I&&!o&&!i){G({animations:a,animationsDef:d.animations,resources:r,previousResourceId:b,currentResourceId:void 0,previousTargetId:b,currentTargetId:void 0,animationPath:`character.items[${f}].animations`,idPrefix:"character"});continue}if(d.animations&&!g&&!h)continue;if(!g||g.length===0||!h){console.warn("Character item missing sprites or transformId:",d);continue}let x=xn(d,f),w=r.transforms[h];if(!w){console.warn("Transform not found:",h);continue}let v={type:"container",id:x,x:d.x??w.x,y:d.y??w.y,anchorX:w.anchorX,anchorY:w.anchorY,rotation:w.rotation,scaleX:w.scaleX,scaleY:w.scaleY,children:[]};for(let _ of g){let C=r.images[_.resourceId];if(!C){console.warn(`Image resource not found: ${_.resourceId}`);continue}v.children.push({type:"sprite",id:`${x}-${_.id}`,src:C.fileId,width:C.width,height:C.height,x:0,y:0})}c.children.push(v),d.animations&&!o&&!i&&G({animations:a,animationsDef:d.animations,resources:r,previousResourceId:b,currentResourceId:x,previousTargetId:b,currentTargetId:x,animationPath:`character.items[${f}].animations`,idPrefix:"character"})}}return e},No=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,autoMode:a,skipMode:c,isChoiceVisible:l,canRollback:u,saveSlots:f=[]})=>{let{elements:d,animations:h}=e;if(t.visual&&r){let g=d.find(y=>y.id==="story");if(!g)return e;let m=t.visual.items;for(let y of m){if(y.resourceId){let{images:I={},videos:A={},spritesheets:b={}}=r,x=b[y.resourceId];if(x){let w=mt(r,y),v=y.animationName;if(v){let _=x.animations?.[v];if(!_)throw new Error(`Animation '${v}' not found in spritesheet resource '${y.resourceId}'`);let C={id:`visual-${y.id}`,type:"animated-sprite",x:y.x??w.x,y:y.y??w.y,width:y.width??x.width,height:y.height??x.height,alpha:y.alpha??1,anchorX:w.anchorX,anchorY:w.anchorY,rotation:w.rotation,scaleX:w.scaleX,scaleY:w.scaleY,spritesheetSrc:x.fileId,spritesheetData:x.jsonData,animation:{frames:_.frames,animationSpeed:y.animationSpeed??_.animationSpeed??.5,loop:y.loop??_.loop??!0}};g.children.push(structuredClone(C))}}else{let w=I[y.resourceId]||A[y.resourceId];if(w){let v=A[y.resourceId]!==void 0,_=mt(r,y),C={id:`visual-${y.id}`,type:v?"video":"sprite",src:w.fileId,width:w.width,height:w.height,x:_.x,y:_.y,anchorX:_.anchorX,anchorY:_.anchorY,rotation:_.rotation,scaleX:_.scaleX,scaleY:_.scaleY};v&&(C.loop=w.loop??!1,C.volume=w.volume??500),g.children.push(C)}}}if(y.resourceId){let{layouts:I={}}=r,A=I[y.resourceId];if(A){let b=mt(r,y),x={id:`visual-${y.id}`,type:"container",children:structuredClone(A.elements),x:b.x,y:b.y,anchorX:b.anchorX,anchorY:b.anchorY,rotation:b.rotation,scaleX:b.scaleX,scaleY:b.scaleY},w=N(x,ee({variables:s,saveSlots:f,isLineCompleted:o,autoMode:a,skipMode:c,isChoiceVisible:l,canRollback:u}),{functions:Z});g.children.push(Q(te(w,{isLineCompleted:o,skipMode:c,skipTransitionsAndAnimations:i}),r))}}if(y.animations&&!o&&!i){let A=(n?.visual?.items||[]).find(b=>b.id===y.id);G({animations:h,animationsDef:y.animations,resources:r,previousResourceId:A?.resourceId,currentResourceId:y.resourceId,previousTargetId:A?.resourceId?`visual-${y.id}`:void 0,currentTargetId:y.resourceId?`visual-${y.id}`:void 0,animationPath:`visual.items[${y.id}].animations`,idPrefix:y.id})}}}return e},Vo=(e,{presentationState:t,previousPresentationState:n,resources:r={},dialogueUIHidden:o,autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:c,skipOnlyViewedLines:l,isLineCompleted:u,skipTransitionsAndAnimations:f,variables:d,saveSlots:h=[]})=>{let{elements:g,animations:m}=e;if(!t.dialogue||o)return e;let y=g.find(I=>I.id==="story");if(!y)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:I={}}=r,A=I[t.dialogue.ui.resourceId];if(A){let b;t.dialogue.characterId&&(b=r.characters[t.dialogue.characterId]),t.dialogue.character&&(b={...b,name:t.dialogue.character.name});let x={elements:A.elements},w=t.dialogue?.content===void 0?[{text:""}]:An(t.dialogue.content,"dialogue.content"),v=(t.dialogue?.lines||[]).map((z,ar)=>({content:An(z.content,`dialogue.lines[${ar}].content`).map(Ft=>({...Ft,text:In(Ft.text,{variables:d})})),characterName:z.characterId&&r.characters?.[z.characterId]?.name||""})),_={variables:d,autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:c,skipOnlyViewedLines:l,isLineCompleted:u,saveSlots:h,effectiveSoundVolume:d?._muteAll?0:d?._soundVolume??500,textSpeed:d?._textSpeed??50,dialogueLines:v,dialogue:{character:{name:b?.name||""},content:w.map(z=>({...z,text:In(z.text,{variables:d})})),lines:v}},C={functions:Z},Y=Ne(x,_,C),He=N(Y,_,C),ie=Q(te(He?.elements,{isLineCompleted:u,skipMode:s,skipTransitionsAndAnimations:f}),r);if(Array.isArray(ie))for(let z of ie)y.children.push(z);else ie&&y.children.push(ie)}}return t.dialogue.ui?.animations&&!u&&!f&&G({animations:m,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"}),e},Do=(e,{presentationState:t,previousPresentationState:n,resources:r,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:a,autoMode:c,skipMode:l,isChoiceVisible:u,canRollback:f,saveSlots:d=[]})=>{let{elements:h,animations:g}=e;if(t.choice&&r){let m=De(h);if(!m)return e;let y=r?.layouts[t.choice.resourceId];if(y&&y.elements){let I={elements:y.elements},A=N(I,{...ee({variables:a,saveSlots:d,isLineCompleted:i,autoMode:c,skipMode:l,isChoiceVisible:u??!!t.choice,canRollback:f}),choice:{items:t.choice?.items??[]}},{functions:Z}),b=wt(Q(te(A?.elements,{isLineCompleted:i,skipMode:l,skipTransitionsAndAnimations:s}),r));if(Array.isArray(b))for(let x of b)m.children.push(x);else b&&m.children.push(b)}t.choice.animations&&!i&&!s&&G({animations:g,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"})}return e},Mo=(e,{presentationState:t,resources:n={},variables:r,isLineCompleted:o,autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:c,saveSlots:l=[],skipTransitionsAndAnimations:u})=>{if(!t.control?.resourceId)return e;let f=n.controls?.[t.control.resourceId];if(!f)return e;let d=Ro(f.keyboard);if(d&&Object.keys(d).length>0&&(e.global.keyboard=d),!Array.isArray(f.elements)||f.elements.length===0)return e;let h=De(e.elements);if(!h)return e;let g={id:`control-${t.control.resourceId}`,type:"container",x:0,y:0,children:f.elements};return h.children.push(Nn({container:g,resources:n,templateData:ee({variables:r,saveSlots:l,isLineCompleted:o,autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:c}),isLineCompleted:o,skipMode:s,skipTransitionsAndAnimations:u})),e},jo=(e,{presentationState:t,resources:n,variables:r})=>{let{elements:o,audio:i}=e;if(t.bgm&&n){if(!De(o))return e;let a=n.sounds[t.bgm.resourceId];if(!a)return e;let c=r?._muteAll?0:r?._musicVolume??500;i.push({id:"bgm",type:"sound",src:a.fileId,loop:t.bgm.loop??!0,volume:c,delay:t.bgm.delay??null})}return e},Bo=(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??500,delay:i.delay??s.delay??null})}}return e},zo=(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??500,loop:s??!1}),e},Fo=(e,{presentationState:t,previousPresentationState:n,resources:r={},variables:o,autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:c,saveSlots:l=[],isLineCompleted:u,skipTransitionsAndAnimations:f})=>{let{elements:d,animations:h}=e;if(t.layout){let g=De(d);if(!g)return e;let m=r.layouts[t.layout.resourceId];if(!m)return e;Array.isArray(m.transitions)&&!u&&!f&&vt({animations:h,transitions:m.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`});let y={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:m.elements||[]};g.children.push(Nn({container:y,resources:r,templateData:ee({variables:o,saveSlots:l,isLineCompleted:u,autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:c}),isLineCompleted:u,skipMode:s,skipTransitionsAndAnimations:f}))}if(t.layout?.animations&&!u&&!f){let g=n?.layout?.resourceId,m=t.layout?.resourceId;G({animations:h,animationsDef:t.layout.animations,resources:r,previousResourceId:g,currentResourceId:m,previousTargetId:g?`layout-${g}`:void 0,currentTargetId:m?`layout-${m}`:void 0,animationPath:"layout.animations",idPrefix:"layout"})}return e},Uo=(e,{resources:t={},variables:n,autoMode:r,skipMode:o,isChoiceVisible:i,canRollback:s,layeredViews:a=[],dialogueHistory:c=[],saveSlots:l=[],screen:u,isLineCompleted:f,skipTransitionsAndAnimations:d})=>{let{elements:h,animations:g}=e;return a&&a.length>0&&a.forEach((m,y)=>{let I=t.layouts[m.resourceId];if(!I){console.warn(`LayeredView layout not found: ${m.resourceId}`);return}Array.isArray(I.transitions)&&(d||vt({animations:g,transitions:I.transitions,defaultTargetId:`layeredView-${y}`,idPrefix:`layeredView-${y}`}));let A={id:`layeredView-${y}`,type:"container",x:0,y:0,children:[Tn({id:`layeredView-${y}-blocker`,screen:u}),...I.elements||[]]},b=Pn(c,t.characters),x=ee({variables:n,saveSlots:l,isLineCompleted:f,autoMode:r,skipMode:o,isChoiceVisible:i,canRollback:s,historyDialogue:b,characters:t.characters||{}}),w=N(A,x,{functions:Z}),[v,..._]=w.children||[],C=Q(te({...w,children:_},{isLineCompleted:f,skipMode:o,skipTransitionsAndAnimations:d}),t);h.push({...C,children:v?[v,...C.children||[]]:C.children})}),e},Wo=(e,{resources:t={},variables:n,saveSlots:r=[],autoMode:o,skipMode:i,isChoiceVisible:s,canRollback:a,confirmDialog:c,dialogueHistory:l=[],screen:u,isLineCompleted:f,skipTransitionsAndAnimations:d})=>{let{elements:h,animations:g}=e;if(!c?.resourceId)return e;let m=t.layouts?.[c.resourceId];if(!m)return console.warn(`ConfirmDialog layout not found: ${c.resourceId}`),e;Array.isArray(m.transitions)&&!d&&vt({animations:g,transitions:m.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog"});let y={id:"confirmDialog",type:"container",x:0,y:0,children:[Tn({id:"confirmDialog-blocker",screen:u}),...m.elements||[]]},I=Pn(l,t.characters),A=N(y,ee({variables:n,saveSlots:r,isLineCompleted:f,autoMode:o,skipMode:i,isChoiceVisible:s,canRollback:a,confirmDialog:c,historyDialogue:I,characters:t.characters||{}}),{functions:Z}),[b,...x]=A.children||[],w=Q(te({...A,children:x},{isLineCompleted:f,skipMode:i,skipTransitionsAndAnimations:d}),t);return h.push({...w,children:b?[b,...w.children||[]]:w.children}),e},Vn=e=>Se(Oo,[Mo,To,Po,No,Vo,Do,Fo,jo,Bo,zo,Uo,Wo])(e);var Me={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},jn=1,ze=()=>({manual:{...Me.manual},auto:{...Me.auto},applyMode:Me.applyMode}),_t=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let n=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...ze()},n&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},D=e=>{let t=F(e)?rt(e):e;return structuredClone(t)},V=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Fe=e=>String(e),Ct=()=>({sections:[],resources:[]}),je=()=>({sectionId:void 0,lineId:void 0}),Yo=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",Ho=()=>({resourceId:void 0}),Ko=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},Bn=(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}},zn=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)}}},Fn=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},Un=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==jn)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},qo=(e,t={})=>{let n;try{n=Un(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let r={...t,formatVersion:n,slotId:Fn(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete r.slotKey,delete r.date,r},Jo=(e={})=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,qo(t,n)])),Dn=(e,t,n)=>{let r=t==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[r]:String(e)};if(!V(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}},Xo=e=>{if(e===void 0)return Ct();if(!V(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=Dn(r,"sections",o);return[i.sectionId,i]}))),resources:Object.values(Object.fromEntries(n.map((r,o)=>{let i=Dn(r,"resources",o);return[i.resourceId,i]})))}},$t=(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}=Bn(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}},Go=(e,t)=>{if(!V(e)||typeof e.sectionId!="string"||e.sectionId.length===0||typeof e.lineId!="string"||e.lineId.length===0)return je();try{let n=$t(e,t,"contexts[*].pointers.history");return{sectionId:n.sectionId,lineId:n.lineId}}catch{return je()}},Zo=(e,t,n)=>{if(!V(e)||!Array.isArray(e.timeline))return ae({pointer:t,replayStartIndex:1});let r=e.timeline.flatMap((a,c)=>{if(!V(a))return[];try{let l=$t(a,n,`rollback.timeline[${c}]`),u=Be({sectionId:l.sectionId,lineId:l.lineId,rollbackPolicy:a.rollbackPolicy});return Array.isArray(a.executedActions)&&(u.executedActions=D(a.executedActions)),[u]}catch{return[]}});if(r.length===0)return ae({pointer:t,replayStartIndex:1});let o=typeof e.currentIndex=="number"?Math.trunc(e.currentIndex):r.length-1;(o<0||o>=r.length)&&(o=r.length-1);let i=r[o];if(i?.sectionId!==t.sectionId||i?.lineId!==t.lineId){let a=r.findLastIndex(c=>c.sectionId===t.sectionId&&c.lineId===t.lineId);a>=0?o=a:(r.push(Be({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}},Qo=(e,t,n)=>{if(!V(e))throw new Error(`Malformed save slot contexts[${n}] entry.`);let r=kt(t),o=$t(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.`);let i=Go(e.pointers?.history,t);return{currentPointerMode:e.currentPointerMode==="history"&&i.lineId?"history":"read",pointers:{read:o,history:i},configuration:V(e.configuration)?D(e.configuration):{},views:Array.isArray(e.views)?D(e.views):[],bgm:V(e.bgm)?D(e.bgm):{resourceId:void 0},variables:{...r,...e.variables?D(e.variables):{}},rollback:Zo(e.rollback,o,t)}},ei=(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{viewedRegistry:Xo(e.viewedRegistry),contexts:e.contexts.map((n,r)=>Qo(n,t,r))}},ti=(e,t)=>{if(!V(e))throw new Error("Malformed save slot.");let n=Un(e.formatVersion);return{...e,formatVersion:n,state:ei(e.state,t)}},Mn=(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=D(e);return Object.prototype.hasOwnProperty.call(r,"hideConfirmDialog")||(r.hideConfirmDialog={}),r},ni=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:Mn(e.confirmActions,"confirmActions",{required:!0}),cancelActions:Mn(e.cancelActions,"cancelActions")}},ue=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},ne=[],Lt=()=>ne[ne.length-1]??null,St=e=>{let t=Lt();t&&(t.checkpointIndex=e)},ri=()=>{let e=Lt();e&&(e.pendingStorySessionReset=!0)},Wn=()=>{let e=Lt();return e?.pendingStorySessionReset?(delete e.pendingStorySessionReset,!0):!1},Be=({sectionId:e,lineId:t,rollbackPolicy:n})=>({sectionId:e,lineId:t,rollbackPolicy:n??"free"}),kt=e=>{let{contextVariableDefaultValues:t}=ft(e??{});return D(t)},Yn=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:D(e),history:je()},configuration:{},views:[],bgm:Ho(),variables:kt(t),rollback:ae({pointer:e})}),oi=e=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,ue(e),e.global.viewedRegistry=Ct(),e.global.nextLineConfig=ze(),e.global.layeredViews=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})},Hn=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},ae=({pointer:e,replayStartIndex:t=0})=>{let n=e?.sectionId&&e?.lineId;return{currentIndex:n?0:-1,isRestoring:!1,replayStartIndex:t,timeline:n?[Be({sectionId:e.sectionId,lineId:e.lineId})]:[]}},oe=(e,t={})=>{if(e?.rollback)return Hn(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=ae({pointer:n,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},Rt=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return;let r=oe(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(Be(t)),r.currentIndex=r.timeline.length-1},ii=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=ne[ne.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)},si=({state:e})=>{let n=e.contexts?.[e.contexts.length-1]?.rollback;return!n||n.isRestoring||!Array.isArray(n.timeline)||typeof n.currentIndex!="number"||n.currentIndex<0||n.currentIndex>=n.timeline.length?(ne.push({checkpointIndex:null}),e):(n.currentIndex<n.timeline.length-1&&(n.timeline=n.timeline.slice(0,n.currentIndex+1)),ne.push({checkpointIndex:n.currentIndex}),e)},li=({state:e})=>(ne.pop(),e),W=(e,t,n)=>{let r=ii(e);r&&(Array.isArray(r.executedActions)||(r.executedActions=[]),r.executedActions.push({type:t,payload:D(n)}))},ci=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return;let r=t?.operations??[];for(let{variableId:o,op:i,value:s}of r){let a=e.projectData.resources?.variables?.[o],c=a?.scope,l=a?.type;ke(c,o),Re(l,i,o),c==="context"&&(n.variables[o]=Oe(n.variables[o],i,s))}},ai=(e,t)=>{if(!Array.isArray(t?.executedActions))return!1;let n={showDialogueUI:fe,hideDialogueUI:We,toggleDialogueUI:Mt,setNextLineConfig:jt,pushLayeredView:Pt,popLayeredView:Nt,replaceLastLayeredView:Vt,clearLayeredViews:Dt};return t.executedActions.forEach(({type:r,payload:o})=>{if(r==="updateVariable"){ci(e,o);return}let i=n[r];i&&i({state:e},o)}),!0},ui=(e,t)=>{let{sectionId:n,lineId:r}=t,s=k({state:e},{sectionId:n})?.lines?.find(l=>l.id===r)?.actions?.updateVariable;if(!s)return;let a=e.contexts?.[e.contexts.length-1];if(!a)return;let c=s.operations||[];for(let{variableId:l,op:u,value:f}of c){let d=e.projectData.resources?.variables?.[l],h=d?.scope,g=d?.type;ke(h,l),Re(g,u,l),h==="context"&&(a.variables[l]=Oe(a.variables[l],u,f))}},fi=(e,t)=>{let{sectionId:n,lineId:r}=t,s=k({state:e},{sectionId:n})?.lines?.find(c=>c.id===r)?.actions;if(!s)return;let a={showDialogueUI:fe,hideDialogueUI:We,toggleDialogueUI:Mt,setNextLineConfig:jt,pushLayeredView:Pt,popLayeredView:Nt,replaceLastLayeredView:Vt,clearLayeredViews:Dt};Object.entries(s).forEach(([c,l])=>{let u=a[c];u&&u({state:e},l)})},Kn=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return e;let r=oe(n),o=r.timeline[t];if(!o)return e;e.global.autoMode&&Ae({state:e}),e.global.skipMode&&re({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),r.isRestoring=!0,r.currentIndex=t;try{n.variables=kt(e.projectData),e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=D(Me),e.global.layeredViews=[],ue(e),e.global.isLineCompleted=!0;let i=r.replayStartIndex??0;for(let s=i;s<=t;s++)s>i&&_t(e),ai(e,r.timeline[s])||(ui(e,r.timeline[s]),fi(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},di=e=>{let{projectData:t}=e,n=e.global??{},{saveSlots:r={},variables:o={}}=n;zn(t);let i=t.story.initialSceneId,s=t.story.scenes[i],a=s.initialSectionId,c=s.sections[a],l={sceneId:i,sectionId:a,lineId:c.initialLineId??c.lines[0].id},{globalVariablesDefaultValues:u}=ft(t),f={...u,...o};return{projectData:t,global:{isLineCompleted:!1,pendingEffects:[],autoMode:!1,skipMode:!1,dialogueUIHidden:!1,confirmDialog:null,viewedRegistry:Ct(),nextLineConfig:ze(),saveSlots:Jo(r),layeredViews:[],variables:f},contexts:[Yn({pointer:l,projectData:t})]}},pi=({state:e})=>e.global.layeredViews||[],hi=({state:e})=>e.global.pendingEffects,qn=({state:e})=>e.global.skipMode,gi=({state:e})=>e.global.autoMode,Jn=({state:e})=>e.global.dialogueUIHidden,Xn=({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=k({state:e},{sectionId:r});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(l=>l.id===o);return i.lines.slice(0,s+1).filter(l=>l.actions?.dialogue).map(l=>{let u=l.actions.dialogue,f="";return u.characterId&&(f=e.projectData.resources?.characters?.[u.characterId]?.name||""),{sectionId:r,lineId:l.id,content:u.content,text:Yo(u.content),characterId:u.characterId,characterName:f}})},yi=({state:e})=>e.global.confirmDialog??null,Ot=({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=k({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),a=i.lines.findIndex(c=>c.id===r);return s===-1||a===-1?o.lastLineId===r:a<=s},mi=({state:e},t)=>{let{resourceId:n}=t;return!!e.global.viewedRegistry.resources.find(o=>o.resourceId===n)},bi=({state:e})=>e.global.nextLineConfig,Gn=({state:e,pointer:t}={})=>{let n=t??j({state:e})?.pointer;if(!n)return;let r=n?.sectionId,o=n?.lineId,s=k({state:e},{sectionId:r})?.lines||[],a=s.findIndex(l=>l.id===o);if(a<0)return;let c;for(let l of s.slice(0,a+1)){let u=l?.actions;if(u?.cleanAll&&(c=void 0),!u||!Object.prototype.hasOwnProperty.call(u,"choice")){c=void 0;continue}let f=u.choice;if(f?.resourceId){c=f.resourceId;continue}f?.animations||(c=void 0)}return c},B=({state:e})=>!!Gn({state:e}),Ii=({state:e})=>structuredClone(e),Zn=({state:e})=>e.global.saveSlots,Ai=({state:e},t)=>{let n=t?.slotId,r=Fe(n);return e.global.saveSlots[r]},xi=({state:e})=>({...e.global?.variables??{},...e.contexts?.[e.contexts.length-1]?.variables??{}}),j=({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}},k=({state:e},t)=>{let{sectionId:n}=t;return Bn(e.projectData,n).section},Qn=({state:e})=>{let t=j({state:e});if(!t?.pointer)return;let{sectionId:n,lineId:r}=t.pointer,o=k({state:e},{sectionId:n});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===r)},er=({state:e})=>{let{sectionId:t,lineId:n}=j({state:e}).pointer,o=k({state:e},{sectionId:t})?.lines||[],i=o.findIndex(l=>l.id===n),a=o.slice(0,i+1).map(l=>{let u=l.actions||{},f={};return Object.keys(u).forEach(d=>{f[d]=u[d]}),f});return ye(a)},wi=({state:e})=>{let t=tr({state:e}),r=Qn({state:e})?.actions??{},o=ye([t??{},r]);return pt(t??{},o??{})},vi=({state:e},{sectionId:t})=>{let n=k({state:e},{sectionId:t});if(!n?.lines)return{lines:[]};let r=[],o={};for(let i of n.lines){let s=i.actions||{},a=ye([o,s]),c=pt(o,a);r.push({id:i.id,changes:c}),o=ht(a)}return{lines:r}},tr=({state:e})=>{let{sectionId:t,lineId:n}=j({state:e}).pointer,o=k({state:e},{sectionId:t})?.lines||[],i=o.findIndex(c=>c.id===n);if(i<=0)return null;let a=o.slice(0,i).map(c=>{let l=c.actions||{},u={};return Object.keys(l).forEach(f=>{u[f]=l[f]}),u});return ht(ye(a))},Tt=({state:e},{slotsPerPage:t=6}={})=>{let o=(({...e.global.variables,...e.contexts[e.contexts.length-1].variables}.loadPage??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let a=o+s,c=e.global.saveSlots&&e.global.saveSlots[Fe(a)]||{};i.push({...c,slotId:a})}return{saveSlots:i}},Ei=Zn,_i=Tt,Ci=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},$i=({state:e})=>{let t=er({state:e}),n=tr({state:e}),r={...e.global.variables,...e.contexts[e.contexts.length-1].variables},{saveSlots:o}=Tt({state:e}),i=Ci(e);return Vn({presentationState:t,previousPresentationState:n,resources:e.projectData.resources,screen:e.projectData.screen,dialogueUIHidden:e.global.dialogueUIHidden,autoMode:e.global.autoMode,skipMode:e.global.skipMode,isChoiceVisible:B({state:e}),canRollback:ir({state:e}),skipOnlyViewedLines:!r._skipUnseenText,isLineCompleted:e.global.isLineCompleted,skipTransitionsAndAnimations:!!r._skipTransitionsAndAnimations||i,layeredViews:e.global.layeredViews,confirmDialog:e.global.confirmDialog,dialogueHistory:Xn({state:e}),saveSlots:o,variables:r})},Li=({state:e},t)=>(e.global.confirmDialog=ni(t),e.global.pendingEffects.push({name:"render"}),e),Si=({state:e})=>(e.global.confirmDialog&&(ue(e),e.global.pendingEffects.push({name:"render"})),e),Pt=({state:e},t)=>(e.global.layeredViews.push(t),e.global.pendingEffects.push({name:"render"}),W(e,"pushLayeredView",t),e),Nt=({state:e})=>(e.global.layeredViews.pop(),e.global.pendingEffects.push({name:"render"}),W(e,"popLayeredView",void 0),e),Vt=({state:e},t)=>(e.global.layeredViews.length>0&&(e.global.layeredViews[e.global.layeredViews.length-1]=t),e.global.pendingEffects.push({name:"render"}),W(e,"replaceLastLayeredView",t),e),Dt=({state:e})=>(e.global.layeredViews=[],ue(e),e.global.pendingEffects.push({name:"render"}),W(e,"clearLayeredViews",void 0),e),ki=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"})},Ue=(e,t)=>{e.global.isLineCompleted=!1;let n=!!Gn({state:e,pointer:t});return n&&ki(e),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:n}},nr=({state:e})=>{if(B({state:e}))return e;if(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){let t=e.global.variables._autoForwardTime??1e3;e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:t}})}return e.global.pendingEffects.push({name:"render"}),e},Ae=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Ri=({state:e})=>{let t=e.global.autoMode;return B({state:e})&&!t||(t?Ae({state:e}):nr({state:e})),e},rr=({state:e})=>(B({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),re=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Oi=({state:e})=>{let t=qn({state:e});return B({state:e})&&!t||(t?re({state:e}):rr({state:e})),e},fe=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),W(e,"showDialogueUI",void 0),e),We=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),W(e,"hideDialogueUI",void 0),e),Mt=({state:e})=>(Jn({state:e})?fe({state:e}):We({state:e}),e),Ti=({state:e})=>(e.global.pendingEffects=[],e),Pi=({state:e},t)=>(e.global.pendingEffects.push(t),e),Ni=({state:e})=>{let t=e.contexts?.[e.contexts.length-1],n=t?.pointers?.read;return!t||!n?.sectionId||!n?.lineId||(e.contexts[e.contexts.length-1]=Yn({pointer:n,projectData:e.projectData}),oi(e),ri(),St(0)),e},Ie=(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=k({state:e},{sectionId:t});if(o?.lines&&r.lastLineId!==void 0){let i=o.lines.findIndex(a=>a.id===r.lastLineId),s=o.lines.findIndex(a=>a.id===n);(i===-1||s>i)&&(r.lastLineId=n)}else r.lastLineId=n}else e.global.viewedRegistry.sections.push({sectionId:t,lastLineId:n})},Vi=({state:e},t)=>(Ie(e,t),e.global.pendingEffects.push({name:"render"}),e),Di=({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},jt=({state:e},t)=>{let n=Ko(t.manual),{auto:r,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,s=e.global.nextLineConfig?.applyMode,a=e.contexts?.[e.contexts.length-1]?.rollback?.isRestoring===!0;n&&r?(e.global.nextLineConfig={manual:n,auto:r},o!==void 0?e.global.nextLineConfig.applyMode=o:s!==void 0&&(e.global.nextLineConfig.applyMode=s)):(n&&(e.global.nextLineConfig.manual=n),r&&(e.global.nextLineConfig.auto=r),o!==void 0&&(e.global.nextLineConfig.applyMode=o));let c=e.global.nextLineConfig.auto?.enabled,l=B({state:e});return!a&&!l&&c===!0&&!i?e.global.nextLineConfig.auto?.trigger==="fromStart"?e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):e.global.isLineCompleted&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):!a&&c===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),W(e,"setNextLineConfig",t),e},Mi=({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=Fe(n),s=D(e.contexts);s?.forEach(l=>{Hn(l.rollback)});let a={contexts:s,viewedRegistry:D(e.global.viewedRegistry)},c={formatVersion:jn,slotId:Fn(n),savedAt:typeof o=="number"?o:Date.now(),image:r,state:a};return e.global.saveSlots[i]=c,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},ji=({state:e},t)=>{let n=t?.slotId;if(n==null||n==="")throw new Error("loadSlot requires slotId");let r=Fe(n),o=e.global.saveSlots[r];if(o){let i=ti(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=ze(),e.global.layeredViews=[],e.global.isLineCompleted=!0,ue(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},Bi=({state:e},t)=>{let{projectData:n}=t;return zn(n),e.projectData=n,ue(e),e.global.pendingEffects.push({name:"render"}),e},zi=({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&&!k({state:e},{sectionId:n}))return console.warn(`Section not found: ${n}`),e;let s=k({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},Wn()&&(o.rollback=ae({pointer:o.pointers.read}),St(o.rollback.currentIndex)),Ue(e,o.pointers.read),e):(console.warn(`Line not found: ${r} in section ${i}`),e)},Fi=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return fe({state:e}),e;if(B({state:e})&&t?._interactionSource!=="choice")return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0;let l=j({state:e})?.pointer,u=l?.sectionId,f=l?.lineId;if(u&&f&&Ie(e,{sectionId:u,lineId:f}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode){let h=e.global.variables._autoForwardTime??1e3;e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:h}})}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=j({state:e})?.pointer,r=n?.sectionId,o=k({state:e},{sectionId:r}),i=e.contexts[e.contexts.length-1],s=o?.lines||[],c=s.findIndex(l=>l.id===n?.lineId)+1;if(c<s.length){let l=s[c],u=!e.global.variables?._skipUnseenText;if(e.global.skipMode&&u&&!Ot({state:e},{sectionId:r,lineId:l.id}))return re({state:e}),e;if(i&&!i.rollback&&oe(i,{compatibilityAnchor:!0}),i){let h=i.pointers.read.lineId;h&&r&&Ie(e,{sectionId:r,lineId:h}),i.pointers.read={sectionId:r,lineId:l.id}}Rt(e,{sectionId:r,lineId:l.id}),_t(e);let{isChoiceVisible:f}=Ue(e,{sectionId:r,lineId:l.id}),d=e.global.nextLineConfig;d?.auto?.enabled&&!f&&d.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:d.auto.delay}})}else e.global.autoMode&&Ae({state:e}),e.global.skipMode&&re({state:e});return e},Ui=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0;let t=B({state:e});if(e.global.autoMode&&!t){let s=e.global.variables._autoForwardTime??1e3;e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:s}})}let n=j({state:e})?.pointer,r=n?.sectionId,o=n?.lineId;r&&o&&Ie(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},Wi=({state:e},t)=>{let n=t?.sectionId??j({state:e})?.pointer?.sectionId,r=k({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.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(l=>l.id===i.pointers.history.lineId)-1;if(c>=0&&c<o.length){let l=o[c];i.pointers.history={sectionId:n,lineId:l.id},e.global.pendingEffects.push({name:"render"})}return e},Yi=({state:e},t)=>{let{sectionId:n}=t,r=k({state:e},{sectionId:n});if(!r)return console.warn(`Section not found: ${n}`),e;let o=r.lines?.[0];if(!o)return console.warn(`Section ${n} has no lines`),e;e.global.autoMode&&Ae({state:e}),e.global.skipMode&&re({state:e});let i=e.contexts[e.contexts.length-1];return i&&(i.rollback||oe(i,{compatibilityAnchor:!0}),i.pointers.read={sectionId:n,lineId:o.id},Wn()?(i.rollback=ae({pointer:i.pointers.read}),St(i.rollback.currentIndex)):Rt(e,{sectionId:n,lineId:o.id})),Ue(e,i?.pointers?.read),e},Hi=({state:e})=>{if(e.global.dialogueUIHidden)return fe({state:e}),e;if(B({state:e}))return e;let t=j({state:e})?.pointer,n=t?.sectionId,r=k({state:e},{sectionId:n}),o=e.contexts[e.contexts.length-1],i=r?.lines||[],a=i.findIndex(c=>c.id===t?.lineId)+1;if(a<i.length){let c=i[a],l=!e.global.variables?._skipUnseenText;if(e.global.skipMode&&l&&!Ot({state:e},{sectionId:n,lineId:c.id}))return re({state:e}),e;if(o&&!o.rollback&&oe(o,{compatibilityAnchor:!0}),o){let f=o.pointers.read.lineId;f&&n&&Ie(e,{sectionId:n,lineId:f}),o.pointers.read={sectionId:n,lineId:c.id}}Rt(e,{sectionId:n,lineId:c.id}),_t(e);let{isChoiceVisible:u}=Ue(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},Ki=({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,a=!1,c=[];if(r.forEach(({variableId:l,op:u,value:f})=>{let d=e.projectData.resources?.variables?.[l],h=d?.scope,g=d?.type;ke(h,l),Re(g,u,l);let m=h==="context"?o.variables:e.global.variables;h==="context"?(i=!0,c.push({variableId:l,op:u,value:f})):h==="global-device"?s=!0:h==="global-account"&&(a=!0),m[l]=Oe(m[l],u,f)}),i&&W(e,"updateVariable",{id:n,operations:c}),s){let l=dt(e.global.variables,e.projectData.resources?.variables,"global-device");e.global.pendingEffects.push({name:"saveGlobalDeviceVariables",payload:{globalDeviceVariables:l}})}if(a){let l=dt(e.global.variables,e.projectData.resources?.variables,"global-account");e.global.pendingEffects.push({name:"saveGlobalAccountVariables",payload:{globalAccountVariables:l}})}return e.global.pendingEffects.push({name:"render"}),e},or=({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}},ir=({state:e})=>or({state:e},{offset:-1})!==null,qi=({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=oe(r,{compatibilityAnchor:!r.rollback}),i=o.currentIndex+n;return i<0||i>=o.timeline.length?e:Kn(e,i)},Ji=({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=oe(o,{compatibilityAnchor:!o.rollback}),a=i.timeline.slice(0,i.currentIndex+1).findLastIndex(c=>c.sectionId===n&&c.lineId===r);if(a===-1)throw new Error(`Line ${r} not found in section ${n} rollback timeline`);return a===i.currentIndex?e:Kn(e,a)},sr=e=>{let t=di(e);return hn(t,{selectPendingEffects:hi,selectSkipMode:qn,selectAutoMode:gi,selectIsChoiceVisible:B,selectDialogueUIHidden:Jn,selectDialogueHistory:Xn,selectConfirmDialog:yi,selectIsLineViewed:Ot,selectIsResourceViewed:mi,selectNextLineConfig:bi,selectSystemState:Ii,selectSaveSlotMap:Zn,selectSaveSlots:Ei,selectSaveSlot:Ai,selectAllVariables:xi,selectCurrentPointer:j,selectSection:k,selectCurrentLine:Qn,selectPresentationState:er,selectPresentationChanges:wi,selectSectionLineChanges:vi,selectSaveSlotPage:Tt,selectCurrentPageSlots:_i,selectRenderState:$i,selectLayeredViews:pi,selectLineIdByOffset:or,selectCanRollback:ir,startAutoMode:nr,stopAutoMode:Ae,toggleAutoMode:Ri,startSkipMode:rr,stopSkipMode:re,toggleSkipMode:Oi,showDialogueUI:fe,hideDialogueUI:We,toggleDialogueUI:Mt,showConfirmDialog:Li,hideConfirmDialog:Si,resetStorySession:Ni,clearPendingEffects:Ti,appendPendingEffect:Pi,beginRollbackActionBatch:si,endRollbackActionBatch:li,addViewedLine:Vi,addViewedResource:Di,setNextLineConfig:jt,saveSlot:Mi,loadSlot:ji,updateProjectData:Bi,sectionTransition:Yi,jumpToLine:zi,nextLine:Fi,markLineCompleted:Ui,prevLine:Wi,rollbackToLine:Ji,rollbackByOffset:qi,pushLayeredView:Pt,popLayeredView:Nt,replaceLastLayeredView:Vt,clearLayeredViews:Dt,updateVariable:Ki,nextLineFromSystem:Hi},{transformActionFirstArgument:r=>({state:r}),transformSelectorFirstArgument:r=>({state:r})})};function Bt(e){let t,n=0,{handlePendingEffects:r}=e,o=()=>{for(;t.selectPendingEffects().length>0;){let v=[...t.selectPendingEffects()];t.clearPendingEffects();try{r(v)}catch(_){throw t.clearPendingEffects(),v.forEach(C=>{t.appendPendingEffect(C)}),_}}},i=({initialState:v})=>{t=sr(v),n=0,t.appendPendingEffect({name:"handleLineActions"}),o()},s=()=>t.selectPresentationState(),a=()=>t.selectPresentationChanges(),c=v=>t.selectSectionLineChanges(v),l=()=>(n+=1,{...t.selectRenderState(),id:`render-${n}`}),u=()=>t.selectSystemState(),f=()=>t.selectSaveSlotMap(),d=v=>t.selectSaveSlot(v),h=v=>t.selectSaveSlotPage(v),g=()=>t.selectSkipMode(),m=()=>t.selectAutoMode(),y=()=>t.selectIsChoiceVisible(),I=(v,_)=>{t[v]&&(t[v](_),o())},A=(v,_)=>{I(v,_)},b=v=>{if(!v)return{variables:t.selectAllVariables?t.selectAllVariables():void 0};if(Object.prototype.hasOwnProperty.call(v,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:_,...C}=v,Y=t.selectAllVariables?t.selectAllVariables():void 0;return{...C,_event:_,variables:Y}},x=(v,_)=>{let C=b(_),Y=mn(v,C);t.beginRollbackActionBatch({});try{Object.entries(Y).forEach(([He,ie])=>{I(He,ie)})}finally{t.endRollbackActionBatch({})}};return{init:i,handleAction:I,handleInternalAction:A,handleActions:x,selectRenderState:l,selectPresentationState:s,selectPresentationChanges:a,selectSectionLineChanges:c,selectSystemState:u,selectSaveSlotMap:f,selectSaveSlot:d,selectSaveSlotPage:h,selectSaveSlots:f,selectIsChoiceVisible:y,handleLineActions:()=>{let v=t.selectCurrentLine();return v?.actions?(x(v.actions),!0):!1}}}var zt=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:n=>{e=n},addElapsed:n=>{e+=n},getCallback:()=>t,setCallback:n=>{t=n}}};var cr=({engine:e,routeGraphics:t,trackRenderDispatch:n},r)=>{let o=e.selectRenderState();n?.(o),t.render(o)},Xi=({engine:e,routeGraphics:t,trackRenderDispatch:n,getRenderDispatchCount:r},o)=>{let i=r?.()??0,s=e.handleLineActions();(r?.()??0)===i&&cr({engine:e,routeGraphics:t,trackRenderDispatch:n},o)},Gi=({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),Ye(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},Zi=({ticker:e,autoTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Qi=({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??80;n.getElapsed()>=a&&(n.setElapsed(0),Ye(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},es=({ticker:e,skipTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},ts=({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),Ye(e,"nextLineFromSystem",{}),t.remove(i),n.setCallback(null))};n.setCallback(i),t.add(i)},ns=({ticker:e,nextLineConfigTimerState:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},rs=({},e)=>{localStorage.setItem("saveSlots",JSON.stringify(e.saveSlots))},os=({},e)=>{localStorage.setItem("globalDeviceVariables",JSON.stringify(e.globalDeviceVariables))},is=({},e)=>{localStorage.setItem("globalAccountVariables",JSON.stringify(e.globalAccountVariables))},lr={render:cr,saveSlots:rs,saveGlobalDeviceVariables:os,saveGlobalAccountVariables:is,handleLineActions:Xi,startAutoNextTimer:Gi,clearAutoNextTimer:Zi,startSkipNextTimer:Qi,clearSkipNextTimer:es,nextLineConfigTimer:ts,clearNextLineConfigTimer:ns},ss=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),Ye=(e,t,n)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,n)},ls=(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(!ss.has(o.name)){n.unshift(o);continue}t.has(o.name)||(t.add(o.name),n.unshift(o))}return n},cs=({getEngine:e,routeGraphics:t,ticker:n,handleUnhandledEffect:r})=>{let o=zt(),i=zt(),s=zt(),a=null,c=null,l=!1,u=0,f=b=>{let x=typeof b?.id=="string"&&b.id.length>0?b.id:null;u+=1,a=x,l=!1},d=()=>u,h=(b={})=>{if(b?.aborted===!0)return!1;let x=typeof b?.id=="string"&&b.id.length>0?b.id:null;return x?x!==a||x===c?!1:(c=x,!0):a!==null||l?!1:(l=!0,!0)},g=(b,x={})=>{if(b!=="renderComplete"||!h(x))return!1;let w=e();return Ye(w,"markLineCompleted",{}),!0},m=(b={})=>{if(b?._interactionSource==="choice")return!0;let x=b?.actions;return!x||typeof x!="object"||Array.isArray(x)?!1:Object.values(x).some(w=>w?._interactionSource==="choice")},y=(b,x={})=>!x?.actions||typeof b?.selectIsChoiceVisible!="function"||!b.selectIsChoiceVisible()?!1:!m(x),I=({preprocessPayload:b,onEvent:x}={})=>async(w,v={})=>{let _=e();if(y(_,v))return x?.(w,v);let C=await b?.(w,v)??v;if(y(_,C))return x?.(w,C);if(g(w,C),C?.actions){let Y=C?._event?{_event:C._event}:C?.event?{_event:C.event}:void 0;_.handleActions(C.actions,Y)}return x?.(w,C)},A=b=>{let x=e(),w=ls(b);w.forEach(_=>{if(!lr[_.name]&&!r)throw new Error(`Unhandled pending effect "${_.name}".`)});let v={engine:x,routeGraphics:t,ticker:n,autoTimer:o,skipTimer:i,nextLineConfigTimerState:s,trackRenderDispatch:f,getRenderDispatchCount:d};for(let _ of w){let C=lr[_.name];if(C){C(v,_.payload);continue}r(_,v)}};return A.handleRouteGraphicsEvent=g,A.createRouteGraphicsEventHandler=I,A},as=cs;var us=(e,t={})=>{let{resources:n={}}=t;return Et(e,n)};var fl=Bt;export{as as createEffectsHandler,fl as default,us as resolveLayoutReferences};
|
|
1
|
+
var yr=Object.defineProperty;var br=(e,t)=>{for(var n in t)yr(e,n,{get:t[n],enumerable:!0})};var en=Symbol.for("immer-nothing"),Gt=Symbol.for("immer-draftable"),M=Symbol.for("immer-state");function Y(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var de=Object.getPrototypeOf;function J(e){return!!e&&!!e[M]}function ee(e){return e?tn(e)||Array.isArray(e)||!!e[Gt]||!!e.constructor?.[Gt]||Oe(e)||Pe(e):!1}var Ir=Object.prototype.constructor.toString();function tn(e){if(!e||typeof e!="object")return!1;let t=de(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)===Ir}function Le(e,t){ke(e)===0?Reflect.ownKeys(e).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function ke(e){let t=e[M];return t?t.type_:Array.isArray(e)?1:Oe(e)?2:Pe(e)?3:0}function et(e,t){return ke(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function nn(e,t,n){let r=ke(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function wr(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Oe(e){return e instanceof Map}function Pe(e){return e instanceof Set}function Q(e){return e.copy_||e.base_}function tt(e,t){if(Oe(e))return new Map(e);if(Pe(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let n=tn(e);if(t===!0||t==="class_only"&&!n){let r=Object.getOwnPropertyDescriptors(e);delete r[M];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(de(e),r)}else{let r=de(e);if(r!==null&&n)return{...e};let o=Object.create(r);return Object.assign(o,e)}}function st(e,t=!1){return Te(e)||J(e)||!ee(e)||(ke(e)>1&&(e.set=e.add=e.clear=e.delete=xr),Object.freeze(e),t&&Object.entries(e).forEach(([n,r])=>st(r,!0))),e}function xr(){Y(2)}function Te(e){return Object.isFrozen(e)}var Ar={};function te(e){let t=Ar[e];return t||Y(0,e),t}var be;function rn(){return be}function vr(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function Jt(e,t){t&&(te("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function nt(e){rt(e),e.drafts_.forEach(Er),e.drafts_=null}function rt(e){e===be&&(be=e.parent_)}function Xt(e){return be=vr(be,e)}function Er(e){let t=e[M];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function Zt(e,t){t.unfinalizedDrafts_=t.drafts_.length;let n=t.drafts_[0];return e!==void 0&&e!==n?(n[M].modified_&&(nt(t),Y(4)),ee(e)&&(e=Se(t,e),t.parent_||Re(t,e)),t.patches_&&te("Patches").generateReplacementPatches_(n[M].base_,e,t.patches_,t.inversePatches_)):e=Se(t,n,[]),nt(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==en?e:void 0}function Se(e,t,n){if(Te(t))return t;let r=t[M];if(!r)return Le(t,(o,i)=>Qt(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Re(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),Le(i,(a,l)=>Qt(e,r,o,a,l,n,s)),Re(e,o,!1),n&&e.patches_&&te("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function Qt(e,t,n,r,o,i,s){if(J(o)){let a=i&&t&&t.type_!==3&&!et(t.assigned_,r)?i.concat(r):void 0,l=Se(e,o,a);if(nn(n,r,l),J(l))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if(ee(o)&&!Te(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Se(e,o),(!t||!t.scope_.parent_)&&typeof r!="symbol"&&Object.prototype.propertyIsEnumerable.call(n,r)&&Re(e,o)}}function Re(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&st(t,n)}function _r(e,t){let n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:rn(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=r,i=ct;n&&(o=[r],i=Ie);let{revoke:s,proxy:a}=Proxy.revocable(o,i);return r.draft_=a,r.revoke_=s,a}var ct={get(e,t){if(t===M)return e;let n=Q(e);if(!et(n,t))return $r(e,n,t);let r=n[t];return e.finalized_||!ee(r)?r:r===Ze(e.base_,t)?(Qe(e),e.copy_[t]=it(r,e)):r},has(e,t){return t in Q(e)},ownKeys(e){return Reflect.ownKeys(Q(e))},set(e,t,n){let r=on(Q(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){let o=Ze(Q(e),t),i=o?.[M];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(wr(n,o)&&(n!==void 0||et(e.base_,t)))return!0;Qe(e),ot(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 Ze(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,Qe(e),ot(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let n=Q(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){Y(11)},getPrototypeOf(e){return de(e.base_)},setPrototypeOf(){Y(12)}},Ie={};Le(ct,(e,t)=>{Ie[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});Ie.deleteProperty=function(e,t){return Ie.set.call(this,e,t,void 0)};Ie.set=function(e,t,n){return ct.set.call(this,e[0],t,n,e[0])};function Ze(e,t){let n=e[M];return(n?Q(n):e)[t]}function $r(e,t,n){let r=on(t,n);return r?"value"in r?r.value:r.get?.call(e.draft_):void 0}function on(e,t){if(!(t in e))return;let n=de(e);for(;n;){let r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=de(n)}}function ot(e){e.modified_||(e.modified_=!0,e.parent_&&ot(e.parent_))}function Qe(e){e.copy_||(e.copy_=tt(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Cr=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"&&Y(6),r!==void 0&&typeof r!="function"&&Y(7);let o;if(ee(t)){let i=Xt(this),s=it(t,void 0),a=!0;try{o=n(s),a=!1}finally{a?nt(i):rt(i)}return Jt(i,r),Zt(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===en&&(o=void 0),this.autoFreeze_&&st(o,!0),r){let i=[],s=[];te("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else Y(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){ee(e)||Y(8),J(e)&&(e=lt(e));let t=Xt(this),n=it(e,void 0);return n[M].isManual_=!0,rt(t),n}finishDraft(e,t){let n=e&&e[M];(!n||!n.isManual_)&&Y(9);let{scope_:r}=n;return Jt(r,t),Zt(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=te("Patches").applyPatches_;return J(e)?r(e,t):this.produce(e,o=>r(o,t))}};function it(e,t){let n=Oe(e)?te("MapSet").proxyMap_(e,t):Pe(e)?te("MapSet").proxySet_(e,t):_r(e,t);return(t?t.scope_:rn()).drafts_.push(n),n}function lt(e){return J(e)||Y(10,e),sn(e)}function sn(e){if(!ee(e)||Te(e))return e;let t=e[M],n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=tt(e,t.scope_.immer_.useStrictShallowCopy_)}else n=tt(e,!0);return Le(n,(r,o)=>{nn(n,r,sn(o))}),t&&(t.finalized_=!1),n}var B=new Cr,at=B.produce,Os=B.produceWithPatches.bind(B),Ps=B.setAutoFreeze.bind(B),Ts=B.setUseStrictShallowCopy.bind(B),Vs=B.applyPatches.bind(B),Ns=B.createDraft.bind(B),Ds=B.finishDraft.bind(B);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},S={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},we={NOT:0};var x=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},V=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var ut=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}')`)},cn=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 ln=(e,t,n=!1)=>{if(t===null)return new V(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new V(`Cannot iterate over undefined value at '$for ${e}'`);let r=typeof t;return n?new V(`Cannot iterate over non-array value in loop '${e}' - got ${r} instead`):new V(`Cannot iterate over non-array value (got: ${r}) at '$for ${e}'`)},an=(e,t)=>{let n=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new V(`Unknown function '${e}' (${n})`)};var Lr=(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=$(e,{functions:r,partials:o},t,{});return s===void 0?{}:s},$=(e,t,n,r)=>{let o=t.functions||t;if(e.var&&!e.type)return O(e.var,n,r);if(e.type===h.LITERAL)return e.value;if(e.type===h.VARIABLE)return O(e.path,n,r);if(e.type===h.INTERPOLATION)return Rr(e.parts,t,n,r);switch(e.type){case h.FUNCTION:return fn(e,t,n,r);case h.BINARY:return dn(e,t,n,r);case h.UNARY:return pn(e,t,n,r);case h.CONDITIONAL:return Or(e,t,n,r);case h.LOOP:return Dr(e,t,n,r);case h.OBJECT:return Mr(e,t,n,r);case h.ARRAY:return Br(e,t,n,r);case h.PARTIAL:return zr(e,t,n,r);case h.PATH_REFERENCE:return Fr(e,t,n,r);default:throw new Error(`Unknown node type: ${e.type}`)}},un=new Map,Sr=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},O=(e,t,n)=>{if(!e)return;if(e in n)return n[e];let r=un.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=Sr(l.trim());r.push(...c)}un.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},Rr=(e,t,n,r)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let s=$(i,t,n,r);o.push(s!=null?String(s):"")}return o.join("")},fn=(e,t,n,r)=>{let o=t.functions||t,i=o[e.name];if(!i)throw an(e.name,o);let s=e.args.map(a=>$(a,t,n,r));return i(...s)},pe=(e,t,n,r)=>{if(e.var&&!e.type)return O(e.var,n,r);switch(e.type){case h.VARIABLE:return O(e.path,n,r);case h.LITERAL:return e.value;case h.BINARY:return dn(e,t,n,r);case h.UNARY:return pn(e,t,n,r);case h.FUNCTION:return fn(e,t,n,r);default:return $(e,t,n,r)}},dn=(e,t,n,r)=>{if(e.op===S.AND||e.op===S.OR){let s=pe(e.left,t,n,r),a=pe(e.right,t,n,r);switch(e.op){case S.AND:return s&&a;case S.OR:return s||a}}let o=$(e.left,t,n,r),i=$(e.right,t,n,r);switch(e.op){case S.EQ:return o==i;case S.NEQ:return o!=i;case S.GT:return o>i;case S.LT:return o<i;case S.GTE:return o>=i;case S.LTE:return o<=i;case S.IN:return Array.isArray(i)?i.includes(o):!1;case S.ADD:if(typeof o!="number"||typeof i!="number")throw new V(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case S.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new V(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},pn=(e,t,n,r)=>{let o=e.op===we.NOT?pe(e.operand,t,n,r):$(e.operand,t,n,r);if(e.op===we.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},kr=(e,t,n,r)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===h.VARIABLE)if(O(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?$(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]=O(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=O(d.path,n,r);f.push(p!=null?String(p):"")}else{let p=$(d,t,n,r);f.push(p!=null?String(p):"")}a[c]=f.join("")}else a[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?$(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]=O(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=O(d.path,n,r);f.push(p!=null?String(p):"")}else{let p=$(d,t,n,r);f.push(p!=null?String(p):"")}a[c]=f.join("")}else a[c]=$(u,t,n,r)}return a}}}return null},Or=(e,t,n,r)=>{let o=kr(e,t,n,r);if(o!==null)return o;for(let i=0;i<e.conditions.length;i++){let s=e.conditions[i];if(s===null||pe(s,t,n,r))return $(e.bodies[i],t,n,r)}return hn},Pr=(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 g=p.path;if(g===r)u[d]=c;else if(g.startsWith(r+".")){let y=g.substring(r.length+1);u[d]=c[y]}else return null}else if(p.type===h.INTERPOLATION){let g=[],y=!0;for(let m of p.parts)if(typeof m=="string")g.push(m);else if(m.type===h.VARIABLE){let b=m.path;if(b===r)g.push(c!=null?String(c):"");else if(b.startsWith(r+".")){let I=b.substring(r.length+1),w=c[I];g.push(w!=null?String(w):"")}else{y=!1;break}}else{y=!1;break}if(!y)return null;u[d]=g.join("")}else return null}a.push(u)}}return a}}}return null},Tr=(e,t)=>{let n=e.body,r=e.itemVar,o=Pr(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},Vr=(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 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__,[a]:`${p}[${c}]`,...l&&{[l]:c}};for(let g of s.properties){let y=g.parsedKey?$(g.parsedKey,t,n,d):g.key,m=g.value;if(m.type===h.LITERAL)f[y]=m.value;else if(m.type===h.VARIABLE){let b=m.path;if(b===a)f[y]=u;else if(b===l)f[y]=c;else if(b.startsWith(a+".")){let I=b.substring(a.length+1);!I.includes(".")&&!I.includes("[")?f[y]=u[I]:f[y]=O(b,n,{...r,[a]:u,...l&&{[l]:c}})}else f[y]=O(b,n,{...r,[a]:u,...l&&{[l]:c}})}else if(m.type===h.INTERPOLATION){let b=[];for(let I of m.parts)if(typeof I=="string")b.push(I);else if(I.type===h.VARIABLE){let w=I.path,_;if(w===a)_=u;else if(w===l)_=c;else if(w.startsWith(a+".")){let v=w.substring(a.length+1);!v.includes(".")&&!v.includes("[")?_=u[v]:_=O(w,n,{...r,[a]:u,...l&&{[l]:c}})}else _=O(w,n,{...r,[a]:u,...l&&{[l]:c}});b.push(_!=null?String(_):"")}else{let w={...r,[a]:u,...l&&{[l]:c}},_=$(I,t,n,w);b.push(_!=null?String(_):"")}f[y]=b.join("")}else{let b={...r,[a]:u,...l&&{[l]:c}};f[y]=$(m,t,n,b)}}i.push(f)}return i}return null},Nr=(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},Dr=(e,t,n,r)=>{let o=$(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 ln(f,o,u)}if(!e.indexVar){let c=Nr(e,o,e.itemVar);if(c!==null)return c}if(!e.indexVar){let c=Tr(e,o);if(c!==null)return c}let i=Vr(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=$(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},jr=(e,t,n,r)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?$(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?$(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]=O(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=O(g.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 g of d.properties){let y=g.key,m=g.value;if(m.type===h.LITERAL)p[y]=m.value;else if(m.type===h.VARIABLE)p[y]=O(m.path,n,r);else if(m.type===h.INTERPOLATION){let b=[];for(let I of m.parts)if(typeof I=="string")b.push(I);else if(I.type===h.VARIABLE){let w=O(I.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},Mr=(e,t,n,r)=>{let o=t.functions||t;if(e.whenCondition&&!pe(e.whenCondition,o,n,r))return;let i=jr(e,t,n,r);if(i!==null)return i;if(e.fast){let c={};for(let u of e.properties){let f=u.parsedKey?$(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]=O(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=O(g.path,n,r);p.push(y!=null?String(y):"")}else{let y=$(g,t,n,r);p.push(y!=null?String(y):"")}c[f]=p.join("")}else c[f]=$(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.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.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=$(f.value,t,n,r);d!==void 0&&(s[c.key]=d)}else{let d=$(c.value,t,n,r);d!==void 0&&(s[c.key]=d)}}else{let f=c.parsedKey?$(c.parsedKey,t,n,r):c.key,d=$(c.value,t,n,r);d!==void 0&&(s[f]=d)}}return s},hn={},Br=(e,t,n,r)=>{let o=[];for(let i of e.items)if(i.type===h.LOOP){let s=$(i,t,n,r);Array.isArray(s)&&i.flatten!==!1?o.push(...s):o.push(s)}else{let s=$(i,t,n,r);s!==hn&&s!==void 0&&o.push(s)}return o},zr=(e,t,n,r)=>{let{name:o,data:i,whenCondition:s}=e,a=t.partials||{},l=t.functions||t;if(s&&!pe(s,l,n,r))return;if(!a[o])throw new V(`Partial '${o}' is not defined`);let c=r._partialStack||[];if(c.includes(o))throw new V(`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=$(i,t,n,r);f={...f,...p}}return $(u,t,f,d)},Fr=(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 V(`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 V(`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 V(`Path reference '#{${o}}' - cannot access properties on index variable '${s}'`);return String(l)}return a.length>0&&(l+="."+a.join(".")),l},ft=Lr;var Ur=/\$\{([^}]*)\}/g,Wr=/#\{([^}]*)\}/g,mn=(e,t={})=>{let n=e.match(/^(\w+)\((.*)\)$/);if(!n)return{isFunction:!1};let[,r,o]=n,i=Yr(o,t);return{isFunction:!0,type:h.FUNCTION,name:r,args:i}},Yr=(e,t={})=>e.trim()?Hr(e).map(r=>qr(r.trim(),t)):[],Hr=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},qr=(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=mn(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=ne(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 T(r,t)}catch{return{type:h.VARIABLE,path:r}}return{type:h.VARIABLE,path:r}},yn=/^\w+\(.*\)$/,Kr=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,Gr=e=>{if(!(!e||e.trim()===""||yn.test(e))&&Kr.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}"`)},gn=e=>{let t=e.trim();if(yn.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}},xe=(e,t={})=>{let n=e.trim();Gr(n);let r=mn(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}},dt=(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(Ur)],i=[...n.matchAll(Wr)],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"?xe(c[1],t):gn(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 g=n.substring(l,p);for(let y=0;y<r.length;y++)g=g.replace(`__ESCAPED_${y}__`,r[y]);g&&a.push(g)}try{let g;u==="variable"?g=xe(d.trim(),t):g=gn(d.trim()),a.push(g)}catch(g){if(g.message==="Invalid array index syntax")a.push(f);else throw g}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 X=(e,t)=>typeof e=="string"?dt(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?Xr(e,t):Zr(e,t):{type:h.LITERAL,value:e},Jr=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}},Xr=(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=Jr(i),c=Object.keys(l);if(c.length===1&&/^\$for(?::\w+)?\s/.test(c[0])){let u=bn(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=bn(a[0],i[a[0]],t);n.push(l),r=!0;continue}}let s=X(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}},Zr=(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 I of l)if(b===I||b.startsWith(I+" ")||b.startsWith(I+"#")){c.push(I);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={},g=!1;for(let[b,I]of Object.entries(d)){let w=b;(b.startsWith("\\$")||b.startsWith("$$"))&&(w=b.slice(1)),p[w]=I,g=!0}let y=null;if(g&&(y=X(p,t),y.type===h.OBJECT)){let b=!1;for(let I of y.properties)if(I.value.type===h.VARIABLE||I.value.type===h.INTERPOLATION||I.value.type===h.FUNCTION||I.value.type===h.CONDITIONAL||I.value.type===h.OBJECT&&!I.value.fast||I.value.type===h.ARRAY&&!I.value.fast){b=!0;break}b&&(y.fast=!1)}let m={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=T(f,t)}else b={type:h.LITERAL,value:f};m.whenCondition=b}return m}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=T(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=Qr(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=X(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=dt(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},Qr=(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());ut(c);let u=T(c,n);for(r.push(u),o.push(X(a,n)),i++;i<e.length;){let[f,d]=e[i],p=!1,g;if(l?f.startsWith(`$elif#${l} `)?(g=f.substring(`$elif#${l} `.length),g.endsWith(":")&&(g=g.slice(0,-1).trim()),p=!0):(f===`$else#${l}`||f===`$else#${l}:`)&&(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{ut(g);let y=T(g,n);r.push(y)}if(o.push(X(d,n)),i++,g===null)break}else break}return{node:{type:h.CONDITIONAL,conditions:r,bodies:o,id:l},nextIndex:i}},T=(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 T(c,t)}let n=ne(e,"||");if(n!==-1)return{type:h.BINARY,op:S.OR,left:T(e.substring(0,n).trim(),t),right:T(e.substring(n+2).trim(),t)};let r=ne(e,"&&");if(r!==-1)return{type:h.BINARY,op:S.AND,left:T(e.substring(0,r).trim(),t),right:T(e.substring(r+2).trim(),t)};let o=[{op:">=",type:S.GTE},{op:"<=",type:S.LTE},{op:"==",type:S.EQ},{op:"!=",type:S.NEQ},{op:">",type:S.GT},{op:"<",type:S.LT},{op:" in ",type:S.IN}];for(let{op:c,type:u}of o){let f=ne(e,c);if(f!==-1)return{type:h.BINARY,op:u,left:T(e.substring(0,f).trim(),t),right:T(e.substring(f+c.length).trim(),t)}}let i=-1,s=null,a=[{op:" + ",type:S.ADD},{op:" - ",type:S.SUBTRACT}];for(let{op:c,type:u}of a){let f=0;for(;f<e.length;){let d=ne(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:T(e.substring(0,i).trim(),t),right:T(e.substring(i+s.op.length).trim(),t)};let l=[" * "," / "," % "];for(let c of l)if(ne(e,c)!==-1)throw new x(`Arithmetic operations are not allowed in conditionals: "${c}"`);return e.startsWith("!")?{type:h.UNARY,op:we.NOT,operand:T(e.substring(1).trim(),t)}:In(e,t)},ne=(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},eo=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}},In=(e,t)=>{let n=e.trim();if(n.match(/^(\w+)\((.*)\)$/))return xe(n,t);let o=eo(n);if(o.type===h.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(n))return{type:h.VARIABLE,path:n};try{return xe(n,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},to=(e,t=!1)=>{let n=t?"$each":"$for";try{cn(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}},bn=(e,t,n,r=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let m=r?"$each":"$for";throw new x(`Invalid loop syntax (got: '${e.replace("$for",m)}')`)}let s=i[1],a=i[2].trim();to(a,r);let l=a.match(/^(.+?)\s+in\s+(.+)$/);if(!l){let m=r?"$each":"$for";throw new x(`Invalid loop syntax - missing 'in' keyword (got: '${m} ${a}')`)}let c=l[1].trim(),u=l[2].trim(),f,d=null;if(c.includes(",")){let m=c.split(",").map(b=>b.trim());if(m.length!==2)throw new x(`Invalid loop variables: ${c}. Expected format: "item" or "item, index"`);f=m[0],d=m[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 g=In(u,n),y=X(t,n);return{type:h.LOOP,itemVar:f,indexVar:d,iterable:g,body:y,flatten:s!=="nested"}};var no=(e,t={})=>{let{functions:n={}}=t;return X(e,n)},Ve=no;var pt={};br(pt,{now:()=>ro});var ro=()=>Date.now();var oo=(e,t,n={})=>{let{functions:r={},partials:o={}}=n,i={...pt,...r},s=Ve(e,{functions:i}),a={};for(let[l,c]of Object.entries(o))a[l]=Ve(c,{functions:i});return ft(s,t,{functions:i,partials:a})},z=oo;var wn=(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=at(r,d=>c(a(d),...u))});return{...o,...i}},Ne=(e,t)=>n=>{let r=e(),o=Array.isArray(n)?n:[n];return at(r,i=>{o.forEach(s=>{t.forEach(a=>{a(i,s)})})})};var io=(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{}}},mt=e=>{let t={},n={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([r,o])=>{let i=io(o,r);o.scope==="context"?t[r]=i:n[r]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}},De=(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(", ")}`)},je=(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(", ")}`)},Me=(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}`)}},yt=(e,t,n)=>Object.fromEntries(Object.entries(e).filter(([r])=>t?.[r]?.scope===n)),xn=(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()))},so=(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},bt=(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=so(e.dialogue,t.dialogue);return i&&(n.dialogue=i),o("choice"),o("layout"),o("animation"),o("control"),o("character"),o("visual"),o("sfx"),n},It=(e={})=>{let t=structuredClone(e);t.background&&(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},co=(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},lo=(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=co(t,n);if(r===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return r},ao={updateProjectData:new Set(["projectData"]),showConfirmDialog:new Set(["confirmActions","cancelActions"])},An=(e,t)=>{let n=e[e.length-1];return n?ao[n]?.has(t)===!0:!1},ht=(e,t,n=[])=>Array.isArray(e)?e.map(r=>ht(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,An(n,r)?o:ht(o,t,[...n,r])])):lo(e,t),gt=(e,t,n=[])=>Array.isArray(e)?e.map(r=>gt(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,An(n,r)?o:gt(o,t,[...n,r])])):typeof e=="string"?z(e,t):e,vn=(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=ht(e,t._event);return gt(n,t)};var Be=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:structuredClone(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},En=(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}},uo=()=>({}),fo=(e,t)=>{if(t.background){let{animationsOnly:n,state:r}=Be(t.background,o=>!!o.resourceId);if(n){e.background=e.background?.resourceId?{...structuredClone(e.background),...r}:r;return}if(!t.background.resourceId){delete e.background;return}e.background=structuredClone(t.background)}else e.background?.animations&&(e.background.animations={})},po=(e,t)=>{if(!t.dialogue){e.dialogue&&e.dialogue.mode==="adv"&&(e.dialogue.content=void 0,e.dialogue.characterId=void 0);return}if(e.dialogue||(e.dialogue={}),t.dialogue.ui){let{animationsOnly:n,state:r}=Be(t.dialogue.ui,o=>!!o.resourceId);n?e.dialogue.ui={...e.dialogue.ui,...r}:e.dialogue.ui={...t.dialogue.ui}}else e.dialogue?.ui?.animations&&(e.dialogue.ui.animations={});if(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),delete e.dialogue.characterId,t.dialogue.characterId&&(e.dialogue.characterId=t.dialogue.characterId),t.dialogue.character?e.dialogue.character={...t.dialogue.character}:delete e.dialogue.character,t.dialogue.clear){delete e.dialogue;return}t.dialogue?.clearPage&&e.dialogue?.mode==="nvl"&&(e.dialogue.lines=[]),e.dialogue?.mode==="nvl"&&t.dialogue.content!==void 0&&e.dialogue.lines.push({content:t.dialogue.content,characterId:t.dialogue.characterId||null})},ho=(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},go=(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}}},mo=(e,t)=>{if(t.visual){let{hasValidItems:n,processedItems:r}=En(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))},yo=(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}=En(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId);n?e.character={items:r}:delete e.character},bo=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},Io=(e,t)=>{if(t.layout){let{animationsOnly:n,state:r}=Be(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},wo=(e,t)=>{if(t.choice){let{animationsOnly:n,state:r}=Be(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},xo=(e,t)=>{if(t.control){if(!t.control.resourceId){delete e.control;return}e.control=t.control}},Ao=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},vo=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(n=>{delete e[n]})},Ae=e=>Ne(uo,[vo,fo,ho,go,mo,po,yo,bo,Io,wo,xo,Ao])(e);var oe={objectValues:e=>Object.entries(e).map(([t,n])=>({id:t,...n})),formatDate:xn},Eo=/^\$for\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+):$/,_o=(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},ze=(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=Eo.exec(s);if(a){let[,l,c,u]=a,f=_o(t,u);if(!Array.isArray(f))continue;let d=Array.isArray(i[s])?i[s]:[];f.forEach((p,g)=>{let y={...t,[l]:p};c&&(y[c]=g),d.forEach(m=>{let b=ze(m,y,n),I=z(b,y,n);Array.isArray(I)?o.push(...I):o.push(I)})});continue}}o.push(ze(i,t,n))}return o}if(!e||typeof e!="object")return e;let r={};return Object.entries(e).forEach(([o,i])=>{r[o]=ze(i,t,n)}),r},$t=({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".`)},$o=({id:e,targetId:t,animation:n,animationPath:r="animation"})=>{let o=structuredClone(n);return $t({animationType:o.type,animationId:e,animationPath:r}),delete o.name,o.id=e,o.targetId=t,o},Co=(e,{animationId:t="animation",animationPath:n="animation"}={})=>{if(!(!e||typeof e!="object"||Array.isArray(e))&&typeof e.type=="string")return $t({animationType:e.type,animationId:t,animationPath:n}),e.type},Lo=e=>{if(typeof e=="string")return e;if(!(!e||typeof e!="object"||Array.isArray(e)))return e.resourceId},So=e=>!e||typeof e!="object"||Array.isArray(e)?!1:["in","out","update"].some(t=>e[t]!==void 0),Ro=(e,t)=>{if(So(e))throw new Error(`[${t}] Legacy animations.in/out/update is no longer supported. Use a single animations.resourceId reference.`)},ve=({animations:e,resources:t,animationId:n,instanceId:r,targetId:o,animationPath:i="animation"})=>{if(!n||!o)return!1;let s=t?.animations?.[n];return s?(e.push($o({id:r,targetId:o,animation:s,animationPath:i})),!0):!1},ko=({hasPrevious:e,hasCurrent:t,previousResourceId:n,currentResourceId:r,sharedTarget:o})=>!e&&t?"enter":e&&!t?"exit":e&&t?n===r&&o?"update":"replace":"none",Oo=({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.`)},Po=(e,{defaultTargetId:t,defaultId:n,animationPath:r="animation"}={})=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let o=structuredClone(e);return $t({animationType:o.type,animationId:o.id??n,animationPath:r}),o.id??=n,o.targetId??=t,o},Ct=({animations:e,transitions:t,defaultTargetId:n,idPrefix:r,animationPathPrefix:o=r})=>{t.forEach((i,s)=>{e.push(Po(i,{defaultTargetId:n,defaultId:`${r}-transition-${s}`,animationPath:`${o}.transitions[${s}]`}))})},_n=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let n=z(e,t);return n&&typeof n=="object"?e:n},$n=(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},Cn=(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))},Ln=(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("-")}`},wt=(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},To=(e={})=>e.textStyles||{},Vo=(e={})=>e.images||{},No=(e={})=>e.colors||{},Do=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,Ee=(e,t)=>e==="root"?`${t}`:`${e}.${t}`,he=(e,t,n)=>{if(typeof e!="string"||e.length===0)throw new Error(`${n} at "${t}" must resolve to a non-empty string`)},Sn=(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},Tn=(e,t)=>{if(typeof e!="string"||!Do.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},Rn=(e,t,n)=>{let r=Tn(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})`},jo=(e={},t)=>{let n=To(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=Sn(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:Rn(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=Sn(n.strokeAlpha,"strokeAlpha",t);s.strokeColor=Rn(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},vt=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>vt(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]=vt(i,t,Ee(n,o)));return e.textStyleId!==void 0&&(he(e.textStyleId,n,"textStyleId"),r.textStyle=jo(t,e.textStyleId)),r},Vn=(e={},t)=>{let n=No(e)?.[t];if(!n)throw new Error(`Color "${t}" not found`);return Tn(n.hex,`Color "${t}"`)},Nn=e=>e==="hover.fill"?"hover.colorId":e==="click.fill"?"click.colorId":e==="rightClick.fill"?"rightClick.colorId":"colorId",xt=(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 ${Nn(`${t}.fill`)} instead`)},Mo=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>_e(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]=_e(i,t,Ee(n,o)));return e.colorId!==void 0&&(he(e.colorId,n,"colorId"),r.fill=Vn(t,e.colorId)),r},_e=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>_e(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 ${Nn("fill")} instead`);xt(e,"hover",n),xt(e,"click",n),xt(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]=Mo(i,t,Ee(n,o));continue}r[o]=_e(i,t,Ee(n,o))}return e.type==="rect"&&e.colorId!==void 0&&(he(e.colorId,n,"colorId"),r.fill=Vn(t,e.colorId)),r},At=(e={},t)=>{let n=Vo(e)?.[t];return n||null},Dn=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 ${Dn(`${t}.${r}`)} instead`)},On=(e,t,n)=>{let r=e[t];e[t]={...r&&typeof r=="object"&&!Array.isArray(r)?r:{},src:n}},Et=(e,t={},n="root")=>{if(Array.isArray(e))return e.map((o,i)=>Et(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 ${Dn(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]=Et(i,t,Ee(n,o)));if(e.type==="sprite"&&e.imageId!==void 0){he(e.imageId,n,"imageId");let o=At(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&&(he(e.hoverImageId,n,"hoverImageId"),On(r,"hover",At(t,e.hoverImageId)?.fileId??e.hoverImageId)),e.type==="sprite"&&e.clickImageId!==void 0&&(he(e.clickImageId,n,"clickImageId"),On(r,"click",At(t,e.clickImageId)?.fileId??e.clickImageId)),r},Lt=(e,t={},n="root")=>Et(_e(vt(e,t,n),t,n),t,n),ie=Lt,Ue=(e=[])=>e.find(t=>t.id==="story"),se=({variables:e,saveSlots:t=[],isLineCompleted:n,autoMode:r,skipMode:o,isChoiceVisible:i,canRollback:s,confirmDialog:a,historyDialogue:l=[],characters:c={}}={})=>({variables:e,saveSlots:t,isLineCompleted:n,autoMode:r,skipMode:o,isChoiceVisible:i,canRollback:s,confirmDialog:a,historyDialogue:l,characters:c,effectiveSoundVolume:e?._muteAll?0:e?._soundVolume??500,textSpeed:e?._textSpeed??50}),Pn=100,Fe=(e,t)=>{if(Array.isArray(e))return e.map(r=>Fe(r,t));if(!e||typeof e!="object")return e;let n={...e};return Object.keys(n).forEach(r=>{n[r]=Fe(n[r],t)}),n.type==="text-revealing"?t(n):n},Bo=e=>Fe(e,t=>({...t,revealEffect:"none"})),zo=e=>Fe(e,t=>{let n=Number(t.speed??t.displaySpeed),r=Number.isFinite(n)?Math.max(n,Pn):Pn;return{...t,speed:r,...Object.prototype.hasOwnProperty.call(t,"displaySpeed")?{displaySpeed:r}:{}}}),ce=(e,{isLineCompleted:t=!1,skipMode:n=!1,skipTransitionsAndAnimations:r=!1}={})=>t||r?Bo(e):n?zo(e):e,jn=({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:{}}}}),_t=e=>{if(Array.isArray(e))return e.map(_t);if(!e||typeof e!="object")return e;let t={};for(let[i,s]of Object.entries(e))t[i]=_t(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}}:{}}}}},Mn=(e=[],t={})=>e.map(n=>{let r=t?.[n.characterId],o=typeof n.text=="string"?n.text:Array.isArray(n.content)?n.content.map(i=>i?.text??"").join(""):"";return{...n,text:o,characterName:r?.name||""}}),Bn=({container:e,resources:t,templateData:n,isLineCompleted:r=!1,skipMode:o=!1,skipTransitionsAndAnimations:i=!1})=>{let s=z(e,n,{functions:oe});return ie(ce(s,{isLineCompleted:r,skipMode:o,skipTransitionsAndAnimations:i}),t)},Fo=(e={})=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,{payload:{actions:structuredClone(n?.actions||{})}}]))},re=({animations:e,animationsDef:t,resources:n,previousResourceId:r,currentResourceId:o,previousTargetId:i,currentTargetId:s,animationPath:a,idPrefix:l,allowIncomingUpdateFallback:c=!1})=>{if(!t)return;let u=r!=null&&r!==!1,f=o!=null&&o!==!1,d=i&&s&&i===s,p=ko({hasPrevious:u,hasCurrent:f,previousResourceId:r,currentResourceId:o,sharedTarget:d});Ro(t,a);let g=Lo(t),y=n?.animations?.[g],m=Co(y,{animationId:g,animationPath:a}),b=c&&m==="update"&&p!=="update"&&f&&s;if(b||Oo({animationType:m,animationId:g,animationPath:a,lifecycle:p}),m==="update"){u&&f&&r===o&&d?ve({animations:e,resources:n,animationId:g,instanceId:`${l}-animation-update`,targetId:s,animationPath:a}):b&&ve({animations:e,resources:n,animationId:g,instanceId:`${l}-animation-update`,targetId:s,animationPath:a});return}if(m==="transition"){if(u&&f&&d){ve({animations:e,resources:n,animationId:g,instanceId:`${l}-animation-transition`,targetId:s,animationPath:a});return}u&&ve({animations:e,resources:n,animationId:g,instanceId:`${l}-animation-out`,targetId:i,animationPath:a}),f&&ve({animations:e,resources:n,animationId:g,instanceId:`${l}-animation-in`,targetId:s,animationPath:a})}},Uo=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),Wo=(e,{presentationState:t,previousPresentationState:n,resources:r={},isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,autoMode:a,skipMode:l,isChoiceVisible:c,canRollback:u,saveSlots:f=[]})=>{let{elements:d,animations:p}=e;if(t.background){let g=d.find(b=>b.id==="story");if(!g)return e;let y=n?.background?.resourceId,m=t.background.resourceId??(t.background.animations?y:void 0);if(m){let{images:b={},videos:I={}}=r,w=b[m]||I[m];if(w){let _=I[m]!==void 0,v={id:`bg-cg-${m}`,type:_?"video":"sprite",x:0,y:0,src:w.fileId,width:w.width,height:w.height,alpha:1,anchorX:0,anchorY:0,rotation:0,scaleX:1,scaleY:1};_&&(v.loop=t.background.loop??!1,v.volume=w.volume??500),g.children.push(v)}}if(m){let{layouts:b={}}=r,I=b[m];if(I){let w={id:`bg-cg-${m}`,type:"container",children:I.elements},_=z(w,se({variables:s,saveSlots:f,isLineCompleted:o,autoMode:a,skipMode:l,isChoiceVisible:c,canRollback:u}),{functions:oe});g.children.push(ie(ce(_,{isLineCompleted:o,skipMode:l,skipTransitionsAndAnimations:i}),r))}}t.background.animations&&!o&&!i&&re({animations:p,animationsDef:t.background.animations,resources:r,previousResourceId:y,currentResourceId:m,previousTargetId:y?`bg-cg-${y}`:void 0,currentTargetId:m?`bg-cg-${m}`:void 0,animationPath:"background.animations",idPrefix:"bg-cg",allowIncomingUpdateFallback:!0})}return e},Yo=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i})=>{let{elements:s,animations:a}=e;if(t.character&&r){let l=s.find(p=>p.id==="story");if(!l)return e;let c=t.character.items||[],u=n?.character?.items||[],f=Cn(c),d=Cn(u);for(let p=0;p<c.length;p++){let g=c[p],{transformId:y,sprites:m}=g,b=u.find(R=>R.id===g.id),I=u.findIndex(R=>R.id===g.id),w=b?.sprites&&b.sprites.length>0,_=m&&m.length>0,v=I>=0?Ln(b,I,d):void 0;if(g.animations&&!m&&!y&&w&&!o&&!i){re({animations:a,animationsDef:g.animations,resources:r,previousResourceId:v,currentResourceId:void 0,previousTargetId:v,currentTargetId:void 0,animationPath:`character.items[${p}].animations`,idPrefix:"character"});continue}if(g.animations&&!m&&!y)continue;if(!m||m.length===0||!y){console.warn("Character item missing sprites or transformId:",g);continue}let k=Ln(g,p,f),C=r.transforms[y];if(!C){console.warn("Transform not found:",y);continue}let A={type:"container",id:k,x:g.x??C.x,y:g.y??C.y,anchorX:C.anchorX,anchorY:C.anchorY,rotation:C.rotation,scaleX:C.scaleX,scaleY:C.scaleY,children:[]};for(let R of m){let N=r.images[R.resourceId];if(!N){console.warn(`Image resource not found: ${R.resourceId}`);continue}A.children.push({type:"sprite",id:`${k}-${R.id}`,src:N.fileId,width:N.width,height:N.height,x:0,y:0})}l.children.push(A),g.animations&&!o&&!i&&re({animations:a,animationsDef:g.animations,resources:r,previousResourceId:v,currentResourceId:k,previousTargetId:v,currentTargetId:k,animationPath:`character.items[${p}].animations`,idPrefix:"character"})}}return e},Ho=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:s,autoMode:a,skipMode:l,isChoiceVisible:c,canRollback:u,saveSlots:f=[]})=>{let{elements:d,animations:p}=e;if(t.visual&&r){let g=d.find(m=>m.id==="story");if(!g)return e;let y=t.visual.items;for(let m of y){if(m.resourceId){let{images:b={},videos:I={},spritesheets:w={}}=r,_=w[m.resourceId];if(_){let v=wt(r,m),k=m.animationName;if(k){let C=_.animations?.[k];if(!C)throw new Error(`Animation '${k}' not found in spritesheet resource '${m.resourceId}'`);let A={id:`visual-${m.id}`,type:"animated-sprite",x:m.x??v.x,y:m.y??v.y,width:m.width??_.width,height:m.height??_.height,alpha:m.alpha??1,anchorX:v.anchorX,anchorY:v.anchorY,rotation:v.rotation,scaleX:v.scaleX,scaleY:v.scaleY,spritesheetSrc:_.fileId,spritesheetData:_.jsonData,animation:{frames:C.frames,animationSpeed:m.animationSpeed??C.animationSpeed??.5,loop:m.loop??C.loop??!0}};g.children.push(structuredClone(A))}}else{let v=b[m.resourceId]||I[m.resourceId];if(v){let k=I[m.resourceId]!==void 0,C=wt(r,m),A={id:`visual-${m.id}`,type:k?"video":"sprite",src:v.fileId,width:v.width,height:v.height,x:C.x,y:C.y,anchorX:C.anchorX,anchorY:C.anchorY,rotation:C.rotation,scaleX:C.scaleX,scaleY:C.scaleY};k&&(A.loop=v.loop??!1,A.volume=v.volume??500),g.children.push(A)}}}if(m.resourceId){let{layouts:b={}}=r,I=b[m.resourceId];if(I){let w=wt(r,m),_={id:`visual-${m.id}`,type:"container",children:structuredClone(I.elements),x:w.x,y:w.y,anchorX:w.anchorX,anchorY:w.anchorY,rotation:w.rotation,scaleX:w.scaleX,scaleY:w.scaleY},v=z(_,se({variables:s,saveSlots:f,isLineCompleted:o,autoMode:a,skipMode:l,isChoiceVisible:c,canRollback:u}),{functions:oe});g.children.push(ie(ce(v,{isLineCompleted:o,skipMode:l,skipTransitionsAndAnimations:i}),r))}}if(m.animations&&!o&&!i){let I=(n?.visual?.items||[]).find(w=>w.id===m.id);re({animations:p,animationsDef:m.animations,resources:r,previousResourceId:I?.resourceId,currentResourceId:m.resourceId,previousTargetId:I?.resourceId?`visual-${m.id}`:void 0,currentTargetId:m.resourceId?`visual-${m.id}`:void 0,animationPath:`visual.items[${m.id}].animations`,idPrefix:m.id})}}}return e},qo=(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,saveSlots:p=[]})=>{let{elements:g,animations:y}=e;if(!t.dialogue||o)return e;let m=g.find(b=>b.id==="story");if(!m)return e;if(t.dialogue.ui&&t.dialogue.ui.resourceId){let{layouts:b={}}=r,I=b[t.dialogue.ui.resourceId];if(I){let w;t.dialogue.characterId&&(w=r.characters[t.dialogue.characterId]),t.dialogue.character&&(w={...w,name:t.dialogue.character.name});let _={elements:I.elements},v=t.dialogue?.content===void 0?[{text:""}]:$n(t.dialogue.content,"dialogue.content"),k=(t.dialogue?.lines||[]).map((E,L)=>({content:$n(E.content,`dialogue.lines[${L}].content`).map(H=>({...H,text:_n(H.text,{variables:d})})),characterName:E.characterId&&r.characters?.[E.characterId]?.name||""})),C={variables:d,autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:l,skipOnlyViewedLines:c,isLineCompleted:u,saveSlots:p,effectiveSoundVolume:d?._muteAll?0:d?._soundVolume??500,textSpeed:d?._textSpeed??50,dialogueLines:k,dialogue:{character:{name:w?.name||""},content:v.map(E=>({...E,text:_n(E.text,{variables:d})})),lines:k}},A={functions:oe},R=ze(_,C,A),N=z(R,C,A),U=ie(ce(N?.elements,{isLineCompleted:u,skipMode:s,skipTransitionsAndAnimations:f}),r);if(Array.isArray(U))for(let E of U)m.children.push(E);else U&&m.children.push(U)}}return t.dialogue.ui?.animations&&!u&&!f&&re({animations:y,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"}),e},Ko=(e,{presentationState:t,previousPresentationState:n,resources:r,screen:o,isLineCompleted:i,skipTransitionsAndAnimations:s,variables:a,autoMode:l,skipMode:c,isChoiceVisible:u,canRollback:f,saveSlots:d=[]})=>{let{elements:p,animations:g}=e;if(t.choice&&r){let y=Ue(p);if(!y)return e;let m=r?.layouts[t.choice.resourceId];if(m&&m.elements){let b={elements:m.elements},I=z(b,{...se({variables:a,saveSlots:d,isLineCompleted:i,autoMode:l,skipMode:c,isChoiceVisible:u??!!t.choice,canRollback:f}),choice:{items:t.choice?.items??[]}},{functions:oe}),w=_t(ie(ce(I?.elements,{isLineCompleted:i,skipMode:c,skipTransitionsAndAnimations:s}),r));if(Array.isArray(w))for(let _ of w)y.children.push(_);else w&&y.children.push(w)}t.choice.animations&&!i&&!s&&re({animations:g,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"})}return e},Go=(e,{presentationState:t,resources:n={},variables:r,isLineCompleted:o,autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:l,saveSlots:c=[],skipTransitionsAndAnimations:u})=>{if(!t.control?.resourceId)return e;let f=n.controls?.[t.control.resourceId];if(!f)return e;let d=Fo(f.keyboard);if(d&&Object.keys(d).length>0&&(e.global.keyboard=d),!Array.isArray(f.elements)||f.elements.length===0)return e;let p=Ue(e.elements);if(!p)return e;let g={id:`control-${t.control.resourceId}`,type:"container",x:0,y:0,children:f.elements};return p.children.push(Bn({container:g,resources:n,templateData:se({variables:r,saveSlots:c,isLineCompleted:o,autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:l}),isLineCompleted:o,skipMode:s,skipTransitionsAndAnimations:u})),e},Jo=(e,{presentationState:t,resources:n,variables:r})=>{let{elements:o,audio:i}=e;if(t.bgm&&n){if(!Ue(o))return e;let a=n.sounds[t.bgm.resourceId];if(!a)return e;let l=r?._muteAll?0:r?._musicVolume??500;i.push({id:"bgm",type:"sound",src:a.fileId,loop:t.bgm.loop??!0,volume:l,delay:t.bgm.delay??null})}return e},Xo=(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??500,delay:i.delay??s.delay??null})}}return e},Zo=(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??500,loop:s??!1}),e},Qo=(e,{presentationState:t,previousPresentationState:n,resources:r={},variables:o,autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:l,saveSlots:c=[],isLineCompleted:u,skipTransitionsAndAnimations:f})=>{let{elements:d,animations:p}=e;if(t.layout){let g=Ue(d);if(!g)return e;let y=r.layouts[t.layout.resourceId];if(!y)return e;Array.isArray(y.transitions)&&!u&&!f&&Ct({animations:p,transitions:y.transitions,defaultTargetId:`layout-${t.layout.resourceId}`,idPrefix:`layout-${t.layout.resourceId}`,animationPathPrefix:"layout"});let m={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:y.elements||[]};g.children.push(Bn({container:m,resources:r,templateData:se({variables:o,saveSlots:c,isLineCompleted:u,autoMode:i,skipMode:s,isChoiceVisible:a,canRollback:l}),isLineCompleted:u,skipMode:s,skipTransitionsAndAnimations:f}))}if(t.layout?.animations&&!u&&!f){let g=n?.layout?.resourceId,y=t.layout?.resourceId;re({animations:p,animationsDef:t.layout.animations,resources:r,previousResourceId:g,currentResourceId:y,previousTargetId:g?`layout-${g}`:void 0,currentTargetId:y?`layout-${y}`:void 0,animationPath:"layout.animations",idPrefix:"layout"})}return e},ei=(e,{resources:t={},variables:n,autoMode:r,skipMode:o,isChoiceVisible:i,canRollback:s,layeredViews:a=[],dialogueHistory:l=[],saveSlots:c=[],screen:u,isLineCompleted:f,skipTransitionsAndAnimations:d})=>{let{elements:p,animations:g}=e;return a&&a.length>0&&a.forEach((y,m)=>{let b=t.layouts[y.resourceId];if(!b){console.warn(`LayeredView layout not found: ${y.resourceId}`);return}Array.isArray(b.transitions)&&(d||Ct({animations:g,transitions:b.transitions,defaultTargetId:`layeredView-${m}`,idPrefix:`layeredView-${m}`,animationPathPrefix:`layeredViews[${m}]`}));let I={id:`layeredView-${m}`,type:"container",x:0,y:0,children:[jn({id:`layeredView-${m}-blocker`,screen:u}),...b.elements||[]]},w=Mn(l,t.characters),_=se({variables:n,saveSlots:c,isLineCompleted:f,autoMode:r,skipMode:o,isChoiceVisible:i,canRollback:s,historyDialogue:w,characters:t.characters||{}}),v=z(I,_,{functions:oe}),[k,...C]=v.children||[],A=ie(ce({...v,children:C},{isLineCompleted:f,skipMode:o,skipTransitionsAndAnimations:d}),t);p.push({...A,children:k?[k,...A.children||[]]:A.children})}),e},ti=(e,{resources:t={},variables:n,saveSlots:r=[],autoMode:o,skipMode:i,isChoiceVisible:s,canRollback:a,confirmDialog:l,dialogueHistory:c=[],screen:u,isLineCompleted:f,skipTransitionsAndAnimations:d})=>{let{elements:p,animations:g}=e;if(!l?.resourceId)return e;let y=t.layouts?.[l.resourceId];if(!y)return console.warn(`ConfirmDialog layout not found: ${l.resourceId}`),e;Array.isArray(y.transitions)&&!d&&Ct({animations:g,transitions:y.transitions,defaultTargetId:"confirmDialog",idPrefix:"confirmDialog",animationPathPrefix:"confirmDialog"});let m={id:"confirmDialog",type:"container",x:0,y:0,children:[jn({id:"confirmDialog-blocker",screen:u}),...y.elements||[]]},b=Mn(c,t.characters),I=z(m,se({variables:n,saveSlots:r,isLineCompleted:f,autoMode:o,skipMode:i,isChoiceVisible:s,canRollback:a,confirmDialog:l,historyDialogue:b,characters:t.characters||{}}),{functions:oe}),[w,..._]=I.children||[],v=ie(ce({...I,children:_},{isLineCompleted:f,skipMode:i,skipTransitionsAndAnimations:d}),t);return p.push({...v,children:w?[w,...v.children||[]]:v.children}),e},zn=e=>Ne(Uo,[Go,Wo,Yo,Ho,qo,Ko,Qo,Jo,Xo,Zo,ei,ti])(e);var We={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},Wn=1,qe=()=>({manual:{...We.manual},auto:{...We.auto},applyMode:We.applyMode}),St=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let n=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={...qe()},n&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},W=e=>{let t=J(e)?lt(e):e;return structuredClone(t)},F=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Ke=e=>String(e),Rt=()=>({sections:[],resources:[]}),Ye=()=>({sectionId:void 0,lineId:void 0}),ni=e=>Array.isArray(e)?e.map(t=>t?.text??"").join(""):"",ri=()=>({resourceId:void 0}),oi=e=>{if(!F(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},Yn=(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}},Hn=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)}}},qn=e=>{if(typeof e=="number"||typeof e!="string")return e;let t=Number(e);return Number.isFinite(t)?t:e},Kn=e=>{if(!Number.isInteger(e)||e<1)throw new Error("Malformed save slot formatVersion.");if(e!==Wn)throw new Error(`Unsupported save slot formatVersion "${e}".`);return e},ii=(e,t={})=>{let n;try{n=Kn(t.formatVersion)}catch(o){throw new Error(`Hydrated save slot "${e}" failed validation: ${o.message}`)}let r={...t,formatVersion:n,slotId:qn(t.slotId??t.slotKey??e),savedAt:typeof t.savedAt=="number"?t.savedAt:t.date};return delete r.slotKey,delete r.date,r},si=(e={})=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,ii(t,n)])),Fn=(e,t,n)=>{let r=t==="sections"?"sectionId":"resourceId";if(typeof e=="string"||typeof e=="number")return{[r]:String(e)};if(!F(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}},ci=e=>{if(e===void 0)return Rt();if(!F(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=Fn(r,"sections",o);return[i.sectionId,i]}))),resources:Object.values(Object.fromEntries(n.map((r,o)=>{let i=Fn(r,"resources",o);return[i.resourceId,i]})))}},kt=(e,t,n)=>{if(!F(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}=Yn(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}},li=(e,t)=>{if(!F(e)||typeof e.sectionId!="string"||e.sectionId.length===0||typeof e.lineId!="string"||e.lineId.length===0)return Ye();try{let n=kt(e,t,"contexts[*].pointers.history");return{sectionId:n.sectionId,lineId:n.lineId}}catch{return Ye()}},ai=(e,t,n)=>{if(!F(e)||!Array.isArray(e.timeline))return ge({pointer:t,replayStartIndex:1});let r=e.timeline.flatMap((a,l)=>{if(!F(a))return[];try{let c=kt(a,n,`rollback.timeline[${l}]`),u=He({sectionId:c.sectionId,lineId:c.lineId,rollbackPolicy:a.rollbackPolicy});return Array.isArray(a.executedActions)&&(u.executedActions=W(a.executedActions)),[u]}catch{return[]}});if(r.length===0)return ge({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(He({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}},ui=(e,t,n)=>{if(!F(e))throw new Error(`Malformed save slot contexts[${n}] entry.`);let r=Tt(t),o=kt(e.pointers?.read,t,`contexts[${n}].pointers.read`);if(e.variables!==void 0&&!F(e.variables))throw new Error(`Malformed save slot contexts[${n}].variables entry.`);let i=li(e.pointers?.history,t);return{currentPointerMode:e.currentPointerMode==="history"&&i.lineId?"history":"read",pointers:{read:o,history:i},configuration:F(e.configuration)?W(e.configuration):{},views:Array.isArray(e.views)?W(e.views):[],bgm:F(e.bgm)?W(e.bgm):{resourceId:void 0},variables:{...r,...e.variables?W(e.variables):{}},rollback:ai(e.rollback,o,t)}},fi=(e,t)=>{if(!F(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:ci(e.viewedRegistry),contexts:e.contexts.map((n,r)=>ui(n,t,r))}},di=(e,t)=>{if(!F(e))throw new Error("Malformed save slot.");let n=Kn(e.formatVersion);return{...e,formatVersion:n,state:fi(e.state,t)}},Un=(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=W(e);return Object.prototype.hasOwnProperty.call(r,"hideConfirmDialog")||(r.hideConfirmDialog={}),r},pi=(e={})=>{if(!e?.resourceId)throw new Error("showConfirmDialog requires resourceId");return{resourceId:e.resourceId,confirmActions:Un(e.confirmActions,"confirmActions",{required:!0}),cancelActions:Un(e.cancelActions,"cancelActions")}},me=e=>{Object.prototype.hasOwnProperty.call(e.global,"confirmDialog")&&(e.global.confirmDialog=null)},le=[],Ot=()=>le[le.length-1]??null,Pt=e=>{let t=Ot();t&&(t.checkpointIndex=e)},hi=()=>{let e=Ot();e&&(e.pendingStorySessionReset=!0)},Gn=()=>{let e=Ot();return e?.pendingStorySessionReset?(delete e.pendingStorySessionReset,!0):!1},He=({sectionId:e,lineId:t,rollbackPolicy:n})=>({sectionId:e,lineId:t,rollbackPolicy:n??"free"}),Tt=e=>{let{contextVariableDefaultValues:t}=mt(e??{});return W(t)},Jn=({pointer:e,projectData:t})=>({currentPointerMode:"read",pointers:{read:W(e),history:Ye()},configuration:{},views:[],bgm:ri(),variables:Tt(t),rollback:ge({pointer:e})}),gi=e=>{e.global.autoMode=!1,e.global.skipMode=!1,e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,me(e),e.global.viewedRegistry=Rt(),e.global.nextLineConfig=qe(),e.global.layeredViews=[],e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})},Xn=e=>{!e||!("baselineVariables"in e)||delete e.baselineVariables},ge=({pointer:e,replayStartIndex:t=0})=>{let n=e?.sectionId&&e?.lineId;return{currentIndex:n?0:-1,isRestoring:!1,replayStartIndex:t,timeline:n?[He({sectionId:e.sectionId,lineId:e.lineId})]:[]}},ue=(e,t={})=>{if(e?.rollback)return Xn(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=ge({pointer:n,replayStartIndex:t.compatibilityAnchor?1:0}),e.rollback},Vt=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return;let r=ue(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(He(t)),r.currentIndex=r.timeline.length-1},mi=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=le[le.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)},yi=({state:e})=>{let n=e.contexts?.[e.contexts.length-1]?.rollback;return!n||n.isRestoring||!Array.isArray(n.timeline)||typeof n.currentIndex!="number"||n.currentIndex<0||n.currentIndex>=n.timeline.length?(le.push({checkpointIndex:null}),e):(n.currentIndex<n.timeline.length-1&&(n.timeline=n.timeline.slice(0,n.currentIndex+1)),le.push({checkpointIndex:n.currentIndex}),e)},bi=({state:e})=>(le.pop(),e),Z=(e,t,n)=>{let r=mi(e);r&&(Array.isArray(r.executedActions)||(r.executedActions=[]),r.executedActions.push({type:t,payload:W(n)}))},Ii=(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;De(l,o),je(c,i,o),l==="context"&&(n.variables[o]=Me(n.variables[o],i,s))}},wi=(e,t)=>{if(!Array.isArray(t?.executedActions))return!1;let n={showDialogueUI:ye,hideDialogueUI:Je,toggleDialogueUI:Ft,setNextLineConfig:Ut,pushLayeredView:jt,popLayeredView:Mt,replaceLastLayeredView:Bt,clearLayeredViews:zt};return t.executedActions.forEach(({type:r,payload:o})=>{if(r==="updateVariable"){Ii(e,o);return}let i=n[r];i&&i({state:e},o)}),!0},xi=(e,t)=>{let{sectionId:n,lineId:r}=t,s=P({state:e},{sectionId:n})?.lines?.find(c=>c.id===r)?.actions?.updateVariable;if(!s)return;let a=e.contexts?.[e.contexts.length-1];if(!a)return;let l=s.operations||[];for(let{variableId:c,op:u,value:f}of l){let d=e.projectData.resources?.variables?.[c],p=d?.scope,g=d?.type;De(p,c),je(g,u,c),p==="context"&&(a.variables[c]=Me(a.variables[c],u,f))}},Ai=(e,t)=>{let{sectionId:n,lineId:r}=t,s=P({state:e},{sectionId:n})?.lines?.find(l=>l.id===r)?.actions;if(!s)return;let a={showDialogueUI:ye,hideDialogueUI:Je,toggleDialogueUI:Ft,setNextLineConfig:Ut,pushLayeredView:jt,popLayeredView:Mt,replaceLastLayeredView:Bt,clearLayeredViews:zt};Object.entries(s).forEach(([l,c])=>{let u=a[l];u&&u({state:e},c)})},Zn=(e,t)=>{let n=e.contexts?.[e.contexts.length-1];if(!n)return e;let r=ue(n),o=r.timeline[t];if(!o)return e;e.global.autoMode&&Ce({state:e}),e.global.skipMode&&ae({state:e}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),r.isRestoring=!0,r.currentIndex=t;try{n.variables=Tt(e.projectData),e.global.dialogueUIHidden=!1,delete e.global.isDialogueHistoryShowing,e.global.nextLineConfig=W(We),e.global.layeredViews=[],me(e),e.global.isLineCompleted=!0;let i=r.replayStartIndex??0;for(let s=i;s<=t;s++)s>i&&St(e),wi(e,r.timeline[s])||(xi(e,r.timeline[s]),Ai(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},vi=e=>{let{projectData:t}=e,n=e.global??{},{saveSlots:r={},variables:o={}}=n;Hn(t);let i=t.story.initialSceneId,s=t.story.scenes[i],a=s.initialSectionId,l=s.sections[a],c={sceneId:i,sectionId:a,lineId:l.initialLineId??l.lines[0].id},{globalVariablesDefaultValues:u}=mt(t),f={...u,...o};return{projectData:t,global:{isLineCompleted:!1,pendingEffects:[],autoMode:!1,skipMode:!1,dialogueUIHidden:!1,confirmDialog:null,viewedRegistry:Rt(),nextLineConfig:qe(),saveSlots:si(r),layeredViews:[],variables:f},contexts:[Jn({pointer:c,projectData:t})]}},Ei=({state:e})=>e.global.layeredViews||[],_i=({state:e})=>e.global.pendingEffects,Qn=({state:e})=>e.global.skipMode,$i=({state:e})=>e.global.autoMode,er=({state:e})=>e.global.dialogueUIHidden,tr=({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=P({state:e},{sectionId:r});if(!i?.lines||!Array.isArray(i.lines))return[];let s=i.lines.findIndex(c=>c.id===o);return i.lines.slice(0,s+1).filter(c=>c.actions?.dialogue).map(c=>{let u=c.actions.dialogue,f="";return u.characterId&&(f=e.projectData.resources?.characters?.[u.characterId]?.name||""),{sectionId:r,lineId:c.id,content:u.content,text:ni(u.content),characterId:u.characterId,characterName:f}})},Ci=({state:e})=>e.global.confirmDialog??null,Nt=({state:e},t)=>{let{sectionId:n,lineId:r}=t,o=e.global.viewedRegistry.sections.find(l=>l.sectionId===n);if(!o)return!1;if(o.lastLineId===void 0||r===void 0)return!0;let i=P({state:e},{sectionId:n});if(!i||!i.lines||!Array.isArray(i.lines))return o.lastLineId===r;let s=i.lines.findIndex(l=>l.id===o.lastLineId),a=i.lines.findIndex(l=>l.id===r);return s===-1||a===-1?o.lastLineId===r:a<=s},Li=({state:e},t)=>{let{resourceId:n}=t;return!!e.global.viewedRegistry.resources.find(o=>o.resourceId===n)},Si=({state:e})=>e.global.nextLineConfig,nr=({state:e,pointer:t}={})=>{let n=t??K({state:e})?.pointer;if(!n)return;let r=n?.sectionId,o=n?.lineId,s=P({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},G=({state:e})=>!!nr({state:e}),Ri=({state:e})=>structuredClone(e),rr=({state:e})=>e.global.saveSlots,ki=({state:e},t)=>{let n=t?.slotId,r=Ke(n);return e.global.saveSlots[r]},Oi=({state:e})=>({...e.global?.variables??{},...e.contexts?.[e.contexts.length-1]?.variables??{}}),K=({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}},P=({state:e},t)=>{let{sectionId:n}=t;return Yn(e.projectData,n).section},or=({state:e})=>{let t=K({state:e});if(!t?.pointer)return;let{sectionId:n,lineId:r}=t.pointer,o=P({state:e},{sectionId:n});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===r)},ir=({state:e})=>{let{sectionId:t,lineId:n}=K({state:e}).pointer,o=P({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 Ae(a)},Pi=({state:e})=>{let t=sr({state:e}),r=or({state:e})?.actions??{},o=Ae([t??{},r]);return bt(t??{},o??{})},Ti=({state:e},{sectionId:t})=>{let n=P({state:e},{sectionId:t});if(!n?.lines)return{lines:[]};let r=[],o={};for(let i of n.lines){let s=i.actions||{},a=Ae([o,s]),l=bt(o,a);r.push({id:i.id,changes:l}),o=It(a)}return{lines:r}},sr=({state:e})=>{let{sectionId:t,lineId:n}=K({state:e}).pointer,o=P({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 It(Ae(a))},Dt=({state:e},{slotsPerPage:t=6}={})=>{let o=(({...e.global.variables,...e.contexts[e.contexts.length-1].variables}.loadPage??1)-1)*t+1,i=[];for(let s=0;s<t;s++){let a=o+s,l=e.global.saveSlots&&e.global.saveSlots[Ke(a)]||{};i.push({...l,slotId:a})}return{saveSlots:i}},Vi=rr,Ni=Dt,Di=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},ji=({state:e})=>{let t=ir({state:e}),n=sr({state:e}),r={...e.global.variables,...e.contexts[e.contexts.length-1].variables},{saveSlots:o}=Dt({state:e}),i=Di(e);return zn({presentationState:t,previousPresentationState:n,resources:e.projectData.resources,screen:e.projectData.screen,dialogueUIHidden:e.global.dialogueUIHidden,autoMode:e.global.autoMode,skipMode:e.global.skipMode,isChoiceVisible:G({state:e}),canRollback:ur({state:e}),skipOnlyViewedLines:!r._skipUnseenText,isLineCompleted:e.global.isLineCompleted,skipTransitionsAndAnimations:!!r._skipTransitionsAndAnimations||i,layeredViews:e.global.layeredViews,confirmDialog:e.global.confirmDialog,dialogueHistory:tr({state:e}),saveSlots:o,variables:r})},Mi=({state:e},t)=>(e.global.confirmDialog=pi(t),e.global.pendingEffects.push({name:"render"}),e),Bi=({state:e})=>(e.global.confirmDialog&&(me(e),e.global.pendingEffects.push({name:"render"})),e),jt=({state:e},t)=>(e.global.layeredViews.push(t),e.global.pendingEffects.push({name:"render"}),Z(e,"pushLayeredView",t),e),Mt=({state:e})=>(e.global.layeredViews.pop(),e.global.pendingEffects.push({name:"render"}),Z(e,"popLayeredView",void 0),e),Bt=({state:e},t)=>(e.global.layeredViews.length>0&&(e.global.layeredViews[e.global.layeredViews.length-1]=t),e.global.pendingEffects.push({name:"render"}),Z(e,"replaceLastLayeredView",t),e),zt=({state:e})=>(e.global.layeredViews=[],me(e),e.global.pendingEffects.push({name:"render"}),Z(e,"clearLayeredViews",void 0),e),zi=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"})},Ge=(e,t)=>{e.global.isLineCompleted=!1;let n=!!nr({state:e,pointer:t});return n&&zi(e),e.global.pendingEffects.push({name:"handleLineActions"}),{isChoiceVisible:n}},cr=({state:e})=>{if(G({state:e}))return e;if(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){let t=e.global.variables._autoForwardTime??1e3;e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:t}})}return e.global.pendingEffects.push({name:"render"}),e},Ce=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Fi=({state:e})=>{let t=e.global.autoMode;return G({state:e})&&!t||(t?Ce({state:e}):cr({state:e})),e},lr=({state:e})=>(G({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),ae=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Ui=({state:e})=>{let t=Qn({state:e});return G({state:e})&&!t||(t?ae({state:e}):lr({state:e})),e},ye=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),Z(e,"showDialogueUI",void 0),e),Je=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),Z(e,"hideDialogueUI",void 0),e),Ft=({state:e})=>(er({state:e})?ye({state:e}):Je({state:e}),e),Wi=({state:e})=>(e.global.pendingEffects=[],e),Yi=({state:e},t)=>(e.global.pendingEffects.push(t),e),Hi=({state:e})=>{let t=e.contexts?.[e.contexts.length-1],n=t?.pointers?.read;return!t||!n?.sectionId||!n?.lineId||(e.contexts[e.contexts.length-1]=Jn({pointer:n,projectData:e.projectData}),gi(e),hi(),Pt(0)),e},$e=(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=P({state:e},{sectionId:t});if(o?.lines&&r.lastLineId!==void 0){let i=o.lines.findIndex(a=>a.id===r.lastLineId),s=o.lines.findIndex(a=>a.id===n);(i===-1||s>i)&&(r.lastLineId=n)}else r.lastLineId=n}else e.global.viewedRegistry.sections.push({sectionId:t,lastLineId:n})},qi=({state:e},t)=>($e(e,t),e.global.pendingEffects.push({name:"render"}),e),Ki=({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},Ut=({state:e},t)=>{let n=oi(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=G({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"}),Z(e,"setNextLineConfig",t),e},Gi=({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=Ke(n),s=W(e.contexts);s?.forEach(c=>{Xn(c.rollback)});let a={contexts:s,viewedRegistry:W(e.global.viewedRegistry)},l={formatVersion:Wn,slotId:qn(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},Ji=({state:e},t)=>{let n=t?.slotId;if(n==null||n==="")throw new Error("loadSlot requires slotId");let r=Ke(n),o=e.global.saveSlots[r];if(o){let i=di(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=qe(),e.global.layeredViews=[],e.global.isLineCompleted=!0,me(e),e.global.pendingEffects.push({name:"clearAutoNextTimer"},{name:"clearSkipNextTimer"},{name:"clearNextLineConfigTimer"},{name:"render"})}return e},Xi=({state:e},t)=>{let{projectData:n}=t;return Hn(n),e.projectData=n,me(e),e.global.pendingEffects.push({name:"render"}),e},Zi=({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&&!P({state:e},{sectionId:n}))return console.warn(`Section not found: ${n}`),e;let s=P({state:e},{sectionId:i});return!s?.lines||!Array.isArray(s.lines)?(console.warn(`Section ${i} has no lines`),e):s.lines.find(l=>l.id===r)?(o.pointers.read={sectionId:i,lineId:r},Gn()&&(o.rollback=ge({pointer:o.pointers.read}),Pt(o.rollback.currentIndex)),Ge(e,o.pointers.read),e):(console.warn(`Line not found: ${r} in section ${i}`),e)},Qi=({state:e},t)=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(e.global.dialogueUIHidden)return ye({state:e}),e;if(G({state:e})&&t?._interactionSource!=="choice")return e;if(!e.global.isLineCompleted){e.global.isLineCompleted=!0;let c=K({state:e})?.pointer,u=c?.sectionId,f=c?.lineId;if(u&&f&&$e(e,{sectionId:u,lineId:f}),e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode){let p=e.global.variables._autoForwardTime??1e3;e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:p}})}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=K({state:e})?.pointer,r=n?.sectionId,o=P({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=!e.global.variables?._skipUnseenText;if(e.global.skipMode&&u&&!Nt({state:e},{sectionId:r,lineId:c.id}))return ae({state:e}),e;if(i&&!i.rollback&&ue(i,{compatibilityAnchor:!0}),i){let p=i.pointers.read.lineId;p&&r&&$e(e,{sectionId:r,lineId:p}),i.pointers.read={sectionId:r,lineId:c.id}}Vt(e,{sectionId:r,lineId:c.id}),St(e);let{isChoiceVisible:f}=Ge(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&&Ce({state:e}),e.global.skipMode&&ae({state:e});return e},es=({state:e})=>{if(e.global.isLineCompleted)return e;e.global.isLineCompleted=!0;let t=G({state:e});if(e.global.autoMode&&!t){let s=e.global.variables._autoForwardTime??1e3;e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:s}})}let n=K({state:e})?.pointer,r=n?.sectionId,o=n?.lineId;r&&o&&$e(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},ts=({state:e},t)=>{let n=t?.sectionId??K({state:e})?.pointer?.sectionId,r=P({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.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 l=o.findIndex(c=>c.id===i.pointers.history.lineId)-1;if(l>=0&&l<o.length){let c=o[l];i.pointers.history={sectionId:n,lineId:c.id},e.global.pendingEffects.push({name:"render"})}return e},ns=({state:e},t)=>{let{sectionId:n}=t,r=P({state:e},{sectionId:n});if(!r)return console.warn(`Section not found: ${n}`),e;let o=r.lines?.[0];if(!o)return console.warn(`Section ${n} has no lines`),e;e.global.autoMode&&Ce({state:e}),e.global.skipMode&&ae({state:e});let i=e.contexts[e.contexts.length-1];return i&&(i.rollback||ue(i,{compatibilityAnchor:!0}),i.pointers.read={sectionId:n,lineId:o.id},Gn()?(i.rollback=ge({pointer:i.pointers.read}),Pt(i.rollback.currentIndex)):Vt(e,{sectionId:n,lineId:o.id})),Ge(e,i?.pointers?.read),e},rs=({state:e})=>{if(e.global.dialogueUIHidden)return ye({state:e}),e;if(G({state:e}))return e;let t=K({state:e})?.pointer,n=t?.sectionId,r=P({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=!e.global.variables?._skipUnseenText;if(e.global.skipMode&&c&&!Nt({state:e},{sectionId:n,lineId:l.id}))return ae({state:e}),e;if(o&&!o.rollback&&ue(o,{compatibilityAnchor:!0}),o){let f=o.pointers.read.lineId;f&&n&&$e(e,{sectionId:n,lineId:f}),o.pointers.read={sectionId:n,lineId:l.id}}Vt(e,{sectionId:n,lineId:l.id}),St(e);let{isChoiceVisible:u}=Ge(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},os=({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,a=!1,l=[];if(r.forEach(({variableId:c,op:u,value:f})=>{let d=e.projectData.resources?.variables?.[c],p=d?.scope,g=d?.type;De(p,c),je(g,u,c);let y=p==="context"?o.variables:e.global.variables;p==="context"?(i=!0,l.push({variableId:c,op:u,value:f})):p==="device"?s=!0:p==="account"&&(a=!0),y[c]=Me(y[c],u,f)}),i&&Z(e,"updateVariable",{id:n,operations:l}),s){let c=yt(e.global.variables,e.projectData.resources?.variables,"device");e.global.pendingEffects.push({name:"saveGlobalDeviceVariables",payload:{globalDeviceVariables:c}})}if(a){let c=yt(e.global.variables,e.projectData.resources?.variables,"account");e.global.pendingEffects.push({name:"saveGlobalAccountVariables",payload:{globalAccountVariables:c}})}return e.global.pendingEffects.push({name:"render"}),e},ar=({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}},ur=({state:e})=>ar({state:e},{offset:-1})!==null,is=({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=ue(r,{compatibilityAnchor:!r.rollback}),i=o.currentIndex+n;return i<0||i>=o.timeline.length?e:Zn(e,i)},ss=({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=ue(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:Zn(e,a)},fr=e=>{let t=vi(e);return wn(t,{selectPendingEffects:_i,selectSkipMode:Qn,selectAutoMode:$i,selectIsChoiceVisible:G,selectDialogueUIHidden:er,selectDialogueHistory:tr,selectConfirmDialog:Ci,selectIsLineViewed:Nt,selectIsResourceViewed:Li,selectNextLineConfig:Si,selectSystemState:Ri,selectSaveSlotMap:rr,selectSaveSlots:Vi,selectSaveSlot:ki,selectAllVariables:Oi,selectCurrentPointer:K,selectSection:P,selectCurrentLine:or,selectPresentationState:ir,selectPresentationChanges:Pi,selectSectionLineChanges:Ti,selectSaveSlotPage:Dt,selectCurrentPageSlots:Ni,selectRenderState:ji,selectLayeredViews:Ei,selectLineIdByOffset:ar,selectCanRollback:ur,startAutoMode:cr,stopAutoMode:Ce,toggleAutoMode:Fi,startSkipMode:lr,stopSkipMode:ae,toggleSkipMode:Ui,showDialogueUI:ye,hideDialogueUI:Je,toggleDialogueUI:Ft,showConfirmDialog:Mi,hideConfirmDialog:Bi,resetStorySession:Hi,clearPendingEffects:Wi,appendPendingEffect:Yi,beginRollbackActionBatch:yi,endRollbackActionBatch:bi,addViewedLine:qi,addViewedResource:Ki,setNextLineConfig:Ut,saveSlot:Gi,loadSlot:Ji,updateProjectData:Xi,sectionTransition:ns,jumpToLine:Zi,nextLine:Qi,markLineCompleted:es,prevLine:ts,rollbackToLine:ss,rollbackByOffset:is,pushLayeredView:jt,popLayeredView:Mt,replaceLastLayeredView:Bt,clearLayeredViews:zt,updateVariable:os,nextLineFromSystem:rs},{transformActionFirstArgument:r=>({state:r}),transformSelectorFirstArgument:r=>({state:r})})};var cs="route-engine",ls="projectPersistence";var dr=()=>({saveSlots:{},globalDeviceVariables:{},globalAccountVariables:{}}),fe=e=>Object.prototype.toString.call(e)==="[object Object]",pr=(e={})=>{let t=fe(e)?e:{};return{saveSlots:fe(t.saveSlots)?t.saveSlots:{},globalDeviceVariables:fe(t.globalDeviceVariables)?t.globalDeviceVariables:{},globalAccountVariables:fe(t.globalAccountVariables)?t.globalAccountVariables:{}}},Yt=e=>{if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null},as=e=>{let t=Yt(e);if(!t)throw new Error("createIndexedDbPersistence requires a non-empty namespace.");return t},us=e=>{let t=e??globalThis.indexedDB;if(!t)throw new Error("IndexedDB is not available in this environment.");return t},fs=({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}".`))}}),ds=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.`))}})},Wt=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=pr(c.result),g={namespace:n,version:1,...dr(),...p,...r},y=l.put(g);y.onerror=()=>{f(y.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}".`))}})},ps=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}".`))}})},Ht=(e={})=>{let{indexedDB:t,databaseName:n=cs,objectStoreName:r=ls,namespace:o}=e,i=us(t),s=as(o),a=fs({indexedDB:i,databaseName:n,objectStoreName:r});return{namespace:s,load:async()=>{let l=await ds({databasePromise:a,objectStoreName:r,namespace:s});return{...dr(),...pr(l)}},clear:async()=>ps({databasePromise:a,objectStoreName:r,namespace:s}),saveSlots:async l=>Wt({databasePromise:a,objectStoreName:r,namespace:s,patch:{saveSlots:fe(l)?l:{}}}),saveGlobalDeviceVariables:async l=>Wt({databasePromise:a,objectStoreName:r,namespace:s,patch:{globalDeviceVariables:fe(l)?l:{}}}),saveGlobalAccountVariables:async l=>Wt({databasePromise:a,objectStoreName:r,namespace:s,patch:{globalAccountVariables:fe(l)?l:{}}})}},hs=Ht;function qt(e){let t,n=0,r=null,{handlePendingEffects:o}=e,i=()=>{for(;t.selectPendingEffects().length>0;){let A=[...t.selectPendingEffects()];t.clearPendingEffects();try{o(A)}catch(R){throw t.clearPendingEffects(),A.forEach(N=>{t.appendPendingEffect(N)}),R}}},s=({initialState:A,namespace:R})=>{t=fr(A),n=0,r=Yt(R),t.appendPendingEffect({name:"handleLineActions"}),i()},a=()=>r,l=()=>t.selectPresentationState(),c=()=>t.selectPresentationChanges(),u=A=>t.selectSectionLineChanges(A),f=()=>(n+=1,{...t.selectRenderState(),id:`render-${n}`}),d=()=>t.selectSystemState(),p=()=>t.selectSaveSlotMap(),g=A=>t.selectSaveSlot(A),y=A=>t.selectSaveSlotPage(A),m=()=>t.selectSkipMode(),b=()=>t.selectAutoMode(),I=()=>t.selectIsChoiceVisible(),w=(A,R)=>{t[A]&&(t[A](R),i())},_=(A,R)=>{w(A,R)},v=A=>{if(!A)return{variables:t.selectAllVariables?t.selectAllVariables():void 0};if(Object.prototype.hasOwnProperty.call(A,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:R,...N}=A,U=t.selectAllVariables?t.selectAllVariables():void 0;return{...N,_event:R,variables:U}},k=(A,R)=>{let N=v(R),U=vn(A,N);t.beginRollbackActionBatch({});try{Object.entries(U).forEach(([E,L])=>{w(E,L)})}finally{t.endRollbackActionBatch({})}};return{init:s,handleAction:w,handleInternalAction:_,handleActions:k,selectRenderState:f,selectPresentationState:l,selectPresentationChanges:c,selectSectionLineChanges:u,selectSystemState:d,selectSaveSlotMap:p,selectSaveSlot:g,selectSaveSlotPage:y,selectSaveSlots:p,selectIsChoiceVisible:I,handleLineActions:()=>{let A=t.selectCurrentLine();return A?.actions?(k(A.actions),!0):!1},getNamespace:a}}var Kt=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:n=>{e=n},addElapsed:n=>{e+=n},getCallback:()=>t,setCallback:n=>{t=n}}},gs=80,gr=({engine:e,routeGraphics:t,trackRenderDispatch:n},r)=>{let o=e.selectRenderState();n?.(o),t.render(o)},ms=({engine:e,routeGraphics:t,trackRenderDispatch:n,getRenderDispatchCount:r},o)=>{let i=r?.()??0,s=e.handleLineActions();(r?.()??0)===i&&gr({engine:e,routeGraphics:t,trackRenderDispatch:n},o)},ys=({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),Xe(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},bs=({ticker:e,autoTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Is=({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??gs;n.getElapsed()>=a&&(n.setElapsed(0),Xe(e,"nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},ws=({ticker:e,skipTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},xs=({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),Xe(e,"nextLineFromSystem",{}),t.remove(i),n.setCallback(null))};n.setCallback(i),t.add(i)},As=({ticker:e,nextLineConfigTimerState:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},vs=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveSlots(t?.saveSlots))},Es=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalDeviceVariables(t?.globalDeviceVariables))},_s=({enqueuePersistenceWrite:e},t)=>{e(n=>n.saveGlobalAccountVariables(t?.globalAccountVariables))},hr={render:gr,saveSlots:vs,saveGlobalDeviceVariables:Es,saveGlobalAccountVariables:_s,handleLineActions:ms,startAutoNextTimer:ys,clearAutoNextTimer:bs,startSkipNextTimer:Is,clearSkipNextTimer:ws,nextLineConfigTimer:xs,clearNextLineConfigTimer:As},$s=new Set(["render","handleLineActions","saveSlots","saveGlobalDeviceVariables","saveGlobalAccountVariables","startAutoNextTimer","clearAutoNextTimer","startSkipNextTimer","clearSkipNextTimer","nextLineConfigTimer","clearNextLineConfigTimer"]),Xe=(e,t,n)=>{(e.handleInternalAction??e.handleAction?.bind(e))?.(t,n)},Cs=(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(!$s.has(o.name)){n.unshift(o);continue}t.has(o.name)||(t.add(o.name),n.unshift(o))}return n},Ls=({getEngine:e,routeGraphics:t,ticker:n,handleUnhandledEffect:r,handlePersistenceError:o,indexedDB:i,persistence:s,namespace:a})=>{let l=Kt(),c=Kt(),u=Kt(),f=s??null,d=Promise.resolve(),p=null,g=null,y=!1,m=0,b=E=>{if(o){o(E);return}console.error("RouteEngine persistence write failed.",E)},I=()=>{if(f)return f;let E=e();return f=Ht({indexedDB:i,namespace:a??E?.getNamespace?.()}),f},w=E=>{d=d.catch(()=>{}).then(()=>{let L=I();return E(L)}).catch(L=>{b(L)})},_=E=>{let L=typeof E?.id=="string"&&E.id.length>0?E.id:null;m+=1,p=L,y=!1},v=()=>m,k=(E={})=>{if(E?.aborted===!0)return!1;let L=typeof E?.id=="string"&&E.id.length>0?E.id:null;return L?L!==p||L===g?!1:(g=L,!0):p!==null||y?!1:(y=!0,!0)},C=(E,L={})=>{if(E!=="renderComplete"||!k(L))return!1;let D=e();return Xe(D,"markLineCompleted",{}),!0},A=(E={})=>{if(E?._interactionSource==="choice")return!0;let L=E?.actions;return!L||typeof L!="object"||Array.isArray(L)?!1:Object.values(L).some(D=>D?._interactionSource==="choice")},R=(E,L={})=>!L?.actions||typeof E?.selectIsChoiceVisible!="function"||!E.selectIsChoiceVisible()?!1:!A(L),N=({preprocessPayload:E,onEvent:L}={})=>async(D,H={})=>{let q=e();if(R(q,H))return L?.(D,H);let j=await E?.(D,H)??H;if(R(q,j))return L?.(D,j);if(C(D,j),j?.actions){let mr=j?._event?{_event:j._event}:j?.event?{_event:j.event}:void 0;q.handleActions(j.actions,mr)}return L?.(D,j)},U=E=>{let L=e(),D=Cs(E);D.forEach(q=>{if(!hr[q.name]&&!r)throw new Error(`Unhandled pending effect "${q.name}".`)});let H={engine:L,routeGraphics:t,ticker:n,autoTimer:l,skipTimer:c,nextLineConfigTimerState:u,trackRenderDispatch:_,getRenderDispatchCount:v,enqueuePersistenceWrite:w};for(let q of D){let j=hr[q.name];if(j){j(H,q.payload);continue}r(q,H)}};return U.handleRouteGraphicsEvent=C,U.createRouteGraphicsEventHandler=N,U},Ss=Ls;var Rs=(e,t={})=>{let{resources:n={}}=t;return Lt(e,n)};var Tc=qt;export{Ss as createEffectsHandler,hs as createIndexedDbPersistence,Tc as default,Rs as resolveLayoutReferences};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "route-engine-js",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"description": "A lightweight Visual Novel engine built in JavaScript for creating interactive narrative games with branching storylines",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -40,12 +40,11 @@
|
|
|
40
40
|
"lint": "bun run prettier src -c",
|
|
41
41
|
"lint:fix": "bun run prettier src -w",
|
|
42
42
|
"coverage": "bun run vitest run --coverage",
|
|
43
|
-
"vt:
|
|
44
|
-
"vt:
|
|
45
|
-
"vt:docker": "bun scripts/sync-vt-route-graphics.js && bun run esbuild.js && docker run --rm ${VT_DOCKER_ARGS:-} --user $(id -u):$(id -g) -e RTGL_VT_DEBUG=true -v \"$PWD:/app\" -w /app docker.io/han4wluc/rtgl:playwright-v1.57.0-rtgl-v1.0.10 rtgl vt screenshot --wait-event vt:ready --concurrency ${VT_DOCKER_CONCURRENCY:-2} --timeout ${VT_DOCKER_TIMEOUT:-60000}",
|
|
43
|
+
"vt:generate": "bun run esbuild.js && rtgl vt generate",
|
|
44
|
+
"vt:docker": "bun run esbuild.js && docker run --rm ${VT_DOCKER_ARGS:-} --user $(id -u):$(id -g) -e RTGL_VT_DEBUG=true -v \"$PWD:/app\" -w /app docker.io/han4wluc/rtgl:playwright-v1.57.0-rtgl-v1.0.10 rtgl vt screenshot --wait-event vt:ready --concurrency ${VT_DOCKER_CONCURRENCY:-2} --timeout ${VT_DOCKER_TIMEOUT:-60000}",
|
|
46
45
|
"vt:report": "bun run vt:docker && rtgl vt report --diff-threshold ${VT_REPORT_DIFF_THRESHOLD:-0.8}",
|
|
47
46
|
"vt:accept": "rtgl vt accept",
|
|
48
|
-
"serve": "bun run
|
|
47
|
+
"serve": "bun run vt:generate && bunx serve -p 3004 .rettangoli/vt/_site"
|
|
49
48
|
},
|
|
50
49
|
"dependencies": {
|
|
51
50
|
"immer": "^10.1.1",
|
|
@@ -59,6 +58,7 @@
|
|
|
59
58
|
"ajv": "^8.18.0",
|
|
60
59
|
"husky": "^9.1.7",
|
|
61
60
|
"prettier": "^3.7.4",
|
|
61
|
+
"route-graphics": "1.7.0",
|
|
62
62
|
"vitest": "^4.0.16"
|
|
63
63
|
}
|
|
64
64
|
}
|