route-engine-js 1.46.6 → 1.47.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  var Ym=Object.defineProperty;var zm=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Xm=(e,t)=>{for(var n in t)Ym(e,n,{get:t[n],enumerable:!0})};var Af=zm(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});function kf(e){let t=e.length,n=0,o=0,a;for(;o<t;)n++,a=e.charCodeAt(o++),a>=55296&&a<=56319&&o<t&&(a=e.charCodeAt(o),(a&64512)===56320&&o++);return n}Ga.default=kf;kf.code='require("ajv/dist/runtime/ucs2length").default'});var Sl=Symbol.for("immer-nothing"),kl=Symbol.for("immer-draftable"),De=Symbol.for("immer-state");function ze(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var mt=Object.getPrototypeOf;function ge(e){return!!e&&!!e[De]}function Hr(e){return e?Ol(e)||Array.isArray(e)||!!e[kl]||!!e.constructor?.[kl]||Ln(e)||Mn(e):!1}var Hm=Object.prototype.constructor.toString();function Ol(e){if(!e||typeof e!="object")return!1;let t=mt(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)===Hm}function Tn(e){return ge(e)||ze(15,e),e[De].base_}function _n(e,t){Dn(e)===0?Reflect.ownKeys(e).forEach(n=>{t(n,e[n],e)}):e.forEach((n,o)=>t(o,n,e))}function Dn(e){let t=e[De];return t?t.type_:Array.isArray(e)?1:Ln(e)?2:Mn(e)?3:0}function Bi(e,t){return Dn(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Rl(e,t,n){let o=Dn(e);o===2?e.set(t,n):o===3?e.add(n):e[t]=n}function Gm(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Ln(e){return e instanceof Map}function Mn(e){return e instanceof Set}function Xr(e){return e.copy_||e.base_}function Ui(e,t){if(Ln(e))return new Map(e);if(Mn(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let n=Ol(e);if(t===!0||t==="class_only"&&!n){let o=Object.getOwnPropertyDescriptors(e);delete o[De];let a=Reflect.ownKeys(o);for(let r=0;r<a.length;r++){let s=a[r],i=o[s];i.writable===!1&&(i.writable=!0,i.configurable=!0),(i.get||i.set)&&(o[s]={configurable:!0,writable:!0,enumerable:i.enumerable,value:e[s]})}return Object.create(mt(e),o)}else{let o=mt(e);if(o!==null&&n)return{...e};let a=Object.create(o);return Object.assign(a,e)}}function Gi(e,t=!1){return Vn(e)||ge(e)||!Hr(e)||(Dn(e)>1&&(e.set=e.add=e.clear=e.delete=Km),Object.freeze(e),t&&Object.entries(e).forEach(([n,o])=>Gi(o,!0))),e}function Km(){ze(2)}function Vn(e){return Object.isFrozen(e)}var Wm={};function Gr(e){let t=Wm[e];return t||ze(0,e),t}var Mt;function Cl(){return Mt}function Jm(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function Al(e,t){t&&(Gr("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Yi(e){zi(e),e.drafts_.forEach(Qm),e.drafts_=null}function zi(e){e===Mt&&(Mt=e.parent_)}function Pl(e){return Mt=Jm(Mt,e)}function Qm(e){let t=e[De];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function El(e,t){t.unfinalizedDrafts_=t.drafts_.length;let n=t.drafts_[0];return e!==void 0&&e!==n?(n[De].modified_&&(Yi(t),ze(4)),Hr(e)&&(e=Nn(t,e),t.parent_||jn(t,e)),t.patches_&&Gr("Patches").generateReplacementPatches_(n[De].base_,e,t.patches_,t.inversePatches_)):e=Nn(t,n,[]),Yi(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Sl?e:void 0}function Nn(e,t,n){if(Vn(t))return t;let o=t[De];if(!o)return _n(t,(a,r)=>xl(e,o,t,a,r,n)),t;if(o.scope_!==e)return t;if(!o.modified_)return jn(e,o.base_,!0),o.base_;if(!o.finalized_){o.finalized_=!0,o.scope_.unfinalizedDrafts_--;let a=o.copy_,r=a,s=!1;o.type_===3&&(r=new Set(a),a.clear(),s=!0),_n(r,(i,l)=>xl(e,o,a,i,l,n,s)),jn(e,a,!1),n&&e.patches_&&Gr("Patches").generatePatches_(o,n,e.patches_,e.inversePatches_)}return o.copy_}function xl(e,t,n,o,a,r,s){if(ge(a)){let i=r&&t&&t.type_!==3&&!Bi(t.assigned_,o)?r.concat(o):void 0,l=Nn(e,a,i);if(Rl(n,o,l),ge(l))e.canAutoFreeze_=!1;else return}else s&&n.add(a);if(Hr(a)&&!Vn(a)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Nn(e,a),(!t||!t.scope_.parent_)&&typeof o!="symbol"&&Object.prototype.propertyIsEnumerable.call(n,o)&&jn(e,a)}}function jn(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&Gi(t,n)}function Zm(e,t){let n=Array.isArray(e),o={type_:n?1:0,scope_:t?t.scope_:Cl(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},a=o,r=Ki;n&&(a=[o],r=Vt);let{revoke:s,proxy:i}=Proxy.revocable(a,r);return o.draft_=i,o.revoke_=s,i}var Ki={get(e,t){if(t===De)return e;let n=Xr(e);if(!Bi(n,t))return ey(e,n,t);let o=n[t];return e.finalized_||!Hr(o)?o:o===qi(e.base_,t)?(Fi(e),e.copy_[t]=Hi(o,e)):o},has(e,t){return t in Xr(e)},ownKeys(e){return Reflect.ownKeys(Xr(e))},set(e,t,n){let o=$l(Xr(e),t);if(o?.set)return o.set.call(e.draft_,n),!0;if(!e.modified_){let a=qi(Xr(e),t),r=a?.[De];if(r&&r.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(Gm(n,a)&&(n!==void 0||Bi(e.base_,t)))return!0;Fi(e),Xi(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 qi(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,Fi(e),Xi(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let n=Xr(e),o=Reflect.getOwnPropertyDescriptor(n,t);return o&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:o.enumerable,value:n[t]}},defineProperty(){ze(11)},getPrototypeOf(e){return mt(e.base_)},setPrototypeOf(){ze(12)}},Vt={};_n(Ki,(e,t)=>{Vt[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});Vt.deleteProperty=function(e,t){return Vt.set.call(this,e,t,void 0)};Vt.set=function(e,t,n){return Ki.set.call(this,e[0],t,n,e[0])};function qi(e,t){let n=e[De];return(n?Xr(n):e)[t]}function ey(e,t,n){let o=$l(t,n);return o?"value"in o?o.value:o.get?.call(e.draft_):void 0}function $l(e,t){if(!(t in e))return;let n=mt(e);for(;n;){let o=Object.getOwnPropertyDescriptor(n,t);if(o)return o;n=mt(n)}}function Xi(e){e.modified_||(e.modified_=!0,e.parent_&&Xi(e.parent_))}function Fi(e){e.copy_||(e.copy_=Ui(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var ry=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,o)=>{if(typeof t=="function"&&typeof n!="function"){let r=n;n=t;let s=this;return function(l=r,...c){return s.produce(l,u=>n.call(this,u,...c))}}typeof n!="function"&&ze(6),o!==void 0&&typeof o!="function"&&ze(7);let a;if(Hr(t)){let r=Pl(this),s=Hi(t,void 0),i=!0;try{a=n(s),i=!1}finally{i?Yi(r):zi(r)}return Al(r,o),El(a,r)}else if(!t||typeof t!="object"){if(a=n(t),a===void 0&&(a=t),a===Sl&&(a=void 0),this.autoFreeze_&&Gi(a,!0),o){let r=[],s=[];Gr("Patches").generateReplacementPatches_(t,a,r,s),o(r,s)}return a}else ze(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...i)=>this.produceWithPatches(s,l=>t(l,...i));let o,a;return[this.produce(t,n,(s,i)=>{o=s,a=i}),o,a]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){Hr(e)||ze(8),ge(e)&&(e=Xe(e));let t=Pl(this),n=Hi(e,void 0);return n[De].isManual_=!0,zi(t),n}finishDraft(e,t){let n=e&&e[De];(!n||!n.isManual_)&&ze(9);let{scope_:o}=n;return Al(o,t),El(void 0,o)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){let a=t[n];if(a.path.length===0&&a.op==="replace"){e=a.value;break}}n>-1&&(t=t.slice(n+1));let o=Gr("Patches").applyPatches_;return ge(e)?o(e,t):this.produce(e,a=>o(a,t))}};function Hi(e,t){let n=Ln(e)?Gr("MapSet").proxyMap_(e,t):Mn(e)?Gr("MapSet").proxySet_(e,t):Zm(e,t);return(t?t.scope_:Cl()).drafts_.push(n),n}function Xe(e){return ge(e)||ze(10,e),_l(e)}function _l(e){if(!Hr(e)||Vn(e))return e;let t=e[De],n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=Ui(e,t.scope_.immer_.useStrictShallowCopy_)}else n=Ui(e,!0);return _n(n,(o,a)=>{Rl(n,o,_l(a))}),t&&(t.finalized_=!1),n}var Ve=new ry,qn=Ve.produce,wA=Ve.produceWithPatches.bind(Ve),IA=Ve.setAutoFreeze.bind(Ve),vA=Ve.setUseStrictShallowCopy.bind(Ve),kA=Ve.applyPatches.bind(Ve),AA=Ve.createDraft.bind(Ve),PA=Ve.finishDraft.bind(Ve);var x={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},ee={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},yt={NOT:0};var D=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},Ne=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var Wi=e=>{if(!e||e.trim()==="")throw new D("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let n=e.includes("===")?"==":"!=";throw new D(`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 D(`Incomplete comparison expression - missing right operand (got: '${e}')`)},Nl=e=>{if(e.trim().endsWith(" in"))throw new D(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new D(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,n]=e.split(" in ");if(!n||n.trim()==="")throw new D(`Missing iterable expression after 'in' (got: '$for ${e}')`);let o=t.includes(",")?t.split(",").map(a=>a.trim()):[t.trim()];for(let a of o){if(!a)throw new D(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(a))throw new D(`Invalid loop syntax (got: '$for ${e}')`)}};var jl=(e,t,n=!1)=>{if(t===null)return new Ne(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new Ne(`Cannot iterate over undefined value at '$for ${e}'`);let o=typeof t;return n?new Ne(`Cannot iterate over non-array value in loop '${e}' - got ${o} instead`):new Ne(`Cannot iterate over non-array value (got: ${o}) at '$for ${e}'`)},Tl=(e,t)=>{let n=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new Ne(`Unknown function '${e}' (${n})`)};var ty=(e,t,n={})=>{let o={},a={};n&&typeof n=="object"&&(n.functions!==void 0||n.partials!==void 0?(o=n.functions||{},a=n.partials||{}):typeof n=="object"&&(o=n));let s=ne(e,{functions:o,partials:a},t,{});return s===void 0?{}:s},ne=(e,t,n,o)=>{let a=t.functions||t;if(e.var&&!e.type)return Ae(e.var,n,o);if(e.type===x.LITERAL)return e.value;if(e.type===x.VARIABLE)return Ae(e.path,n,o);if(e.type===x.INTERPOLATION)return sy(e.parts,t,n,o);switch(e.type){case x.FUNCTION:return Ll(e,t,n,o);case x.BINARY:return Ml(e,t,n,o);case x.UNARY:return Vl(e,t,n,o);case x.CONDITIONAL:return oy(e,t,n,o);case x.LOOP:return py(e,t,n,o);case x.OBJECT:return dy(e,t,n,o);case x.ARRAY:return my(e,t,n,o);case x.PARTIAL:return yy(e,t,n,o);case x.PATH_REFERENCE:return hy(e,t,n,o);default:throw new Error(`Unknown node type: ${e.type}`)}},Dl=new Map,ny=e=>{let t=[],n="",o=!1;for(let a=0;a<e.length;a++){let r=e[a];if(r==="[")n&&(t.push({type:"property",value:n}),n=""),o=!0;else if(r==="]"){if(o&&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 i=s.slice(1,-1);t.push({type:"property",value:i})}else t.push({type:"property",value:s});n=""}o=!1}else n+=r}return n&&t.push({type:"property",value:n}),t},Ae=(e,t,n)=>{if(!e)return;if(e in n)return n[e];let o=Dl.get(e);if(!o){let r=[],s="",i=0;for(let l=0;l<e.length;l++){let c=e[l];c==="["?(i++,s+=c):c==="]"?(i--,s+=c):c==="."&&i===0?s&&(r.push(s),s=""):s+=c}s&&r.push(s),o=[];for(let l of r){let c=ny(l.trim());o.push(...c)}Dl.set(e,o)}let a=t;for(let r=0;r<o.length;r++){let s=o[r];if(s.type==="property"&&s.value in n){a=n[s.value];continue}if(a==null)return;(s.type==="property"||s.type==="index")&&(a=a[s.value])}return a},sy=(e,t,n,o)=>{let a=[];for(let r of e)if(typeof r=="string")a.push(r);else{let s=ne(r,t,n,o);a.push(s!=null?String(s):"")}return a.join("")},Ll=(e,t,n,o)=>{let a=t.functions||t,r=a[e.name];if(!r)throw Tl(e.name,a);let s=e.args.map(i=>ne(i,t,n,o));return r(...s)},Or=(e,t,n,o)=>{if(e.var&&!e.type)return Ae(e.var,n,o);switch(e.type){case x.VARIABLE:return Ae(e.path,n,o);case x.LITERAL:return e.value;case x.BINARY:return Ml(e,t,n,o);case x.UNARY:return Vl(e,t,n,o);case x.FUNCTION:return Ll(e,t,n,o);default:return ne(e,t,n,o)}},Ml=(e,t,n,o)=>{if(e.op===ee.AND||e.op===ee.OR){let s=Or(e.left,t,n,o),i=Or(e.right,t,n,o);switch(e.op){case ee.AND:return s&&i;case ee.OR:return s||i}}let a=ne(e.left,t,n,o),r=ne(e.right,t,n,o);switch(e.op){case ee.EQ:return a==r;case ee.NEQ:return a!=r;case ee.GT:return a>r;case ee.LT:return a<r;case ee.GTE:return a>=r;case ee.LTE:return a<=r;case ee.IN:return Array.isArray(r)?r.includes(a):!1;case ee.ADD:if(typeof a!="number"||typeof r!="number")throw new Ne(`Arithmetic operations require numbers. Got ${typeof a} + ${typeof r}`);return a+r;case ee.SUBTRACT:if(typeof a!="number"||typeof r!="number")throw new Ne(`Arithmetic operations require numbers. Got ${typeof a} - ${typeof r}`);return a-r;default:throw new Error(`Unknown binary operator: ${e.op}`)}},Vl=(e,t,n,o)=>{let a=e.op===yt.NOT?Or(e.operand,t,n,o):ne(e.operand,t,n,o);if(e.op===yt.NOT)return!a;throw new Error(`Unknown unary operator: ${e.op}`)},iy=(e,t,n,o)=>{if(e.conditions.length===2&&e.conditions[1]===null){let a=e.conditions[0];if(a.type===x.VARIABLE)if(Ae(a.path,n,o)){let s=e.bodies[0];if(s.type===x.OBJECT&&s.fast===!0&&!s.whenCondition&&s.properties.length<=5){let i={};for(let l of s.properties){let c=l.parsedKey?ne(l.parsedKey,t,n,o):l.key,u=l.value;if(u.type===x.LITERAL)i[c]=u.value;else if(u.type===x.VARIABLE)i[c]=Ae(u.path,n,o);else if(u.type===x.INTERPOLATION){let p=[];for(let m of u.parts)if(typeof m=="string")p.push(m);else if(m.type===x.VARIABLE){let d=Ae(m.path,n,o);p.push(d!=null?String(d):"")}else{let d=ne(m,t,n,o);p.push(d!=null?String(d):"")}i[c]=p.join("")}else i[c]=ne(u,t,n,o)}return i}}else{let s=e.bodies[1];if(s.type===x.OBJECT&&s.fast===!0&&!s.whenCondition&&s.properties.length<=5){let i={};for(let l of s.properties){let c=l.parsedKey?ne(l.parsedKey,t,n,o):l.key,u=l.value;if(u.type===x.LITERAL)i[c]=u.value;else if(u.type===x.VARIABLE)i[c]=Ae(u.path,n,o);else if(u.type===x.INTERPOLATION){let p=[];for(let m of u.parts)if(typeof m=="string")p.push(m);else if(m.type===x.VARIABLE){let d=Ae(m.path,n,o);p.push(d!=null?String(d):"")}else{let d=ne(m,t,n,o);p.push(d!=null?String(d):"")}i[c]=p.join("")}else i[c]=ne(u,t,n,o)}return i}}}return null},oy=(e,t,n,o)=>{let a=iy(e,t,n,o);if(a!==null)return a;for(let r=0;r<e.conditions.length;r++){let s=e.conditions[r];if(s===null||Or(s,t,n,o))return ne(e.bodies[r],t,n,o)}return Fl},ay=(e,t)=>{let n=e.body,o=e.itemVar;if(n.type===x.CONDITIONAL&&n.conditions.length===1&&n.conditions[0].type===x.VARIABLE){let a=n.conditions[0].path,r=n.bodies[0];if(a.startsWith(o+".")){let s=a.substring(o.length+1);if(r.type===x.OBJECT&&r.properties.length<=5){for(let l of r.properties)if(l.parsedKey)return null;let i=[];for(let l=0;l<t.length;l++){let c=t[l];if(c[s]){let u={};for(let p of r.properties){let m=p.key,d=p.value;if(d.type===x.LITERAL)u[m]=d.value;else if(d.type===x.VARIABLE){let f=d.path;if(f===o)u[m]=c;else if(f.startsWith(o+".")){let h=f.substring(o.length+1);u[m]=c[h]}else return null}else if(d.type===x.INTERPOLATION){let f=[],h=!0;for(let g of d.parts)if(typeof g=="string")f.push(g);else if(g.type===x.VARIABLE){let y=g.path;if(y===o)f.push(c!=null?String(c):"");else if(y.startsWith(o+".")){let w=y.substring(o.length+1),b=c[w];f.push(b!=null?String(b):"")}else{h=!1;break}}else{h=!1;break}if(!h)return null;u[m]=f.join("")}else return null}i.push(u)}}return i}}}return null},ly=(e,t)=>{let n=e.body,o=e.itemVar,a=ay(e,t);if(a!==null)return a;if(n.type===x.OBJECT&&n.properties.length<=5&&!n.whenCondition){for(let i of n.properties)if(i.parsedKey)return null;let r=[],s=!0;for(let i of n.properties){let l=i.key,c=i.value;if(c.type===x.LITERAL)r.push({key:l,type:"literal",value:c.value});else if(c.type===x.VARIABLE){let u=c.path;if(u===o)r.push({key:l,type:"item"});else if(u.startsWith(o+".")){let p=u.substring(o.length+1);if(!p.includes(".")&&!p.includes("["))r.push({key:l,type:"prop",prop:p});else{s=!1;break}}else{s=!1;break}}else if(c.type===x.INTERPOLATION&&c.parts.length===1){let u=c.parts[0];if(u.type===x.VARIABLE){let p=u.path;if(p===o)r.push({key:l,type:"item_string"});else if(p.startsWith(o+".")){let m=p.substring(o.length+1);if(!m.includes(".")&&!m.includes("["))r.push({key:l,type:"prop_string",prop:m});else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}else{s=!1;break}}if(s){let i=new Array(t.length);if(r.length===3&&r[0].type==="prop"&&r[0].key==="id"&&r[1].type==="prop_string"&&r[1].key==="title"&&r[2].type==="prop"&&r[2].key==="completed")for(let l=0;l<t.length;l++){let c=t[l];i[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 p of r)if(p.type==="literal")u[p.key]=p.value;else if(p.type==="item")u[p.key]=c;else if(p.type==="prop")u[p.key]=c[p.prop];else if(p.type==="item_string")u[p.key]=c!=null?String(c):"";else if(p.type==="prop_string"){let m=c[p.prop];u[p.key]=m!=null?String(m):""}i[l]=u}return i}}return null},cy=(e,t,n,o,a)=>{let r=[],s=e.body;if(s.type===x.OBJECT&&s.fast!==!1){let i=e.itemVar,l=e.indexVar;for(let c=0;c<a.length;c++){let u=a[c],p={},m={...o,[i]:u,...l&&{[l]:c}};m.__paths__||(m.__paths__=o.__paths__||{});let d=e.iterable.path||"";if(o&&o.__paths__&&d){let f=d.split("."),h=f[0];h in o.__paths__&&(d=o.__paths__[h],f.length>1&&(d+="."+f.slice(1).join(".")))}m.__paths__={...m.__paths__,[i]:`${d}[${c}]`,...l&&{[l]:c}};for(let f of s.properties){let h=f.parsedKey?ne(f.parsedKey,t,n,m):f.key,g=f.value;if(g.type===x.LITERAL)p[h]=g.value;else if(g.type===x.VARIABLE){let y=g.path;if(y===i)p[h]=u;else if(y===l)p[h]=c;else if(y.startsWith(i+".")){let w=y.substring(i.length+1);!w.includes(".")&&!w.includes("[")?p[h]=u[w]:p[h]=Ae(y,n,{...o,[i]:u,...l&&{[l]:c}})}else p[h]=Ae(y,n,{...o,[i]:u,...l&&{[l]:c}})}else if(g.type===x.INTERPOLATION){let y=[];for(let w of g.parts)if(typeof w=="string")y.push(w);else if(w.type===x.VARIABLE){let b=w.path,A;if(b===i)A=u;else if(b===l)A=c;else if(b.startsWith(i+".")){let k=b.substring(i.length+1);!k.includes(".")&&!k.includes("[")?A=u[k]:A=Ae(b,n,{...o,[i]:u,...l&&{[l]:c}})}else A=Ae(b,n,{...o,[i]:u,...l&&{[l]:c}});y.push(A!=null?String(A):"")}else{let b={...o,[i]:u,...l&&{[l]:c}},A=ne(w,t,n,b);y.push(A!=null?String(A):"")}p[h]=y.join("")}else{let y={...o,[i]:u,...l&&{[l]:c}};p[h]=ne(g,t,n,y)}}r.push(p)}return r}return null},uy=(e,t,n)=>{let o=e.body;if(o.type===x.OBJECT&&o.properties.length===1&&o.properties[0].key==="$if item.visible"){let r=o.properties[0].value;if(r.type===x.CONDITIONAL&&r.conditions.length===1&&r.conditions[0].type===x.VARIABLE&&r.conditions[0].path==="item.visible"){let s=r.bodies[0];if(s.type===x.OBJECT&&s.properties.length===2){let i=s.properties[0],l=s.properties[1];if(i.key==="id"&&i.value.type===x.VARIABLE&&i.value.path==="item.id"&&l.key==="$if item.highlighted"&&l.value.type===x.CONDITIONAL){let c=[];for(let u=0;u<t.length;u++){let p=t[u];if(p.visible){let m={id:p.id};p.highlighted?(m.highlight=!0,m.message=`This item is highlighted: ${p.name}`):(m.highlight=!1,m.message=p.name),c.push(m)}}return c}}}}return null},py=(e,t,n,o)=>{let a=ne(e.iterable,t,n,o);if(!Array.isArray(a)){let c,u=!1;if(e.iterable.type===x.FUNCTION){u=!0;let m=e.iterable.args.map(d=>d.type===x.LITERAL?typeof d.value=="string"?`'${d.value}'`:String(d.value):d.type===x.VARIABLE?d.path:d.type===x.FUNCTION?`${d.name}(...)`:"?").join(", ");c=`${e.iterable.name}(${m})`}else c=e.iterable.path||"undefined";let p=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${c}`;throw jl(p,a,u)}if(!e.indexVar){let c=uy(e,a,e.itemVar);if(c!==null)return c}if(!e.indexVar){let c=ly(e,a);if(c!==null)return c}let r=cy(e,t,n,o,a);if(r!==null)return r;let s=[],i=e.iterable.path||"";if(o&&o.__paths__&&i){let c=i.split("."),u=c[0];u in o.__paths__&&(i=o.__paths__[u],c.length>1&&(i+="."+c.slice(1).join(".")))}let l=!1;e.body.type===x.ARRAY&&(e.body.items.length<=1?l=!1:l=e.body._shouldPreserveArray??=e.body.items.some(c=>c.type===x.OBJECT&&c.properties.some(u=>u.key.startsWith("$if ")||u.key.startsWith("$when "))));for(let c=0;c<a.length;c++){let u=e.indexVar?{...o,[e.itemVar]:a[c],[e.indexVar]:c}:{...o,[e.itemVar]:a[c]};u.__paths__||(u.__paths__=o.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${i}[${c}]`},e.indexVar&&(u.__paths__[e.indexVar]=c);let p=ne(e.body,t,n,u);if(Array.isArray(p)&&p.length===1&&!l){let m=p[0];s.push(m===void 0?{}:m)}else s.push(p===void 0?{}:p)}return s},ql=(e,t,n)=>e.type!==x.OBJECT||e.whenCondition||e.properties.length>t?!1:e.properties.every(({value:o})=>{switch(o.type){case x.LITERAL:case x.VARIABLE:return!0;case x.INTERPOLATION:return o.parts.every(a=>typeof a=="string"||a.type===x.VARIABLE);case x.OBJECT:return n&&ql(o,5,!1);default:return!1}}),fy=(e,t,n,o)=>{if(e.whenCondition||e.properties.length!==1||!ql(e.properties[0].value,10,!0))return null;let a=e.properties[0],r=a.parsedKey?ne(a.parsedKey,t,n,o):a.key,s=a.value,i={},l={};for(let c of s.properties){let u=c.parsedKey?ne(c.parsedKey,t,n,o):c.key,p=c.value;if(p.type===x.LITERAL)l[u]=p.value;else if(p.type===x.VARIABLE)l[u]=Ae(p.path,n,o);else if(p.type===x.INTERPOLATION){let m=[];for(let d of p.parts)if(typeof d=="string")m.push(d);else if(d.type===x.VARIABLE){let f=Ae(d.path,n,o);m.push(f!=null?String(f):"")}l[u]=m.join("")}else if(p.type===x.OBJECT){let m={};for(let d of p.properties){let f=d.parsedKey?ne(d.parsedKey,t,n,o):d.key,h=d.value;if(h.type===x.LITERAL)m[f]=h.value;else if(h.type===x.VARIABLE)m[f]=Ae(h.path,n,o);else if(h.type===x.INTERPOLATION){let g=[];for(let y of h.parts)if(typeof y=="string")g.push(y);else if(y.type===x.VARIABLE){let w=Ae(y.path,n,o);g.push(w!=null?String(w):"")}m[f]=g.join("")}}l[u]=m}}return i[r]=l,i},dy=(e,t,n,o)=>{let a=t.functions||t;if(e.whenCondition&&!Or(e.whenCondition,a,n,o))return;let r=fy(e,t,n,o);if(r!==null)return r;if(e.fast){let c={};for(let u of e.properties){let p=u.parsedKey?ne(u.parsedKey,t,n,o):u.key,m=u.value;if(m.type===x.LITERAL)c[p]=m.value;else if(m.type===x.VARIABLE)c[p]=Ae(m.path,n,o);else if(m.type===x.INTERPOLATION){let d=[];for(let f of m.parts)if(typeof f=="string")d.push(f);else if(f.type===x.VARIABLE){let h=Ae(f.path,n,o);d.push(h!=null?String(h):"")}else{let h=ne(f,t,n,o);d.push(h!=null?String(h):"")}c[p]=d.join("")}else c[p]=ne(m,t,n,o)}return c}let s={},i=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=ne(c.value,t,n,o);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 ne(c.value,t,n,o)}else{let u=c.parsedKey?ne(c.parsedKey,t,n,o):c.key,p=c.value;if(p&&p.type===x.OBJECT&&p.properties){let m=p.properties.find(d=>d.key.startsWith("$for "));if(m){let d=ne(m.value,t,n,o);d!==void 0&&(s[u]=d)}else{let d=ne(c.value,t,n,o);d!==void 0&&(s[u]=d)}}else{let m=ne(c.value,t,n,o);(m!==void 0||p?.type===x.VARIABLE||p?.type===x.FUNCTION)&&(s[u]=m)}}return s},Fl={},my=(e,t,n,o)=>{let a=[];for(let r of e.items)if(r.type===x.LOOP){let s=ne(r,t,n,o);Array.isArray(s)&&r.flatten!==!1?a.push(...s):a.push(s)}else{let s=ne(r,t,n,o);s!==Fl&&s!==void 0&&a.push(s)}return a},yy=(e,t,n,o)=>{let{name:a,data:r,whenCondition:s}=e,i=t.partials||{},l=t.functions||t;if(s&&!Or(s,l,n,o))return;if(!i[a])throw new Ne(`Partial '${a}' is not defined`);let c=o._partialStack||[];if(c.includes(a))throw new Ne(`Circular partial reference detected: ${a}`);let u=i[a],p=n,m={...o,_partialStack:[...c,a]};if(o){p={...n};for(let d of Object.keys(o))d.startsWith("_")||(p[d]=o[d])}if(r){let d=ne(r,t,n,o);p={...p,...d}}return ne(u,t,p,m)},hy=(e,t,n,o)=>{let{path:a}=e,r=a.split("."),s=r[0],i=r.slice(1);if(!o||!(s in o))throw new Ne(`Path reference '#{${a}}' refers to '${s}' which is not a loop variable in the current scope`);if(o.__paths__||(o.__paths__={}),!(s in o.__paths__))throw new Ne(`Path reference '#{${a}}' cannot be resolved - path tracking may not be initialized properly`);let l=o.__paths__[s];if(typeof l=="number"){if(i.length>0)throw new Ne(`Path reference '#{${a}}' - cannot access properties on index variable '${s}'`);return String(l)}return i.length>0&&(l+="."+i.join(".")),l};var Ji=ty;var gy=/\$\{([^}]*)\}/g,by=/#\{([^}]*)\}/g,Ul=(e,t={})=>{let n=e.match(/^(\w+)\((.*)\)$/);if(!n)return{isFunction:!1};let[,o,a]=n,r=wy(a,t);return{isFunction:!0,type:x.FUNCTION,name:o,args:r}},wy=(e,t={})=>e.trim()?Iy(e).map(o=>vy(o.trim(),t)):[],Iy=e=>{let t=[],n="",o=0,a=!1,r="";for(let s=0;s<e.length;s++){let i=e[s],l=s>0?e[s-1]:"";!a&&(i==='"'||i==="'")?(a=!0,r=i,n+=i):a&&i===r&&l!=="\\"?(a=!1,r="",n+=i):!a&&i==="("?(o++,n+=i):!a&&i===")"?(o--,n+=i):!a&&i===","&&o===0?(t.push(n),n=""):n+=i}return n&&t.push(n),t},vy=(e,t={})=>{if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:x.LITERAL,value:e.slice(1,-1)};if(/^-?\d+(\.\d+)?$/.test(e))return{type:x.LITERAL,value:parseFloat(e)};if(e==="true")return{type:x.LITERAL,value:!0};if(e==="false")return{type:x.LITERAL,value:!1};if(e==="null")return{type:x.LITERAL,value:null};let n=Ul(e,t);if(n.isFunction)return{type:n.type,name:n.name,args:n.args};let o=e.trim(),a=[{op:" + ",type:"ADD"},{op:" - ",type:"SUBTRACT"}],r=-1,s=null;for(let{op:i,type:l}of a){let c=0;for(;c<o.length;){let u=Kr(o.substring(c),i);if(u===-1)break;let p=c+u;p>r&&(r=p,s={op:i,type:l}),c=p+i.length}}if(r!==-1)try{return Ee(o,t)}catch{return{type:x.VARIABLE,path:o}}return{type:x.VARIABLE,path:o}},Yl=/^\w+\(.*\)$/,ky=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,Ay=e=>{if(!(!e||e.trim()===""||Yl.test(e))&&ky.test(e))throw e.includes("?")&&e.includes(":")?new D(`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 D(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new D(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},Bl=e=>{let t=e.trim();if(Yl.test(t))throw new D(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new D(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new D(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new D(`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 D(`Complex expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);return{type:x.PATH_REFERENCE,path:t}},qt=(e,t={})=>{let n=e.trim();Ay(n);let o=Ul(n,t);if(o.isFunction)return{type:o.type,name:o.name,args:o.args};if(n.includes("[")&&!/[\s+\-*/%|&?:]/.test(n)){let a=0;for(let r of n)r==="["?a++:r==="]"&&a--;if(a!==0)throw new Error("Invalid array index syntax")}return{type:x.VARIABLE,path:n}},Qi=(e,t={})=>{let n=e,o=[];(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 p=`__ESCAPED_${o.length}__`;return o.push(u),p}),n=n.replace(/\\(#\{[^}]*\})/g,(c,u)=>{let p=`__ESCAPED_${o.length}__`;return o.push(u),p}),n=n.replace(/\\DOUBLE_ESC_VAR/g,"\\"),n=n.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let a=[...n.matchAll(gy)],r=[...n.matchAll(by)],s=[...a.map(c=>({match:c,type:"variable"})),...r.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<o.length;u++)c=c.replace(`__ESCAPED_${u}__`,o[u]);return{type:x.LITERAL,value:c}}if(s.length===1&&s[0].match[0]===n&&o.length===0){let{match:c,type:u}=s[0];try{return u==="variable"?qt(c[1],t):Bl(c[1])}catch(p){if(p.message==="Invalid array index syntax")return{type:x.LITERAL,value:n};throw p}}let i=[],l=0;for(let{match:c,type:u}of s){let[p,m]=c,d=c.index;if(d>l){let f=n.substring(l,d);for(let h=0;h<o.length;h++)f=f.replace(`__ESCAPED_${h}__`,o[h]);f&&i.push(f)}try{let f;u==="variable"?f=qt(m.trim(),t):f=Bl(m.trim()),i.push(f)}catch(f){if(f.message==="Invalid array index syntax")i.push(p);else throw f}l=d+p.length}if(l<n.length){let c=n.substring(l);for(let u=0;u<o.length;u++)c=c.replace(`__ESCAPED_${u}__`,o[u]);c&&i.push(c)}return{type:x.INTERPOLATION,parts:i}};var ro=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Hl=e=>Object.keys(e),Ce=e=>e.join("."),Rr=(e,t,n)=>{let o=Hl(e).filter(a=>!t.has(a));if(o.length>0)throw new D(`Unexpected key '${o[0]}' in condition JSON at '${Ce(n)}'`)},Cr=(e,t)=>typeof e=="string"?Qi(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?Ey(e,t):xy(e,t):{type:x.LITERAL,value:e},Py=e=>{let{$each:t,...n}=e;if(typeof t!="string")throw new D("$each value must be a non-empty string");let o=t.trim();if(o==="")throw new D("$each value must be a non-empty string");if(Object.keys(n).length===0)throw new D("Empty $each body not allowed");if(n.$partial!==void 0)throw new D("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${o}`]:n}},Ey=(e,t)=>{let n=[],o=!1;for(let a=0;a<e.length;a++){let r=e[a];if(typeof r=="object"&&r!==null&&!Array.isArray(r)){if(r.$each!==void 0)try{let l=Py(r),c=Object.keys(l);if(c.length===1&&/^\$for(?::\w+)?\s/.test(c[0])){let u=Xl(c[0],l[c[0]],t,!0);n.push(u),o=!0;continue}}catch(l){throw l instanceof D?l:new D(l.message)}let i=Object.keys(r);if(i.length===1&&/^\$for(?::\w+)?\s/.test(i[0])){let l=Xl(i[0],r[i[0]],t);n.push(l),o=!0;continue}}let s=Cr(r,t);n.push(s),(s.type===x.FUNCTION||s.type===x.CONDITIONAL||s.type===x.LOOP||s.type===x.PARTIAL||s.type===x.OBJECT&&!s.fast||s.type===x.ARRAY&&!s.fast)&&(o=!0)}return{type:x.ARRAY,items:n,fast:!o}},xy=(e,t)=>{let n=[],o=!1,a=null,r=Object.entries(e),s=0;if(e.$partial!==void 0){if(typeof e.$partial!="string")throw new D("$partial value must be a string");if(e.$partial.trim()==="")throw new D("$partial value cannot be an empty string");let l=["$if","$elif","$else","$for"],c=[];for(let[y]of r)for(let w of l)if(y===w||y.startsWith(w+" ")||y.startsWith(w+"#")){c.push(w);break}if(c.length>0)throw new D(`Cannot use $partial with ${c.join(", ")} at the same level. Wrap $partial in a parent object if you need conditionals.`);let{$partial:u,$when:p,...m}=e,d={},f=!1;for(let[y,w]of Object.entries(m)){let b=y;(y.startsWith("\\$")||y.startsWith("$$"))&&(b=y.slice(1)),d[b]=w,f=!0}let h=null;if(f&&(h=Cr(d,t),h.type===x.OBJECT)){let y=!1;for(let w of h.properties)if(w.value.type===x.VARIABLE||w.value.type===x.INTERPOLATION||w.value.type===x.FUNCTION||w.value.type===x.CONDITIONAL||w.value.type===x.OBJECT&&!w.value.fast||w.value.type===x.ARRAY&&!w.value.fast){y=!0;break}y&&(h.fast=!1)}let g={type:x.PARTIAL,name:u,data:h};return p!==void 0&&(g.whenCondition=zl(p,t)),g}for(let[l,c]of r)if(l==="$when"){if(a!==null)throw new D("Multiple '$when' directives on the same object are not allowed");if(c==null)throw new D("Missing condition expression after '$when'");a=zl(c,t),o=!0}else if(l.startsWith("$when#")||l.startsWith("$when "))throw new D("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;s<r.length;){let[l,c]=r[s];if(l==="$when"){s++;continue}if(l==="$each")throw new D("$each can only be used inside arrays");if(l.startsWith("$if ")||l.match(/^\$if#\w+\s/)||l.match(/^\$if\s+\w+.*:$/)){let u=Sy(r,s,t);n.push({key:l,value:u.node}),o=!0,s=u.nextIndex}else if(/^\$for(?::\w+)?\s/.test(l)){let u=l.match(/^\$for(?::(\w+))?\s/)?.[1]||"",p=u?`:${u}`:"";throw new D(`$for loops must be inside arrays - use '- $for${p} item in items:' instead of '$for${p} item in items:'. For cleaner object generation syntax, consider using $each.`)}else{if(l.startsWith("$elif ")||l.startsWith("$else"))throw new D(`'${l.split(" ")[0]}' without matching '$if'`);if(l==="$if"||l==="$if:")throw new D("Missing condition expression after '$if'");{let u=Cr(c,t);(u.type===x.FUNCTION||u.type===x.CONDITIONAL||u.type===x.PARTIAL||u.type===x.OBJECT&&!u.fast||u.type===x.ARRAY&&!u.fast)&&(o=!0);let p=Qi(l,t),m={key:l,value:u};(p.type!==x.LITERAL||p.value!==l)&&(m.parsedKey=p),n.push(m),s++}}}let i={type:x.OBJECT,properties:n,fast:!o};return a&&(i.whenCondition=a),i},Sy=(e,t,n={})=>{let o=[],a=[],r=t,[s,i]=e[r],l=null,c;if(s.startsWith("$if#")){let p=s.match(/^\$if#(\w+)\s+(.+)$/);if(p)l=p[1],c=p[2];else throw new D(`Invalid conditional syntax: ${s}`)}else c=s.substring(4),c.endsWith(":")&&(c=c.slice(0,-1).trim());Wi(c);let u=Ee(c,n);for(o.push(u),a.push(Cr(i,n)),r++;r<e.length;){let[p,m]=e[r],d=!1,f;if(l?p.startsWith(`$elif#${l} `)?(f=p.substring(`$elif#${l} `.length),f.endsWith(":")&&(f=f.slice(0,-1).trim()),d=!0):(p===`$else#${l}`||p===`$else#${l}:`)&&(d=!0,f=null):p.startsWith("$elif ")?(f=p.substring(6),f.endsWith(":")&&(f=f.slice(0,-1).trim()),d=!0):(p==="$else"||p==="$else:")&&(d=!0,f=null),d){if(f===null)o.push(null);else{Wi(f);let h=Ee(f,n);o.push(h)}if(a.push(Cr(m,n)),r++,f===null)break}else break}return{node:{type:x.CONDITIONAL,conditions:o,bodies:a,id:l},nextIndex:r}},Zi={eq:ee.EQ,neq:ee.NEQ,gt:ee.GT,gte:ee.GTE,lt:ee.LT,lte:ee.LTE,in:ee.IN,add:ee.ADD,sub:ee.SUBTRACT},eo={all:ee.AND,any:ee.OR},Oy=new Set(["var","literal","call","not",...Object.keys(Zi),...Object.keys(eo)]),Ry=(e,t,n)=>{if(!Array.isArray(e))throw new D(`Condition JSON operator '${t}' at '${Ce(n)}' requires an array`);if(e.length!==2)throw new D(`Condition JSON operator '${t}' at '${Ce(n)}' requires exactly 2 operands`);return e},Cy=(e,t,n,o,a)=>{if(!Array.isArray(e))throw new D(`Condition JSON operator '${t}' at '${Ce(a)}' requires an array`);if(e.length===0)throw new D(`Condition JSON operator '${t}' at '${Ce(a)}' requires at least 1 condition`);return e.map((s,i)=>Le(s,o,[...a,i])).reduce((s,i)=>({type:x.BINARY,op:n,left:s,right:i}))},$y=(e,t,n)=>{let o,a;if(typeof e.call=="string")o=e.call,a=e.args??[],Rr(e,new Set(["call","args"]),n);else if(ro(e.call))o=e.call.name,a=e.call.args??[],Rr(e,new Set(["call"]),n),Rr(e.call,new Set(["name","args"]),[...n,"call"]);else throw new D(`Condition JSON call at '${Ce(n)}' requires a function name`);if(typeof o!="string"||o.trim()==="")throw new D(`Condition JSON call at '${Ce(n)}' requires a non-empty function name`);if(!/^\w+$/.test(o))throw new D(`Invalid condition JSON function name '${o}' at '${Ce(n)}'`);if(!Array.isArray(a))throw new D(`Condition JSON call '${o}' at '${Ce(n)}' requires args to be an array`);return{type:x.FUNCTION,name:o,args:a.map((r,s)=>Le(r,t,[...n,"args",s]))}},Le=(e,t={},n=["$when"])=>{if(typeof e=="string"||typeof e=="number"||typeof e=="boolean"||e===null)return{type:x.LITERAL,value:e};if(Array.isArray(e))throw new D(`Condition JSON array at '${Ce(n)}' must be wrapped in an operator or { literal: [...] }`);if(!ro(e))throw new D(`Invalid condition JSON value at '${Ce(n)}'`);let o=Hl(e);if(o.length===0)throw new D(`Condition JSON object at '${Ce(n)}' must contain an operator`);let a=o.filter(s=>Oy.has(s));if(a.length===0)throw new D(`Unknown condition JSON operator '${o[0]}' at '${Ce(n)}'`);if(a.length>1)throw new D(`Condition JSON at '${Ce(n)}' must contain exactly one operator`);let r=a.includes("call")?"call":a[0];if(r==="var"){if(Rr(e,new Set(["var"]),n),typeof e.var!="string"||e.var.trim()==="")throw new D(`Condition JSON var at '${Ce(n)}' requires a non-empty path`);return{type:x.VARIABLE,path:e.var}}if(r==="literal")return Rr(e,new Set(["literal"]),n),{type:x.LITERAL,value:e.literal};if(r==="call")return $y(e,t,n);if(r==="not")return Rr(e,new Set(["not"]),n),{type:x.UNARY,op:yt.NOT,operand:Le(e.not,t,[...n,"not"])};if(r in eo)return Rr(e,new Set([r]),n),Cy(e[r],r,eo[r],t,[...n,r]);if(r in Zi){Rr(e,new Set([r]),n);let s=Ry(e[r],r,[...n,r]);return{type:x.BINARY,op:Zi[r],left:Le(s[0],t,[...n,r,0]),right:Le(s[1],t,[...n,r,1])}}throw new D(`Unknown condition JSON operator '${r}' at '${Ce(n)}'`)},zl=(e,t={})=>{if(e==null)throw new D("Missing condition expression after '$when'");if(typeof e=="string"){if(e.trim()==="")throw new D("Empty condition expression after '$when'");return Ee(e,t)}return ro(e)||Array.isArray(e)?Le(e,t):{type:x.LITERAL,value:e}},Ee=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let c=e.slice(1,-1),u=0,p=!0;for(let m=0;m<c.length;m++)if(c[m]==="("?u++:c[m]===")"&&u--,u<0){p=!1;break}if(p&&u===0)return Ee(c,t)}let n=Kr(e,"||");if(n!==-1)return{type:x.BINARY,op:ee.OR,left:Ee(e.substring(0,n).trim(),t),right:Ee(e.substring(n+2).trim(),t)};let o=Kr(e,"&&");if(o!==-1)return{type:x.BINARY,op:ee.AND,left:Ee(e.substring(0,o).trim(),t),right:Ee(e.substring(o+2).trim(),t)};let a=[{op:">=",type:ee.GTE},{op:"<=",type:ee.LTE},{op:"==",type:ee.EQ},{op:"!=",type:ee.NEQ},{op:">",type:ee.GT},{op:"<",type:ee.LT},{op:" in ",type:ee.IN}];for(let{op:c,type:u}of a){let p=Kr(e,c);if(p!==-1)return{type:x.BINARY,op:u,left:Ee(e.substring(0,p).trim(),t),right:Ee(e.substring(p+c.length).trim(),t)}}let r=-1,s=null,i=[{op:" + ",type:ee.ADD},{op:" - ",type:ee.SUBTRACT}];for(let{op:c,type:u}of i){let p=0;for(;p<e.length;){let m=Kr(e.substring(p),c);if(m===-1)break;let d=p+m;d>r&&(r=d,s={op:c,type:u}),p=d+c.length}}if(r!==-1&&s)return{type:x.BINARY,op:s.type,left:Ee(e.substring(0,r).trim(),t),right:Ee(e.substring(r+s.op.length).trim(),t)};let l=[" * "," / "," % "];for(let c of l)if(Kr(e,c)!==-1)throw new D(`Arithmetic operations are not allowed in conditionals: "${c}"`);return e.startsWith("!")?{type:x.UNARY,op:yt.NOT,operand:Ee(e.substring(1).trim(),t)}:Gl(e,t)},Kr=(e,t)=>{let n=0,o=0;for(;o<=e.length-t.length;){if(e[o]==="(")n++;else if(e[o]===")")n--;else if(n===0&&e.substring(o,o+t.length)===t)return o;o++}return-1},_y=e=>{if(e=e.trim(),e==="true")return{type:x.LITERAL,value:!0};if(e==="false")return{type:x.LITERAL,value:!1};if(e==="null")return{type:x.LITERAL,value:null};if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:x.LITERAL,value:e.slice(1,-1)};if(e==='""'||e==="''")return{type:x.LITERAL,value:""};if(e==="{}")return{type:x.LITERAL,value:{}};if(e==="[]")return{type:x.LITERAL,value:[]};let t=Number(e);return!isNaN(t)&&isFinite(t)?{type:x.LITERAL,value:t}:{type:x.VARIABLE,path:e}},Gl=(e,t)=>{let n=e.trim();if(n.match(/^(\w+)\((.*)\)$/))return qt(n,t);let a=_y(n);if(a.type===x.LITERAL)return a;if(/^[a-zA-Z_$][\w.$]*$/.test(n))return{type:x.VARIABLE,path:n};try{return qt(n,t)}catch(r){if(r.message&&r.message.includes("not supported"))return a;throw r}},Ny=(e,t=!1)=>{let n=t?"$each":"$for";try{Nl(e)}catch(o){if(o instanceof D&&t){let a=o.message.replace(/\$for/g,"$each");throw new D(a.replace("Parse Error: ",""))}throw o}},Xl=(e,t,n,o=!1)=>{let a=/^\$for(?::(\w+))?\s+(.+)$/,r=e.match(a);if(!r){let g=o?"$each":"$for";throw new D(`Invalid loop syntax (got: '${e.replace("$for",g)}')`)}let s=r[1],i=r[2].trim();Ny(i,o);let l=i.match(/^(.+?)\s+in\s+(.+)$/);if(!l){let g=o?"$each":"$for";throw new D(`Invalid loop syntax - missing 'in' keyword (got: '${g} ${i}')`)}let c=l[1].trim(),u=l[2].trim(),p,m=null;if(c.includes(",")){let g=c.split(",").map(y=>y.trim());if(g.length!==2)throw new D(`Invalid loop variables: ${c}. Expected format: "item" or "item, index"`);p=g[0],m=g[1]}else p=c;let d=["this","undefined","null","true","false"];if(d.includes(p))throw new D(`Reserved variable name: ${p}`);if(m&&d.includes(m))throw new D(`Reserved variable name: ${m}`);let f=Gl(u,n),h=Cr(t,n);return{type:x.LOOP,itemVar:p,indexVar:m,iterable:f,body:h,flatten:s!=="nested"}};var jy=(e,t={})=>{let{functions:n={}}=t;return Cr(e,n)},Fn=jy;var Ft={};Xm(Ft,{now:()=>Ty});var Ty=()=>Date.now();var Dy=(e,t,n={})=>{let{functions:o={},partials:a={}}=n,r={...Ft,...o},s=Fn(e,{functions:r}),i={};for(let[l,c]of Object.entries(a))i[l]=Fn(c,{functions:r});return Ji(s,t,{functions:r,partials:i})},Wr=Dy;var Ly=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.type=="number",My=(e={})=>!e||typeof e!="object"?{}:Object.prototype.hasOwnProperty.call(e,"functions")||Object.prototype.hasOwnProperty.call(e,"partials")?e.functions||{}:e,Vy=(e,t)=>{if(Ly(e))return e;if(typeof e=="string"){if(e.trim()==="")throw new D("Empty condition expression");return Ee(e,t)}return Le(e,t)},qy=(e,t={},n={})=>{let o=My(n),a={...Ft,...o},r=Vy(e,a);return!!Or(r,{functions:a,partials:{}},t,{})},to=qy;var po=Symbol("runStoreTransaction"),oo="__routeEngineConditionComparison",Bn=(e,t)=>typeof e=="number"&&typeof t=="number"&&Number.isFinite(e)&&Number.isFinite(t)||typeof e=="string"&&typeof t=="string",$r=Object.freeze({eq:(e,t)=>e===t,neq:(e,t)=>e!==t,gt:(e,t)=>Bn(e,t)&&e>t,gte:(e,t)=>Bn(e,t)&&e>=t,lt:(e,t)=>Bn(e,t)&&e<t,lte:(e,t)=>Bn(e,t)&&e<=t}),tc=Object.freeze(Object.fromEntries(Object.keys($r).map(e=>[e,`${oo}${e}`]))),Fy=Object.freeze(Object.fromEntries(Object.entries(tc).map(([e,t])=>[t,$r[e]]))),Kl=(e,t)=>Object.prototype.hasOwnProperty.call(e??{},t),By=e=>{if(typeof e?.call=="string")return e.call;if(e?.call!==null&&typeof e?.call=="object"&&!Array.isArray(e.call))return e.call.name},Un=e=>{if(Array.isArray(e))return e.map(Un);if(e===null||typeof e!="object"||Kl(e,"literal")||Kl(e,"var"))return e;if(By(e)?.startsWith(oo))throw new Error(`Condition function names beginning with "${oo}" are reserved`);let n=Object.entries(e);if(n.length===1){let[[o,a]]=n,r=tc[o];if(r)return{call:r,args:a.map(Un)}}return Object.fromEntries(n.map(([o,a])=>[o,Un(a)]))},Ut=(e,t={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return Le(e),to(Un(e),t,{functions:Fy})},Uy=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],nc=(e,t,n={})=>{let o={},a={},{transformSelectorFirstArgument:r=h=>h,transformActionFirstArgument:s=h=>h,createTransactionalMetadata:i,updateTransactionalMetadata:l,finalizeTransactionalMetadata:c}=n,u=typeof i=="function",p={state:structuredClone(e),...u?{transactionalMetadata:structuredClone(i())}:{}},m=0,d=(h,g)=>!u||!c?h:qn(h,y=>{c({state:y.state,transactionalMetadata:y.transactionalMetadata,previousState:g.state,previousTransactionalMetadata:g.transactionalMetadata})});for(let[h,g]of Object.entries(t))h!=="createInitialState"&&(h.startsWith("select")?o[h]=(...y)=>g(r(p.state,p.transactionalMetadata),...y):a[h]=(...y)=>{let w,b=p,A=qn(p,k=>{let P=g(s(k.state,k.transactionalMetadata),...y);w=P!==void 0&&!ge(P)?P:void 0,u&&l&&l({actionName:h,args:y,state:k.state,transactionalMetadata:k.transactionalMetadata,previousState:b.state,previousTransactionalMetadata:b.transactionalMetadata})});return m===0&&(A=d(A,b)),p=A,w});let f=h=>{if(typeof h!="function")throw new Error("Store transaction requires a callback");let g=p,y=m===0;m+=1;let w;try{w=h()}catch(b){throw m-=1,p=g,b}if(m-=1,y)try{p=d(p,g)}catch(b){throw p=g,b}return w};return{...o,...a,[po]:f}},Hn=(e,t)=>n=>{let o=e(),a=Array.isArray(n)?n:[n];return qn(o,r=>{a.forEach(s=>{t.forEach(i=>{i(r,s)})})})};var Yy=(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{}}},Z=(e,t)=>Object.prototype.hasOwnProperty.call(e??{},t),ao=(e,t,n)=>{Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0})},Pe=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),zy=new Set(["pageSize","groups"]),Xy=new Set(["id","variants"]),Hy=new Set(["id","imageId"]),Gy=new Set(["pageSize","tracks"]),Ky=new Set(["id","soundId","title","artist","album","description","coverImageId"]),Wy=new Set(["pageSize","replays"]),Jy=new Set(["sceneId","title","thumbnailImageId","initialVariables"]),Jr=(e,t,n)=>{Object.keys(e).forEach(o=>{if(!t.has(o))throw new Error(`${n} contains unsupported property "${o}"`)})},ht=(e,t)=>{if(typeof e!="string"||e.length===0)throw new Error(`${t} must be a non-empty string`)},Yt=(e={})=>{let t=e?.resources?.imageGallery;if(t===void 0)return;if(!Pe(t))throw new Error("resources.imageGallery must be an object");if(Jr(t,zy,"resources.imageGallery"),!Number.isInteger(t.pageSize)||t.pageSize<1)throw new Error("resources.imageGallery.pageSize must be an integer greater than or equal to 1");if(!Array.isArray(t.groups))throw new Error("resources.imageGallery.groups must be an array");let n=new Set;for(let[o,a]of t.groups.entries()){let r=`resources.imageGallery.groups[${o}]`;if(!Pe(a))throw new Error(`${r} must be an object`);if(Jr(a,Xy,r),ht(a.id,`${r}.id`),n.has(a.id))throw new Error(`Duplicate image gallery group id "${a.id}"`);if(n.add(a.id),!Array.isArray(a.variants)||a.variants.length===0)throw new Error(`${r}.variants must be a non-empty array`);let s=new Set;for(let[i,l]of a.variants.entries()){let c=`${r}.variants[${i}]`;if(!Pe(l))throw new Error(`${c} must be an object`);if(Jr(l,Hy,c),ht(l.id,`${c}.id`),ht(l.imageId,`${c}.imageId`),s.has(l.id))throw new Error(`Duplicate image gallery variant id "${l.id}" in group "${a.id}"`);if(s.add(l.id),!Z(e?.resources?.images,l.imageId))throw new Error(`Image gallery variant "${a.id}.${l.id}" references unknown image "${l.imageId}"`)}}},zt=(e={})=>{let t=e?.resources?.musicRoom;if(t===void 0)return;if(!Pe(t))throw new Error("resources.musicRoom must be an object");if(Jr(t,Gy,"resources.musicRoom"),!Number.isInteger(t.pageSize)||t.pageSize<1)throw new Error("resources.musicRoom.pageSize must be an integer greater than or equal to 1");if(!Array.isArray(t.tracks))throw new Error("resources.musicRoom.tracks must be an array");let n=new Set;for(let[o,a]of t.tracks.entries()){let r=`resources.musicRoom.tracks[${o}]`;if(!Pe(a))throw new Error(`${r} must be an object`);Jr(a,Ky,r);for(let l of["id","soundId","title"])ht(a[l],`${r}.${l}`);for(let l of["artist","album","description","coverImageId"])a[l]!==void 0&&ht(a[l],`${r}.${l}`);if(n.has(a.id))throw new Error(`Duplicate music room track id "${a.id}"`);n.add(a.id);let s=e?.resources?.sounds?.[a.soundId];if(!Z(e?.resources?.sounds,a.soundId))throw new Error(`Music room track "${a.id}" references unknown sound "${a.soundId}"`);if(!Pe(s))throw new Error(`Music room track "${a.id}" references invalid sound "${a.soundId}"`);if(s.playbackRate!==void 0&&(typeof s.playbackRate!="number"||!Number.isFinite(s.playbackRate)||s.playbackRate<=0))throw new Error(`Music room sound "${a.soundId}" playbackRate must be a finite number greater than 0`);let i=s.startAt??0;if(typeof i!="number"||!Number.isFinite(i)||i<0)throw new Error(`Music room sound "${a.soundId}" startAt must be a finite non-negative number`);if(s.endAt!==void 0&&s.endAt!==null&&(typeof s.endAt!="number"||!Number.isFinite(s.endAt)||s.endAt<=i))throw new Error(`Music room sound "${a.soundId}" endAt must be a finite number greater than startAt`);if(a.coverImageId!==void 0&&!Z(e?.resources?.images,a.coverImageId))throw new Error(`Music room track "${a.id}" references unknown cover image "${a.coverImageId}"`)}},Qy=(e,t,n)=>{let o=Array.isArray(n)?"array":typeof n;switch(t.type){case"number":if(typeof n!="number"||!Number.isFinite(n))throw new Error(`Scene replay initial variable "${e}" expected type number, got ${o}`);return;case"boolean":if(typeof n!="boolean")throw new Error(`Scene replay initial variable "${e}" expected type boolean, got ${o}`);return;case"string":if(typeof n!="string")throw new Error(`Scene replay initial variable "${e}" expected type string, got ${o}`);return;case"object":if(n===null||typeof n!="object")throw new Error(`Scene replay initial variable "${e}" expected type object, got ${o}`);return;default:throw new Error(`Scene replay initial variable "${e}" has invalid variable type "${t.type}"`)}},Xt=(e={})=>{let t=e?.resources?.sceneReplay;if(t===void 0)return;if(!Pe(t))throw new Error("resources.sceneReplay must be an object");if(Jr(t,Wy,"resources.sceneReplay"),!Number.isInteger(t.pageSize)||t.pageSize<1)throw new Error("resources.sceneReplay.pageSize must be an integer greater than or equal to 1");if(!Array.isArray(t.replays))throw new Error("resources.sceneReplay.replays must be an array");let n=e?.story?.scenes??{},o=new Set;for(let[a,r]of t.replays.entries()){let s=`resources.sceneReplay.replays[${a}]`;if(!Pe(r))throw new Error(`${s} must be an object`);Jr(r,Jy,s);for(let u of["sceneId","title","thumbnailImageId"])ht(r[u],`${s}.${u}`);if(o.has(r.sceneId))throw new Error(`Duplicate scene replay sceneId "${r.sceneId}"`);if(o.add(r.sceneId),!Z(e?.resources?.images,r.thumbnailImageId))throw new Error(`Scene replay scene "${r.sceneId}" references unknown thumbnail image "${r.thumbnailImageId}"`);let i=n[r.sceneId];if(!i)throw new Error(`Scene replay references unknown scene "${r.sceneId}"`);let l=i.initialSectionId,c=i.sections?.[l];if(!c)throw new Error(`Scene replay scene "${r.sceneId}" references unknown initial section "${l}"`);if(c.initialLineId!==void 0&&!c.lines?.some(u=>u.id===c.initialLineId))throw new Error(`Scene replay scene "${r.sceneId}" initial section "${l}" references unknown initial line "${c.initialLineId}"`);if(r.initialVariables!==void 0){if(!Pe(r.initialVariables))throw new Error(`${s}.initialVariables must be an object`);for(let[u,p]of Object.entries(r.initialVariables)){let m=e?.resources?.variables?.[u];if(!m)throw new Error(`Scene replay scene "${r.sceneId}" initialVariables references unknown variable "${u}"`);if($e(m))throw new Error(`Scene replay scene "${r.sceneId}" cannot initialize computed variable "${u}"`);if(m.readonly===!0)throw new Error(`Scene replay scene "${r.sceneId}" cannot initialize readonly variable "${u}"`);if(m.scope!=="context")throw new Error(`Scene replay scene "${r.sceneId}" can only initialize context variable "${u}"`);Qy(u,m,p)}}}},sc=e=>{let t=ge(e)?Xe(e):e;return structuredClone(t)},Zy=({characterId:e,resourceCharacter:t,variables:n={}}={})=>{if(!Z(t,"nameVariableId"))return;let o=t.nameVariableId,a=n?.[o];if(typeof a!="string")throw new Error(`Character "${e}" nameVariableId "${o}" must resolve to a string variable`);return a},Gn=({characterId:e,character:t,characterName:n,characters:o={},variables:a={}}={})=>{let r=e?o?.[e]:void 0;if(t?.name!==void 0)return t.name;if(n!==void 0)return n;let s=Zy({characterId:e,resourceCharacter:r,variables:a});return s!==void 0?s:r?.name||""},$e=e=>Z(e,"computed"),fo=(e,t)=>{switch(e?.type){case"number":return typeof t=="number"&&Number.isFinite(t);case"boolean":return typeof t=="boolean";case"string":return typeof t=="string";case"object":return t!==null&&typeof t=="object"&&!Array.isArray(t);default:return!1}},Ht=(e={},t={},{allowedScopes:n,preserveUnknown:o=!1}={})=>Object.fromEntries(Object.entries(e??{}).filter(([a,r])=>{let s=t[a];return s===void 0?o:!$e(s)&&(!n||n.includes(s.scope))&&fo(s,r)})),Ge=(e,t)=>new Error(`${t} has invalid path: ${JSON.stringify(e)}`),eh=(e,t,n)=>{if(e[0]==='"')try{return JSON.parse(e)}catch{throw Ge(t,n)}let a="";for(let r=1;r<e.length-1;r+=1){let s=e[r];if(s!=="\\"){if(s.charCodeAt(0)<32)throw Ge(t,n);a+=s;continue}if(r+=1,r>=e.length-1)throw Ge(t,n);let i=e[r];if(i==="u"){let c=e.slice(r+1,r+5);if(c.length!==4||!/^[0-9a-fA-F]{4}$/.test(c))throw Ge(t,n);a+=String.fromCharCode(Number.parseInt(c,16)),r+=4;continue}let l={"\\":"\\",'"':'"',"'":"'","/":"/",n:`
2
- `,r:"\r",t:" ",b:"\b",f:"\f"};if(!Z(l,i))throw Ge(t,n);a+=l[i]}return a},ic=(e,t="Computed expression var")=>{if(typeof e!="string"||e.length===0||e.trim()!==e)throw Ge(e,t);let n=[],o=0,a=()=>{let s=o;for(;o<e.length&&e[o]!=="."&&e[o]!=="["&&e[o]!=="]";)o+=1;let i=e.slice(s,o);if(i.length===0||i.trim()!==i||/\s/.test(i))throw Ge(e,t);n.push(i)},r=()=>{for(o+=1;o<e.length&&/\s/.test(e[o]);)o+=1;let s=e[o];if(/\d/.test(s??"")){let u=o;for(;o<e.length&&/\d/.test(e[o]);)o+=1;let p=e.slice(u,o);for(;o<e.length&&/\s/.test(e[o]);)o+=1;if(e[o]!=="]"||p.length>1&&p.startsWith("0"))throw Ge(e,t);o+=1,n.push(p);return}if(s!=='"'&&s!=="'")throw Ge(e,t);let i=s,l=o;o+=1;let c=!1;for(;o<e.length;){let u=e[o];if(c)c=!1;else if(u==="\\")c=!0;else if(u===i){let p=e.slice(l,o+1);for(o+=1;o<e.length&&/\s/.test(e[o]);)o+=1;if(e[o]!=="]")throw Ge(e,t);o+=1,n.push(eh(p,e,t));return}o+=1}if(c||o>=e.length)throw Ge(e,t)};for(a();o<e.length;){if(e[o]==="."){o+=1,a();continue}if(e[o]==="["){r();continue}throw Ge(e,t)}return n},no=(e,t)=>{let n=e;for(let o of t){if(n==null||!Z(n,o))return;n=n[o]}return n},oc=(e,t={})=>{if(typeof e!="string"||e.trim()==="")throw new Error("Computed expression var requires a non-empty string path");let n=ic(e),[o,a,...r]=n;if(o==="variables"){if(!a)return t.variables;let s=typeof t.resolveVariable=="function"?t.resolveVariable(a):t.variables?.[a];return no(s,r)}return o==="runtime"?no(t.runtime,n.slice(1)):no(t,n)},ac=(e,t,n)=>{if(!Array.isArray(t))throw new Error(`Computed expression operator "${e}" requires an array`);if(n!==void 0&&t.length!==n)throw new Error(`Computed expression operator "${e}" requires ${n} operand(s)`)},lo=(e,t)=>{if(!Array.isArray(t))throw new Error(`Computed expression operator "${e}" requires an array`);if(t.length===0)throw new Error(`Computed expression operator "${e}" requires at least one operand`)},rh=(e,t)=>{if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Computed expression operator "${e}" requires finite numeric operands`)},er=(e,t,n,o)=>(ac(e,t,o),t.map(a=>Xn(a,n))),He=(e,t,n,o)=>{let a=er(e,t,n,o);return a.forEach(r=>rh(e,r)),a},th=(e,t,n)=>{switch(e){case"var":return oc(t,n);case"add":{let[o,a]=He(e,t,n,2);return o+a}case"sub":{let[o,a]=He(e,t,n,2);return o-a}case"mul":{let[o,a]=He(e,t,n,2);return o*a}case"div":{let[o,a]=He(e,t,n,2);return o/a}case"mod":{let[o,a]=He(e,t,n,2);return o%a}case"neg":{let[o]=He(e,t,n,1);return-o}case"round":{let[o]=He(e,t,n,1);return Math.round(o)}case"floor":{let[o]=He(e,t,n,1);return Math.floor(o)}case"ceil":{let[o]=He(e,t,n,1);return Math.ceil(o)}case"min":{let[o,a]=He(e,t,n,2);return Math.min(o,a)}case"max":{let[o,a]=He(e,t,n,2);return Math.max(o,a)}case"clamp":{let[o,a,r]=He(e,t,n,3);return Math.min(r,Math.max(a,o))}case"eq":{let[o,a]=er(e,t,n,2);return $r.eq(o,a)}case"neq":{let[o,a]=er(e,t,n,2);return $r.neq(o,a)}case"gt":{let[o,a]=er(e,t,n,2);return $r.gt(o,a)}case"gte":{let[o,a]=er(e,t,n,2);return $r.gte(o,a)}case"lt":{let[o,a]=er(e,t,n,2);return $r.lt(o,a)}case"lte":{let[o,a]=er(e,t,n,2);return $r.lte(o,a)}case"in":{let[o,a]=er(e,t,n,2);return Array.isArray(a)?a.includes(o):!1}case"and":case"all":return lo(e,t),t.every(o=>!!Xn(o,n));case"or":case"any":return lo(e,t),t.some(o=>!!Xn(o,n));case"not":{let[o]=er(e,t,n,1);return!o}case"length":{let[o]=er(e,t,n,1);return typeof o=="string"||Array.isArray(o)?o.length:Pe(o)?Object.keys(o).length:0}case"includes":{let[o,a]=er(e,t,n,2);return typeof o=="string"?typeof a=="string"&&o.includes(a):Array.isArray(o)?o.includes(a):!1}case"literal":return sc(t);default:throw new Error(`Unknown computed expression operator: ${e}`)}},Xn=(e,t={})=>{if(e===null||typeof e!="object")return e;if(Array.isArray(e))throw new Error("Computed expression arrays are not valid; use value for literal arrays");let n=Object.entries(e);if(n.length!==1)throw new Error("Computed expression objects must contain exactly one operator");let[[o,a]]=n;return th(o,a,t)},co=(e,t)=>{if(e===null||typeof e!="object"||Z(e,"literal"))return e;if(Z(e,"var"))return{literal:oc(e.var,t)};if(Z(e,"call"))throw new Error("Function calls are not supported in computed-variable conditions");return Object.fromEntries(Object.entries(e).map(([n,o])=>[n,Array.isArray(o)?o.map(a=>co(a,t)):co(o,t)]))},nh=(e,t={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return Le(e),Ut(co(e,t))},lc=(e,t)=>{if(!Pe(e))throw new Error(`${t} must be an object`);let n=Z(e,"expr"),o=Z(e,"value");if(n===o)throw new Error(`${t} must contain exactly one of expr or value`)},so=(e,t,n)=>(lc(e,t),Z(e,"value")?sc(e.value):Xn(e.expr,n)),sh=(e,t={},n="unknown")=>{if(!Pe(e))throw new Error(`Computed variable "${n}" computed must be an object`);let o=Z(e,"expr"),a=Z(e,"value");if(Z(e,"branches")){if(o||a)throw new Error(`Computed variable "${n}" cannot combine branches with expr or value`);if(!Array.isArray(e.branches))throw new Error(`Computed variable "${n}" branches must be an array`);if(e.branches.length===0)throw new Error(`Computed variable "${n}" branches must not be empty`);if(!Pe(e.default))throw new Error(`Computed variable "${n}" requires default`);for(let s=0;s<e.branches.length;s+=1){let i=e.branches[s];if(!Pe(i))throw new Error(`Computed variable "${n}" branch ${s} must be an object`);if(!Z(i,"when"))throw new Error(`Computed variable "${n}" branch ${s} requires when`);if(nh(i.when,t))return so(i,`Computed variable "${n}" branch ${s}`,t)}return so(e.default,`Computed variable "${n}" default`,t)}if(o===a)throw new Error(`Computed variable "${n}" must contain exactly one of expr, value, or branches`);return so(e,`Computed variable "${n}"`,t)},cc=(e,t,n)=>{switch(t){case"number":if(typeof n!="number"||!Number.isFinite(n))throw new Error(`Computed variable "${e}" expected type number, got ${Array.isArray(n)?"array":typeof n}`);return;case"boolean":if(typeof n!="boolean")throw new Error(`Computed variable "${e}" expected type boolean, got ${Array.isArray(n)?"array":typeof n}`);return;case"string":if(typeof n!="string")throw new Error(`Computed variable "${e}" expected type string, got ${Array.isArray(n)?"array":typeof n}`);return;case"object":if(n===null||typeof n!="object")throw new Error(`Computed variable "${e}" expected type object, got ${typeof n}`);return;default:throw new Error(`Invalid variable type: ${t} for computed variable ${e}`)}},ih=Object.freeze({add:2,sub:2,mul:2,div:2,mod:2,neg:1,round:1,floor:1,ceil:1,min:2,max:2,clamp:3,eq:2,neq:2,gt:2,gte:2,lt:2,lte:2,in:2,not:1,length:1,includes:2}),oh=new Set(["and","or","all","any"]),ah=new Set(["add","sub","mul","div","mod","neg","round","floor","ceil","min","max","clamp","length"]),lh=new Set(["add","sub","mul","div","mod","neg","round","floor","ceil","min","max","clamp"]),ch=new Set(["eq","neq","gt","gte","lt","lte","in","and","or","all","any","not","includes"]),uh=new Set(["all","any","eq","neq","gt","gte","lt","lte","in","add","sub"]),uc=new WeakMap,Wl=e=>e===null?"null":Array.isArray(e)?"object":typeof e,Yn=(e,t,n)=>{for(let o of Object.keys(e))if(!t.has(o))throw new Error(`${n} contains unsupported property "${o}"`)},ph=(e,t,n,o)=>{if(n!==void 0&&n!==t)throw new Error(`Computed variable "${e}" ${o} expected type ${t}, got ${n}`)},pc=(e,{variableId:t,variableConfigs:n,dependencies:o,path:a})=>{let r=`Computed variable "${t}" ${a} var`,[s,i,...l]=ic(e,r);if(s!=="variables"&&s!=="runtime")throw new Error(`${r} must reference variables.* or runtime.*, got ${JSON.stringify(e)}`);if(!i)throw new Error(`${r} must reference a concrete ${s} member, got ${JSON.stringify(e)}`);if(s==="runtime")return;if(!Z(n,i))throw new Error(`Computed variable "${t}" ${a} references unknown variable "${i}"`);let c=n[i];return $e(c)&&o.add(i),l.length===0?c?.type:void 0},fc=(e,{variableId:t,variableConfigs:n,dependencies:o,path:a})=>{if(e===null||typeof e!="object"){if(typeof e=="number"&&!Number.isFinite(e))throw new Error(`Computed variable "${t}" ${a} must use finite numeric literals`);return Wl(e)}if(Array.isArray(e))throw new Error("Computed expression arrays are not valid; use value for literal arrays");let r=Object.entries(e);if(r.length!==1)throw new Error("Computed expression objects must contain exactly one operator");let[[s,i]]=r;if(s==="var"){if(typeof i!="string"||i.trim()==="")throw new Error("Computed expression var requires a non-empty string path");return pc(i,{variableId:t,variableConfigs:n,dependencies:o,path:a})}if(s==="literal"){if(typeof i=="number"&&!Number.isFinite(i))throw new Error(`Computed variable "${t}" ${a} must use finite numeric literals`);return Wl(i)}let l=ih[s];if(l===void 0&&!oh.has(s))throw new Error(`Unknown computed expression operator: ${s}`);l===void 0?lo(s,i):ac(s,i,l);let c=i.map((u,p)=>fc(u,{variableId:t,variableConfigs:n,dependencies:o,path:`${a}.${s}[${p}]`}));if(lh.has(s)&&c.forEach(u=>{if(u!==void 0&&u!=="number")throw new Error(`Computed expression operator "${s}" requires numeric operands`)}),ah.has(s))return"number";if(ch.has(s))return"boolean"},fh=(e,{variableId:t,variableConfigs:n,dependencies:o,path:a})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");try{Le(e)}catch(s){throw new Error(`Computed variable "${t}" ${a} is invalid: ${s.message}`,{cause:s})}let r=(s,i)=>{if(s===null||typeof s!="object"||Z(s,"literal"))return;if(Z(s,"var")){pc(s.var,{variableId:t,variableConfigs:n,dependencies:o,path:i});return}if(Z(s,"call"))throw new Error(`Computed variable "${t}" ${i} function calls are not supported`);if(Z(s,"not")){r(s.not,`${i}.not`);return}let l=Object.keys(s).find(c=>uh.has(c));s[l].forEach((c,u)=>{r(c,`${i}.${l}[${u}]`)})};r(e,a)},io=(e,{variableId:t,variableConfig:n,variableConfigs:o,dependencies:a,path:r,allowedKeys:s=new Set(["expr","value"])})=>{if(lc(e,`Computed variable "${t}" ${r}`),Yn(e,s,r),Z(e,"value")){cc(t,n.type,e.value);return}let i=fc(e.expr,{variableId:t,variableConfigs:o,dependencies:a,path:`${r}.expr`});ph(t,n.type,i,`${r}.expr`)},dh=(e,t,n)=>{let o=t.computed;if(!Pe(o))throw new Error(`Computed variable "${e}" computed must be an object`);let a=new Set,r=Z(o,"expr"),s=Z(o,"value");if(Z(o,"branches")){if(Yn(o,new Set(["branches","default"]),`Computed variable "${e}" computed`),r||s)throw new Error(`Computed variable "${e}" cannot combine branches with expr or value`);if(!Array.isArray(o.branches))throw new Error(`Computed variable "${e}" branches must be an array`);if(o.branches.length===0)throw new Error(`Computed variable "${e}" branches must not be empty`);if(!Pe(o.default))throw new Error(`Computed variable "${e}" requires default`);return o.branches.forEach((l,c)=>{if(!Pe(l))throw new Error(`Computed variable "${e}" branch ${c} must be an object`);if(Yn(l,new Set(["when","expr","value"]),`Computed variable "${e}" branch ${c}`),!Z(l,"when"))throw new Error(`Computed variable "${e}" branch ${c} requires when`);fh(l.when,{variableId:e,variableConfigs:n,dependencies:a,path:`computed.branches[${c}].when`}),io(l,{variableId:e,variableConfig:t,variableConfigs:n,dependencies:a,path:`computed.branches[${c}]`,allowedKeys:new Set(["when","expr","value"])})}),io(o.default,{variableId:e,variableConfig:t,variableConfigs:n,dependencies:a,path:"computed.default"}),a}if(Yn(o,new Set(["expr","value"]),`Computed variable "${e}" computed`),r===s)throw new Error(`Computed variable "${e}" must contain exactly one of expr, value, or branches`);return io(o,{variableId:e,variableConfig:t,variableConfigs:n,dependencies:a,path:"computed"}),a},Qr=(e={})=>{if(!Pe(e))throw new Error("Variable configs must be an object");if(Z(e,"__proto__"))throw new Error('Variable id "__proto__" is reserved');if(Z(e,""))throw new Error("Variable ids must not be empty");let t=new Map;Object.entries(e).forEach(([r,s])=>{if($e(s)){if(!Pe(s))throw new Error(`Computed variable "${r}" must be an object`);if(!Z(s,"type"))throw new Error(`Computed variable "${r}" requires type`);if(!Z(s,"scope"))throw new Error(`Computed variable "${r}" requires scope`);if(Z(s,"default"))throw new Error(`Computed variable "${r}" must not declare a top-level default`);if(Gt(s.scope,r),!["number","boolean","string","object"].includes(s.type))throw new Error(`Invalid variable type: ${s.type} for computed variable ${r}`);t.set(r,dh(r,s,e))}});let n=new Set,o=[];t.forEach((r,s)=>{if(n.has(s))return;let i=[{variableId:s,dependencies:[...t.get(s)??[]],nextDependencyIndex:0}],l=new Map([[s,0]]);for(;i.length>0;){let c=i.at(-1);if(c.nextDependencyIndex>=c.dependencies.length){i.pop(),l.delete(c.variableId),n.add(c.variableId),o.push(c.variableId);continue}let u=c.dependencies[c.nextDependencyIndex];if(c.nextDependencyIndex+=1,n.has(u))continue;let p=l.get(u);if(p!==void 0){let m=[...i.slice(p).map(({variableId:d})=>d),u].join(" -> ");throw new Error(`Computed variable cycle detected: ${m}`)}l.set(u,i.length),i.push({variableId:u,dependencies:[...t.get(u)??[]],nextDependencyIndex:0})}});let a=Object.freeze({evaluationOrder:Object.freeze(o)});return uc.set(e,a),a},gt=({variables:e={},runtime:t={},variableConfigs:n={},eager:o=!0}={})=>{let{evaluationOrder:a}=uc.get(n)??Qr(n),r=Ht(e,n,{preserveUnknown:!0}),s=Object.entries(n).filter(([,g])=>$e(g)).map(([g])=>g),i=Object.create(null),l=[],c=new Map(a.map((g,y)=>[g,y])),u=-1,p=!1,m=g=>{if(Z(i,g))return i[g];let y=n[g];if(!$e(y))return Z(r,g)?r[g]:void 0;let w=l.indexOf(g);if(w>=0){let b=[...l.slice(w),g].join(" -> ");throw new Error(`Computed variable cycle detected: ${b}`)}l.push(g);try{let b=sh(y.computed,h,g);return cc(g,y.type,b),ao(i,g,b),b}finally{l.pop()}},d=g=>{if(Z(i,g))return i[g];let y=n[g];if(!$e(y))return Z(r,g)?r[g]:void 0;let w=c.get(g);if(o&&!p&&w!==void 0&&w>u){p=!0;try{for(let b=u+1;b<=w;b+=1)m(a[b]),u=b}finally{p=!1}return i[g]}return m(g)},f=new Proxy({},{get:(g,y)=>{if(typeof y=="string")return d(y)},has:(g,y)=>typeof y=="string"&&(Z(r,y)||s.includes(y)),ownKeys:()=>[...new Set([...Object.keys(r),...s])],getOwnPropertyDescriptor:(g,y)=>{if(!(typeof y!="string"||!Z(r,y)&&!s.includes(y)))return{enumerable:!0,configurable:!0}}}),h={variables:f,runtime:t,resolveVariable:d};return o?(s.forEach(g=>{d(g)}),{...r,...i}):f},mh=({variables:e={},runtime:t={},variableConfigs:n,projectData:o}={})=>{let a=n??o?.resources?.variables??{};return Qr(a),gt({variables:e,runtime:t,variableConfigs:a,eager:!0})},Kn=e=>{let t={},n={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([o,a])=>{if($e(a))return;let r=Yy(a,o);a.scope==="context"?ao(t,o,r):ao(n,o,r)}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}},Gt=(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(", ")}`)},Kt=(e,t,n)=>{let o={number:["set","increment","decrement","multiply","divide"],boolean:["set","toggle"],string:["set"],object:["set"]},a=o[e];if(!a)throw new Error(`Unknown variable type: ${e} for variable ${n}`);if(!Object.values(o).flat().includes(t))throw new Error(`Unknown operation: ${t}`);if(!a.includes(t))throw new Error(`Operation "${t}" is not valid for variable "${n}" of type "${e}". Valid operations: ${a.join(", ")}`)},yh=2,Jl=12,dc=(e=yh)=>{if(!Number.isInteger(e)||e<0||e>Jl)throw new Error(`Operation "divide" requires roundTo to be an integer between 0 and ${Jl}.`);return e},hh=(e,t)=>{let n=10**t;return Math.round((e+Number.EPSILON)*n)/n},zn=e=>typeof e=="number"&&Number.isFinite(e),Wn=(e,t,n,o,a={})=>{if(e==="number"){if(t==="set"&&!zn(n))throw new Error(`Operation "set" requires value to be a number for variable "${o}".`);if(t==="multiply"&&!zn(n))throw new Error(`Operation "multiply" requires value to be a number for variable "${o}".`);if(t==="divide"&&!zn(n))throw new Error(`Operation "divide" requires value to be a number for variable "${o}".`);if(t==="divide"){if(n===0)throw new Error(`Operation "divide" requires value to be a non-zero number for variable "${o}".`);dc(a.roundTo)}}},Jn=(e,t,n,o={})=>{let a=(s,i,l)=>{let c=s??i;if(!zn(c))throw new Error(`Operation "${t}" requires ${l} to be a number.`);return c},r=s=>{let i=a(s,void 0,"value");if(i===0)throw new Error(`Operation "${t}" requires value to be a non-zero number.`);return i};switch(t){case"set":return n;case"multiply":return a(e,1,"current value")*a(n,void 0,"value");case"divide":return hh(a(e,0,"current value")/r(n),dc(o.roundTo));case"increment":return a(e,0,"current value")+a(n,1,"value");case"decrement":return a(e,0,"current value")-a(n,1,"value");case"toggle":return!e;default:throw new Error(`Unknown operation: ${t}`)}};var mo=(e,t="DD/MM/YYYY - HH:mm")=>{if(!e)return"";let n=new Date(e),o=s=>String(s).padStart(2,"0"),a=String(n.getFullYear()),r={DD:o(n.getDate()),MM:o(n.getMonth()+1),MMM:Uy[n.getMonth()],YYYY:a,YY:a.slice(-2),HH:o(n.getHours()),mm:o(n.getMinutes()),ss:o(n.getSeconds())};return t.replace(/YYYY|MMM|YY|MM|DD|HH|mm|ss/g,s=>r[s])},gh=(e,t)=>{let n=r=>r?.ui,o=n(e),a=n(t);return JSON.stringify(o)===JSON.stringify(a)?null:o&&!a?{changeType:"delete",data:e}:a&&!o?{changeType:"add",data:t}:a&&o?{changeType:"update",data:t}:null},Bt=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,bh=(e,t)=>{let n=e?.character?.sprite,o=t?.character?.sprite,a=Bt(n)?n:void 0,r=Bt(o)?o:void 0;return JSON.stringify(a)===JSON.stringify(r)?null:a&&!r?{changeType:"delete",data:a}:r&&!a?{changeType:"add",data:r}:r&&a?{changeType:"update",data:r}:null},Ql=e=>{if(e?.resourceId===void 0)return;let t={resourceId:e.resourceId};e.transformId!==void 0&&(t.transformId=e.transformId);for(let n of["x","y","anchorX","anchorY","scaleX","scaleY","flipX","flipY","rotation","originX","originY"])e[n]!==void 0&&(t[n]=e[n]);for(let n of["animationName","animationSpeed","loop"])e[n]!==void 0&&(t[n]=e[n]);return t},Zl=e=>{if(e?.colorId!==void 0)return{colorId:e.colorId}},ec=(e,t)=>t&&!e?{changeType:"add",data:t}:e&&!t?{changeType:"delete",data:e}:e&&t&&JSON.stringify(e)!==JSON.stringify(t)?{changeType:"update",data:t}:null,wh=(e,t)=>{let n={},o=ec(Ql(e),Ql(t)),a=ec(Zl(e),Zl(t));return o&&(n.resource=o),a&&(n.color=a),Object.keys(n).length>0?n:null},yo=(e={},t={})=>{let n={},o=["voice"],a=l=>{let c=e[l],u=t[l];if(u&&!c)n[l]={changeType:"add",data:u};else if(c&&!u){let p=l==="sfx"&&c.channels?.some(m=>m.applyMode==="persistent");!o.includes(l)&&(l!=="sfx"||p)&&(n[l]={changeType:"delete",data:c})}else c&&u&&JSON.stringify(c)!==JSON.stringify(u)&&(n[l]={changeType:"update",data:u})},r=wh(e.background,t.background);r&&(n.background=r),a("screen"),a("bgm"),a("voice");let s=gh(e.dialogue,t.dialogue);s&&(n.dialogue=s);let i=bh(e.dialogue,t.dialogue);return i&&(n.dialogueSprite=i),a("choice"),a("form"),a("layout"),a("animation"),a("control"),a("character"),a("visual"),a("sfx"),n},ho=(e={})=>{let t=structuredClone(e);if(t.sfx){let a=Array.isArray(t.sfx.channels)?t.sfx.channels.filter(r=>r.applyMode==="persistent"):[];a.length>0?t.sfx={channels:a}:delete t.sfx}t.background&&(t.background.animations?.playback?.continuity!=="persistent"&&delete t.background.animations,!t.background.resourceId&&!t.background.colorId&&delete t.background);let n=a=>{t[a]&&(delete t[a].animations,Object.keys(t[a]).length===0&&delete t[a])};n("layout"),n("choice"),n("form"),n("screen"),t.dialogue?.ui&&(delete t.dialogue.ui.animations,Object.keys(t.dialogue.ui).length===0&&delete t.dialogue.ui,Object.keys(t.dialogue).length===0&&delete t.dialogue),t.dialogue?.character?.sprite&&(delete t.dialogue.character.sprite.animations,Object.keys(t.dialogue.character.sprite).length===0&&delete t.dialogue.character.sprite,Object.keys(t.dialogue.character).length===0&&delete t.dialogue.character,Object.keys(t.dialogue).length===0&&delete t.dialogue);let o=(a,r)=>{let s=t[a]?.items;Array.isArray(s)&&(t[a].items=s.map(i=>{let l={...i};return l.animations?.playback?.continuity!=="persistent"&&delete l.animations,r(l)?l:null}).filter(Boolean),t[a].items.length===0&&delete t[a])};return o("character",a=>a.sprites&&a.sprites.length>0||a.transformId||a.resourceId),o("visual",a=>a.resourceId||a.text||a.layout||a.transformId||a.transform),t},Ih=(e,t)=>{if(!e||!t)return;let n=e;for(let o of t.split(".")){if(n==null||o==="__proto__"||o==="prototype"||o==="constructor"||!Object.prototype.hasOwnProperty.call(Object(n),o))return;n=n[o]}return n},rc=e=>e!==null&&typeof e=="object"?structuredClone(e):e,vh=(e,t,n)=>{if(typeof e!="string")return e;let o=Object.prototype.hasOwnProperty.call(t??{},n)?t[n]:void 0;if(e===n){if(o==null)throw new Error(`Action template binding "${n}" requires event context "${n}".`);return rc(o)}if(!e.startsWith(`${n}.`))return e;if(o==null)throw new Error(`Action template binding "${e}" requires event context "${n}".`);let a=e.slice(n.length+1),r=Ih(o,a);if(r===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "${n}".`);return rc(r)},kh={conditional:new Set(["branches"]),updateProjectData:new Set(["projectData"]),showConfirmDialog:new Set(["confirmActions","cancelActions"]),form:new Set(["submitActions","cancelActions"]),submitForm:new Set(["actions"]),cancelForm:new Set(["actions"])},Ah=(e,t)=>{let n=e[e.length-1];return n?kh[n]?.has(t)===!0:!1},uo=(e,t,n=[])=>Array.isArray(e)?e.map(o=>uo(o,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([o,a])=>[o,Ah(n,o)?a:uo(a,t,[...n,o])])):typeof e=="string"?e==="_event"||e.startsWith("_event.")?vh(e,t,"_event"):Wr(e,t):e,Wt=(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".');return uo(e,t)};var Ph=11102230246251565e-32,mc=128,yc=1e3,hc=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Jt=(e,t,n)=>{let o=Object.keys(e).find(a=>!t.has(a));if(o!==void 0)throw new Error(`${n}.${o} is not supported`)},Qn=(e,t)=>{if(!hc(e))throw new Error(`${t} must be an object`)},Zn=(e,t,{min:n,max:o}={})=>{if(!Number.isSafeInteger(e))throw new Error(`${t} must be a safe integer`);if(n!==void 0&&e<n)throw new Error(`${t} must be at least ${n}`);if(o!==void 0&&e>o)throw new Error(`${t} must be at most ${o}`);return e},Eh=(e,t,{min:n,max:o}={})=>{if(typeof e!="number"||!Number.isFinite(e))throw new Error(`${t} must be a finite number`);if(n!==void 0&&e<n)throw new Error(`${t} must be at least ${n}`);if(o!==void 0&&e>o)throw new Error(`${t} must be at most ${o}`);return e},go=e=>{let t=structuredClone(e),n=o=>(o&&typeof o=="object"&&!Object.isFrozen(o)&&(Object.values(o).forEach(n),Object.freeze(o)),o);return n(t)},xh=()=>({nextUint32(){return typeof globalThis.crypto?.getRandomValues=="function"?globalThis.crypto.getRandomValues(new Uint32Array(1))[0]:Math.floor(Math.random()*4294967296)}}),gc=e=>{let t=e??xh();if(!hc(t)||typeof t.nextUint32!="function")throw new TypeError("randomSource must provide nextUint32()");return{nextUint32(){let n=t.nextUint32();if(!Number.isInteger(n)||n<0||n>=4294967296)throw new Error("randomSource.nextUint32() must return an integer from 0 through 4294967295");return n}}},Sh=(e,t)=>{let n=4294967296-4294967296%t;for(let o=0;o<mc;o+=1){let a=e.nextUint32();if(a<n)return a%t}throw new Error(`random source exhausted after ${mc} rejected samples`)},Oh=e=>{let t=e.nextUint32()>>>5,n=e.nextUint32()>>>6;return(t*67108864+n)/9007199254740992},Rh=(e,t)=>{if(Jt(e,new Set(["type","min","max"]),"random.distribution"),!Object.prototype.hasOwnProperty.call(e,"min"))throw new Error("random.distribution.min is required");if(!Object.prototype.hasOwnProperty.call(e,"max"))throw new Error("random.distribution.max is required");let n=Zn(e.min,"random.distribution.min"),a=Zn(e.max,"random.distribution.max")-n+1;if(!Number.isSafeInteger(a)||a<1||a>4294967296)throw new Error("random integer range must contain from 1 through 4294967296 values");return go({type:"integer",value:a===1?n:n+Sh(t,a)})},Ch=(e,t)=>{if(Jt(e,new Set(["type","outcomes"]),"random.distribution"),!Array.isArray(e.outcomes)||e.outcomes.length<1||e.outcomes.length>yc)throw new Error("random.distribution.outcomes must contain from 1 through 1000 items");let n=e.outcomes.map((c,u)=>{let p=`random.distribution.outcomes[${u}]`;if(Qn(c,p),Jt(c,new Set(["weight","actions"]),p),!Object.prototype.hasOwnProperty.call(c,"weight"))throw new Error(`${p}.weight is required`);return Qn(c.actions,`${p}.actions`),{weight:Eh(c.weight,`${p}.weight`,{min:0})}}),o=Math.max(...n.map(({weight:c})=>c));if(o<=0)throw new Error("random weighted total weight must be positive");let a=n.map(c=>({...c,weight:c.weight/o})),r=a.reduce((c,u)=>c+u.weight,0);a.forEach((c,u)=>{if(n[u].weight>0&&(c.weight===0||c.weight/r<=Ph))throw new Error(`random.distribution.outcomes[${u}].weight is below the supported probability resolution`)});let s=Oh(t)*r,i=0,l=a.findLastIndex(({weight:c})=>c>0);for(let c=0;c<a.length;c+=1){let u=a[c];if(i+=u.weight,s<i){l=c;break}}return go({type:"weighted",outcomeIndex:l})},bc=(e,{randomSource:t})=>{Qn(e,"random.distribution");let o={integer:Rh,weighted:Ch}[e.type];if(!o)throw new Error('random.distribution.type must be "integer" or "weighted"');return o(e,t)},es=(e,t)=>{if(Qn(e,"random result"),e.type!==t)throw new Error("random result type does not match its recorded type");if(t==="integer")Jt(e,new Set(["type","value"]),"random result"),Zn(e.value,"random result.value");else if(t==="weighted")Jt(e,new Set(["type","outcomeIndex"]),"random result"),Zn(e.outcomeIndex,"random result.outcomeIndex",{min:0,max:yc-1});else throw new Error(`unsupported recorded random result type: ${t}`);return go(e)};var Zr=(e,t)=>Object.freeze({name:e,actions:Object.freeze(t)}),vc=Object.freeze([Zr("cleanup",["clearPendingEffects","cleanAll"]),Zr("state",["addViewedLine","addViewedResource","updateVariable","updateFormField","updateProjectData","updateLocalizationPackage","markLineCompleted","random:integer"]),Zr("decision",["submitForm","cancelForm","random:weighted","conditional"]),Zr("presentation",["screen","background","dialogue","character","visual","choice","form","sfx","bgm","voice","control","layout"]),Zr("runtime",["setNextLineConfig","startAutoMode","stopAutoMode","toggleAutoMode","startSkipMode","stopSkipMode","toggleSkipMode","showDialogueUI","hideDialogueUI","toggleDialogueUI","setDialogueTextSpeed","setAutoForwardDelay","setAutoForwardSpeed","setSkipUnseenText","setSkipTransitionsAndAnimations","setSoundVolume","setMusicVolume","setMuteAll","setSaveLoadPagination","incrementSaveLoadPagination","decrementSaveLoadPagination","setMenuPage","setMenuEntryPoint","showConfirmDialog","hideConfirmDialog","pushOverlay","popOverlay","replaceLastOverlay","clearOverlays","completeAchievement","setAchievementProgress","showImageGalleryVariant","moveToPreviousImageGalleryVariant","moveToNextImageGalleryVariant","clearImageGallerySelection","moveToImageGalleryPage","moveToNextImageGalleryPage","moveToPreviousImageGalleryPage","playMusicRoomTrack","playMusicRoom","pauseMusicRoom","stopMusicRoom","seekMusicRoom","playPreviousMusicRoomTrack","playNextMusicRoomTrack","clearMusicRoomSelection","moveToMusicRoomPage","moveToNextMusicRoomPage","moveToPreviousMusicRoomPage","finishSceneReplay","moveToSceneReplayPage","moveToNextSceneReplayPage","moveToPreviousSceneReplayPage","musicRoomSoundReady","musicRoomSoundProgress","musicRoomSoundComplete","musicRoomSoundError","appendPendingEffect","beginRollbackActionBatch","endRollbackActionBatch","ensureRandomReplayOccurrence","recordRandomOutcome","markRollbackCheckpointTransient","markSavedRollbackCheckpointTransient","recordCurrentDialogueHistory"]),Zr("persistence",["saveSlot"]),Zr("navigation",["loadSlot","rollbackByOffset","rollbackToLine","resetStoryAtSection","sectionTransition","jumpToLine","startSceneReplay","exitSceneReplay","nextLine","nextLineFromSystem"])]),bt=new Map;vc.forEach(e=>{e.actions.forEach(t=>{if(bt.has(t))throw new Error(`duplicate action execution key: ${t}`);bt.set(t,bt.size)})});var $h=new Set(vc.find(({name:e})=>e==="navigation").actions),wc=bt.get("saveSlot")-.5,Ic=(e,t)=>e!=="random"?e:t?.distribution?.type==="weighted"?"random:weighted":"random:integer",_h=(e,t)=>e<t?-1:e>t?1:0,rs=e=>Object.entries(e).sort((t,n)=>{let o=Ic(...t),a=Ic(...n),r=bt.get(o),s=bt.get(a),i=r??wc,l=s??wc;return i!==l?i-l:r!==void 0&&s!==void 0?0:_h(o,a)}),ts=e=>$h.has(e),ns=e=>{let t=e.map(([n])=>n).filter(ts);if(!(t.length<=1))throw new Error(`action batch cannot contain multiple navigation actions: ${t.join(", ")}`)};var Nh=e=>String(e).replaceAll("%","%25").replaceAll(":","%3A"),ir=(...e)=>e.map(Nh).join(":"),ss=e=>Array.isArray(e?.sounds)?e.sounds:e?.resourceId?[{id:e.resourceId,resourceId:e.resourceId,loop:e.loop??!0,volume:e.volume,startDelayMs:e.startDelayMs??0}]:[],bo=e=>!Array.isArray(e?.sounds)&&e?.startDelayMs>0,Qt=(e,t)=>bo(e)?ir("bgm","legacy-delay",t.resourceId):ir("bgm",t.id==="default"?t.resourceId:t.id),kc=({bgm:e,resources:t,previousBgmRender:n})=>{let o=ss(e).filter(c=>t.sounds?.[c.resourceId]),a=ss(n?.bgm).filter(c=>n.resources?.sounds?.[c.resourceId]).map((c,u)=>({sound:c,renderId:n.channel?.children[u]?.id})).filter(({renderId:c})=>c!==void 0),r=new Map,s=new Set,i=(c,u)=>{!u||s.has(u.renderId)||(r.set(c.id,u.renderId),s.add(u.renderId))};return bo(e)===bo(n?.bgm)&&(o.forEach(c=>i(c,a.find(u=>u.sound.id===c.id))),o.forEach(c=>{r.has(c.id)||i(c,a.find(u=>u.sound.resourceId===c.resourceId&&Qt(n.bgm,u.sound)===Qt(e,c)))})),[...o].sort((c,u)=>+(c.id==="default")-+(u.id==="default")).forEach(c=>{if(r.has(c.id))return;let u=Qt(e,c);s.has(u)&&(u=ir("bgm",c.id)),s.has(u)&&(u=ir("bgm","clip",c.id));let p=0;for(;s.has(u);)u=ir("bgm","clip",c.id,++p);r.set(c.id,u),s.add(u)}),r};var _r=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Zt=Object.freeze({volume:100,pan:0,playbackRate:1}),is=["volume","pan","playbackRate"],jh=["src","startAt","endAt","startDelayMs"],Ac=(e,t)=>{if(!e)return null;let n=e.children??[];if(n.length!==1)throw new Error(`[${t}.audioEffects] Audio effects require exactly one BGM sound on each present side.`);return n[0]},ko=(e,t)=>e?.id===t?.id&&jh.every(n=>(e?.[n]??(n==="endAt"?null:0))===(t?.[n]??(n==="endAt"?null:0))),Ec=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Th=(e,t)=>e===t||Math.abs(e-t)<=Number.EPSILON*Math.max(1,Math.abs(e),Math.abs(t)),Io=e=>Math.max(-1,Math.min(1,e)),vo=({bgm:e,resources:t,renderedSound:n,property:o})=>{let a=e?.sounds?.length===1?e.sounds[0]:e?.sounds?.find(s=>Qt(e,s)===n?.id),r=t.sounds?.[a?.resourceId];return a?.[o]??r?.[o]??Zt[o]},Dh=({property:e,value:t,relative:n,bgm:o,resources:a,renderedSound:r})=>{if(!o||!r)return t;if(e==="volume"){let s=vo({bgm:o,resources:a,renderedSound:r,property:e});return t*s/100}if(e==="pan"&&!n){let s=vo({bgm:o,resources:a,renderedSound:r,property:e});return Io(t+s)}return t},Lh=({authoredInitialValue:e,authoredKeyframes:t,baselineBgm:n,compiledKeyframes:o,bgm:a,resources:r,renderedSound:s})=>{if(!a||!s)return o;let i=vo({bgm:a,resources:r,renderedSound:s,property:"pan"}),l=e??n?.pan??Zt.pan;return o.map((c,u)=>{let p=t[u];if(p.relative!==!0)return l=p.value,c;let m=_r(p,"startValue")?l+p.startValue:l,d=m+p.value,{relative:f,...h}=c;return l=d,{...h,..._r(p,"startValue")?{startValue:Io(m+i)}:{},value:Io(d+i)}})},xc=(e,t)=>{let n=e?.playback?.speed??1;if(typeof n!="number"||!Number.isFinite(n)||n<=0)throw new Error(`[${t}.playback.speed] Audio effect speed must be a finite number greater than 0.`);return n},Mh=(e,t)=>({..._r(e,"startValue")?{startValue:e.startValue}:{},value:e.value,delay:(e.delay??0)/t,duration:e.duration/t,easing:e.easing??"linear",...e.relative===!0?{relative:!0}:{}}),Sc=({property:e,authored:t,speed:n,propertyPath:o,normalizeValue:a=({value:r})=>r})=>{let r=t.keyframes.at(-1);if(typeof r?.value!="number"||!Number.isFinite(r.value)||r.relative===!0)throw new Error(`[${o}.keyframes] The final keyframe must use an absolute finite numeric value.`);let s={keyframes:t.keyframes.map(i=>{let l=Mh(i,n),c=l.relative===!0;return l.value=a({property:e,value:l.value,relative:c}),_r(l,"startValue")&&(l.startValue=a({property:e,value:l.startValue,relative:c})),l})};return _r(t,"initialValue")&&(s.initialValue=a({property:e,value:t.initialValue,relative:!1})),s},Vh=({authored:e,bgm:t,baselineBgm:n=t,property:o,propertyPath:a,renderedSound:r,resources:s,speed:i})=>{let l=Sc({property:o,authored:e,speed:i,propertyPath:a,normalizeValue:({value:c,relative:u})=>Dh({property:o,value:c,relative:u,bgm:t,resources:s,renderedSound:r})});return o==="pan"&&(l.keyframes=Lh({authoredInitialValue:e.initialValue,authoredKeyframes:e.keyframes,baselineBgm:n,compiledKeyframes:l.keyframes,bgm:t,resources:s,renderedSound:r})),l},qh=({actionPath:e,compiled:t,property:n,propertyPath:o,renderedSound:a})=>{let r=a[n]??Zt[n],s=t.keyframes.at(-1);if(!Th(s.value,r))throw new Error(`[${e}.audioEffects]
2
+ `,r:"\r",t:" ",b:"\b",f:"\f"};if(!Z(l,i))throw Ge(t,n);a+=l[i]}return a},ic=(e,t="Computed expression var")=>{if(typeof e!="string"||e.length===0||e.trim()!==e)throw Ge(e,t);let n=[],o=0,a=()=>{let s=o;for(;o<e.length&&e[o]!=="."&&e[o]!=="["&&e[o]!=="]";)o+=1;let i=e.slice(s,o);if(i.length===0||i.trim()!==i||/\s/.test(i))throw Ge(e,t);n.push(i)},r=()=>{for(o+=1;o<e.length&&/\s/.test(e[o]);)o+=1;let s=e[o];if(/\d/.test(s??"")){let u=o;for(;o<e.length&&/\d/.test(e[o]);)o+=1;let p=e.slice(u,o);for(;o<e.length&&/\s/.test(e[o]);)o+=1;if(e[o]!=="]"||p.length>1&&p.startsWith("0"))throw Ge(e,t);o+=1,n.push(p);return}if(s!=='"'&&s!=="'")throw Ge(e,t);let i=s,l=o;o+=1;let c=!1;for(;o<e.length;){let u=e[o];if(c)c=!1;else if(u==="\\")c=!0;else if(u===i){let p=e.slice(l,o+1);for(o+=1;o<e.length&&/\s/.test(e[o]);)o+=1;if(e[o]!=="]")throw Ge(e,t);o+=1,n.push(eh(p,e,t));return}o+=1}if(c||o>=e.length)throw Ge(e,t)};for(a();o<e.length;){if(e[o]==="."){o+=1,a();continue}if(e[o]==="["){r();continue}throw Ge(e,t)}return n},no=(e,t)=>{let n=e;for(let o of t){if(n==null||!Z(n,o))return;n=n[o]}return n},oc=(e,t={})=>{if(typeof e!="string"||e.trim()==="")throw new Error("Computed expression var requires a non-empty string path");let n=ic(e),[o,a,...r]=n;if(o==="variables"){if(!a)return t.variables;let s=typeof t.resolveVariable=="function"?t.resolveVariable(a):t.variables?.[a];return no(s,r)}return o==="runtime"?no(t.runtime,n.slice(1)):no(t,n)},ac=(e,t,n)=>{if(!Array.isArray(t))throw new Error(`Computed expression operator "${e}" requires an array`);if(n!==void 0&&t.length!==n)throw new Error(`Computed expression operator "${e}" requires ${n} operand(s)`)},lo=(e,t)=>{if(!Array.isArray(t))throw new Error(`Computed expression operator "${e}" requires an array`);if(t.length===0)throw new Error(`Computed expression operator "${e}" requires at least one operand`)},rh=(e,t)=>{if(typeof t!="number"||!Number.isFinite(t))throw new Error(`Computed expression operator "${e}" requires finite numeric operands`)},er=(e,t,n,o)=>(ac(e,t,o),t.map(a=>Xn(a,n))),He=(e,t,n,o)=>{let a=er(e,t,n,o);return a.forEach(r=>rh(e,r)),a},th=(e,t,n)=>{switch(e){case"var":return oc(t,n);case"add":{let[o,a]=He(e,t,n,2);return o+a}case"sub":{let[o,a]=He(e,t,n,2);return o-a}case"mul":{let[o,a]=He(e,t,n,2);return o*a}case"div":{let[o,a]=He(e,t,n,2);return a===0?0:o/a}case"mod":{let[o,a]=He(e,t,n,2);return a===0?0:o%a}case"neg":{let[o]=He(e,t,n,1);return-o}case"round":{let[o]=He(e,t,n,1);return Math.round(o)}case"floor":{let[o]=He(e,t,n,1);return Math.floor(o)}case"ceil":{let[o]=He(e,t,n,1);return Math.ceil(o)}case"min":{let[o,a]=He(e,t,n,2);return Math.min(o,a)}case"max":{let[o,a]=He(e,t,n,2);return Math.max(o,a)}case"clamp":{let[o,a,r]=He(e,t,n,3);return Math.min(r,Math.max(a,o))}case"eq":{let[o,a]=er(e,t,n,2);return $r.eq(o,a)}case"neq":{let[o,a]=er(e,t,n,2);return $r.neq(o,a)}case"gt":{let[o,a]=er(e,t,n,2);return $r.gt(o,a)}case"gte":{let[o,a]=er(e,t,n,2);return $r.gte(o,a)}case"lt":{let[o,a]=er(e,t,n,2);return $r.lt(o,a)}case"lte":{let[o,a]=er(e,t,n,2);return $r.lte(o,a)}case"in":{let[o,a]=er(e,t,n,2);return Array.isArray(a)?a.includes(o):!1}case"and":case"all":return lo(e,t),t.every(o=>!!Xn(o,n));case"or":case"any":return lo(e,t),t.some(o=>!!Xn(o,n));case"not":{let[o]=er(e,t,n,1);return!o}case"length":{let[o]=er(e,t,n,1);return typeof o=="string"||Array.isArray(o)?o.length:Pe(o)?Object.keys(o).length:0}case"includes":{let[o,a]=er(e,t,n,2);return typeof o=="string"?typeof a=="string"&&o.includes(a):Array.isArray(o)?o.includes(a):!1}case"literal":return sc(t);default:throw new Error(`Unknown computed expression operator: ${e}`)}},Xn=(e,t={})=>{if(e===null||typeof e!="object")return e;if(Array.isArray(e))throw new Error("Computed expression arrays are not valid; use value for literal arrays");let n=Object.entries(e);if(n.length!==1)throw new Error("Computed expression objects must contain exactly one operator");let[[o,a]]=n;return th(o,a,t)},co=(e,t)=>{if(e===null||typeof e!="object"||Z(e,"literal"))return e;if(Z(e,"var"))return{literal:oc(e.var,t)};if(Z(e,"call"))throw new Error("Function calls are not supported in computed-variable conditions");return Object.fromEntries(Object.entries(e).map(([n,o])=>[n,Array.isArray(o)?o.map(a=>co(a,t)):co(o,t)]))},nh=(e,t={})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");return Le(e),Ut(co(e,t))},lc=(e,t)=>{if(!Pe(e))throw new Error(`${t} must be an object`);let n=Z(e,"expr"),o=Z(e,"value");if(n===o)throw new Error(`${t} must contain exactly one of expr or value`)},so=(e,t,n)=>(lc(e,t),Z(e,"value")?sc(e.value):Xn(e.expr,n)),sh=(e,t={},n="unknown")=>{if(!Pe(e))throw new Error(`Computed variable "${n}" computed must be an object`);let o=Z(e,"expr"),a=Z(e,"value");if(Z(e,"branches")){if(o||a)throw new Error(`Computed variable "${n}" cannot combine branches with expr or value`);if(!Array.isArray(e.branches))throw new Error(`Computed variable "${n}" branches must be an array`);if(e.branches.length===0)throw new Error(`Computed variable "${n}" branches must not be empty`);if(!Pe(e.default))throw new Error(`Computed variable "${n}" requires default`);for(let s=0;s<e.branches.length;s+=1){let i=e.branches[s];if(!Pe(i))throw new Error(`Computed variable "${n}" branch ${s} must be an object`);if(!Z(i,"when"))throw new Error(`Computed variable "${n}" branch ${s} requires when`);if(nh(i.when,t))return so(i,`Computed variable "${n}" branch ${s}`,t)}return so(e.default,`Computed variable "${n}" default`,t)}if(o===a)throw new Error(`Computed variable "${n}" must contain exactly one of expr, value, or branches`);return so(e,`Computed variable "${n}"`,t)},cc=(e,t,n)=>{switch(t){case"number":if(typeof n!="number"||!Number.isFinite(n))throw new Error(`Computed variable "${e}" expected type number, got ${Array.isArray(n)?"array":typeof n}`);return;case"boolean":if(typeof n!="boolean")throw new Error(`Computed variable "${e}" expected type boolean, got ${Array.isArray(n)?"array":typeof n}`);return;case"string":if(typeof n!="string")throw new Error(`Computed variable "${e}" expected type string, got ${Array.isArray(n)?"array":typeof n}`);return;case"object":if(n===null||typeof n!="object")throw new Error(`Computed variable "${e}" expected type object, got ${typeof n}`);return;default:throw new Error(`Invalid variable type: ${t} for computed variable ${e}`)}},ih=Object.freeze({add:2,sub:2,mul:2,div:2,mod:2,neg:1,round:1,floor:1,ceil:1,min:2,max:2,clamp:3,eq:2,neq:2,gt:2,gte:2,lt:2,lte:2,in:2,not:1,length:1,includes:2}),oh=new Set(["and","or","all","any"]),ah=new Set(["add","sub","mul","div","mod","neg","round","floor","ceil","min","max","clamp","length"]),lh=new Set(["add","sub","mul","div","mod","neg","round","floor","ceil","min","max","clamp"]),ch=new Set(["eq","neq","gt","gte","lt","lte","in","and","or","all","any","not","includes"]),uh=new Set(["all","any","eq","neq","gt","gte","lt","lte","in","add","sub"]),uc=new WeakMap,Wl=e=>e===null?"null":Array.isArray(e)?"object":typeof e,Yn=(e,t,n)=>{for(let o of Object.keys(e))if(!t.has(o))throw new Error(`${n} contains unsupported property "${o}"`)},ph=(e,t,n,o)=>{if(n!==void 0&&n!==t)throw new Error(`Computed variable "${e}" ${o} expected type ${t}, got ${n}`)},pc=(e,{variableId:t,variableConfigs:n,dependencies:o,path:a})=>{let r=`Computed variable "${t}" ${a} var`,[s,i,...l]=ic(e,r);if(s!=="variables"&&s!=="runtime")throw new Error(`${r} must reference variables.* or runtime.*, got ${JSON.stringify(e)}`);if(!i)throw new Error(`${r} must reference a concrete ${s} member, got ${JSON.stringify(e)}`);if(s==="runtime")return;if(!Z(n,i))throw new Error(`Computed variable "${t}" ${a} references unknown variable "${i}"`);let c=n[i];return $e(c)&&o.add(i),l.length===0?c?.type:void 0},fc=(e,{variableId:t,variableConfigs:n,dependencies:o,path:a})=>{if(e===null||typeof e!="object"){if(typeof e=="number"&&!Number.isFinite(e))throw new Error(`Computed variable "${t}" ${a} must use finite numeric literals`);return Wl(e)}if(Array.isArray(e))throw new Error("Computed expression arrays are not valid; use value for literal arrays");let r=Object.entries(e);if(r.length!==1)throw new Error("Computed expression objects must contain exactly one operator");let[[s,i]]=r;if(s==="var"){if(typeof i!="string"||i.trim()==="")throw new Error("Computed expression var requires a non-empty string path");return pc(i,{variableId:t,variableConfigs:n,dependencies:o,path:a})}if(s==="literal"){if(typeof i=="number"&&!Number.isFinite(i))throw new Error(`Computed variable "${t}" ${a} must use finite numeric literals`);return Wl(i)}let l=ih[s];if(l===void 0&&!oh.has(s))throw new Error(`Unknown computed expression operator: ${s}`);l===void 0?lo(s,i):ac(s,i,l);let c=i.map((u,p)=>fc(u,{variableId:t,variableConfigs:n,dependencies:o,path:`${a}.${s}[${p}]`}));if(lh.has(s)&&c.forEach(u=>{if(u!==void 0&&u!=="number")throw new Error(`Computed expression operator "${s}" requires numeric operands`)}),ah.has(s))return"number";if(ch.has(s))return"boolean"},fh=(e,{variableId:t,variableConfigs:n,dependencies:o,path:a})=>{if(typeof e=="string")throw new Error("String condition expressions are not supported; use semantic JSON conditions");try{Le(e)}catch(s){throw new Error(`Computed variable "${t}" ${a} is invalid: ${s.message}`,{cause:s})}let r=(s,i)=>{if(s===null||typeof s!="object"||Z(s,"literal"))return;if(Z(s,"var")){pc(s.var,{variableId:t,variableConfigs:n,dependencies:o,path:i});return}if(Z(s,"call"))throw new Error(`Computed variable "${t}" ${i} function calls are not supported`);if(Z(s,"not")){r(s.not,`${i}.not`);return}let l=Object.keys(s).find(c=>uh.has(c));s[l].forEach((c,u)=>{r(c,`${i}.${l}[${u}]`)})};r(e,a)},io=(e,{variableId:t,variableConfig:n,variableConfigs:o,dependencies:a,path:r,allowedKeys:s=new Set(["expr","value"])})=>{if(lc(e,`Computed variable "${t}" ${r}`),Yn(e,s,r),Z(e,"value")){cc(t,n.type,e.value);return}let i=fc(e.expr,{variableId:t,variableConfigs:o,dependencies:a,path:`${r}.expr`});ph(t,n.type,i,`${r}.expr`)},dh=(e,t,n)=>{let o=t.computed;if(!Pe(o))throw new Error(`Computed variable "${e}" computed must be an object`);let a=new Set,r=Z(o,"expr"),s=Z(o,"value");if(Z(o,"branches")){if(Yn(o,new Set(["branches","default"]),`Computed variable "${e}" computed`),r||s)throw new Error(`Computed variable "${e}" cannot combine branches with expr or value`);if(!Array.isArray(o.branches))throw new Error(`Computed variable "${e}" branches must be an array`);if(o.branches.length===0)throw new Error(`Computed variable "${e}" branches must not be empty`);if(!Pe(o.default))throw new Error(`Computed variable "${e}" requires default`);return o.branches.forEach((l,c)=>{if(!Pe(l))throw new Error(`Computed variable "${e}" branch ${c} must be an object`);if(Yn(l,new Set(["when","expr","value"]),`Computed variable "${e}" branch ${c}`),!Z(l,"when"))throw new Error(`Computed variable "${e}" branch ${c} requires when`);fh(l.when,{variableId:e,variableConfigs:n,dependencies:a,path:`computed.branches[${c}].when`}),io(l,{variableId:e,variableConfig:t,variableConfigs:n,dependencies:a,path:`computed.branches[${c}]`,allowedKeys:new Set(["when","expr","value"])})}),io(o.default,{variableId:e,variableConfig:t,variableConfigs:n,dependencies:a,path:"computed.default"}),a}if(Yn(o,new Set(["expr","value"]),`Computed variable "${e}" computed`),r===s)throw new Error(`Computed variable "${e}" must contain exactly one of expr, value, or branches`);return io(o,{variableId:e,variableConfig:t,variableConfigs:n,dependencies:a,path:"computed"}),a},Qr=(e={})=>{if(!Pe(e))throw new Error("Variable configs must be an object");if(Z(e,"__proto__"))throw new Error('Variable id "__proto__" is reserved');if(Z(e,""))throw new Error("Variable ids must not be empty");let t=new Map;Object.entries(e).forEach(([r,s])=>{if($e(s)){if(!Pe(s))throw new Error(`Computed variable "${r}" must be an object`);if(!Z(s,"type"))throw new Error(`Computed variable "${r}" requires type`);if(!Z(s,"scope"))throw new Error(`Computed variable "${r}" requires scope`);if(Z(s,"default"))throw new Error(`Computed variable "${r}" must not declare a top-level default`);if(Gt(s.scope,r),!["number","boolean","string","object"].includes(s.type))throw new Error(`Invalid variable type: ${s.type} for computed variable ${r}`);t.set(r,dh(r,s,e))}});let n=new Set,o=[];t.forEach((r,s)=>{if(n.has(s))return;let i=[{variableId:s,dependencies:[...t.get(s)??[]],nextDependencyIndex:0}],l=new Map([[s,0]]);for(;i.length>0;){let c=i.at(-1);if(c.nextDependencyIndex>=c.dependencies.length){i.pop(),l.delete(c.variableId),n.add(c.variableId),o.push(c.variableId);continue}let u=c.dependencies[c.nextDependencyIndex];if(c.nextDependencyIndex+=1,n.has(u))continue;let p=l.get(u);if(p!==void 0){let m=[...i.slice(p).map(({variableId:d})=>d),u].join(" -> ");throw new Error(`Computed variable cycle detected: ${m}`)}l.set(u,i.length),i.push({variableId:u,dependencies:[...t.get(u)??[]],nextDependencyIndex:0})}});let a=Object.freeze({evaluationOrder:Object.freeze(o)});return uc.set(e,a),a},gt=({variables:e={},runtime:t={},variableConfigs:n={},eager:o=!0}={})=>{let{evaluationOrder:a}=uc.get(n)??Qr(n),r=Ht(e,n,{preserveUnknown:!0}),s=Object.entries(n).filter(([,g])=>$e(g)).map(([g])=>g),i=Object.create(null),l=[],c=new Map(a.map((g,y)=>[g,y])),u=-1,p=!1,m=g=>{if(Z(i,g))return i[g];let y=n[g];if(!$e(y))return Z(r,g)?r[g]:void 0;let w=l.indexOf(g);if(w>=0){let b=[...l.slice(w),g].join(" -> ");throw new Error(`Computed variable cycle detected: ${b}`)}l.push(g);try{let b=sh(y.computed,h,g);return cc(g,y.type,b),ao(i,g,b),b}finally{l.pop()}},d=g=>{if(Z(i,g))return i[g];let y=n[g];if(!$e(y))return Z(r,g)?r[g]:void 0;let w=c.get(g);if(o&&!p&&w!==void 0&&w>u){p=!0;try{for(let b=u+1;b<=w;b+=1)m(a[b]),u=b}finally{p=!1}return i[g]}return m(g)},f=new Proxy({},{get:(g,y)=>{if(typeof y=="string")return d(y)},has:(g,y)=>typeof y=="string"&&(Z(r,y)||s.includes(y)),ownKeys:()=>[...new Set([...Object.keys(r),...s])],getOwnPropertyDescriptor:(g,y)=>{if(!(typeof y!="string"||!Z(r,y)&&!s.includes(y)))return{enumerable:!0,configurable:!0}}}),h={variables:f,runtime:t,resolveVariable:d};return o?(s.forEach(g=>{d(g)}),{...r,...i}):f},mh=({variables:e={},runtime:t={},variableConfigs:n,projectData:o}={})=>{let a=n??o?.resources?.variables??{};return Qr(a),gt({variables:e,runtime:t,variableConfigs:a,eager:!0})},Kn=e=>{let t={},n={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([o,a])=>{if($e(a))return;let r=Yy(a,o);a.scope==="context"?ao(t,o,r):ao(n,o,r)}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}},Gt=(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(", ")}`)},Kt=(e,t,n)=>{let o={number:["set","increment","decrement","multiply","divide"],boolean:["set","toggle"],string:["set"],object:["set"]},a=o[e];if(!a)throw new Error(`Unknown variable type: ${e} for variable ${n}`);if(!Object.values(o).flat().includes(t))throw new Error(`Unknown operation: ${t}`);if(!a.includes(t))throw new Error(`Operation "${t}" is not valid for variable "${n}" of type "${e}". Valid operations: ${a.join(", ")}`)},yh=2,Jl=12,dc=(e=yh)=>{if(!Number.isInteger(e)||e<0||e>Jl)throw new Error(`Operation "divide" requires roundTo to be an integer between 0 and ${Jl}.`);return e},hh=(e,t)=>{let n=10**t;return Math.round((e+Number.EPSILON)*n)/n},zn=e=>typeof e=="number"&&Number.isFinite(e),Wn=(e,t,n,o,a={})=>{if(e==="number"){if(t==="set"&&!zn(n))throw new Error(`Operation "set" requires value to be a number for variable "${o}".`);if(t==="multiply"&&!zn(n))throw new Error(`Operation "multiply" requires value to be a number for variable "${o}".`);if(t==="divide"&&!zn(n))throw new Error(`Operation "divide" requires value to be a number for variable "${o}".`);if(t==="divide"){if(n===0)throw new Error(`Operation "divide" requires value to be a non-zero number for variable "${o}".`);dc(a.roundTo)}}},Jn=(e,t,n,o={})=>{let a=(s,i,l)=>{let c=s??i;if(!zn(c))throw new Error(`Operation "${t}" requires ${l} to be a number.`);return c},r=s=>{let i=a(s,void 0,"value");if(i===0)throw new Error(`Operation "${t}" requires value to be a non-zero number.`);return i};switch(t){case"set":return n;case"multiply":return a(e,1,"current value")*a(n,void 0,"value");case"divide":return hh(a(e,0,"current value")/r(n),dc(o.roundTo));case"increment":return a(e,0,"current value")+a(n,1,"value");case"decrement":return a(e,0,"current value")-a(n,1,"value");case"toggle":return!e;default:throw new Error(`Unknown operation: ${t}`)}};var mo=(e,t="DD/MM/YYYY - HH:mm")=>{if(!e)return"";let n=new Date(e),o=s=>String(s).padStart(2,"0"),a=String(n.getFullYear()),r={DD:o(n.getDate()),MM:o(n.getMonth()+1),MMM:Uy[n.getMonth()],YYYY:a,YY:a.slice(-2),HH:o(n.getHours()),mm:o(n.getMinutes()),ss:o(n.getSeconds())};return t.replace(/YYYY|MMM|YY|MM|DD|HH|mm|ss/g,s=>r[s])},gh=(e,t)=>{let n=r=>r?.ui,o=n(e),a=n(t);return JSON.stringify(o)===JSON.stringify(a)?null:o&&!a?{changeType:"delete",data:e}:a&&!o?{changeType:"add",data:t}:a&&o?{changeType:"update",data:t}:null},Bt=e=>!!e?.transformId&&Array.isArray(e.items)&&e.items.length>0,bh=(e,t)=>{let n=e?.character?.sprite,o=t?.character?.sprite,a=Bt(n)?n:void 0,r=Bt(o)?o:void 0;return JSON.stringify(a)===JSON.stringify(r)?null:a&&!r?{changeType:"delete",data:a}:r&&!a?{changeType:"add",data:r}:r&&a?{changeType:"update",data:r}:null},Ql=e=>{if(e?.resourceId===void 0)return;let t={resourceId:e.resourceId};e.transformId!==void 0&&(t.transformId=e.transformId);for(let n of["x","y","anchorX","anchorY","scaleX","scaleY","flipX","flipY","rotation","originX","originY"])e[n]!==void 0&&(t[n]=e[n]);for(let n of["animationName","animationSpeed","loop"])e[n]!==void 0&&(t[n]=e[n]);return t},Zl=e=>{if(e?.colorId!==void 0)return{colorId:e.colorId}},ec=(e,t)=>t&&!e?{changeType:"add",data:t}:e&&!t?{changeType:"delete",data:e}:e&&t&&JSON.stringify(e)!==JSON.stringify(t)?{changeType:"update",data:t}:null,wh=(e,t)=>{let n={},o=ec(Ql(e),Ql(t)),a=ec(Zl(e),Zl(t));return o&&(n.resource=o),a&&(n.color=a),Object.keys(n).length>0?n:null},yo=(e={},t={})=>{let n={},o=["voice"],a=l=>{let c=e[l],u=t[l];if(u&&!c)n[l]={changeType:"add",data:u};else if(c&&!u){let p=l==="sfx"&&c.channels?.some(m=>m.applyMode==="persistent");!o.includes(l)&&(l!=="sfx"||p)&&(n[l]={changeType:"delete",data:c})}else c&&u&&JSON.stringify(c)!==JSON.stringify(u)&&(n[l]={changeType:"update",data:u})},r=wh(e.background,t.background);r&&(n.background=r),a("screen"),a("bgm"),a("voice");let s=gh(e.dialogue,t.dialogue);s&&(n.dialogue=s);let i=bh(e.dialogue,t.dialogue);return i&&(n.dialogueSprite=i),a("choice"),a("form"),a("layout"),a("animation"),a("control"),a("character"),a("visual"),a("sfx"),n},ho=(e={})=>{let t=structuredClone(e);if(t.sfx){let a=Array.isArray(t.sfx.channels)?t.sfx.channels.filter(r=>r.applyMode==="persistent"):[];a.length>0?t.sfx={channels:a}:delete t.sfx}t.background&&(t.background.animations?.playback?.continuity!=="persistent"&&delete t.background.animations,!t.background.resourceId&&!t.background.colorId&&delete t.background);let n=a=>{t[a]&&(delete t[a].animations,Object.keys(t[a]).length===0&&delete t[a])};n("layout"),n("choice"),n("form"),n("screen"),t.dialogue?.ui&&(delete t.dialogue.ui.animations,Object.keys(t.dialogue.ui).length===0&&delete t.dialogue.ui,Object.keys(t.dialogue).length===0&&delete t.dialogue),t.dialogue?.character?.sprite&&(delete t.dialogue.character.sprite.animations,Object.keys(t.dialogue.character.sprite).length===0&&delete t.dialogue.character.sprite,Object.keys(t.dialogue.character).length===0&&delete t.dialogue.character,Object.keys(t.dialogue).length===0&&delete t.dialogue);let o=(a,r)=>{let s=t[a]?.items;Array.isArray(s)&&(t[a].items=s.map(i=>{let l={...i};return l.animations?.playback?.continuity!=="persistent"&&delete l.animations,r(l)?l:null}).filter(Boolean),t[a].items.length===0&&delete t[a])};return o("character",a=>a.sprites&&a.sprites.length>0||a.transformId||a.resourceId),o("visual",a=>a.resourceId||a.text||a.layout||a.transformId||a.transform),t},Ih=(e,t)=>{if(!e||!t)return;let n=e;for(let o of t.split(".")){if(n==null||o==="__proto__"||o==="prototype"||o==="constructor"||!Object.prototype.hasOwnProperty.call(Object(n),o))return;n=n[o]}return n},rc=e=>e!==null&&typeof e=="object"?structuredClone(e):e,vh=(e,t,n)=>{if(typeof e!="string")return e;let o=Object.prototype.hasOwnProperty.call(t??{},n)?t[n]:void 0;if(e===n){if(o==null)throw new Error(`Action template binding "${n}" requires event context "${n}".`);return rc(o)}if(!e.startsWith(`${n}.`))return e;if(o==null)throw new Error(`Action template binding "${e}" requires event context "${n}".`);let a=e.slice(n.length+1),r=Ih(o,a);if(r===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "${n}".`);return rc(r)},kh={conditional:new Set(["branches"]),updateProjectData:new Set(["projectData"]),showConfirmDialog:new Set(["confirmActions","cancelActions"]),form:new Set(["submitActions","cancelActions"]),submitForm:new Set(["actions"]),cancelForm:new Set(["actions"])},Ah=(e,t)=>{let n=e[e.length-1];return n?kh[n]?.has(t)===!0:!1},uo=(e,t,n=[])=>Array.isArray(e)?e.map(o=>uo(o,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([o,a])=>[o,Ah(n,o)?a:uo(a,t,[...n,o])])):typeof e=="string"?e==="_event"||e.startsWith("_event.")?vh(e,t,"_event"):Wr(e,t):e,Wt=(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".');return uo(e,t)};var Ph=11102230246251565e-32,mc=128,yc=1e3,hc=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Jt=(e,t,n)=>{let o=Object.keys(e).find(a=>!t.has(a));if(o!==void 0)throw new Error(`${n}.${o} is not supported`)},Qn=(e,t)=>{if(!hc(e))throw new Error(`${t} must be an object`)},Zn=(e,t,{min:n,max:o}={})=>{if(!Number.isSafeInteger(e))throw new Error(`${t} must be a safe integer`);if(n!==void 0&&e<n)throw new Error(`${t} must be at least ${n}`);if(o!==void 0&&e>o)throw new Error(`${t} must be at most ${o}`);return e},Eh=(e,t,{min:n,max:o}={})=>{if(typeof e!="number"||!Number.isFinite(e))throw new Error(`${t} must be a finite number`);if(n!==void 0&&e<n)throw new Error(`${t} must be at least ${n}`);if(o!==void 0&&e>o)throw new Error(`${t} must be at most ${o}`);return e},go=e=>{let t=structuredClone(e),n=o=>(o&&typeof o=="object"&&!Object.isFrozen(o)&&(Object.values(o).forEach(n),Object.freeze(o)),o);return n(t)},xh=()=>({nextUint32(){return typeof globalThis.crypto?.getRandomValues=="function"?globalThis.crypto.getRandomValues(new Uint32Array(1))[0]:Math.floor(Math.random()*4294967296)}}),gc=e=>{let t=e??xh();if(!hc(t)||typeof t.nextUint32!="function")throw new TypeError("randomSource must provide nextUint32()");return{nextUint32(){let n=t.nextUint32();if(!Number.isInteger(n)||n<0||n>=4294967296)throw new Error("randomSource.nextUint32() must return an integer from 0 through 4294967295");return n}}},Sh=(e,t)=>{let n=4294967296-4294967296%t;for(let o=0;o<mc;o+=1){let a=e.nextUint32();if(a<n)return a%t}throw new Error(`random source exhausted after ${mc} rejected samples`)},Oh=e=>{let t=e.nextUint32()>>>5,n=e.nextUint32()>>>6;return(t*67108864+n)/9007199254740992},Rh=(e,t)=>{if(Jt(e,new Set(["type","min","max"]),"random.distribution"),!Object.prototype.hasOwnProperty.call(e,"min"))throw new Error("random.distribution.min is required");if(!Object.prototype.hasOwnProperty.call(e,"max"))throw new Error("random.distribution.max is required");let n=Zn(e.min,"random.distribution.min"),a=Zn(e.max,"random.distribution.max")-n+1;if(!Number.isSafeInteger(a)||a<1||a>4294967296)throw new Error("random integer range must contain from 1 through 4294967296 values");return go({type:"integer",value:a===1?n:n+Sh(t,a)})},Ch=(e,t)=>{if(Jt(e,new Set(["type","outcomes"]),"random.distribution"),!Array.isArray(e.outcomes)||e.outcomes.length<1||e.outcomes.length>yc)throw new Error("random.distribution.outcomes must contain from 1 through 1000 items");let n=e.outcomes.map((c,u)=>{let p=`random.distribution.outcomes[${u}]`;if(Qn(c,p),Jt(c,new Set(["weight","actions"]),p),!Object.prototype.hasOwnProperty.call(c,"weight"))throw new Error(`${p}.weight is required`);return Qn(c.actions,`${p}.actions`),{weight:Eh(c.weight,`${p}.weight`,{min:0})}}),o=Math.max(...n.map(({weight:c})=>c));if(o<=0)throw new Error("random weighted total weight must be positive");let a=n.map(c=>({...c,weight:c.weight/o})),r=a.reduce((c,u)=>c+u.weight,0);a.forEach((c,u)=>{if(n[u].weight>0&&(c.weight===0||c.weight/r<=Ph))throw new Error(`random.distribution.outcomes[${u}].weight is below the supported probability resolution`)});let s=Oh(t)*r,i=0,l=a.findLastIndex(({weight:c})=>c>0);for(let c=0;c<a.length;c+=1){let u=a[c];if(i+=u.weight,s<i){l=c;break}}return go({type:"weighted",outcomeIndex:l})},bc=(e,{randomSource:t})=>{Qn(e,"random.distribution");let o={integer:Rh,weighted:Ch}[e.type];if(!o)throw new Error('random.distribution.type must be "integer" or "weighted"');return o(e,t)},es=(e,t)=>{if(Qn(e,"random result"),e.type!==t)throw new Error("random result type does not match its recorded type");if(t==="integer")Jt(e,new Set(["type","value"]),"random result"),Zn(e.value,"random result.value");else if(t==="weighted")Jt(e,new Set(["type","outcomeIndex"]),"random result"),Zn(e.outcomeIndex,"random result.outcomeIndex",{min:0,max:yc-1});else throw new Error(`unsupported recorded random result type: ${t}`);return go(e)};var Zr=(e,t)=>Object.freeze({name:e,actions:Object.freeze(t)}),vc=Object.freeze([Zr("cleanup",["clearPendingEffects","cleanAll"]),Zr("state",["addViewedLine","addViewedResource","updateVariable","updateFormField","updateProjectData","updateLocalizationPackage","markLineCompleted","random:integer"]),Zr("decision",["submitForm","cancelForm","random:weighted","conditional"]),Zr("presentation",["screen","background","dialogue","character","visual","choice","form","sfx","bgm","voice","control","layout"]),Zr("runtime",["setNextLineConfig","startAutoMode","stopAutoMode","toggleAutoMode","startSkipMode","stopSkipMode","toggleSkipMode","showDialogueUI","hideDialogueUI","toggleDialogueUI","setDialogueTextSpeed","setAutoForwardDelay","setAutoForwardSpeed","setSkipUnseenText","setSkipTransitionsAndAnimations","setSoundVolume","setMusicVolume","setMuteAll","setSaveLoadPagination","incrementSaveLoadPagination","decrementSaveLoadPagination","setMenuPage","setMenuEntryPoint","showConfirmDialog","hideConfirmDialog","pushOverlay","popOverlay","replaceLastOverlay","clearOverlays","completeAchievement","setAchievementProgress","showImageGalleryVariant","moveToPreviousImageGalleryVariant","moveToNextImageGalleryVariant","clearImageGallerySelection","moveToImageGalleryPage","moveToNextImageGalleryPage","moveToPreviousImageGalleryPage","playMusicRoomTrack","playMusicRoom","pauseMusicRoom","stopMusicRoom","seekMusicRoom","playPreviousMusicRoomTrack","playNextMusicRoomTrack","clearMusicRoomSelection","moveToMusicRoomPage","moveToNextMusicRoomPage","moveToPreviousMusicRoomPage","finishSceneReplay","moveToSceneReplayPage","moveToNextSceneReplayPage","moveToPreviousSceneReplayPage","musicRoomSoundReady","musicRoomSoundProgress","musicRoomSoundComplete","musicRoomSoundError","appendPendingEffect","beginRollbackActionBatch","endRollbackActionBatch","ensureRandomReplayOccurrence","recordRandomOutcome","markRollbackCheckpointTransient","markSavedRollbackCheckpointTransient","recordCurrentDialogueHistory"]),Zr("persistence",["saveSlot"]),Zr("navigation",["loadSlot","rollbackByOffset","rollbackToLine","resetStoryAtSection","sectionTransition","jumpToLine","startSceneReplay","exitSceneReplay","nextLine","nextLineFromSystem"])]),bt=new Map;vc.forEach(e=>{e.actions.forEach(t=>{if(bt.has(t))throw new Error(`duplicate action execution key: ${t}`);bt.set(t,bt.size)})});var $h=new Set(vc.find(({name:e})=>e==="navigation").actions),wc=bt.get("saveSlot")-.5,Ic=(e,t)=>e!=="random"?e:t?.distribution?.type==="weighted"?"random:weighted":"random:integer",_h=(e,t)=>e<t?-1:e>t?1:0,rs=e=>Object.entries(e).sort((t,n)=>{let o=Ic(...t),a=Ic(...n),r=bt.get(o),s=bt.get(a),i=r??wc,l=s??wc;return i!==l?i-l:r!==void 0&&s!==void 0?0:_h(o,a)}),ts=e=>$h.has(e),ns=e=>{let t=e.map(([n])=>n).filter(ts);if(!(t.length<=1))throw new Error(`action batch cannot contain multiple navigation actions: ${t.join(", ")}`)};var Nh=e=>String(e).replaceAll("%","%25").replaceAll(":","%3A"),ir=(...e)=>e.map(Nh).join(":"),ss=e=>Array.isArray(e?.sounds)?e.sounds:e?.resourceId?[{id:e.resourceId,resourceId:e.resourceId,loop:e.loop??!0,volume:e.volume,startDelayMs:e.startDelayMs??0}]:[],bo=e=>!Array.isArray(e?.sounds)&&e?.startDelayMs>0,Qt=(e,t)=>bo(e)?ir("bgm","legacy-delay",t.resourceId):ir("bgm",t.id==="default"?t.resourceId:t.id),kc=({bgm:e,resources:t,previousBgmRender:n})=>{let o=ss(e).filter(c=>t.sounds?.[c.resourceId]),a=ss(n?.bgm).filter(c=>n.resources?.sounds?.[c.resourceId]).map((c,u)=>({sound:c,renderId:n.channel?.children[u]?.id})).filter(({renderId:c})=>c!==void 0),r=new Map,s=new Set,i=(c,u)=>{!u||s.has(u.renderId)||(r.set(c.id,u.renderId),s.add(u.renderId))};return bo(e)===bo(n?.bgm)&&(o.forEach(c=>i(c,a.find(u=>u.sound.id===c.id))),o.forEach(c=>{r.has(c.id)||i(c,a.find(u=>u.sound.resourceId===c.resourceId&&Qt(n.bgm,u.sound)===Qt(e,c)))})),[...o].sort((c,u)=>+(c.id==="default")-+(u.id==="default")).forEach(c=>{if(r.has(c.id))return;let u=Qt(e,c);s.has(u)&&(u=ir("bgm",c.id)),s.has(u)&&(u=ir("bgm","clip",c.id));let p=0;for(;s.has(u);)u=ir("bgm","clip",c.id,++p);r.set(c.id,u),s.add(u)}),r};var _r=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Zt=Object.freeze({volume:100,pan:0,playbackRate:1}),is=["volume","pan","playbackRate"],jh=["src","startAt","endAt","startDelayMs"],Ac=(e,t)=>{if(!e)return null;let n=e.children??[];if(n.length!==1)throw new Error(`[${t}.audioEffects] Audio effects require exactly one BGM sound on each present side.`);return n[0]},ko=(e,t)=>e?.id===t?.id&&jh.every(n=>(e?.[n]??(n==="endAt"?null:0))===(t?.[n]??(n==="endAt"?null:0))),Ec=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Th=(e,t)=>e===t||Math.abs(e-t)<=Number.EPSILON*Math.max(1,Math.abs(e),Math.abs(t)),Io=e=>Math.max(-1,Math.min(1,e)),vo=({bgm:e,resources:t,renderedSound:n,property:o})=>{let a=e?.sounds?.length===1?e.sounds[0]:e?.sounds?.find(s=>Qt(e,s)===n?.id),r=t.sounds?.[a?.resourceId];return a?.[o]??r?.[o]??Zt[o]},Dh=({property:e,value:t,relative:n,bgm:o,resources:a,renderedSound:r})=>{if(!o||!r)return t;if(e==="volume"){let s=vo({bgm:o,resources:a,renderedSound:r,property:e});return t*s/100}if(e==="pan"&&!n){let s=vo({bgm:o,resources:a,renderedSound:r,property:e});return Io(t+s)}return t},Lh=({authoredInitialValue:e,authoredKeyframes:t,baselineBgm:n,compiledKeyframes:o,bgm:a,resources:r,renderedSound:s})=>{if(!a||!s)return o;let i=vo({bgm:a,resources:r,renderedSound:s,property:"pan"}),l=e??n?.pan??Zt.pan;return o.map((c,u)=>{let p=t[u];if(p.relative!==!0)return l=p.value,c;let m=_r(p,"startValue")?l+p.startValue:l,d=m+p.value,{relative:f,...h}=c;return l=d,{...h,..._r(p,"startValue")?{startValue:Io(m+i)}:{},value:Io(d+i)}})},xc=(e,t)=>{let n=e?.playback?.speed??1;if(typeof n!="number"||!Number.isFinite(n)||n<=0)throw new Error(`[${t}.playback.speed] Audio effect speed must be a finite number greater than 0.`);return n},Mh=(e,t)=>({..._r(e,"startValue")?{startValue:e.startValue}:{},value:e.value,delay:(e.delay??0)/t,duration:e.duration/t,easing:e.easing??"linear",...e.relative===!0?{relative:!0}:{}}),Sc=({property:e,authored:t,speed:n,propertyPath:o,normalizeValue:a=({value:r})=>r})=>{let r=t.keyframes.at(-1);if(typeof r?.value!="number"||!Number.isFinite(r.value)||r.relative===!0)throw new Error(`[${o}.keyframes] The final keyframe must use an absolute finite numeric value.`);let s={keyframes:t.keyframes.map(i=>{let l=Mh(i,n),c=l.relative===!0;return l.value=a({property:e,value:l.value,relative:c}),_r(l,"startValue")&&(l.startValue=a({property:e,value:l.startValue,relative:c})),l})};return _r(t,"initialValue")&&(s.initialValue=a({property:e,value:t.initialValue,relative:!1})),s},Vh=({authored:e,bgm:t,baselineBgm:n=t,property:o,propertyPath:a,renderedSound:r,resources:s,speed:i})=>{let l=Sc({property:o,authored:e,speed:i,propertyPath:a,normalizeValue:({value:c,relative:u})=>Dh({property:o,value:c,relative:u,bgm:t,resources:s,renderedSound:r})});return o==="pan"&&(l.keyframes=Lh({authoredInitialValue:e.initialValue,authoredKeyframes:e.keyframes,baselineBgm:n,compiledKeyframes:l.keyframes,bgm:t,resources:s,renderedSound:r})),l},qh=({actionPath:e,compiled:t,property:n,propertyPath:o,renderedSound:a})=>{let r=a[n]??Zt[n],s=t.keyframes.at(-1);if(!Th(s.value,r))throw new Error(`[${e}.audioEffects]
3
3
  [${o}.keyframes] The final keyframe value must match the persistent BGM ${n} value.`);s.value=r},Oc=({selection:e,selectionPath:t,resources:n={}})=>{if(!e)return;let o=e.resourceId,a=`resources.audioEffects.${o}`,r=n.audioEffects?.[o];if(!r)throw new Error(`[${t}.resourceId]
4
4
  [${a}] Unknown audio effect resource "${o}".`);if(r.type!=="update")throw new Error(`[${t}]
5
5
  [${a}] Sound beginEffect and endEffect selections require an audio effect resource with type "update".`);let s=xc(e,t),i={};for(let l of is)_r(r.tween,l)&&(i[l]=Sc({property:l,authored:r.tween[l],speed:s,propertyPath:`${a}.tween.${l}`}));return i},Rc=({bgm:e,resources:t={}})=>{let n=e?.audioEffects?.resourceId,o=t.audioEffects?.[n],a=o?.type==="update"?o.tween:o?.type==="transition"?o.next:void 0;if(!a||(e.sounds??[]).length===0)return e;let s=structuredClone(e);for(let i of is){if(!_r(a,i))continue;let l=a[i].keyframes.at(-1);typeof l?.value!="number"||!Number.isFinite(l.value)||l.relative===!0||(i==="volume"?s.volume=l.value:i==="pan"?s.pan=l.value:s.sounds.forEach(c=>{c.playbackRate=l.value}))}return s},Fh=(e,t)=>({id:`audio-effect:${e.occurrenceId}`,type:"audio-transition",targetId:t}),Pc=e=>{if(!e)return e;let t={...e};return delete t.beginEffect,delete t.endEffect,t},wo=({phase:e,side:t,baselineBgm:n,authored:o,property:a,propertyPath:r,actionPath:s,speed:i})=>{let l=Vh({authored:o,bgm:t.bgm,baselineBgm:n,property:a,propertyPath:r,renderedSound:t.sound,resources:t.resources,speed:i});return e!=="exit"&&qh({actionPath:s,compiled:l,property:a,propertyPath:r,renderedSound:t.sound}),l},Bh=(e,t)=>t?!e||!ko(e,t)?"enter":"update":"exit",Uh=({occurrence:e,resources:t={},previousResources:n=t,nextResources:o=t,previousChannel:a,nextChannel:r,previousBgm:s,nextBgm:i})=>{if(!e?.selection)return null;let l=e.selection,c=e.actionPath??"bgm",u=l.resourceId,p=`resources.audioEffects.${u}`,m=t.audioEffects?.[u];if(!m)throw new Error(`[${c}.audioEffects.resourceId]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "route-engine-js",
3
- "version": "1.46.6",
3
+ "version": "1.47.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",