narraleaf-react 0.9.0 → 0.9.1

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.
Files changed (41) hide show
  1. package/LICENSE +373 -373
  2. package/README.md +165 -147
  3. package/dist/built-in.d.ts +3 -0
  4. package/dist/built-in.js +1 -0
  5. package/dist/game/nlcore/action/action.d.ts +9 -5
  6. package/dist/game/nlcore/action/actionTypes.d.ts +10 -10
  7. package/dist/game/nlcore/action/actions/menuAction.d.ts +1 -4
  8. package/dist/game/nlcore/action/logicAction.d.ts +29 -29
  9. package/dist/game/nlcore/common/elements.d.ts +4 -2
  10. package/dist/game/nlcore/common/transition.d.ts +2 -1
  11. package/dist/game/nlcore/elements/built-in/DevTools.d.ts +2 -0
  12. package/dist/game/nlcore/elements/built-in/built-in.d.ts +2 -0
  13. package/dist/game/nlcore/elements/built-in/screenEffects.d.ts +31 -0
  14. package/dist/game/nlcore/elements/character/avatar.d.ts +35 -0
  15. package/dist/game/nlcore/elements/character/sentence.d.ts +14 -0
  16. package/dist/game/nlcore/elements/character.d.ts +30 -0
  17. package/dist/game/nlcore/elements/displayable/displayable.d.ts +84 -0
  18. package/dist/game/nlcore/elements/displayable/image.d.ts +2 -2
  19. package/dist/game/nlcore/elements/displayable/text.d.ts +2 -2
  20. package/dist/game/nlcore/elements/layer.d.ts +1 -2
  21. package/dist/game/nlcore/elements/scene.d.ts +2 -1
  22. package/dist/game/nlcore/elements/transform/transform.d.ts +26 -3
  23. package/dist/game/nlcore/elements/transform/type.d.ts +30 -2
  24. package/dist/game/nlcore/elements/transition/transitions/image/maskTransition.d.ts +38 -0
  25. package/dist/game/player/Tasks.d.ts +4 -1
  26. package/dist/game/player/elements/Player.d.ts +1 -1
  27. package/dist/game/player/elements/menu/type.d.ts +1 -0
  28. package/dist/game/player/elements/say/Avatar.d.ts +13 -0
  29. package/dist/game/player/elements/say/Sentence.d.ts +70 -1
  30. package/dist/game/player/elements/say/UIDialog.d.ts +6 -2
  31. package/dist/game/player/elements/say/type.d.ts +4 -2
  32. package/dist/game/player/elements/say/useDialog.d.ts +3 -0
  33. package/dist/game/player/elements/type.d.ts +6 -0
  34. package/dist/game/player/gameState.d.ts +3 -0
  35. package/dist/game/player/lib/AudioManager.d.ts +1 -0
  36. package/dist/game/player/lib/ErrorFallback.d.ts +5 -1
  37. package/dist/game/player/libElements.d.ts +5 -2
  38. package/dist/game/player/provider/game-state.d.ts +1 -0
  39. package/dist/main.js +42 -40
  40. package/dist/util/data.d.ts +15 -2
  41. package/package.json +114 -107
package/dist/main.js CHANGED
@@ -1,66 +1,68 @@
1
- var he={action:"displayable:action",applyTransform:"displayable:applyTransform",applyTransition:"displayable:applyTransition",init:"displayable:init"},Bt={say:"character:say",action:"character:action",setName:"character:setName"},H={action:"scene:action",init:"scene:init",exit:"scene:exit",jumpTo:"scene:jumpTo",setBackgroundMusic:"scene:setBackgroundMusic",preUnmount:"scene:preUnmount",transitionToScene:"scene:transitionToScene",nvlBlock:"scene:nvlBlock",nvlShow:"scene:nvlShow",nvlHide:"scene:nvlHide",nvlEnd:"scene:nvlEnd"};var Ge={action:"image:action",setSrc:"image:setSrc",flush:"image:flush",initWearable:"image:initWearable",setAppearance:"image:setAppearance",setDarkness:"image:setDarkness"},jo={action:"condition:action"},qo={action:"script:action"},Qo={action:"menu:action"},dt={action:"sound:action",play:"sound:play",stop:"sound:stop",setVolume:"sound:setVolume",setRate:"sound:setRate",pause:"sound:pause",resume:"sound:resume",mute:"sound:mute"},pe={action:"control:action",do:"control:do",doAsync:"control:doAsync",any:"control:any",all:"control:all",allAsync:"control:allAsync",repeat:"control:repeat",while:"control:while",break:"control:break",sleep:"control:sleep",waitForClick:"control:waitForClick"},On={action:"text:action",setText:"text:setText",setFontSize:"text:setFontSize"},ln={action:"persistent:action",set:"persistent:set",assign:"persistent:assign"},It={action:"layer:action",setZIndex:"layer:setZIndex"},$t={action:"video:action",show:"video:show",hide:"video:hide",play:"video:play",pause:"video:pause",resume:"video:resume",stop:"video:stop",seek:"video:seek"};var Xo=(p=>(p[p.string=0]="string",p[p.number=1]="number",p[p.boolean=2]="boolean",p[p.object=3]="object",p[p.array=4]="array",p[p.function=5]="function",p[p.symbol=6]="symbol",p[p.undefined=7]="undefined",p[p.null=8]="null",p[p.date=9]="date",p[p.regexp=10]="regexp",p[p.other=11]="other",p))(Xo||{}),$i=function(o){return typeof o=="string"?0:typeof o=="number"?1:typeof o=="boolean"?2:typeof o=="object"?Array.isArray(o)?4:o===null?8:o instanceof Date?9:o instanceof RegExp?10:3:typeof o=="function"?5:typeof o=="symbol"?6:typeof o>"u"?7:11};$i.DataTypes=Xo;function I(o,e,...t){let n=(s,a)=>Object.prototype.hasOwnProperty.call(s,a),i={},r=(s,a,c)=>$i(a)===3&&$i(c)===3?a.constructor!==Object||c.constructor!==Object?c||a:I(a,c):Array.isArray(a)&&Array.isArray(c)?c&&c.length>0?[...c]:[...a]:a===void 0&&Array.isArray(c)?[...c]:c===void 0?Array.isArray(a)?[...a]:a:Array.isArray(c)?[...c]:c;for(let s in o)n(o,s)&&(i[s]=r(s,o[s],e[s]));for(let s in e)n(e,s)&&!n(i,s)&&(typeof e[s]=="object"&&e[s]!==null?e[s].constructor===Object?i[s]=I({},e[s]):Array.isArray(e[s])?i[s]=[...e[s]]:i[s]=e[s]:i[s]=e[s]);if(t.length){let[s,...a]=t;return I(i,s,...a)}return i}var Ee=class Ee{constructor(e=n=>n,t){this.solved=!1;this.aborted=!1;this.listeners=[];this.onRegisterSkipController=[];this.receiver=e,this.skipController=t,this.__stack=ji()}static isAwaitable(e){return e instanceof Ee}static fromPromise(e){let t=new Ee;return e.then(n=>t.resolve(n)),t}static resolve(e){let t=new Ee;return t.resolve(e),t}static delay(e){let t=new Ee;return setTimeout(()=>t.resolve(),e),t}static create(e){let t=new Ee;return e(t),t}static wait(e){let t=new Ee;return e.then(()=>t.resolve()),t}static race(e){let t=new Ee;return e.length===0?(t.resolve(void 0),t):(e.forEach(n=>{n.then(i=>{e.forEach(r=>{r!==n&&r.skipController?.abort()}),t.resolve(i)})}),t.registerSkipController(new M(()=>{e.forEach(n=>n.skipController?.abort())})),t)}static forward(e,t,n){let i=new Ee().registerSkipController(n||new M(()=>t));e.then(()=>i.resolve(t));let r=e.skipController?.onAbort(()=>{i.skipController?.abort(),r?.cancel(),s?.cancel()}),s=i.skipController?.onAbort(()=>{e.skipController?.abort(),r?.cancel(),s?.cancel()});return i}static toPromise(e){return new Promise(t=>{e.then(t)})}static toPromiseForce(e){return new Promise(t=>{e.onSettled(t)})}static any(...e){let t=new Ee;return e.forEach(n=>{n.onSettled(()=>t.resolve())}),t}static all(...e){let t=new Ee,n=0;return e.forEach(i=>{i.onSettled(()=>{n++,n===e.length&&t.resolve()})}),t}registerSkipController(e){this.skipController=e;for(let t of this.onRegisterSkipController)t(e);return this}resolve(e){if(!this.solved){this.result=this.receiver(e),this.solved=!0,this.skipController&&this.skipController.cancel();for(let t of this.listeners)t(this.result)}}then(e){return this.solved?e(this.result):this.pushListener(e),this}onSettled(e){if(this.solved)e();else{this.pushListener(e);let t=[];return t.push(this.onSkipControllerRegister(n=>{t.push(n.onAbort(()=>{e()}))})),{cancel:()=>{t.forEach(n=>n.cancel()),this.offListener(e)}}}return{cancel:()=>{}}}onSkipControllerRegister(e){return this.skipController?e(this.skipController):this.onRegisterSkipController.push(e),{cancel:()=>{this.offSkipControllerRegister(e)}}}offSkipControllerRegister(e){let t=this.onRegisterSkipController.indexOf(e);return t!==-1&&this.onRegisterSkipController.splice(t,1),this}abort(){return this.aborted=!0,this.skipController?this.skipController.abort():this.result}isSolved(){return this.solved&&!this.aborted}isAborted(){return this.aborted}isSettled(){return this.solved||this.aborted}pushListener(e){return this.listeners.length>=Ee.maxListeners&&console.warn("NarraLeaf-React: Awaitable has too many listeners, this may cause performance issues."),this.listeners.push(e),this}offListener(e){let t=this.listeners.indexOf(e);return t!==-1&&this.listeners.splice(t,1),this}};Ee.nothing=e=>e,Ee.maxListeners=8;var g=Ee;function Yo(o){let e=new WeakSet;function t(n){if(n===null||typeof n!="object")return n;if(e.has(n))return;if(e.add(n),Array.isArray(n)){let r=[];for(let s of n)r.push(t(s));return r}let i={};for(let r in n)Object.prototype.hasOwnProperty.call(n,r)&&(i[r]=t(n[r]));return i}return t(o)}function mt(o){return typeof o=="string"?o:`#${(o.r||0).toString(16).padStart(2,"0")}${(o.g||0).toString(16).padStart(2,"0")}${(o.b||0).toString(16).padStart(2,"0")}${o.a===void 0?"":o.a.toString(16).padStart(2,"0")}`}var W=class{constructor(){this.events={};this.maxListeners=10}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),this.events[e].length>this.maxListeners&&console.warn(`NarraLeaf-React: Event ${e} has more than ${this.maxListeners} listeners (total: ${this.events[e].length}), this may cause performance issues.`),this.emit("event:EventDispatcher.register",e,t),{type:e,listener:t,cancel:()=>{this.off(e,t)}}}depends(e){return{cancel:()=>{e.forEach(t=>t.cancel())}}}off(e,t){this.events[e]&&(this.events[e]=this.events[e].filter(n=>n!==t))}emit(e,...t){if(!this.events[e])return 0;let n=this.events[e].length;return this.events[e].forEach(i=>{i(...t)}),n}once(e,t){let n=(...i)=>{t(...i),this.off(e,n)};return this.on(e,n)}async any(e,...t){if(this.events[e]||(this.events[e]=[]),this.events[e].length>0){await Promise.all(this.events[e].map(n=>n(...t)));return}return new Promise(n=>{let i="event:EventDispatcher.register",r=this.on(i,(s,a)=>{if(s===e){this.off(i,r);let c=a?.(...t);c!==null&&typeof c=="object"&&c.then?c.then(n):n(c)}}).listener})}setMaxListeners(e){return this.maxListeners=e,this}hasListeners(e){return this.events[e]?.length>0}clear(){this.events={}}};function ji(o=1){let e=new Error().stack;return e?e.split(`
1
+ var be={action:"displayable:action",applyTransform:"displayable:applyTransform",applyTransition:"displayable:applyTransition",init:"displayable:init"},Jt={say:"character:say",action:"character:action",setName:"character:setName"},V={action:"scene:action",init:"scene:init",exit:"scene:exit",jumpTo:"scene:jumpTo",setBackgroundMusic:"scene:setBackgroundMusic",preUnmount:"scene:preUnmount",transitionToScene:"scene:transitionToScene",nvlBlock:"scene:nvlBlock",nvlShow:"scene:nvlShow",nvlHide:"scene:nvlHide",nvlEnd:"scene:nvlEnd"};var Oe={action:"image:action",setSrc:"image:setSrc",flush:"image:flush",initWearable:"image:initWearable",setAppearance:"image:setAppearance",setDarkness:"image:setDarkness"},rr={action:"condition:action"},sr={action:"script:action"},ar={action:"menu:action"},vt={action:"sound:action",play:"sound:play",stop:"sound:stop",setVolume:"sound:setVolume",setRate:"sound:setRate",pause:"sound:pause",resume:"sound:resume",mute:"sound:mute"},ve={action:"control:action",do:"control:do",doAsync:"control:doAsync",any:"control:any",all:"control:all",allAsync:"control:allAsync",repeat:"control:repeat",while:"control:while",break:"control:break",sleep:"control:sleep",waitForClick:"control:waitForClick"},jn={action:"text:action",setText:"text:setText",setFontSize:"text:setFontSize"},yn={action:"persistent:action",set:"persistent:set",assign:"persistent:assign"},Ut={action:"layer:action",setZIndex:"layer:setZIndex"},Zt={action:"video:action",show:"video:show",hide:"video:hide",play:"video:play",pause:"video:pause",resume:"video:resume",stop:"video:stop",seek:"video:seek"};var cr=(d=>(d[d.string=0]="string",d[d.number=1]="number",d[d.boolean=2]="boolean",d[d.object=3]="object",d[d.array=4]="array",d[d.function=5]="function",d[d.symbol=6]="symbol",d[d.undefined=7]="undefined",d[d.null=8]="null",d[d.date=9]="date",d[d.regexp=10]="regexp",d[d.other=11]="other",d))(cr||{}),Ji=(function(o){return typeof o=="string"?0:typeof o=="number"?1:typeof o=="boolean"?2:typeof o=="object"?Array.isArray(o)?4:o===null?8:o instanceof Date?9:o instanceof RegExp?10:3:typeof o=="function"?5:typeof o=="symbol"?6:typeof o>"u"?7:11});Ji.DataTypes=cr;function H(o,e,...t){let n=(s,a)=>Object.prototype.hasOwnProperty.call(s,a),i={},r=(s,a,c)=>Ji(a)===3&&Ji(c)===3?a.constructor!==Object||c.constructor!==Object?c||a:H(a,c):Array.isArray(a)&&Array.isArray(c)?c&&c.length>0?[...c]:[...a]:a===void 0&&Array.isArray(c)?[...c]:c===void 0?Array.isArray(a)?[...a]:a:Array.isArray(c)?[...c]:c;for(let s in o)n(o,s)&&(i[s]=r(s,o[s],e[s]));for(let s in e)n(e,s)&&!n(i,s)&&(typeof e[s]=="object"&&e[s]!==null?e[s].constructor===Object?i[s]=H({},e[s]):Array.isArray(e[s])?i[s]=[...e[s]]:i[s]=e[s]:i[s]=e[s]);if(t.length){let[s,...a]=t;return H(i,s,...a)}return i}var Ee=class Ee{constructor(e=(n=>n),t){this.solved=!1;this.aborted=!1;this.failed=!1;this.error=null;this.listeners=[];this.failListeners=[];this.settledListeners=[];this.onRegisterSkipController=[];this.skipControllerAbortToken=null;this.settledNotified=!1;this.receiver=e,this.skipController=t,this.__stack=Zi()}static isAwaitable(e){return e instanceof Ee}static fromPromise(e){let t=new Ee;return e.then(n=>t.resolve(n)).catch(n=>t.fail(n)),t}static resolve(e){let t=new Ee;return t.resolve(e),t}static delay(e){let t=new Ee;return setTimeout(()=>t.resolve(),e),t}static create(e){let t=new Ee;return e(t),t}static wait(e){let t=new Ee;return e.then(()=>t.resolve()),e.onFailed(n=>t.fail(n)),t}static race(e){let t=new Ee;return e.length===0?(t.resolve(void 0),t):(e.forEach(n=>{n.then(i=>{e.forEach(r=>{r!==n&&r.skipController?.abort()}),t.resolve(i)}),n.onFailed(i=>t.fail(i))}),t.registerSkipController(new G(()=>{e.forEach(n=>n.skipController?.abort())})),t)}static forward(e,t,n){let i=new Ee().registerSkipController(n||new G(()=>t));e.then(()=>i.resolve(t)),e.onFailed(a=>i.fail(a));let r=e.skipController?.onAbort(()=>{i.skipController?.abort(),r?.cancel(),s?.cancel()}),s=i.skipController?.onAbort(()=>{e.skipController?.abort(),r?.cancel(),s?.cancel()});return i}static toPromise(e){return new Promise((t,n)=>{e.then(t),e.onFailed(n)})}static toPromiseForce(e){return new Promise(t=>{e.onSettled(t)})}static any(...e){let t=new Ee;return e.length===0?(t.resolve(),t):(e.forEach(n=>{n.onSettled(()=>t.resolve()),n.onFailed(i=>{e.forEach(r=>{r!==n&&r.abort()}),t.fail(i)})}),t.registerSkipController(new G(()=>{e.forEach(n=>n.abort())})),t)}static all(...e){let t=new Ee;if(e.length===0)return t.resolve(),t;let n=0;return e.forEach(i=>{i.onSettled(()=>{n++,n===e.length&&t.resolve()}),i.onFailed(r=>{e.forEach(s=>{s!==i&&s.abort()}),t.fail(r)})}),t.registerSkipController(new G(()=>{e.forEach(i=>i.abort())})),t}registerSkipController(e){this.skipControllerAbortToken?.cancel(),this.skipController=e,this.skipControllerAbortToken=e.onAbort(()=>{this.aborted=!0,this.notifySettled()});for(let t of this.onRegisterSkipController)t(e);return this}resolve(e){if(!this.isSettled()){this.result=this.receiver(e),this.solved=!0,this.skipController&&this.skipController.cancel();for(let t of this.listeners)t(this.result);this.notifySettled()}}fail(e){if(!this.isSettled()){this.error=e,this.failed=!0,this.skipController&&this.skipController.cancel();for(let t of this.failListeners)t(e);this.notifySettled()}}then(e,t){return this.solved?e(this.result):this.failed?t?.(this.error):(this.pushListener(e),t&&this.pushFailListener(t)),this}onSettled(e){if(this.isSettled())e();else return this.settledListeners.push(e),{cancel:()=>{this.offSettledListener(e)}};return{cancel:()=>{}}}onFailed(e){if(this.failed)e(this.error);else if(!this.isSettled())return this.pushFailListener(e),{cancel:()=>{this.offFailListener(e)}};return{cancel:()=>{}}}onSkipControllerRegister(e){return this.skipController?e(this.skipController):this.onRegisterSkipController.push(e),{cancel:()=>{this.offSkipControllerRegister(e)}}}offSkipControllerRegister(e){let t=this.onRegisterSkipController.indexOf(e);return t!==-1&&this.onRegisterSkipController.splice(t,1),this}abort(){return this.isSettled()?this.result:(this.aborted=!0,this.skipController?this.skipController.abort():this.notifySettled(),this.result)}isSolved(){return this.solved&&!this.aborted&&!this.failed}isAborted(){return this.aborted}isFailed(){return this.failed}isSettled(){return this.solved||this.aborted||this.failed}pushListener(e){return this.listeners.length>=Ee.maxListeners&&console.warn("NarraLeaf-React: Awaitable has too many listeners, this may cause performance issues."),this.listeners.push(e),this}pushFailListener(e){return this.failListeners.length>=Ee.maxListeners&&console.warn("NarraLeaf-React: Awaitable has too many failure listeners, this may cause performance issues."),this.failListeners.push(e),this}offListener(e){let t=this.listeners.indexOf(e);return t!==-1&&this.listeners.splice(t,1),this}offFailListener(e){let t=this.failListeners.indexOf(e);return t!==-1&&this.failListeners.splice(t,1),this}offSettledListener(e){let t=this.settledListeners.indexOf(e);return t!==-1&&this.settledListeners.splice(t,1),this}notifySettled(){if(!this.settledNotified){this.settledNotified=!0;for(let e of this.settledListeners)e()}}};Ee.nothing=e=>e,Ee.maxListeners=8;var y=Ee;function lr(o){let e=new WeakSet;function t(n){if(n===null||typeof n!="object")return n;if(e.has(n))return;if(e.add(n),Array.isArray(n)){let r=[];for(let s of n)r.push(t(s));return r}let i={};for(let r in n)Object.prototype.hasOwnProperty.call(n,r)&&(i[r]=t(n[r]));return i}return t(o)}function Ye(o){return typeof o=="string"?o:`#${(o.r||0).toString(16).padStart(2,"0")}${(o.g||0).toString(16).padStart(2,"0")}${(o.b||0).toString(16).padStart(2,"0")}${o.a===void 0?"":o.a.toString(16).padStart(2,"0")}`}var J=class{constructor(){this.events={};this.maxListeners=10}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),this.events[e].length>this.maxListeners&&console.warn(`NarraLeaf-React: Event ${e} has more than ${this.maxListeners} listeners (total: ${this.events[e].length}), this may cause performance issues.`),this.emit("event:EventDispatcher.register",e,t),{type:e,listener:t,cancel:()=>{this.off(e,t)}}}depends(e){return{cancel:()=>{e.forEach(t=>t.cancel())}}}off(e,t){this.events[e]&&(this.events[e]=this.events[e].filter(n=>n!==t))}emit(e,...t){if(!this.events[e])return 0;let n=this.events[e].length;return this.events[e].forEach(i=>{i(...t)}),n}once(e,t){let n=(...i)=>{t(...i),this.off(e,n)};return this.on(e,n)}async any(e,...t){if(this.events[e]||(this.events[e]=[]),this.events[e].length>0){await Promise.all(this.events[e].map(n=>n(...t)));return}return new Promise(n=>{let i="event:EventDispatcher.register",r=this.on(i,(s,a)=>{if(s===e){this.off(i,r);let c=a?.(...t);c!==null&&typeof c=="object"&&c.then?c.then(n):n(c)}}).listener})}setMaxListeners(e){return this.maxListeners=e,this}hasListeners(e){return this.events[e]?.length>0}clear(){this.events={}}};function Zi(o=1){let e=new Error().stack;return e?e.split(`
2
2
  `).slice(o+1).join(`
3
- `).trim():""}function Qn(o){return new Promise(e=>setTimeout(e,o))}var qn=class qn{constructor(e){this.abortHandler=e;this.events=new W;this.aborted=!1}abort(...e){this.aborted||(this.aborted=!0,this.abortHandler(...e),this.events.emit(qn.EventTypes["event:skipController.abort"]))}isAborted(){return this.aborted}cancel(){this.aborted=!0}onAbort(e){return this.events.on("event:skipController.abort",e)}};qn.EventTypes={"event:skipController.abort":"event:skipController.abort"};var M=qn;var un=class{constructor(){this.locked=!1;this.listeners=[];this.unlockListeners=[]}lock(){return this.locked=!0,this}unlock(){this.locked=!1;for(let e of this.listeners)e();for(let e of this.unlockListeners)e();return this.listeners=[],this}onUnlock(e){return this.unlockListeners.push(e),e}offUnlock(e){this.unlockListeners=this.unlockListeners.filter(t=>t!==e)}async nextUnlock(){if(this.locked)return new Promise(e=>{this.listeners.push(e)})}isLocked(){return this.locked}},jt=class{constructor(){this.locks=[]}unlock(e){return e.unlock(),this.off(e),e}register(e){let t=e||new un;return this.locks.push(t),t}off(e){this.locks=this.locks.filter(t=>t!==e)}async nextUnlock(){let e=this.locks.map(t=>t.nextUnlock());return Promise.all(e)}isLocked(){return this.locks.some(e=>e.isLocked())}};function Xn(o,e,t={}){return o?e:t}function Jo(o,e){if(e<=0)return o;let t=null;return function(...n){t&&clearTimeout(t),t=setTimeout(()=>{o(...n)},e)}}var Wn=class{constructor(){this.taskToken=null}scheduleTask(e,t){this.taskToken&&this.taskToken.cancel();let n=!1,i=setTimeout(()=>{n||e()},t);return this.taskToken={cancel:()=>{clearTimeout(i),n=!0},isCancelled:()=>n},this.taskToken}cancelTask(){return this.taskToken&&(this.taskToken.cancel(),this.taskToken=null),this}};function Zo(o,e){let t=[];for(let n=0;n<Math.max(o.length,e.length);n++)n<o.length&&t.push(o[n]),n<e.length&&t.push(e[n]);return t}async function _o(o,e){return new Promise((t,n)=>{fetch(o,e).then(i=>i.blob()).then(i=>{let r=new FileReader;r.onload=()=>{t(r.result)},r.readAsDataURL(i)}).catch(n)})}var pn=class{constructor(e,t){this.concurrency=e;this.delay=t;this.tasks=[]}addTask(e){this.tasks.push(e)}async start(){let e=async()=>{if(this.tasks.length===0)return;let t=this.tasks.splice(0,this.concurrency);await Promise.all(t.map(n=>n())),await Qn(this.delay),await e()};await e()}};function ze(o){let e,t=Promise.resolve().then(()=>{e=o()});return()=>{t.then(()=>{e&&e()})}}function er(o,e){let t={};for(let n in o)e.includes(n)||(t[n]=o[n]);return t}var Le=class o{constructor(e={},t={}){this.serializer=e;this.deserializer=t}serialize(e){let t={};for(let n of Object.keys(e))n in this.serializer&&e[n]!==void 0?t[n]=this.serializer[n]?.(e[n]):t[n]=e[n];return t}deserialize(e){let t={};for(let n of Object.keys(e))typeof this.deserializer[n]=="function"&&e[n]!==void 0?t[n]=this.deserializer[n](e[n]):t[n]=e[n];return t}extend(e,t){let n={...this.serializer,...e},i={...this.deserializer,...t};return new o(n,i)}};function tr(o){return["aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkgrey","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkslategrey","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dimgrey","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","green","greenyellow","grey","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightgrey","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightslategrey","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","slategrey","snow","springgreen","steelblue","tan","teal","thistle","tomato","transparent","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen"].includes(o)}function nr(o){return o.constructor.name==="AsyncFunction"||Object.prototype.toString.call(o)==="[object AsyncFunction]"}function qi(o){let e={};for(let t in o)o[t]!==void 0&&(e[t]=o[t]);return e}function Qi(o,e=new WeakSet){if(o===null||typeof o!="object"||Array.isArray(o)||o instanceof Date||o instanceof RegExp||Object.getPrototypeOf(o)!==Object.prototype||e.has(o))return!1;e.add(o);for(let t in o)if(Object.prototype.hasOwnProperty.call(o,t)){let n=o[t];if(n!==null&&typeof n=="object"&&!Qi(n,e)||typeof n=="function"||typeof n=="symbol")return!1}return!0}var zn=class{constructor(e=""){this.prefix=e;this.counter=0}next(){return`${this.prefix?this.prefix+"-":""}${this.counter++}`}};function ir(o=16){let e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=t.length;for(let i=0;i<o;i++)e+=t.charAt(Math.floor(Math.random()*n));return e}function or(o=16){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",t="";for(let n=0;n<o;n++)t+=e[Math.floor(Math.random()*e.length)];return t}var Bn=class{constructor(e=""){this.prefix=e;this.counter=0}generateId(){return`${this.prefix?this.prefix+"-":""}${this.counter++}`}},$n=class{constructor(){this.hooks={}}hook(e,t){return this.hooks[e]=this.hooks[e]||[],this.hooks[e].push(t),{cancel:()=>this.unhook(e,t)}}unhook(e,t){this.hooks[e]=this.hooks[e]?.filter(n=>n!==t)||[]}trigger(e,t){let n=this.hooks[e];if(!n)return()=>{};let i=n.map(r=>r(...t));return()=>{i.forEach(r=>r&&r())}}rawTrigger(e,t){let n=this.hooks[e];if(!n)return()=>{};let i=n.map(r=>r(...t()));return()=>{i.forEach(r=>r&&r())}}};var jn=class{constructor(e){this.items=[];this.pushValidator=[];e&&(this.items=[...e])}addPushValidator(e){return this.pushValidator.push(e),this}removePushValidator(e){this.pushValidator=this.pushValidator.filter(t=>t!==e)}push(...e){for(let t of e)this.pushValidator.some(n=>!n(t))||this.items.push(t)}pop(){return this.items.pop()}peek(){return this.items[this.items.length-1]}isEmpty(){return this.items.length===0}size(){return this.items.length}clear(){this.items=[]}toArray(){return[...this.items]}forEach(e){this.items.forEach(e)}forEachReverse(e){for(let t=this.items.length-1;t>=0;t--)e(this.items[t])}map(e){return this.items.map(e)}get(e){return this.items[e]}};function rr(o,e){let t={},n=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&(e.includes(i)?n.push(i):t[i]=o[i]);return[t,n]}function sr(o){let e=3421674724,t=2216829733;for(let n=0;n<o.length;n++){let i=o.charCodeAt(n);e^=i;let r=e>>>0,s=t>>>0,a=435,c=16777216,l=r*a>>>0,u=r*c+s*a>>>0,m=s*c+(u>>>0)>>>0;e=l,t=m}return("00000000"+t.toString(16)).slice(-8)+("00000000"+e.toString(16)).slice(-8)}var dn=class{constructor(e,t,n){this.callee=e,this.type=t,this.contentNode=n,this.__stack=ji(),this._id=""}executeAction(e,t){return{type:this.type,node:this.contentNode.getChild()}}getId(){return this._id}setId(e){this._id=e}setContent(e){return this.contentNode.setContent(e),this}setContentNode(e){return this.contentNode=e,this}getFutureActions(e,t){let n=this.contentNode.getChild();return n&&n.action?[n.action]:[]}};dn.ActionTypes={action:"action"};var U=class extends dn{constructor(e,t,n){super(e,t,n),this.callee=e.getSelf(),this.contentNode.action=this}unknownTypeError(){throw new Error("Unknown action type: "+this.type)}resolveAwaitable(e,t){let n=t||new g(i=>i);return(async()=>await e(n.resolve.bind(n),n))(),n}is(e,t){return this instanceof e&&this.type===t}stringify(e,t,n){return this.stringifyWithName("Action")}stringifyWithName(e){return`${e}#${this._id}(${this.type})`}stringifyWithContent(e,t){return`${e}#${this._id}(${this.type}){${t}}`}};var Xi=class{constructor(e){this.type=e,this.content=void 0}setContent(e){return this.content=e,this}getContent(){return this.content}},v=class o extends Xi{static create(e){return new o().setContent(e)}static forEachParent(e,t){let n=new Set,i=e;for(;i&&!n.has(i);)n.add(i),t(i),i=i.getParent()}static forEachChild(e,t){let n=new Set,i=e;for(;i&&!n.has(i);)n.add(i),t(i),i=i.getChild()}constructor(e,t,n){super("ContentNode"),this.child=n||null,this.parent=t||null,this.action=e||null}setParent(e){if(e===this)throw new Error("Cannot set parent to itself");return this.parent&&this.parent.setChild(null),this.parent=e,this}setChild(e){if(e===this)throw new Error("Cannot set child to itself");return this.child&&(this.child.parent=null),this.child=e,e&&e.parent!==this&&(e.remove(),e.parent=this),this}getChild(){return this.child||null}getParent(){return this.parent||null}addChild(e){return this.setChild(e),this}removeChild(e){return e&&this.child===e?(this.child=null,e.setParent(null)):e||(this.child=null),this}remove(){return this.parent&&this.parent.removeChild(this),this.child&&this.child.setParent(null),this}hasChild(){return!!this.child}};var Yn={center:"center",left:"left",right:"right"};import{animate as Ms}from"motion/react";var mn=(n=>(n.Left="left",n.Center="center",n.Right="right",n))(mn||{}),ar={left:"33.33%",center:"50%",right:"66.66%"},Be=class Be{static isUnknown(e){return e===Be.Unknown}static D2PositionToCSS(e,t=!1,n=!1){let i=this.calc(e.y,e.yoffset),r=this.calc(e.x,e.xoffset),s=n?{bottom:i}:{top:i},a=t?{right:r}:{left:r};return this.wrap({...s,...a})}static calc(e,t){return!e||Be.isUnknown(e)?"auto":t===void 0||Be.isUnknown(t)?`calc(${e} + 0px)`:`calc(${typeof e=="number"?`${e}px`:e} + ${t}px)`}static toCoord2D(e){if($e.isCommonPositionType(e))return Ie.fromCommonPosition(e);if(Ie.isCoord2DPosition(e))return e;if(Rt.isAlignPosition(e))return Ie.fromAlignPosition(e);if(typeof e=="object"&&["x","y","xoffset","yoffset"].some(t=>t in e)){let t=e;return new Ie(t)}else throw new Error("Invalid position type")}static orUnknown(e){return Be.isUnknown(e)||e===void 0?Be.Unknown:e}static mergePosition(e,t){let n=this.toCoord2D(e),i=this.toCoord2D(t);return Ie.merge(n,i)}static serializePosition(e){let t=this.toCoord2D(e);return{x:Be.isUnknown(t.x)?0:t.x,y:Be.isUnknown(t.y)?0:t.y,xoffset:Be.isUnknown(t.xoffset)?0:t.xoffset,yoffset:Be.isUnknown(t.yoffset)?0:t.yoffset}}static isRawCommonPositionType(e){return Object.values(mn).includes(e)}static isRawCoord2DPosition(e){return typeof e=="object"&&("x"in e||"y"in e||"xoffset"in e||"yoffset"in e)}static isRawAlignPosition(e){return typeof e=="object"&&("xalign"in e||"yalign"in e||"xoffset"in e||"yoffset"in e)}static isRawPosition(e){return this.isRawCommonPositionType(e)||this.isRawCoord2DPosition(e)||this.isRawAlignPosition(e)}static isPosition(e){return e instanceof $e||e instanceof Ie||e instanceof Rt}static rawPositionToCoord2D(e){if(this.isRawCommonPositionType(e))return Ie.fromCommonPosition(new $e(e));if(this.isRawCoord2DPosition(e))return new Ie(e);if(this.isRawAlignPosition(e))return Ie.fromAlignPosition(e);throw new Error("Invalid position type")}static tryParsePosition(e){if(this.isPosition(e))return e;if(this.isRawPosition(e))return this.rawPositionToCoord2D(e);throw new Error("Invalid position type")}static wrap(e){return{left:"auto",top:"auto",right:"auto",bottom:"auto",...e}}};Be.Unknown=Symbol("Unknown");var k=Be,Jn=class Jn{static isCommonPositionType(e){return e instanceof Jn}constructor(e){this.position=e}toCSS(){return{x:ar[this.position],y:"50%",xoffset:0,yoffset:0}}};Jn.Positions=mn;var $e=Jn,Ie=class o{static isCoord2DPosition(e){return e instanceof o}static fromCommonPosition(e){return new o({x:ar[e.position],y:"50%"})}static fromAlignPosition(e){let t=n=>!n||k.isUnknown(n)?k.Unknown:`${n*100}%`;return new o({x:t(e.xalign),y:t(e.yalign),xoffset:e.xoffset,yoffset:e.yoffset})}static merge(e,t){return new o({x:k.isUnknown(t.x)?e.x:t.x,y:k.isUnknown(t.y)?e.y:t.y,xoffset:k.isUnknown(t.xoffset)?e.xoffset:t.xoffset,yoffset:k.isUnknown(t.yoffset)?e.yoffset:t.yoffset})}constructor(e,t){typeof e=="object"?(this.x=k.orUnknown(e.x),this.y=k.orUnknown(e.y),this.xoffset=k.orUnknown(e.xoffset),this.yoffset=k.orUnknown(e.yoffset)):(this.x=k.orUnknown(e),this.y=k.orUnknown(t),this.xoffset=k.Unknown,this.yoffset=k.Unknown),this.check()}check(){let e=t=>/^-?\d+(\.\d+)?%$/.test(t);if(typeof this.x=="string"&&!e(this.x))throw new Error(`Invalid x position: ${this.x}`);if(typeof this.y=="string"&&!e(this.y))throw new Error(`Invalid y position: ${this.y}`)}toCSS(){return{x:this.x,y:this.y,xoffset:this.xoffset,yoffset:this.yoffset}}},Rt=class o{static isAlignPosition(e){return e instanceof o}constructor(e,t){typeof e=="object"?(this.xalign=k.orUnknown(e.xalign),this.yalign=k.orUnknown(e.yalign),this.xoffset=k.orUnknown(e.xoffset),this.yoffset=k.orUnknown(e.yoffset)):(this.xalign=k.orUnknown(e),this.yalign=k.orUnknown(t),this.xoffset=k.Unknown,this.yoffset=k.Unknown),this.check()}check(){if(typeof this.xalign=="number"&&isNaN(this.xalign))throw new Error("Invalid xalign position: "+this.xalign);if(typeof this.yalign=="number"&&isNaN(this.yalign))throw new Error("Invalid yalign position: "+this.yalign)}toCSS(){return{x:k.isUnknown(this.xalign)?this.xalign:`${this.xalign*100}%`,y:k.isUnknown(this.yalign)?this.yalign:`${this.yalign*100}%`,xoffset:this.xoffset,yoffset:this.yoffset}}};var K=class o{constructor(e,t){this.defaultConfig=e;this.handlers=t||{}}create(e={}){return new Yi(this.mergeWithDefaultConfig(e))}copy(){return new o(I({},this.defaultConfig),this.handlers)}keys(){return Object.keys(this.defaultConfig)}getDefaultConfig(){return this.defaultConfig}mergeWithDefaultConfig(e){return Object.fromEntries(Object.entries(this.defaultConfig).map(([t,n])=>[t,this.mergeValue(t,n,e[t])]))}mergeValue(e,t,n){return this.isPlainObject(n)?I({},n):Array.isArray(t)?Array.isArray(n)&&n.length>0?[...n]:[...t]:n!==void 0?this.applyHandler(e,n):t}isPlainObject(e){return typeof e=="object"&&!Array.isArray(e)&&e!==null&&Object.getPrototypeOf(e)===Object.prototype}applyHandler(e,t){return typeof this.handlers[e]=="function"?this.handlers[e](t):t}},Yi=class o{constructor(e){this.config=e}get(){return this.config}copy(){return new o(I({},this.config))}join(e){let t=er(this.config,Object.keys(e));return new o(Object.assign(t,e instanceof o?e.get():e))}extract(e){let t={},n={};for(let i of e)t[i]=this.config[i];for(let i in this.config)e.includes(i)||(n[i]=this.config[i]);return[new o(t),new o(n)]}assign(e){return new o(Object.assign({},this.config,e))}};var Gs={[Yn.left]:"25.33%",[Yn.center]:"50%",[Yn.right]:"75.66%"},Xe=class Xe{constructor(e={}){this.state={};this.locked=null;this.frozen=!1;this.state=e}static deserialize(e){return new Xe(Xe.TransformStateSerializer.deserialize(e))}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?k.toCoord2D(k.tryParsePosition(e||t)):k.mergePosition(k.tryParsePosition(e),k.tryParsePosition(t))}static mergeState(e,t){if("position"in e&&"position"in t){let n=this.mergePosition(e.position,t.position);return{...Object.assign({},e,t),position:n}}return{...Object.assign({},e,t)}}get(){return this.state}freeze(){return this.frozen=!0,this}assign(e,t){if(this.frozen)throw new Error("Trying to write a frozen transform state.");if(!this.canWrite(e))throw new Error("Trying to write a locked transform state.");return this.state=Xe.mergeState(this.state,t),this}lock(){if(this.locked)throw new Error("Transform state is already locked.");return this.locked=Symbol(),this.locked}isLocked(){return!!this.locked}canWrite(e){return this.locked===null||this.locked===e}unlock(e){return this.locked===e&&(this.locked=null),this}toFramesDefinition(e,t){return qi(z.constructStyle(e,this.state,t))}toStyle(e,t){return qi(z.constructStyle(e,this.state,t))}serialize(){return Xe.TransformStateSerializer.serialize(this.state)}clone(){return new Xe(Xe.mergeState({},this.state))}overwrite(e,t){if(this.frozen)throw new Error("Trying to write a frozen transform state.");if(!this.canWrite(e))throw new Error("Trying to write a locked transform state.");return this.state=Xe.mergeState(this.state,t),this}forceOverwrite(e){return this.state=e,this}};Xe.DefaultTransformState=new K({scaleX:1,scaleY:1,zoom:1,rotation:0,position:new $e("center"),opacity:0,alt:""}),Xe.TransformStateSerializer=new Le({position:e=>k.serializePosition(k.tryParsePosition(e))},{position:e=>k.toCoord2D(e)});var me=Xe,de=class de{constructor(e,t){this.sequences=[];this.stagedChanges=[];if(Array.isArray(e))this.sequences.push(...e),this.config=Object.assign({},de.defaultConfig,t||{});else{let[n,i]=[e,t||de.defaultOptions];this.sequences.push({props:n,options:i||de.defaultOptions}),this.config=Object.assign({},de.defaultConfig)}}static isPosition(e){return $e.isCommonPositionType(e)||Ie.isCoord2DPosition(e)||Rt.isAlignPosition(e)}static immediate(e){return new de(e,{duration:0,ease:"linear"})}static left(e,t){return new de({position:$e.Positions.Left},{duration:e,ease:t})}static right(e,t){return new de({position:$e.Positions.Right},{duration:e,ease:t})}static center(e,t){return new de({position:$e.Positions.Center},{duration:e,ease:t})}static create(e){return new de([],e)}static positionToCSS(e,t,n){return e?k.isRawPosition(e)?k.D2PositionToCSS(k.rawPositionToCoord2D(e),n,t):k.D2PositionToCSS(e.toCSS(),n,t):{}}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?k.toCoord2D(k.tryParsePosition(e||t)):k.mergePosition(k.tryParsePosition(e),k.tryParsePosition(t))}static mergeState(e,t){let n=this.mergePosition(e.position,t.position);return{...I(e,t),position:n}}static propToCSSTransform(e,t,n){let{invertY:i,invertX:r}=e.getStory().getInversionConfig(),{translate:s=[]}=n||{},a=t.zoom??1,c=function(p,h,d){return typeof p>"u"?typeof d<"u"?h(d):"":h(p)},l=s[0]||(r?"":"-")+"50%",u=s[1]||(i?"":"-")+"50%";return[`translate(${l}, ${u})`,c(t.rotation,p=>`rotate(${p}deg)`,0),c(t.scaleX,p=>`scaleX(${p*a})`,1),c(t.scaleY,p=>`scaleY(${p*a})`,1)].filter(Boolean).join(" ")}static constructStyle(e,t,n){let{invertY:i,invertX:r}=e.getStory().getInversionConfig(),{overwrite:s}=n||{};return{...de.positionToCSS(t.position,i,r),opacity:t.opacity,color:"fontColor"in t&&t.fontColor?mt(t.fontColor):void 0,transform:de.propToCSSTransform(e,t),...s?s(t):{}}}animate(e,{gameState:t,ref:n,overwrites:i}){if(!n.current)throw new Error("No ref found when animating.");this.commit();let{finalState:r,sequences:s,options:a}=this.constructAnimation({gameState:t,transformState:e,overwrites:i,current:n.current});s.length||t.logger.warn("Transform","No sequences to animate.");let c=!1,l=e.lock(),u=Ms(s,a),m=()=>{e.overwrite(l,r.get()).unlock(l),u.complete(),c=!0},p=new g().registerSkipController(new M(m)),h=()=>{c||e.overwrite(l,r.get()).unlock(l),c=!0,t.logger.debug("Transform","Transform Completed",e.toStyle(t,i)),p.resolve()};return u.then(h,d=>{t.logger.error("Failed to animate transform. "+(d?.toString?.()||""))}),u.play(),t.logger.debug("Transform","Ready to animate transform.",{finalState:r,sequences:s,options:a},this),p}repeat(e){let t=this.copy();return t.config.repeat||(t.config.repeat=1),t.config.repeat*=e,t}getOptions(e){if(!e)return{...de.defaultOptions};let{duration:t,ease:n,delay:i,at:r}=e;return{duration:this.toSeconds(t,void 0),ease:n,delay:this.toSeconds(i,void 0),at:this.atToSeconds(r)}}constructAnimation({gameState:e,transformState:t,overwrites:n={},current:i}){let r=t.clone(),s=r.lock(),a=this.sequences.map(({props:c,options:l})=>{let u=r.assign(s,c).toFramesDefinition(e,n);return[i,u,this.getOptions(l)]});return{finalState:r.unlock(s).freeze(),sequences:a,options:this.getSequenceOptions()}}getSequenceOptions(){let{repeat:e,repeatDelay:t}=this.config;return{repeat:e,repeatDelay:this.toSeconds(t,void 0)}}copy(){return new de(this.sequences,this.config)}commit(e){if(!this.stagedChanges.length)return this;let t=this.constructCommit(this.stagedChanges,this.getSequenceOptions());return this.sequences.push({props:t.props,options:{...this.getSequenceOptions(),...e}}),this.stagedChanges=[],this}zoom(e){return this.pushChange({key:"zoom",props:e})}scaleX(e){return this.pushChange({key:"scaleX",props:e})}scaleY(e){return this.pushChange({key:"scaleY",props:e})}scale(e,t){return this.pushChange({key:"scaleX",props:e}).pushChange({key:"scaleY",props:t})}rotation(e){return this.pushChange({key:"rotation",props:e})}position(e){return this.pushChange({key:"position",props:e})}opacity(e){return this.pushChange({key:"opacity",props:e})}fontColor(e){return this.pushChange({key:"fontColor",props:e})}constructCommit(e,t){let n={props:{},options:t};for(let i of e)n.props[i.key]=i.props;return n}pushChange(e){return this.stagedChanges.push(e),this}toSeconds(e,t){return typeof e>"u"?t:e/1e3}atToSeconds(e){if(typeof e>"u")return e;if(typeof e=="number")return e/1e3;let n=/^([+-])(\d+)$/.exec(e);if(!n)throw new te("Invalid at definition. At definition must be a number or a string in the format of `+n` or `-n`.");let[i,r,s]=n,a=Number(s);if(isNaN(a))throw new te("Invalid number in at definition.");let c=a/1e3;return r==="+"?`+${c}`:`-${c}`}};de.defaultConfig={sync:!0},de.defaultOptions={duration:0,ease:"linear"},de.CommonImagePositionMap=Gs;var z=de;var Zn=class{constructor(){this.id=""}setId(e){this.id=e}getId(){return this.id}reset(){}fromData(e){return this}construct(e){for(let t=0;t<e.length;t++){let n=e[t];t!==0&&e[t-1]?.contentNode.setChild(n.contentNode)}return e}};var cr=Symbol("_Chained"),lr;lr=cr;var Ji=class Ji{constructor(e){this[lr]=!0;this.__actions=[];this.__self=e}static isChained(e){return e&&e[cr]}static toActions(e){return e.flat(2).map(t=>Ji.isChained(t)?t.fromChained(t):t).flat(3)}push(...e){this.__actions.push(...e)}getActions(){return this.__actions}getSelf(){return this.__self}newChain(){return this.getSelf().chain()}},ge=Ji,qt=class extends Zn{chain(e){let t=ge.isChained(this)?this:this.proxy(this,new ge(this));if(!e)return t;let n=Array.isArray(e)?e:[e];return t.push(...n),t}proxy(e,t){let n=new Proxy(e,{get:function(i,r){if(r in t)return t[r];let s=i[r];return typeof s=="function"?s.bind(n):s},set:function(i,r,s){return i[r]=s,!0}});return n}combineActions(e,t){let n=t(this.chain().newChain()),i=e.do([n]).getActions()[0];return this.chain(i)}};var X=class extends qt{constructor(){super()}toData(){return null}fromChained(e){return e.getActions()}};var tt=class extends U{executeAction(e,t){let n=this.callee.evaluate(this.contentNode.getContent(),{gameState:e});return n?.length?[{type:this.type,node:this.contentNode.getChild()},{type:this.type,node:n[0].contentNode}]:super.executeAction(e,t)}getFutureActions(e,t){return[...this.callee._getFutureActions(),...super.getFutureActions(e,t)]}stringify(e,t,n){let i=this.contentNode.getContent(),r=s=>{let a=s.condition?n?s.condition.toString():"Lambda(unknown)":"null",c=s.action?s.action.map(l=>l.stringify(e,t,n)).join(";"):"null";return`(${a}) {${c}}`};return super.stringifyWithContent("Condition",`if ${r(i.If)} ${i.ElseIf.length>0?`else if ${i.ElseIf.map(r).join(";")} `:""}${i.Else?`else {${r(i.Else)}}`:""}`)}};tt.ActionTypes=jo;var nt=class o{static isSerializable(e){return["number","string","boolean"].includes(typeof e)||e instanceof Date||e==null?!0:Array.isArray(e)?e.every(o.isSerializable):typeof e=="object"?Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every(o.isSerializable):!1}constructor(e,t,n){this.name=e,this.key=n||e,this.content=I({},t),this.defaultContent=t}set(e,t){return o.isSerializable(t)?(this.content[e]=t,this):(console.warn(`Value "${t}" in key "${String(e)}" is not serializable, and will not be set
4
- at namespace "${this.name}"`),this.content[e]=t,this)}get(e){return this.content[e]}equals(e,t){return this.content[e]===t}assign(e){return Object.entries(e).forEach(([t,n])=>{this.set(t,n)}),this}has(e){return this.content[e]!==void 0}keys(){return Object.keys(this.content)}values(){return Object.values(this.content)}entries(){return Object.entries(this.content)}reset(){return this.content=I({},this.defaultContent),this}getContent(){return this.content}toData(){return this.serialize()}load(e){if(!e){console.warn("No data to load");return}this.content=e}serialize(){let e={};return Object.entries(this.content).forEach(([t,n])=>{e[t]=this.wrap(n)}),e}deserialize(e){if(!e){console.warn("No data to load");return}Object.entries(e).forEach(([t,n])=>{this.content[t]=this.unwrap(n)})}toTypeName(e){return e instanceof Date?"date":"any"}wrap(e){let t={any:i=>({type:"any",data:i}),date:i=>({type:"date",data:i.toString()})},n=this.toTypeName(e);return t[n](e)}unwrap(e){return{any:n=>n.data,date:n=>new Date(n.data)}[e.type](e)}},fn=class{constructor(){this.namespaces={}}static createNamespace(e,t,n){return new nt(e,t,n)}addNamespace(e){if(!this.namespaces[e.key])return this.namespaces[e.key]=e,this}getNamespace(e){if(!this.namespaces[e])throw new b(`Namespace ${e} is not initialized, did you forget to register it?
5
- Use \`story.registerPersistent\` to register a persistent namespace`);return this.namespaces[e]}setNamespace(e,t){return this.namespaces[e]=t,this}hasNamespace(e){return!!this.namespaces[e]}removeNamespace(e){return delete this.namespaces[e],this}getNamespaces(){return this.namespaces}keys(){return Object.keys(this.namespaces)}values(){return Object.values(this.namespaces)}entries(){return Object.entries(this.namespaces)}toData(){return this.entries().reduce((e,[t,n])=>(e[t]=n.toData(),e),{})}load(e){if(!e){console.warn("No data to load");return}Object.entries(e).forEach(([t,n])=>{this.namespaces[t]?this.namespaces[t].load(n):this.namespaces[t]=new nt(t,n)})}clear(){return this.namespaces={},this}};var Re=class extends U{executeAction(e,t){let n={action:this,stackModel:t.stackModel};if(this.type===dt.play){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=g.forward(e.audioManager.play(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===dt.stop){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=g.forward(e.audioManager.stop(this.callee,i.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===dt.setVolume){let[i,r]=this.contentNode.getContent(),s=this.callee.toData(),a=g.forward(e.audioManager.setVolume(this.callee,i,r),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(a),e.actionHistory.push(n,c=>{c&&this.callee.fromData(c)},[s]),a}else if(this.type===dt.setRate){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=g.forward(e.audioManager.setRate(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===dt.pause){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=g.forward(e.audioManager.pause(this.callee,i.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===dt.resume){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=g.forward(e.audioManager.resume(this.callee,i.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===dt.mute){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=g.forward(e.audioManager.mute(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("SoundAction")}};Re.ActionTypes=dt;var Ct=(n=>(n.Voice="voice",n.Bgm="bgm",n.Sound="sound",n))(Ct||{}),oe=class oe extends X{static toSound(e){return e==null?null:typeof e=="string"?new oe({src:e}):e}static isSound(e){return e instanceof oe}static voice(e){let t=typeof e=="string"?{src:e}:e;return new oe({...t,type:"voice"})}static bgm(e){let t=typeof e=="string"?{src:e}:e;return new oe({...t,type:"bgm"})}static sound(e){let t=typeof e=="string"?{src:e}:e;return new oe({...t,type:"sound"})}constructor(e={}){super();let t=typeof e=="string"?{src:e}:e,n=oe.DefaultUserConfig.create(t),[i]=n.extract(oe.DefaultConfig.keys());this.config=i.get(),this.state=this.getInitialState(n),this.userConfig=n}play(e){if(this.config.type==="bgm")throw new ye(`Sound (src: ${this.config.src}) is marked as bgm, but it is being played as a normal sound.
6
- To prevent unintended behavior, the sound marked as bgm cannot be played using \`play()\`.`);return this.pushAction(Re.ActionTypes.play,[{end:this.state.volume,duration:e||0}])}stop(e){return this.pushAction(Re.ActionTypes.stop,[{end:0,duration:e||0}])}setVolume(e,t){return this.pushAction(Re.ActionTypes.setVolume,[e,t||0])}mute(e=!0){return this.pushAction(Re.ActionTypes.mute,[e])}unmute(){return this.mute(!1)}setRate(e){return this.pushAction(Re.ActionTypes.setRate,[e])}pause(e){return this.pushAction(Re.ActionTypes.pause,[{end:0,duration:e||0}])}resume(e){return this.pushAction(Re.ActionTypes.resume,[{end:this.state.volume,duration:e||0}])}getSrc(){return this.config.src}toData(){return{state:oe.StateSerializer.serialize(this.state)}}fromData(e){return this.state=oe.StateSerializer.deserialize(e.state),this}copy(){return new oe(this.userConfig.get())}reset(){return this.state=this.getInitialState(this.userConfig),this}getInitialState(e){return oe.DefaultState.create({...e.get()}).get()}pushAction(e,t){return this.chain(new Re(this.chain(),e,new v().setContent(t)))}};oe.noSound="data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgA",oe.DefaultUserConfig=new K({src:oe.noSound,loop:!1,volume:1,streaming:!1,rate:1,seek:0,type:"sound"}),oe.DefaultConfig=new K({src:oe.noSound,loop:!1,streaming:!1,seek:0,type:"sound"}),oe.DefaultState=new K({volume:1,rate:1,paused:!1,muted:!1}),oe.StateSerializer=new Le;var Z=oe;var ru={};var Qt=class extends qt{constructor(){super()}fromChained(e){return e.getActions()}forEachChild(e,t,n,i={}){let r=new Set,s=[];for(Array.isArray(t)?s.push(...t):s.push(t);s.length;){let a=s.shift();if(r.has(a))continue;r.add(a),n(a);let c=a.getFutureActions(e,i).filter(l=>!r.has(l));s.push(...c)}}getAllChildren(e,t,n={}){let i=[];return this.forEachChild(e,t,r=>i.push(r),n),i}getAllChildrenMap(e,t){let n=new Map;return this.forEachChild(e,t,i=>n.set(i.getId(),i)),n}getAllElementMap(e,t,n={}){let i=new Map;return this.forEachChild(e,t,r=>i.set(r.callee.getId(),r.callee),n),i}getAllChildrenElements(e,t,n={}){return Array.from(new Set(this.getAllChildren(e,t,n).map(i=>i.callee)))}toData(){return null}constructNodes(e,t){for(let n=0;n<e.length;n++){let i=e[n];n===0&&t?t.setChild(i.contentNode):n>0&&e[n-1].contentNode?.setChild(i.contentNode)}return e.length?e[0].contentNode:null}};var Nt=class Nt{constructor(){this.src=[];this.future=[]}static catSrc(e){let t=new Set,n=new Set,i=new Set;return e.forEach(({type:r,src:s})=>{r===Nt.SrcTypes.image?t.add(s):r===Nt.SrcTypes.video?n.add(s):i.add(s)}),{image:Array.from(t),video:Array.from(n),audio:Array.from(i)}}static getSrc(e){return typeof e=="string"?e:e instanceof G?G.getSrcURL(e):e.type==="image"?G.getSrcURL(e.src):e.type==="video"?e.src:e.type==="audio"?e.src.getSrc():""}static getPreloadableSrc(e,t){if(t.is(O,H.jumpTo)){let n=t.contentNode.getContent()[0],r=e.getScene(n,!0).state.backgroundImage;if(A.isImageURL(r.config.src))return{type:"image",src:r.config.src,activeType:"once"}}else if(t instanceof Y){let n=t;if(t.is(Y,Ge.setSrc)){let i=t.contentNode.getContent()[0];if(A.isImageSrc(i))return{type:"image",src:A.srcToURL(i),activeType:"scene"}}else{if(t.type===Ge.initWearable)return{type:"image",src:t.contentNode.getContent()[0],activeType:"scene"};if(t.type===Ge.setAppearance){let i=t.contentNode.getContent()[0];if(!n.callee.config.src||typeof n.callee.config.src?.resolve!="function")throw n.callee._invalidSrcHandlerError();if(G.isTagSrc(n.callee)&&i.length===n.callee.config.src.groups.length)return{type:"image",src:G.getSrcFromTags(i,n.callee.config.src.resolve),activeType:"scene"}}}}return null}register(e,t){if(Array.isArray(e))e.forEach(n=>this.register(n));else if(e instanceof Z){if(this.isSrcRegistered(e.getSrc()))return this;this.src.push({type:"audio",src:e})}else if(e instanceof G||A.isStaticImageData(e)){if(e instanceof G){if(!A.isImageURL(e.state.currentSrc))return this;if(this.isSrcRegistered(G.getSrcURL(e)))return this}else if(this.isSrcRegistered(A.srcToURL(e.src)))return this;this.src.push({type:"image",src:A.isStaticImageData(e)?A.srcToURL(e):e.state.currentSrc})}else if(typeof e=="object"){if(this.isSrcRegistered(e.src||""))return this;this.src.push(e)}else if(e==="audio"){if(this.isSrcRegistered(t||""))return this;this.src.push({type:e,src:t instanceof Z?t:new Z({src:t})})}else{if(this.isSrcRegistered(t||""))return this;this.src.push({type:e,src:t})}return this}registerRawSrc(e){return this.isSrcRegistered(e)?this:(this.src.push({type:"image",src:e}),this)}isSrcRegistered(e){if(!e)return!1;let t=e instanceof Z?e.getSrc():e;return this.src.some(n=>n.type===Nt.SrcTypes.audio?t===n.src.getSrc():n.type===Nt.SrcTypes.image?t===G.getSrcURL(n.src):t===n.src)}getSrc(){return[...this.src]}getSrcByType(e){return this.src.filter(t=>t.type===e)}registerFuture(e){return this.future.includes(e)||this.hasFuture(e)?this:(this.future.push(e),this)}hasFuture(e){return this.future.includes(e)}getFutureSrc(){return this.future.map(e=>e.getSrc()).flat(2)}};Nt.SrcTypes={image:"image",video:"video",audio:"audio"};var Ae=Nt;var At=class extends U{executeAction(e,t){let n={action:this,stackModel:t.stackModel};if(this.type===On.setText){let i=this.callee.state.text;return this.callee.state.text=this.contentNode.getContent()[0],e.getExposedStateForce(this.callee).flush(),e.actionHistory.push(n,r=>{this.callee.state.text=r},[i]),super.executeAction(e,t)}else if(this.type===On.setFontSize){let i=this.callee.state.fontSize;return this.callee.state.fontSize=this.contentNode.getContent()[0],e.getExposedStateForce(this.callee).flush(),e.actionHistory.push(n,r=>{this.callee.state.fontSize=r},[i]),super.executeAction(e,t)}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("TextAction")}};At.ActionTypes=On;var Se=class extends U{executeAction(e,t){if(this.type===he.applyTransform){let[n]=this.contentNode.getContent(),i=this.callee;return this.applyTransform(e,i,n,t)}else if(this.type===he.applyTransition){let[n,i]=this.contentNode.getContent(),r=this.callee,s=i?i(n):n;return this.applyTransition(e,r,s,t)}else if(this.type===he.init){let[n,i,r]=this.contentNode.getContent(),s=this.callee;return this.initDisplayable(e,n,s,i||null,r,t)}throw this.unknownTypeError()}applyTransform(e,t,n,i,r){let s=new g().registerSkipController(new M(()=>(e.logger.info("Displayable Transition","Skipped"),super.executeAction(e,i)))),a=e.getExposedStateForce(t),c=t.transformState.clone(),l=a.applyTransform(n,()=>{r?.(),s.resolve(super.executeAction(e,i))}),u=e.timelines.attachTimeline(s).attachChild(l);return e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:u},m=>{s.isSettled()||s.abort(),l.abort(),t.transformState.forceOverwrite(m.state)},[c]),s}applyTransition(e,t,n,i,r){let s=new g().registerSkipController(new M(()=>(e.logger.info("Displayable Transition","Skipped"),super.executeAction(e,i)))),c=e.getExposedStateForce(t).applyTransition(n,()=>{r?.(),s.resolve(super.executeAction(e,i))}),l=e.timelines.attachTimeline(s).attachChild(c);return e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:l},()=>{s.isSettled()||s.abort(),c.abort()}),s}initDisplayable(e,t,n,i,r=!0,s){if(r!==!1){let l=e.findElementByDisplayable(this.callee,i);l&&e.disposeDisplayable(n,l.scene,i),e.createDisplayable(n,t,i)}e.flush();let a=new g().registerSkipController(new M(()=>super.executeAction(e,s)));e.getExposedStateAsync(n,l=>{l.initDisplayable(()=>{a.resolve(super.executeAction(e,s))})});let c=e.timelines.attachTimeline(a);return e.actionHistory.push({action:this,stackModel:s.stackModel,timeline:c},()=>{r!==!1&&e.findElementByDisplayable(n,i)&&e.disposeDisplayable(n,t,i)}),a}stringify(e,t,n){return super.stringifyWithName("DisplayableAction")}};Se.ActionTypes=he;var it=class extends X{constructor(){super(...arguments);this.srcManager=new Ae}pos(t,n,i){return this.transform(new z({position:t},{duration:n,ease:i}))}zoom(t,n,i){return this.transform(new z({zoom:t},{duration:n,ease:i}))}scaleX(t,n,i){return this.transform(new z({scaleX:t},{duration:n,ease:i}))}scaleY(t,n,i){return this.transform(new z({scaleY:t},{duration:n,ease:i}))}scale(t,n,i,r){return this.transform(new z({scaleX:t,scaleY:n},{duration:i,ease:r}))}scaleXY(t,n,i,r){return this.scale(t,n,i,r)}rotate(t,n,i){return this.transform(new z({rotation:t},{duration:n,ease:i}))}opacity(t,n,i){return this.transform(new z({opacity:t},{duration:n,ease:i}))}transform(t){let n=this.chain(),i=new Se(n,he.applyTransform,new v().setContent([t.copy()]));return n.chain(i)}show(t){let n=this.chain(),i=t instanceof z?t.copy():new z({opacity:1},t),r=new Se(n,he.applyTransform,new v().setContent([i]));return n.chain(r)}hide(t){let n=this.chain(),i=t instanceof z?t.copy():new z({opacity:0},t),r=new Se(n,he.applyTransform,new v().setContent([i]));return n.chain(r)}};var Mt=(t=>(t[t.Number=0]="Number",t[t.HexColor=1]="HexColor",t))(Mt||{});import{animate as Hs}from"motion/react";var ot=class{requestAnimations(e){let t=e.map(m=>m.start),n=[],i=0,r=[],s=[],a=[];return{onUpdate:m=>(r.push(m),{cancel:()=>{let p=r.indexOf(m);p!==-1&&r.splice(p,1)}}),onComplete:m=>(s.push(m),{cancel:()=>{let p=s.indexOf(m);p!==-1&&s.splice(p,1)}}),onCanceled:m=>(a.push(m),{cancel:()=>{let p=a.indexOf(m);p!==-1&&a.splice(p,1)}}),complete:()=>{i!==e.length&&n.forEach(m=>m.complete())},start:()=>{if(n.length>0)throw new Error("Animation controllers are already started");e.forEach((m,p)=>{n.push(this.requestMotion(m,{onComplete:()=>{t[p]=m.end,r.forEach(h=>h(t)),i++,i===e.length&&s.forEach(h=>h())},onUpdate:h=>{t[p]=h,r.forEach(d=>d(t))}}))})},cancel:()=>{n.forEach(m=>m.cancel()),a.forEach(m=>m())}}}toFinalStyle(e){return e.resolve.map(t=>typeof t=="function"?t(...e.animations.map(n=>n.end)):t.resolver(...e.animations.map(n=>n.end)))}asPrev(e){return{resolver:e,key:"current"}}asTarget(e){return{resolver:e,key:"target"}}requestMotion(e,t){return Hs(e.start,e.end,{duration:e.duration/1e3,onUpdate:n=>{t.onUpdate&&t.onUpdate(n)},onComplete:()=>{t.onComplete&&t.onComplete()},ease:e.ease})}};ot.AnimationType=Mt;var hn=class extends ot{_setElement(e){return this._element=e,this}getTextState(){if(this._element===void 0)throw new b(`Trying to access text state, but element is not set
7
- This should not happen, please report this issue to the developers`);return this._element.state}};var _n=class o extends hn{constructor(t,n,i){super();this.textSize=t;this.duration=n;this.easing=i}createTask(){return{animations:[{type:0,start:this.getTextState().fontSize,end:this.textSize,duration:this.duration,ease:this.easing}],resolve:[this.asTarget(t=>({style:{fontSize:`${t}px`}}))]}}copy(){return new o(this.textSize,this.duration,this.easing)}};var Ne=class Ne extends it{constructor(e,t={}){super();let n=typeof e=="string"?{...t,text:e}:e,i=Ne.DefaultUserConfig.create(n),r=Ne.DefaultTextConfig.create(i.get());this.userConfig=i,this.config=r.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(i)}setText(e){let t=this.chain(),n=new At(t,At.ActionTypes.setText,new v().setContent([e]));return t.chain(n)}setFontColor(e,t=0,n){return this.transform(new z({fontColor:e},{duration:t,ease:n}))}setFontSize(e,t=0,n){return this.combineActions(new He,i=>{if(t){let s=new _n(e,t,n);i.chain(this._applyTransition(i,s))}let r=new At(i,At.ActionTypes.setFontSize,new v().setContent([e]));return i.chain(r)})}useLayer(e){return this.userConfig.get().layer=e,Object.assign(this.config,{layer:e}),this}toData(){return{state:Ne.StateSerializer.serialize(this.state),transformState:this.transformState.serialize()}}fromData(e){return this.state=Ne.StateSerializer.deserialize(e.state),this.transformState=me.deserialize(e.transformState),this}_init(e){return new Se(this.chain(),he.init,new v().setContent([e||null,this.config.layer||null]))}reset(){this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(this.userConfig)}getInitialTransformState(e){let[t]=e.extract(Ne.DefaultTextTransformState.keys());return new me(Ne.DefaultTextTransformState.create(t.get()).get())}_applyTransition(e,t){return new Se(e,he.applyTransition,new v().setContent([t,n=>n._setElement(this)]))}getInitialState(){return Ne.DefaultTextState.create({fontSize:this.userConfig.get().fontSize,text:this.userConfig.get().text}).get()}};Ne.DefaultUserConfig=new K({alignX:"center",alignY:"center",className:"",fontSize:16,fontColor:"#000000",text:""}),Ne.DefaultTextConfig=new K({alignX:"center",alignY:"center",className:"",layer:void 0}),Ne.DefaultTextState=new K({fontSize:16,display:!1,text:""}),Ne.DefaultTextTransformState=new K({fontColor:"#000000",...me.DefaultTransformState.getDefaultConfig()}),Ne.StateSerializer=new Le;var Gt=Ne;var gn=class gn extends U{executeAction(e,t){let n=this;if(n.is(gn,"persistent:set")){let[i,r]=n.contentNode.getContent(),s=e.getStorable().getNamespace(n.callee.getNamespaceName()),a=s.get(i);if(typeof r=="function"){let c=s.get(i);s.set(i,r(c))}else s.set(i,r);return e.actionHistory.push({action:this,stackModel:t.stackModel},c=>{s.set(i,c)},[a]),super.executeAction(e,t)}else if(n.is(gn,"persistent:assign")){let[i]=n.contentNode.getContent(),r=e.getStorable().getNamespace(n.callee.getNamespaceName()),s={},a=typeof i=="function"?i(r.getContent()):i;return Object.keys(a).forEach(c=>{s[c]=r.get(c),r.set(c,a[c])}),e.actionHistory.push({action:this,stackModel:t.stackModel},c=>{Object.keys(c).forEach(l=>{r.set(l,c[l])})},[s]),super.executeAction(e,t)}throw this.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("PersistentAction")}};gn.ActionTypes=ln;var ei=gn;var Pe=class o{static from(e){return o.isPauseConstructor(e)?new o:e}static wait(e){return new o({duration:e})}static isPause(e){return this.isPauseConstructor(e)||e instanceof o}static isPauseConstructor(e){return e===o}constructor(e={}){this.config=e}};var ve=class ve{static isWord(e){return e instanceof ve}static color(e,t){return ve.isWord(e)?e.copy().assign({color:t}):new ve(e,{color:t})}static bold(e){return ve.isWord(e)?e.copy().assign({bold:!0}):new ve(e,{bold:!0})}static italic(e){return ve.isWord(e)?e.copy().assign({italic:!0}):new ve(e,{italic:!0})}static getText(e){return e.filter(t=>!t.isPause()).map(t=>t.toString()).join("")}constructor(e,t={}){this.text=e,this.config=I(ve.defaultConfig,t)}evaluate(e){if(Pe.isPause(this.text))return[this];if(typeof this.text=="function"){let t=this.text(e);return Array.isArray(t)?t.map(n=>ve.isWord(n)?n.inherit(this.config).evaluate(e):new ve(n,this.config)).flat():ve.isWord(t)?t.inherit(this.config).evaluate(e):[new ve(t,this.config)]}return[this]}inherit(e){return this.config.color=this.config.color||e.color,this.config.italic=this.config.italic??e.italic,this.config.bold=this.config.bold??e.bold,this.config.cps=this.config.cps??e.cps,this}assign(e){return this.config=I(this.config,e),this}copy(){return new ve(this.text,this.config)}isPause(){return Pe.isPause(this.text)}toString(){return typeof this.text=="string"?this.text:""}};ve.defaultConfig={},ve.defaultColor="#000";var F=ve;var Me=class Me{static isSentence(e){return e instanceof Me}static toSentence(e){return Me.isSentence(e)?e:new Me(e)}static format(e){let t=[];if(Array.isArray(e))for(let n=0;n<e.length;n++)t.push(this.formatWord(e[n]));else t.push(this.formatWord(e));return t}static formatWord(e){return F.isWord(e)?e:new F(e)}static formatStaticWord(e,t){return Array.isArray(e)?e.map(n=>this.formatStaticWord(n,t)).flat(2):[F.isWord(e)?e:new F(e,t)]}static isSentencePrompt(e){return Array.isArray(e)?e.every(Me.isSingleWord):Me.isSingleWord(e)}static isSingleWord(e){return typeof e=="string"||F.isWord(e)||Pe.isPause(e)||typeof e=="function"}constructor(e,t={}){this.text=Me.format(e),this.config=I(Me.defaultConfig,{...t,voice:typeof t.voice=="string"?Z.voice(t.voice):Z.toSound(t.voice)}),this.state=Yo(Me.defaultState)}toData(){return null}fromData(e){return this.state=I(this.state,e),this}toString(){return this.text.map(e=>e.text).join("")}setCharacter(e){return this.config.character=e,this}evaluate(e){let t=[];for(let n=0;n<this.text.length;n++){let i=this.text[n].evaluate(e);t.push(...Me.formatStaticWord(i))}return t}copy(){return new Me([...this.text],this.config)}};Me.defaultConfig={pause:!0,voice:null,character:null,voiceId:null},Me.defaultState={};var ne=Me;var xt=class extends U{executeAction(e,t){let n=this.contentNode.getContent().execute({gameState:e});return n&&e.actionHistory.push({action:this,stackModel:t.stackModel},()=>{n()},[]),super.executeAction(e,t)}stringify(e,t,n){return super.stringifyWithName("ScriptAction")}};xt.ActionTypes=qo;var re=class o extends X{static getCtx({gameState:e}){let t=e.game.getLiveGame(),n=t.getStorable();return{gameState:e,game:e.game,liveGame:t,storable:n,$:i=>n.getNamespace(i)}}static execute(e){return new o(e)}constructor(e){super(),this.handler=e;let t=this.chain(),n=new xt(t,xt.ActionTypes.action,new v().setContent(this));return this.chain(n)}execute({gameState:e}){return this.handler(o.getCtx({gameState:e}))}fromChained(e){return[new xt(this.chain(),xt.ActionTypes.action,new v().setContent(e))]}};var ti=class{constructor(e){this.config=e;this.watching=null;this.warnings=[]}observe(e){return this.watching=e,this}warn(e,t){return this.warnings.push([e,t]),this.watching?.logger.warn(t),t}getWarnings(){return[...this.warnings]}};var fe=class o{constructor(e,t){this.awaitable=e;this.guard=t;this.children=[];this._onResolved=[];this._onCancelled=[];this._onTimelineRegistered=[];this._ableToAttach=!0;this._status="pending";e.onSettled(()=>{this.resolveStatus()}),ze(()=>{this.preventAttach()})}static proxy(e){let t=new g,n=new g,i=new o(n);return i.onTimelineRegistered(()=>{n.resolve()}).onSettled(()=>{let[r,s]=i.catSettled();e(r,s)}),t.onSkipControllerRegister(r=>{r.onAbort(()=>{i.abort()})}),[t,i]}static any(e){if(e.length===0)throw new b("Cannot create an 'any' timeline with no awaitables.");let t=new g,n=new g,i=new o(n),r=!1;for(let s of e)i.attachChild(s),s.then(a=>{r||(r=!0,t.resolve(a))});return t.onSkipControllerRegister(s=>{s.onAbort(()=>{i.abort()})}),[t,i]}static all(e){if(e.length===0)throw new b("Cannot create an 'all' timeline with no awaitables.");let t=new g,n=new g,i=new o(n),r=new Array(e.length),s=0;for(let a=0;a<e.length;a++){let c=e[a];i.attachChild(c),c.then(l=>{r[a]=l,s++,s===e.length&&t.resolve(r)})}return t.onSkipControllerRegister(a=>{a.onAbort(()=>{i.abort()})}),[t,i]}static sequence(e,t){let n=t,i=null,r=new g,s=()=>{if(i){let a;i.onSkipControllerRegister(c=>{a=c.onAbort(()=>{r.abort()})}),i.then(c=>{a?.cancel(),n=c,i=e(c),i?ze(()=>s()):r.resolve(n)})}else r.resolve(n)};return r.registerSkipController(new M(()=>(i&&i.abort(),t))),i=e(t),i?ze(()=>s()):ze(()=>r.resolve(n)),r}get status(){return this._status}isSettled(){return this._status!=="pending"}isResolved(){return this._status==="resolved"}isCancelled(){return this._status==="cancelled"}onResolved(e){this._onResolved.push(e)}onCancelled(e){this._onCancelled.push(e)}onSettled(e){this.isSettled()?ze(e):(this.onResolved(e),this.onCancelled(e))}abort(){this.isSettled()||(this.awaitable.abort(),this.setStatus("cancelled",this.emitEvents.bind(this)),this.children.forEach(e=>e.abort()))}attachChild(e){if(!this._ableToAttach)throw new b(`Attaching to this timeline violates the timeline's state.
3
+ `).trim():""}function _n(o){return new Promise(e=>setTimeout(e,o))}var Zn=class Zn{constructor(e){this.abortHandler=e;this.events=new J;this.aborted=!1}abort(...e){this.aborted||(this.aborted=!0,this.abortHandler(...e),this.events.emit(Zn.EventTypes["event:skipController.abort"]))}isAborted(){return this.aborted}cancel(){this.aborted=!0}onAbort(e){return this.events.on("event:skipController.abort",e)}};Zn.EventTypes={"event:skipController.abort":"event:skipController.abort"};var G=Zn;var vn=class{constructor(){this.locked=!1;this.listeners=[];this.unlockListeners=[]}lock(){return this.locked=!0,this}unlock(){this.locked=!1;for(let e of this.listeners)e();for(let e of this.unlockListeners)e();return this.listeners=[],this}onUnlock(e){return this.unlockListeners.push(e),e}offUnlock(e){this.unlockListeners=this.unlockListeners.filter(t=>t!==e)}async nextUnlock(){if(this.locked)return new Promise(e=>{this.listeners.push(e)})}isLocked(){return this.locked}},_t=class{constructor(){this.locks=[]}unlock(e){return e.unlock(),this.off(e),e}register(e){let t=e||new vn;return this.locks.push(t),t}off(e){this.locks=this.locks.filter(t=>t!==e)}async nextUnlock(){let e=this.locks.map(t=>t.nextUnlock());return Promise.all(e)}isLocked(){return this.locks.some(e=>e.isLocked())}};function ei(o,e,t={}){return o?e:t}function ur(o,e){if(e<=0)return o;let t=null;return function(...n){t&&clearTimeout(t),t=setTimeout(()=>{o(...n)},e)}}var qn=class{constructor(){this.taskToken=null}scheduleTask(e,t){this.taskToken&&this.taskToken.cancel();let n=!1,i=setTimeout(()=>{n||e()},t);return this.taskToken={cancel:()=>{clearTimeout(i),n=!0},isCancelled:()=>n},this.taskToken}cancelTask(){return this.taskToken&&(this.taskToken.cancel(),this.taskToken=null),this}};function pr(o,e){let t=[];for(let n=0;n<Math.max(o.length,e.length);n++)n<o.length&&t.push(o[n]),n<e.length&&t.push(e[n]);return t}async function dr(o,e){return new Promise((t,n)=>{fetch(o,e).then(i=>i.blob()).then(i=>{let r=new FileReader;r.onload=()=>{t(r.result)},r.readAsDataURL(i)}).catch(n)})}var Sn=class{constructor(e,t){this.concurrency=e;this.delay=t;this.tasks=[]}addTask(e){this.tasks.push(e)}async start(){let e=async()=>{if(this.tasks.length===0)return;let t=this.tasks.splice(0,this.concurrency);await Promise.all(t.map(n=>n())),await _n(this.delay),await e()};await e()}};function We(o){let e,t=Promise.resolve().then(()=>{e=o()});return()=>{t.then(()=>{e&&e()})}}function mr(o,e){let t={};for(let n in o)e.includes(n)||(t[n]=o[n]);return t}var He=class o{constructor(e={},t={}){this.serializer=e;this.deserializer=t}serialize(e){let t={};for(let n of Object.keys(e))n in this.serializer&&e[n]!==void 0?t[n]=this.serializer[n]?.(e[n]):t[n]=e[n];return t}deserialize(e){let t={};for(let n of Object.keys(e))typeof this.deserializer[n]=="function"&&e[n]!==void 0?t[n]=this.deserializer[n](e[n]):t[n]=e[n];return t}extend(e,t){let n={...this.serializer,...e},i={...this.deserializer,...t};return new o(n,i)}};function fr(o){return["aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkgrey","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkslategrey","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dimgrey","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","green","greenyellow","grey","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightgrey","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightslategrey","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","slategrey","snow","springgreen","steelblue","tan","teal","thistle","tomato","transparent","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen"].includes(o)}function hr(o){return o.constructor.name==="AsyncFunction"||Object.prototype.toString.call(o)==="[object AsyncFunction]"}function _i(o){let e={};for(let t in o)o[t]!==void 0&&(e[t]=o[t]);return e}function eo(o,e=new WeakSet){if(o===null||typeof o!="object"||Array.isArray(o)||o instanceof Date||o instanceof RegExp||Object.getPrototypeOf(o)!==Object.prototype||e.has(o))return!1;e.add(o);for(let t in o)if(Object.prototype.hasOwnProperty.call(o,t)){let n=o[t];if(n!==null&&typeof n=="object"&&!eo(n,e)||typeof n=="function"||typeof n=="symbol")return!1}return!0}var Qn=class{constructor(e=""){this.prefix=e;this.counter=0}next(){return`${this.prefix?this.prefix+"-":""}${this.counter++}`}};function gr(o=16){let e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=t.length;for(let i=0;i<o;i++)e+=t.charAt(Math.floor(Math.random()*n));return e}function yr(o=16){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",t="";for(let n=0;n<o;n++)t+=e[Math.floor(Math.random()*e.length)];return t}var Xn=class{constructor(e=""){this.prefix=e;this.counter=0}generateId(){return`${this.prefix?this.prefix+"-":""}${this.counter++}`}},Yn=class{constructor(){this.hooks={}}hook(e,t){return this.hooks[e]=this.hooks[e]||[],this.hooks[e].push(t),{cancel:()=>this.unhook(e,t)}}unhook(e,t){this.hooks[e]=this.hooks[e]?.filter(n=>n!==t)||[]}trigger(e,t){let n=this.hooks[e];if(!n)return()=>{};let i=n.map(r=>r(...t));return()=>{i.forEach(r=>r&&r())}}rawTrigger(e,t){let n=this.hooks[e];if(!n)return()=>{};let i=n.map(r=>r(...t()));return()=>{i.forEach(r=>r&&r())}}};var Jn=class{constructor(e){this.items=[];this.pushValidator=[];e&&(this.items=[...e])}addPushValidator(e){return this.pushValidator.push(e),this}removePushValidator(e){this.pushValidator=this.pushValidator.filter(t=>t!==e)}push(...e){for(let t of e)this.pushValidator.some(n=>!n(t))||this.items.push(t)}pop(){return this.items.pop()}peek(){return this.items[this.items.length-1]}isEmpty(){return this.items.length===0}size(){return this.items.length}clear(){this.items=[]}toArray(){return[...this.items]}forEach(e){this.items.forEach(e)}forEachReverse(e){for(let t=this.items.length-1;t>=0;t--)e(this.items[t])}map(e){return this.items.map(e)}get(e){return this.items[e]}};function vr(o,e){let t={},n=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&(e.includes(i)?n.push(i):t[i]=o[i]);return[t,n]}function Sr(o){let e=3421674724,t=2216829733;for(let n=0;n<o.length;n++){let i=o.charCodeAt(n);e^=i;let r=e>>>0,s=t>>>0,a=435,c=16777216,l=r*a>>>0,p=r*c+s*a>>>0,u=s*c+(p>>>0)>>>0;e=l,t=u}return("00000000"+t.toString(16)).slice(-8)+("00000000"+e.toString(16)).slice(-8)}var Tn=class{constructor(e,t,n){this.callee=e,this.type=t,this.contentNode=n,this.__stack=Zi(),this._id="",this._staticId=null}executeAction(e,t){return{type:this.type,node:this.contentNode.getChild()}}getId(){return this._id}setId(e){this._id=e}getStaticId(){return this._staticId}setStaticId(e){return this._staticId=e,this}resolveId(e){return this.setId(this._staticId||e),this}setContent(e){return this.contentNode.setContent(e),this}setContentNode(e){return this.contentNode=e,this}getFutureActions(e,t){let n=this.contentNode.getChild();return n&&n.action?[n.action]:[]}};Tn.ActionTypes={action:"action"};var O=class extends Tn{constructor(e,t,n){super(e,t,n),this.callee=e.getSelf(),this.contentNode.action=this}unknownTypeError(){throw new Error("Unknown action type: "+this.type)}resolveAwaitable(e,t){let n=t||new y(i=>i);return(async()=>await e(n.resolve.bind(n),n))(),n}is(e,t){return this instanceof e&&this.type===t}stringify(e,t,n){return this.stringifyWithName("Action")}stringifyWithName(e){return`${e}#${this._id}(${this.type})`}stringifyWithContent(e,t){return`${e}#${this._id}(${this.type}){${t}}`}};var to=class{constructor(e){this.type=e,this.content=void 0}setContent(e){return this.content=e,this}getContent(){return this.content}},b=class o extends to{static create(e){return new o().setContent(e)}static forEachParent(e,t){let n=new Set,i=e;for(;i&&!n.has(i);)n.add(i),t(i),i=i.getParent()}static forEachChild(e,t){let n=new Set,i=e;for(;i&&!n.has(i);)n.add(i),t(i),i=i.getChild()}constructor(e,t,n){super("ContentNode"),this.child=n||null,this.parent=t||null,this.action=e||null}setParent(e){if(e===this)throw new Error("Cannot set parent to itself");return this.parent&&this.parent.setChild(null),this.parent=e,this}setChild(e){if(e===this)throw new Error("Cannot set child to itself");return this.child&&(this.child.parent=null),this.child=e,e&&e.parent!==this&&(e.remove(),e.parent=this),this}getChild(){return this.child||null}getParent(){return this.parent||null}addChild(e){return this.setChild(e),this}removeChild(e){return e&&this.child===e?(this.child=null,e.setParent(null)):e||(this.child=null),this}remove(){return this.parent&&this.parent.removeChild(this),this.child&&this.child.setParent(null),this}hasChild(){return!!this.child}};var ti={center:"center",left:"left",right:"right"};import{animate as Js}from"motion/react";var bn=(n=>(n.Left="left",n.Center="center",n.Right="right",n))(bn||{}),Tr={left:"33.33%",center:"50%",right:"66.66%"},je=class je{static isUnknown(e){return e===je.Unknown}static D2PositionToCSS(e,t=!1,n=!1){let i=this.calc(e.y,e.yoffset),r=this.calc(e.x,e.xoffset),s=n?{bottom:i}:{top:i},a=t?{right:r}:{left:r};return this.wrap({...s,...a})}static calc(e,t){return!e||je.isUnknown(e)?"auto":t===void 0||je.isUnknown(t)?`calc(${e} + 0px)`:`calc(${typeof e=="number"?`${e}px`:e} + ${t}px)`}static toCoord2D(e){if(qe.isCommonPositionType(e))return Ue.fromCommonPosition(e);if(Ue.isCoord2DPosition(e))return e;if(Ft.isAlignPosition(e))return Ue.fromAlignPosition(e);if(typeof e=="object"&&["x","y","xoffset","yoffset"].some(t=>t in e)){let t=e;return new Ue(t)}else throw new Error("Invalid position type")}static orUnknown(e){return je.isUnknown(e)||e===void 0?je.Unknown:e}static mergePosition(e,t){let n=this.toCoord2D(e),i=this.toCoord2D(t);return Ue.merge(n,i)}static serializePosition(e){let t=this.toCoord2D(e);return{x:je.isUnknown(t.x)?0:t.x,y:je.isUnknown(t.y)?0:t.y,xoffset:je.isUnknown(t.xoffset)?0:t.xoffset,yoffset:je.isUnknown(t.yoffset)?0:t.yoffset}}static isRawCommonPositionType(e){return Object.values(bn).includes(e)}static isRawCoord2DPosition(e){return typeof e=="object"&&("x"in e||"y"in e||"xoffset"in e||"yoffset"in e)}static isRawAlignPosition(e){return typeof e=="object"&&("xalign"in e||"yalign"in e||"xoffset"in e||"yoffset"in e)}static isRawPosition(e){return this.isRawCommonPositionType(e)||this.isRawCoord2DPosition(e)||this.isRawAlignPosition(e)}static isPosition(e){return e instanceof qe||e instanceof Ue||e instanceof Ft}static rawPositionToCoord2D(e){if(this.isRawCommonPositionType(e))return Ue.fromCommonPosition(new qe(e));if(this.isRawCoord2DPosition(e))return new Ue(e);if(this.isRawAlignPosition(e))return Ue.fromAlignPosition(e);throw new Error("Invalid position type")}static tryParsePosition(e){if(this.isPosition(e))return e;if(this.isRawPosition(e))return this.rawPositionToCoord2D(e);throw new Error("Invalid position type")}static wrap(e){return{left:"auto",top:"auto",right:"auto",bottom:"auto",...e}}};je.Unknown=Symbol("Unknown");var D=je,ni=class ni{static isCommonPositionType(e){return e instanceof ni}constructor(e){this.position=e}toCSS(){return{x:Tr[this.position],y:"50%",xoffset:0,yoffset:0}}};ni.Positions=bn;var qe=ni,Ue=class o{static isCoord2DPosition(e){return e instanceof o}static fromCommonPosition(e){return new o({x:Tr[e.position],y:"50%"})}static fromAlignPosition(e){let t=n=>!n||D.isUnknown(n)?D.Unknown:`${n*100}%`;return new o({x:t(e.xalign),y:t(e.yalign),xoffset:e.xoffset,yoffset:e.yoffset})}static merge(e,t){return new o({x:D.isUnknown(t.x)?e.x:t.x,y:D.isUnknown(t.y)?e.y:t.y,xoffset:D.isUnknown(t.xoffset)?e.xoffset:t.xoffset,yoffset:D.isUnknown(t.yoffset)?e.yoffset:t.yoffset})}constructor(e,t){typeof e=="object"?(this.x=D.orUnknown(e.x),this.y=D.orUnknown(e.y),this.xoffset=D.orUnknown(e.xoffset),this.yoffset=D.orUnknown(e.yoffset)):(this.x=D.orUnknown(e),this.y=D.orUnknown(t),this.xoffset=D.Unknown,this.yoffset=D.Unknown),this.check()}check(){let e=t=>/^-?\d+(\.\d+)?%$/.test(t);if(typeof this.x=="string"&&!e(this.x))throw new Error(`Invalid x position: ${this.x}`);if(typeof this.y=="string"&&!e(this.y))throw new Error(`Invalid y position: ${this.y}`)}toCSS(){return{x:this.x,y:this.y,xoffset:this.xoffset,yoffset:this.yoffset}}},Ft=class o{static isAlignPosition(e){return e instanceof o}constructor(e,t){typeof e=="object"?(this.xalign=D.orUnknown(e.xalign),this.yalign=D.orUnknown(e.yalign),this.xoffset=D.orUnknown(e.xoffset),this.yoffset=D.orUnknown(e.yoffset)):(this.xalign=D.orUnknown(e),this.yalign=D.orUnknown(t),this.xoffset=D.Unknown,this.yoffset=D.Unknown),this.check()}check(){if(typeof this.xalign=="number"&&isNaN(this.xalign))throw new Error("Invalid xalign position: "+this.xalign);if(typeof this.yalign=="number"&&isNaN(this.yalign))throw new Error("Invalid yalign position: "+this.yalign)}toCSS(){return{x:D.isUnknown(this.xalign)?this.xalign:`${this.xalign*100}%`,y:D.isUnknown(this.yalign)?this.yalign:`${this.yalign*100}%`,xoffset:this.xoffset,yoffset:this.yoffset}}};var j=class o{constructor(e,t){this.defaultConfig=e;this.handlers=t||{}}create(e={}){return new no(this.mergeWithDefaultConfig(e))}copy(){return new o(H({},this.defaultConfig),this.handlers)}keys(){return Object.keys(this.defaultConfig)}getDefaultConfig(){return this.defaultConfig}mergeWithDefaultConfig(e){return Object.fromEntries(Object.entries(this.defaultConfig).map(([t,n])=>[t,this.mergeValue(t,n,e[t])]))}mergeValue(e,t,n){return this.isPlainObject(n)?H({},n):Array.isArray(t)?Array.isArray(n)&&n.length>0?[...n]:[...t]:n!==void 0?this.applyHandler(e,n):t}isPlainObject(e){return typeof e=="object"&&!Array.isArray(e)&&e!==null&&Object.getPrototypeOf(e)===Object.prototype}applyHandler(e,t){return typeof this.handlers[e]=="function"?this.handlers[e](t):t}},no=class o{constructor(e){this.config=e}get(){return this.config}copy(){return new o(H({},this.config))}join(e){let t=mr(this.config,Object.keys(e));return new o(Object.assign(t,e instanceof o?e.get():e))}extract(e){let t={},n={};for(let i of e)t[i]=this.config[i];for(let i in this.config)e.includes(i)||(n[i]=this.config[i]);return[new o(t),new o(n)]}assign(e){return new o(Object.assign({},this.config,e))}};var Zs={[ti.left]:"25.33%",[ti.center]:"50%",[ti.right]:"75.66%"},Je=class Je{constructor(e={}){this.state={};this.locked=null;this.frozen=!1;this.state=e}static deserialize(e){return new Je(Je.TransformStateSerializer.deserialize(e))}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?D.toCoord2D(D.tryParsePosition(e||t)):D.mergePosition(D.tryParsePosition(e),D.tryParsePosition(t))}static mergeState(e,t){if("position"in e&&"position"in t){let n=this.mergePosition(e.position,t.position);return{...Object.assign({},e,t),position:n}}return{...Object.assign({},e,t)}}get(){return this.state}freeze(){return this.frozen=!0,this}assign(e,t){if(this.frozen)throw new Error("Trying to write a frozen transform state.");if(!this.canWrite(e))throw new Error("Trying to write a locked transform state.");return this.state=Je.mergeState(this.state,t),this}lock(){if(this.locked)throw new Error("Transform state is already locked.");return this.locked=Symbol(),this.locked}isLocked(){return!!this.locked}canWrite(e){return this.locked===null||this.locked===e}unlock(e){return this.locked===e&&(this.locked=null),this}toFramesDefinition(e,t){return _i(q.constructStyle(e,this.state,t))}toStyle(e,t){return _i(q.constructStyle(e,this.state,t))}serialize(){return Je.TransformStateSerializer.serialize(this.state)}clone(){return new Je(Je.mergeState({},this.state))}overwrite(e,t){if(this.frozen)throw new Error("Trying to write a frozen transform state.");if(!this.canWrite(e))throw new Error("Trying to write a locked transform state.");return this.state=Je.mergeState(this.state,t),this}forceOverwrite(e){return this.state=e,this}};Je.DefaultTransformState=new j({scaleX:1,scaleY:1,zoom:1,rotation:0,position:new qe("center"),opacity:0,alt:"",maskImage:void 0,maskSize:void 0,maskPosition:void 0,maskRepeat:void 0,maskMode:void 0,clipPath:void 0,filter:void 0,backdropFilter:void 0,mixBlendMode:void 0}),Je.TransformStateSerializer=new He({position:e=>D.serializePosition(D.tryParsePosition(e))},{position:e=>D.toCoord2D(e)});var me=Je,de=class de{constructor(e,t){this.sequences=[];this.stagedChanges=[];if(Array.isArray(e))this.sequences.push(...e),this.config=Object.assign({},de.defaultConfig,t||{});else{let[n,i]=[e,t||de.defaultOptions];this.sequences.push({props:n,options:i||de.defaultOptions}),this.config=Object.assign({},de.defaultConfig)}}static isPosition(e){return qe.isCommonPositionType(e)||Ue.isCoord2DPosition(e)||Ft.isAlignPosition(e)}static immediate(e){return new de(e,{duration:0,ease:"linear"})}static left(e,t){return new de({position:qe.Positions.Left},{duration:e,ease:t})}static right(e,t){return new de({position:qe.Positions.Right},{duration:e,ease:t})}static center(e,t){return new de({position:qe.Positions.Center},{duration:e,ease:t})}static create(e){return new de([],e)}static positionToCSS(e,t,n){return e?D.isRawPosition(e)?D.D2PositionToCSS(D.rawPositionToCoord2D(e),n,t):D.D2PositionToCSS(e.toCSS(),n,t):{}}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?D.toCoord2D(D.tryParsePosition(e||t)):D.mergePosition(D.tryParsePosition(e),D.tryParsePosition(t))}static mergeState(e,t){let n=this.mergePosition(e.position,t.position);return{...H(e,t),position:n}}static propToCSSTransform(e,t,n){let{invertY:i,invertX:r}=e.getStory().getInversionConfig(),{translate:s=[]}=n||{},a=t.zoom??1,c=function(d,h,m){return typeof d>"u"?typeof m<"u"?h(m):"":h(d)},l=s[0]||(r?"":"-")+"50%",p=s[1]||(i?"":"-")+"50%";return[`translate(${l}, ${p})`,c(t.rotation,d=>`rotate(${d}deg)`,0),c(t.scaleX,d=>`scaleX(${d*a})`,1),c(t.scaleY,d=>`scaleY(${d*a})`,1)].filter(Boolean).join(" ")}static constructStyle(e,t,n){let{invertY:i,invertX:r}=e.getStory().getInversionConfig(),{overwrite:s}=n||{};return{...de.positionToCSS(t.position,i,r),opacity:t.opacity,color:"fontColor"in t&&t.fontColor?Ye(t.fontColor):void 0,transform:de.propToCSSTransform(e,t),...de.constructVisualEffectStyle(t),...s?s(t):{}}}static constructVisualEffectStyle(e){let t=e;return{maskImage:t.maskImage,WebkitMaskImage:t.maskImage,maskSize:t.maskSize,WebkitMaskSize:t.maskSize,maskPosition:t.maskPosition,WebkitMaskPosition:t.maskPosition,maskRepeat:t.maskRepeat,WebkitMaskRepeat:t.maskRepeat,maskMode:t.maskMode,WebkitMaskMode:t.maskMode,clipPath:t.clipPath,filter:t.filter,backdropFilter:t.backdropFilter,WebkitBackdropFilter:t.backdropFilter,mixBlendMode:t.mixBlendMode}}animate(e,{gameState:t,ref:n,overwrites:i}){if(!n.current)throw new Error("No ref found when animating.");this.commit();let{finalState:r,sequences:s,options:a}=this.constructAnimation({gameState:t,transformState:e,overwrites:i,current:n.current});s.length||t.logger.warn("Transform","No sequences to animate.");let c=!1,l=e.lock(),p=Js(s,a),u=()=>{e.overwrite(l,r.get()).unlock(l),p.complete(),c=!0},d=new y().registerSkipController(new G(u)),h=()=>{c||e.overwrite(l,r.get()).unlock(l),c=!0,t.logger.debug("Transform","Transform Completed",e.toStyle(t,i)),d.resolve()};return p.then(h,(m=>{t.logger.error("Failed to animate transform. "+(m?.toString?.()||""))})),p.play(),t.logger.debug("Transform","Ready to animate transform.",{finalState:r,sequences:s,options:a},this),d}repeat(e){let t=this.copy();return t.config.repeat||(t.config.repeat=1),t.config.repeat*=e,t}getOptions(e){if(!e)return{...de.defaultOptions};let{duration:t,ease:n,delay:i,at:r}=e;return{duration:this.toSeconds(t,void 0),ease:n,delay:this.toSeconds(i,void 0),at:this.atToSeconds(r)}}constructAnimation({gameState:e,transformState:t,overwrites:n={},current:i}){let r=t.clone(),s=r.lock(),a=this.sequences.map(({props:c,options:l})=>{let p=r.assign(s,c).toFramesDefinition(e,n);return[i,p,this.getOptions(l)]});return{finalState:r.unlock(s).freeze(),sequences:a,options:this.getSequenceOptions()}}getSequenceOptions(){let{repeat:e,repeatDelay:t}=this.config;return{repeat:e,repeatDelay:this.toSeconds(t,void 0)}}copy(){return new de(this.sequences,this.config)}commit(e){if(!this.stagedChanges.length)return this;let t=this.constructCommit(this.stagedChanges,this.getSequenceOptions());return this.sequences.push({props:t.props,options:{...this.getSequenceOptions(),...e}}),this.stagedChanges=[],this}zoom(e){return this.pushChange({key:"zoom",props:e})}scaleX(e){return this.pushChange({key:"scaleX",props:e})}scaleY(e){return this.pushChange({key:"scaleY",props:e})}scale(e,t){return this.pushChange({key:"scaleX",props:e}).pushChange({key:"scaleY",props:t})}rotation(e){return this.pushChange({key:"rotation",props:e})}position(e){return this.pushChange({key:"position",props:e})}opacity(e){return this.pushChange({key:"opacity",props:e})}fontColor(e){return this.pushChange({key:"fontColor",props:e})}effect(e){for(let t of Object.keys(e))this.pushChange({key:t,props:e[t]});return this}maskImage(e){return this.pushChange({key:"maskImage",props:e})}clipPath(e){return this.pushChange({key:"clipPath",props:e})}filter(e){return this.pushChange({key:"filter",props:e})}backdropFilter(e){return this.pushChange({key:"backdropFilter",props:e})}mixBlendMode(e){return this.pushChange({key:"mixBlendMode",props:e})}constructCommit(e,t){let n={props:{},options:t};for(let i of e)n.props[i.key]=i.props;return n}pushChange(e){return this.stagedChanges.push(e),this}toSeconds(e,t){return typeof e>"u"?t:e/1e3}atToSeconds(e){if(typeof e>"u")return e;if(typeof e=="number")return e/1e3;let n=/^([+-])(\d+)$/.exec(e);if(!n)throw new ce("Invalid at definition. At definition must be a number or a string in the format of `+n` or `-n`.");let[i,r,s]=n,a=Number(s);if(isNaN(a))throw new ce("Invalid number in at definition.");let c=a/1e3;return r==="+"?`+${c}`:`-${c}`}};de.defaultConfig={sync:!0},de.defaultOptions={duration:0,ease:"linear"},de.CommonImagePositionMap=Zs;var q=de;var ii=class{constructor(){this.id=""}setId(e){this.id=e}getId(){return this.id}reset(){}fromData(e){return this}construct(e){for(let t=0;t<e.length;t++){let n=e[t];t!==0&&e[t-1]?.contentNode.setChild(n.contentNode)}return e}};var br=Symbol("_Chained"),Ar;Ar=br;var io=class io{constructor(e){this[Ar]=!0;this.__actions=[];this.__self=e}static isChained(e){return e&&e[br]}static toActions(e){return e.flat(2).map(t=>io.isChained(t)?t.fromChained(t):t).flat(3)}push(...e){this.__actions.push(...e)}getActions(){return this.__actions}getSelf(){return this.__self}newChain(){return this.getSelf().chain()}},Ae=io,en=class extends ii{chain(e){let t=Ae.isChained(this)?this:this.proxy(this,new Ae(this));if(!e)return t;let n=Array.isArray(e)?e:[e];return t.push(...n),t}proxy(e,t){let n=new Proxy(e,{get:function(i,r){if(r in t)return t[r];let s=i[r];return typeof s=="function"?s.bind(n):s},set:function(i,r,s){return i[r]=s,!0}});return n}combineActions(e,t){let n=t(this.chain().newChain()),i=e.do([n]).getActions()[0];return this.chain(i)}};var te=class extends en{constructor(){super()}toData(){return null}fromChained(e){return e.getActions()}};var rt=class extends O{executeAction(e,t){let n=this.callee.evaluate(this.contentNode.getContent(),{gameState:e});return n?.length?[{type:this.type,node:this.contentNode.getChild()},{type:this.type,node:n[0].contentNode}]:super.executeAction(e,t)}getFutureActions(e,t){return[...this.callee._getFutureActions(),...super.getFutureActions(e,t)]}stringify(e,t,n){let i=this.contentNode.getContent(),r=s=>{let a=s.condition?n?s.condition.toString():"Lambda(unknown)":"null",c=s.action?s.action.map(l=>l.stringify(e,t,n)).join(";"):"null";return`(${a}) {${c}}`};return super.stringifyWithContent("Condition",`if ${r(i.If)} ${i.ElseIf.length>0?`else if ${i.ElseIf.map(r).join(";")} `:""}${i.Else?`else {${r(i.Else)}}`:""}`)}};rt.ActionTypes=rr;var st=class o{static isSerializable(e){return["number","string","boolean"].includes(typeof e)||e instanceof Date||e==null?!0:Array.isArray(e)?e.every(o.isSerializable):typeof e=="object"?Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every(o.isSerializable):!1}constructor(e,t,n){this.name=e,this.key=n||e,this.content=H({},t),this.defaultContent=t}set(e,t){return o.isSerializable(t)?(this.content[e]=t,this):(console.warn(`Value "${t}" in key "${String(e)}" is not serializable, and will not be set
4
+ at namespace "${this.name}"`),this.content[e]=t,this)}get(e){return this.content[e]}equals(e,t){return this.content[e]===t}assign(e){return Object.entries(e).forEach(([t,n])=>{this.set(t,n)}),this}has(e){return this.content[e]!==void 0}keys(){return Object.keys(this.content)}values(){return Object.values(this.content)}entries(){return Object.entries(this.content)}reset(){return this.content=H({},this.defaultContent),this}getContent(){return this.content}toData(){return this.serialize()}load(e){if(!e){console.warn("No data to load");return}this.content=e}serialize(){let e={};return Object.entries(this.content).forEach(([t,n])=>{e[t]=this.wrap(n)}),e}deserialize(e){if(!e){console.warn("No data to load");return}Object.entries(e).forEach(([t,n])=>{this.content[t]=this.unwrap(n)})}toTypeName(e){return e instanceof Date?"date":"any"}wrap(e){let t={any:i=>({type:"any",data:i}),date:i=>({type:"date",data:i.toString()})},n=this.toTypeName(e);return t[n](e)}unwrap(e){return{any:n=>n.data,date:n=>new Date(n.data)}[e.type](e)}},An=class{constructor(){this.namespaces={}}static createNamespace(e,t,n){return new st(e,t,n)}addNamespace(e){if(!this.namespaces[e.key])return this.namespaces[e.key]=e,this}getNamespace(e){if(!this.namespaces[e])throw new x(`Namespace ${e} is not initialized, did you forget to register it?
5
+ Use \`story.registerPersistent\` to register a persistent namespace`);return this.namespaces[e]}setNamespace(e,t){return this.namespaces[e]=t,this}hasNamespace(e){return!!this.namespaces[e]}removeNamespace(e){return delete this.namespaces[e],this}getNamespaces(){return this.namespaces}keys(){return Object.keys(this.namespaces)}values(){return Object.values(this.namespaces)}entries(){return Object.entries(this.namespaces)}toData(){return this.entries().reduce((e,[t,n])=>(e[t]=n.toData(),e),{})}load(e){if(!e){console.warn("No data to load");return}Object.entries(e).forEach(([t,n])=>{this.namespaces[t]?this.namespaces[t].load(n):this.namespaces[t]=new st(t,n)})}clear(){return this.namespaces={},this}};var Fe=class extends O{executeAction(e,t){let n={action:this,stackModel:t.stackModel};if(this.type===vt.play){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=y.forward(e.audioManager.play(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===vt.stop){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=y.forward(e.audioManager.stop(this.callee,i.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===vt.setVolume){let[i,r]=this.contentNode.getContent(),s=this.callee.toData(),a=y.forward(e.audioManager.setVolume(this.callee,i,r),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(a),e.actionHistory.push(n,c=>{c&&this.callee.fromData(c)},[s]),a}else if(this.type===vt.setRate){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=y.forward(e.audioManager.setRate(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===vt.pause){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=y.forward(e.audioManager.pause(this.callee,i.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===vt.resume){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=y.forward(e.audioManager.resume(this.callee,i.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===vt.mute){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=y.forward(e.audioManager.mute(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("SoundAction")}};Fe.ActionTypes=vt;var kt=(n=>(n.Voice="voice",n.Bgm="bgm",n.Sound="sound",n))(kt||{}),le=class le extends te{static toSound(e){return e==null?null:typeof e=="string"?new le({src:e}):e}static isSound(e){return e instanceof le}static voice(e){let t=typeof e=="string"?{src:e}:e;return new le({...t,type:"voice"})}static bgm(e){let t=typeof e=="string"?{src:e}:e;return new le({...t,type:"bgm"})}static sound(e){let t=typeof e=="string"?{src:e}:e;return new le({...t,type:"sound"})}constructor(e={}){super();let t=typeof e=="string"?{src:e}:e,n=le.DefaultUserConfig.create(t),[i]=n.extract(le.DefaultConfig.keys());this.config=i.get(),this.state=this.getInitialState(n),this.userConfig=n}play(e){if(this.config.type==="bgm")throw new Se(`Sound (src: ${this.config.src}) is marked as bgm, but it is being played as a normal sound.
6
+ To prevent unintended behavior, the sound marked as bgm cannot be played using \`play()\`.`);return this.pushAction(Fe.ActionTypes.play,[{end:this.state.volume,duration:e||0}])}stop(e){return this.pushAction(Fe.ActionTypes.stop,[{end:0,duration:e||0}])}setVolume(e,t){return this.pushAction(Fe.ActionTypes.setVolume,[e,t||0])}mute(e=!0){return this.pushAction(Fe.ActionTypes.mute,[e])}unmute(){return this.mute(!1)}setRate(e){return this.pushAction(Fe.ActionTypes.setRate,[e])}pause(e){return this.pushAction(Fe.ActionTypes.pause,[{end:0,duration:e||0}])}resume(e){return this.pushAction(Fe.ActionTypes.resume,[{end:this.state.volume,duration:e||0}])}getSrc(){return this.config.src}toData(){return{state:le.StateSerializer.serialize(this.state)}}fromData(e){return this.state=le.StateSerializer.deserialize(e.state),this}copy(){return new le(this.userConfig.get())}reset(){return this.state=this.getInitialState(this.userConfig),this}getInitialState(e){return le.DefaultState.create({...e.get()}).get()}pushAction(e,t){return this.chain(new Fe(this.chain(),e,new b().setContent(t)))}};le.noSound="data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgA",le.DefaultUserConfig=new j({src:le.noSound,loop:!1,volume:1,streaming:!1,rate:1,seek:0,type:"sound"}),le.DefaultConfig=new j({src:le.noSound,loop:!1,streaming:!1,seek:0,type:"sound"}),le.DefaultState=new j({volume:1,rate:1,paused:!1,muted:!1}),le.StateSerializer=new He;var re=le;var Lu={};var tn=class extends en{constructor(){super()}fromChained(e){return e.getActions()}forEachChild(e,t,n,i={}){let r=new Set,s=[];for(Array.isArray(t)?s.push(...t):s.push(t);s.length;){let a=s.shift();if(r.has(a))continue;r.add(a),n(a);let c=a.getFutureActions(e,i).filter(l=>!r.has(l));s.push(...c)}}getAllChildren(e,t,n={}){let i=[];return this.forEachChild(e,t,r=>i.push(r),n),i}getAllChildrenMap(e,t){let n=new Map;return this.forEachChild(e,t,i=>n.set(i.getId(),i)),n}getAllElementMap(e,t,n={}){let i=new Map;return this.forEachChild(e,t,r=>i.set(r.callee.getId(),r.callee),n),i}getAllChildrenElements(e,t,n={}){return Array.from(new Set(this.getAllChildren(e,t,n).map(i=>i.callee)))}toData(){return null}constructNodes(e,t){for(let n=0;n<e.length;n++){let i=e[n];n===0&&t?t.setChild(i.contentNode):n>0&&e[n-1].contentNode?.setChild(i.contentNode)}return e.length?e[0].contentNode:null}};var Kt=class Kt{constructor(){this.src=[];this.future=[]}static catSrc(e){let t=new Set,n=new Set,i=new Set;return e.forEach(({type:r,src:s})=>{r===Kt.SrcTypes.image?t.add(s):r===Kt.SrcTypes.video?n.add(s):i.add(s)}),{image:Array.from(t),video:Array.from(n),audio:Array.from(i)}}static getSrc(e){return typeof e=="string"?e:e instanceof U?U.getSrcURL(e):e.type==="image"?U.getSrcURL(e.src):e.type==="video"?e.src:e.type==="audio"?e.src.getSrc():""}static getPreloadableSrc(e,t){if(t.is(Y,V.jumpTo)){let n=t.contentNode.getContent()[0],r=e.getScene(n,!0).state.backgroundImage;if(A.isImageURL(r.config.src))return{type:"image",src:r.config.src,activeType:"once"}}else if(t instanceof ne){let n=t;if(t.is(ne,Oe.setSrc)){let i=t.contentNode.getContent()[0];if(A.isImageSrc(i))return{type:"image",src:A.srcToURL(i),activeType:"scene"}}else{if(t.type===Oe.initWearable)return{type:"image",src:t.contentNode.getContent()[0],activeType:"scene"};if(t.type===Oe.setAppearance){let i=t.contentNode.getContent()[0];if(!n.callee.config.src||typeof n.callee.config.src?.resolve!="function")throw n.callee._invalidSrcHandlerError();if(U.isTagSrc(n.callee)&&i.length===n.callee.config.src.groups.length)return{type:"image",src:U.getSrcFromTags(i,n.callee.config.src.resolve),activeType:"scene"}}}}return null}register(e,t){if(Array.isArray(e))e.forEach(n=>this.register(n));else if(e instanceof re){if(this.isSrcRegistered(e.getSrc()))return this;this.src.push({type:"audio",src:e})}else if(e instanceof U||A.isStaticImageData(e)){if(e instanceof U){if(!A.isImageURL(e.state.currentSrc))return this;if(this.isSrcRegistered(U.getSrcURL(e)))return this}else if(this.isSrcRegistered(A.srcToURL(e.src)))return this;this.src.push({type:"image",src:A.isStaticImageData(e)?A.srcToURL(e):e.state.currentSrc})}else if(typeof e=="object"){if(this.isSrcRegistered(e.src||""))return this;this.src.push(e)}else if(e==="audio"){if(this.isSrcRegistered(t||""))return this;this.src.push({type:e,src:t instanceof re?t:new re({src:t})})}else{if(this.isSrcRegistered(t||""))return this;this.src.push({type:e,src:t})}return this}registerRawSrc(e){return this.isSrcRegistered(e)?this:(this.src.push({type:"image",src:e}),this)}isSrcRegistered(e){if(!e)return!1;let t=e instanceof re?e.getSrc():e;return this.src.some(n=>n.type===Kt.SrcTypes.audio?t===n.src.getSrc():n.type===Kt.SrcTypes.image?t===U.getSrcURL(n.src):t===n.src)}getSrc(){return[...this.src]}getSrcByType(e){return this.src.filter(t=>t.type===e)}registerFuture(e){return this.future.includes(e)||this.hasFuture(e)?this:(this.future.push(e),this)}hasFuture(e){return this.future.includes(e)}getFutureSrc(){return this.future.map(e=>e.getSrc()).flat(2)}};Kt.SrcTypes={image:"image",video:"video",audio:"audio"};var De=Kt;var Pt=class extends O{executeAction(e,t){let n={action:this,stackModel:t.stackModel};if(this.type===jn.setText){let i=this.callee.state.text;return this.callee.state.text=this.contentNode.getContent()[0],e.getExposedStateForce(this.callee).flush(),e.actionHistory.push(n,r=>{this.callee.state.text=r},[i]),super.executeAction(e,t)}else if(this.type===jn.setFontSize){let i=this.callee.state.fontSize;return this.callee.state.fontSize=this.contentNode.getContent()[0],e.getExposedStateForce(this.callee).flush(),e.actionHistory.push(n,r=>{this.callee.state.fontSize=r},[i]),super.executeAction(e,t)}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("TextAction")}};Pt.ActionTypes=jn;var Ce=class extends O{executeAction(e,t){if(this.type===be.applyTransform){let[n]=this.contentNode.getContent(),i=this.callee;return this.applyTransform(e,i,n,t)}else if(this.type===be.applyTransition){let[n,i]=this.contentNode.getContent(),r=this.callee,s=i?i(n):n;return this.applyTransition(e,r,s,t)}else if(this.type===be.init){let[n,i,r]=this.contentNode.getContent(),s=this.callee;return this.initDisplayable(e,n,s,i||null,r,t)}throw this.unknownTypeError()}applyTransform(e,t,n,i,r){let s=new y().registerSkipController(new G(()=>(e.logger.info("Displayable Transition","Skipped"),super.executeAction(e,i)))),a=()=>{s.isSettled()||(r?.(),s.resolve(super.executeAction(e,i)))},c=e.getExposedStateForce(t),l=t.transformState.clone(),p=c.applyTransform(n,a),u=e.timelines.attachTimeline(s).attachChild(p);return p.onCancelled(a),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:u},d=>{s.isSettled()||s.abort(),p.abort(),t.transformState.forceOverwrite(d.state)},[l]),s}applyTransition(e,t,n,i,r){let s=new y().registerSkipController(new G(()=>(e.logger.info("Displayable Transition","Skipped"),super.executeAction(e,i)))),a=()=>{s.isSettled()||(r?.(),s.resolve(super.executeAction(e,i)))},l=e.getExposedStateForce(t).applyTransition(n,a),p=e.timelines.attachTimeline(s).attachChild(l);return l.onCancelled(a),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:p},()=>{s.isSettled()||s.abort(),l.abort()}),s}initDisplayable(e,t,n,i,r=!0,s){if(r!==!1){let l=e.findElementByDisplayable(this.callee,i);l&&e.disposeDisplayable(n,l.scene,i),e.createDisplayable(n,t,i)}e.flush();let a=new y().registerSkipController(new G(()=>super.executeAction(e,s)));e.getExposedStateAsync(n,l=>{l.initDisplayable(()=>{a.resolve(super.executeAction(e,s))})});let c=e.timelines.attachTimeline(a);return e.actionHistory.push({action:this,stackModel:s.stackModel,timeline:c},()=>{r!==!1&&e.findElementByDisplayable(n,i)&&e.disposeDisplayable(n,t,i)}),a}stringify(e,t,n){return super.stringifyWithName("DisplayableAction")}};Ce.ActionTypes=be;var at=class o extends te{constructor(){super(...arguments);this.srcManager=new De}pos(t,n,i){return this.transform(new q({position:t},{duration:n,ease:i}))}zoom(t,n,i){return this.transform(new q({zoom:t},{duration:n,ease:i}))}scaleX(t,n,i){return this.transform(new q({scaleX:t},{duration:n,ease:i}))}scaleY(t,n,i){return this.transform(new q({scaleY:t},{duration:n,ease:i}))}scale(t,n,i,r){return this.transform(new q({scaleX:t,scaleY:n},{duration:i,ease:r}))}scaleXY(t,n,i,r){return this.scale(t,n,i,r)}rotate(t,n,i){return this.transform(new q({rotation:t},{duration:n,ease:i}))}opacity(t,n,i){return this.transform(new q({opacity:t},{duration:n,ease:i}))}effect(t,n){return this.registerEffectSrc(t),this.transform(new q(t,n))}mask(t,n={}){let i=A.srcToURL(t),{maskSize:r,maskPosition:s,maskRepeat:a,maskMode:c,...l}=n;return this.srcManager.registerRawSrc(i),this.effect({maskImage:o.toCSSUrl(i),maskSize:r,maskPosition:s,maskRepeat:a,maskMode:c},l)}clearMask(t){return this.effect({maskImage:"none",maskSize:"auto",maskPosition:"0% 0%",maskRepeat:"repeat",maskMode:"match-source"},t)}clip(t,n){return this.effect({clipPath:t},n)}clearClip(t){return this.effect({clipPath:"none"},t)}circleReveal(t={}){let{center:n="50% 50%",from:i=0,to:r=150,clearClip:s=!0,duration:a=600,ease:c="easeInOut",...l}=t,p={duration:a,ease:c,...l},u=o.createClipPathTransform([[o.circleClipPath(i,n),{duration:0}],[o.circleClipPath(r,n),p]]);return s?this.combineActions(new xe,d=>d.transform(u).clearClip({duration:0})):this.transform(u)}circleClose(t={}){let{center:n="50% 50%",from:i=150,to:r=0,clearClip:s=!1,duration:a=600,ease:c="easeInOut",...l}=t,p={duration:a,ease:c,...l},u=o.createClipPathTransform([[o.circleClipPath(i,n),{duration:0}],[o.circleClipPath(r,n),p]]);return s?this.combineActions(new xe,d=>d.transform(u).clearClip({duration:0})):this.transform(u)}wipe(t={}){let{direction:n="left",reverse:i=!1,clearClip:r=!i,duration:s=600,ease:a="easeInOut",...c}=t,l={duration:s,ease:a,...c},p=o.wipeClipPath(n,100),u=o.wipeClipPath(n,0),d=o.createClipPathTransform([[i?u:p,{duration:0}],[i?p:u,l]]);return r?this.combineActions(new xe,h=>h.transform(d).clearClip({duration:0})):this.transform(d)}filter(t,n){return this.effect({filter:t},n)}clearFilter(t){return this.effect({filter:"none"},t)}backdrop(t,n){return this.effect({backdropFilter:t},n)}blend(t,n){return this.effect({mixBlendMode:t},n)}transform(t){let n=this.chain(),i=new Ce(n,be.applyTransform,new b().setContent([t.copy()]));return n.chain(i)}registerEffectSrc(t){let n=t.maskImage;if(typeof n=="string")for(let i of o.extractCSSUrls(n))this.srcManager.registerRawSrc(i)}static toCSSUrl(t){return`url("${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}")`}static extractCSSUrls(t){let n=[],i=/url\(\s*(?:"([^"]*)"|'([^']*)'|([^)]*))\s*\)/g,r;for(;r=i.exec(t);){let s=r[1]||r[2]||r[3];s&&n.push(s.trim())}return n}static createClipPathTransform(t){return new q(t.map(([n,i])=>({props:{clipPath:n},options:i})))}static circleClipPath(t,n){return`circle(${t}% at ${n})`}static wipeClipPath(t,n){switch(t){case"right":return`inset(0 0 0 ${n}%)`;case"top":return`inset(0 0 ${n}% 0)`;case"bottom":return`inset(${n}% 0 0 0)`;case"left":default:return`inset(0 ${n}% 0 0)`}}show(t){let n=this.chain(),i=t instanceof q?t.copy():new q({opacity:1},t),r=new Ce(n,be.applyTransform,new b().setContent([i]));return n.chain(r)}hide(t){let n=this.chain(),i=t instanceof q?t.copy():new q({opacity:0},t),r=new Ce(n,be.applyTransform,new b().setContent([i]));return n.chain(r)}};var Et=(t=>(t[t.Number=0]="Number",t[t.HexColor=1]="HexColor",t))(Et||{});import{animate as _s}from"motion/react";var ct=class{requestAnimations(e){let t=e.map(u=>u.start),n=[],i=0,r=[],s=[],a=[];return{onUpdate:u=>(r.push(u),{cancel:()=>{let d=r.indexOf(u);d!==-1&&r.splice(d,1)}}),onComplete:u=>(s.push(u),{cancel:()=>{let d=s.indexOf(u);d!==-1&&s.splice(d,1)}}),onCanceled:u=>(a.push(u),{cancel:()=>{let d=a.indexOf(u);d!==-1&&a.splice(d,1)}}),complete:()=>{i!==e.length&&n.forEach(u=>u.complete())},start:()=>{if(n.length>0)throw new Error("Animation controllers are already started");e.forEach((u,d)=>{n.push(this.requestMotion(u,{onComplete:()=>{t[d]=u.end,r.forEach(h=>h(t)),i++,i===e.length&&s.forEach(h=>h())},onUpdate:h=>{t[d]=h,r.forEach(m=>m(t))}}))})},cancel:()=>{n.forEach(u=>u.cancel()),a.forEach(u=>u())}}}toFinalStyle(e){return e.resolve.map(t=>typeof t=="function"?t(...e.animations.map(n=>n.end)):t.resolver(...e.animations.map(n=>n.end)))}asPrev(e){return{resolver:e,key:"current"}}asTarget(e){return{resolver:e,key:"target"}}requestMotion(e,t){return _s(e.start,e.end,{duration:e.duration/1e3,onUpdate:n=>{t.onUpdate&&t.onUpdate(n)},onComplete:()=>{t.onComplete&&t.onComplete()},ease:e.ease})}};ct.AnimationType=Et;var Cn=class extends ct{_setElement(e){return this._element=e,this}getTextState(){if(this._element===void 0)throw new x(`Trying to access text state, but element is not set
7
+ This should not happen, please report this issue to the developers`);return this._element.state}};var oi=class o extends Cn{constructor(t,n,i){super();this.textSize=t;this.duration=n;this.easing=i}createTask(){return{animations:[{type:0,start:this.getTextState().fontSize,end:this.textSize,duration:this.duration,ease:this.easing}],resolve:[this.asTarget(t=>({style:{fontSize:`${t}px`}}))]}}copy(){return new o(this.textSize,this.duration,this.easing)}};var Ke=class Ke extends at{constructor(e,t={}){super();let n=typeof e=="string"?{...t,text:e}:e,i=Ke.DefaultUserConfig.create(n),r=Ke.DefaultTextConfig.create(i.get());this.userConfig=i,this.config=r.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(i)}setText(e){let t=this.chain(),n=new Pt(t,Pt.ActionTypes.setText,new b().setContent([e]));return t.chain(n)}setFontColor(e,t=0,n){return this.transform(new q({fontColor:e},{duration:t,ease:n}))}setFontSize(e,t=0,n){return this.combineActions(new xe,i=>{if(t){let s=new oi(e,t,n);i.chain(this._applyTransition(i,s))}let r=new Pt(i,Pt.ActionTypes.setFontSize,new b().setContent([e]));return i.chain(r)})}useLayer(e){return this.userConfig.get().layer=e,Object.assign(this.config,{layer:e}),this}toData(){return{state:Ke.StateSerializer.serialize(this.state),transformState:this.transformState.serialize()}}fromData(e){return this.state=Ke.StateSerializer.deserialize(e.state),this.transformState=me.deserialize(e.transformState),this}_init(e){return new Ce(this.chain(),be.init,new b().setContent([e||null,this.config.layer||null]))}reset(){this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(this.userConfig)}getInitialTransformState(e){let[t]=e.extract(Ke.DefaultTextTransformState.keys());return new me(Ke.DefaultTextTransformState.create(t.get()).get())}_applyTransition(e,t){return new Ce(e,be.applyTransition,new b().setContent([t,n=>n._setElement(this)]))}getInitialState(){return Ke.DefaultTextState.create({fontSize:this.userConfig.get().fontSize,text:this.userConfig.get().text}).get()}};Ke.DefaultUserConfig=new j({alignX:"center",alignY:"center",className:"",fontSize:16,fontColor:"#000000",text:""}),Ke.DefaultTextConfig=new j({alignX:"center",alignY:"center",className:"",layer:void 0}),Ke.DefaultTextState=new j({fontSize:16,display:!1,text:""}),Ke.DefaultTextTransformState=new j({fontColor:"#000000",...me.DefaultTransformState.getDefaultConfig()}),Ke.StateSerializer=new He;var Vt=Ke;var xn=class xn extends O{executeAction(e,t){let n=this;if(n.is(xn,"persistent:set")){let[i,r]=n.contentNode.getContent(),s=e.getStorable().getNamespace(n.callee.getNamespaceName()),a=s.get(i);if(typeof r=="function"){let c=s.get(i);s.set(i,r(c))}else s.set(i,r);return e.actionHistory.push({action:this,stackModel:t.stackModel},c=>{s.set(i,c)},[a]),super.executeAction(e,t)}else if(n.is(xn,"persistent:assign")){let[i]=n.contentNode.getContent(),r=e.getStorable().getNamespace(n.callee.getNamespaceName()),s={},a=typeof i=="function"?i(r.getContent()):i;return Object.keys(a).forEach(c=>{s[c]=r.get(c),r.set(c,a[c])}),e.actionHistory.push({action:this,stackModel:t.stackModel},c=>{Object.keys(c).forEach(l=>{r.set(l,c[l])})},[s]),super.executeAction(e,t)}throw this.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("PersistentAction")}};xn.ActionTypes=yn;var ri=xn;var we=class o{static from(e){return o.isPauseConstructor(e)?new o:e}static wait(e){return new o({duration:e})}static isPause(e){return this.isPauseConstructor(e)||e instanceof o}static isPauseConstructor(e){return e===o}constructor(e={}){this.config=e}};var ke=class ke{static isWord(e){return e instanceof ke}static color(e,t){return ke.isWord(e)?e.copy().assign({color:t}):new ke(e,{color:t})}static bold(e){return ke.isWord(e)?e.copy().assign({bold:!0}):new ke(e,{bold:!0})}static italic(e){return ke.isWord(e)?e.copy().assign({italic:!0}):new ke(e,{italic:!0})}static getText(e){return e.filter(t=>!t.isPause()).map(t=>t.toString()).join("")}constructor(e,t={}){this.text=e,this.config=H(ke.defaultConfig,t)}evaluate(e){if(we.isPause(this.text))return[this];if(typeof this.text=="function"){let t=this.text(e);return Array.isArray(t)?t.map(n=>ke.isWord(n)?n.inherit(this.config).evaluate(e):new ke(n,this.config)).flat():ke.isWord(t)?t.inherit(this.config).evaluate(e):[new ke(t,this.config)]}return[this]}inherit(e){return this.config.color=this.config.color||e.color,this.config.italic=this.config.italic??e.italic,this.config.bold=this.config.bold??e.bold,this.config.cps=this.config.cps??e.cps,this}assign(e){return this.config=H(this.config,e),this}copy(){return new ke(this.text,this.config)}isPause(){return we.isPause(this.text)}toString(){return typeof this.text=="string"?this.text:""}};ke.defaultConfig={},ke.defaultColor="#000";var W=ke;var Ve=class Ve{static isSentence(e){return e instanceof Ve}static toSentence(e){return Ve.isSentence(e)?e:new Ve(e)}static format(e){let t=[];if(Array.isArray(e))for(let n=0;n<e.length;n++)t.push(this.formatWord(e[n]));else t.push(this.formatWord(e));return t}static formatWord(e){return W.isWord(e)?e:new W(e)}static formatStaticWord(e,t){return Array.isArray(e)?e.map(n=>this.formatStaticWord(n,t)).flat(2):[W.isWord(e)?e:new W(e,t)]}static isSentencePrompt(e){return Array.isArray(e)?e.every(Ve.isSingleWord):Ve.isSingleWord(e)}static isSingleWord(e){return typeof e=="string"||W.isWord(e)||we.isPause(e)||typeof e=="function"}getMetadata(){return this.config.metadata}constructor(e,t={}){this.text=Ve.format(e),this.config=H(Ve.defaultConfig,{...t,voice:typeof t.voice=="string"?re.voice(t.voice):re.toSound(t.voice)}),this.state=lr(Ve.defaultState)}toData(){return null}fromData(e){return this.state=H(this.state,e),this}toString(){return this.text.map(e=>e.text).join("")}setCharacter(e){return this.config.character=e,this}evaluate(e){let t=[];for(let n=0;n<this.text.length;n++){let i=this.text[n].evaluate(e);t.push(...Ve.formatStaticWord(i))}return t}copy(){return new Ve([...this.text],this.config)}};Ve.defaultConfig={pause:!0,voice:null,character:null,voiceId:null},Ve.defaultState={};var ie=Ve;var Dt=class extends O{executeAction(e,t){let n=this.contentNode.getContent().execute({gameState:e});return n&&e.actionHistory.push({action:this,stackModel:t.stackModel},()=>{n()},[]),super.executeAction(e,t)}stringify(e,t,n){return super.stringifyWithName("ScriptAction")}};Dt.ActionTypes=sr;var ue=class o extends te{static getCtx({gameState:e}){let t=e.game.getLiveGame(),n=t.getStorable();return{gameState:e,game:e.game,liveGame:t,storable:n,$:i=>n.getNamespace(i)}}static execute(e){return new o(e)}constructor(e){super(),this.handler=e;let t=this.chain(),n=new Dt(t,Dt.ActionTypes.action,new b().setContent(this));return this.chain(n)}execute({gameState:e}){return this.handler(o.getCtx({gameState:e}))}fromChained(e){return[new Dt(this.chain(),Dt.ActionTypes.action,new b().setContent(e))]}};var si=class{constructor(e){this.config=e;this.watching=null;this.warnings=[]}observe(e){return this.watching=e,this}warn(e,t){return this.warnings.push([e,t]),this.watching?.logger.warn(t),t}getWarnings(){return[...this.warnings]}};var Te=class o{constructor(e,t){this.awaitable=e;this.guard=t;this.children=[];this._onResolved=[];this._onCancelled=[];this._onFailed=[];this._onTimelineRegistered=[];this._ableToAttach=!0;this._status="pending";e.onSettled(()=>{this.resolveStatus()}),We(()=>{this.preventAttach()})}static proxy(e){let t=new y,n=new y,i=new o(n);return i.onTimelineRegistered(()=>{n.resolve()}).onSettled(()=>{let[r,s]=i.catSettled();e(r,s)}),t.onSkipControllerRegister(r=>{r.onAbort(()=>{i.abort()})}),[t,i]}static any(e){if(e.length===0)throw new x("Cannot create an 'any' timeline with no awaitables.");let t=new y,n=new y,i=new o(n),r=!1;for(let s of e)i.attachChild(s),s.then(a=>{r||(r=!0,t.resolve(a))});return t.onSkipControllerRegister(s=>{s.onAbort(()=>{i.abort()})}),[t,i]}static all(e){if(e.length===0)throw new x("Cannot create an 'all' timeline with no awaitables.");let t=new y,n=new y,i=new o(n),r=new Array(e.length),s=0;for(let a=0;a<e.length;a++){let c=e[a];i.attachChild(c),c.then(l=>{r[a]=l,s++,s===e.length&&t.resolve(r)})}return t.onSkipControllerRegister(a=>{a.onAbort(()=>{i.abort()})}),[t,i]}static sequence(e,t){let n=t,i=null,r=new y,s=()=>{if(i){let a;i.onSkipControllerRegister(c=>{a=c.onAbort(()=>{r.abort()})}),i.then(c=>{a?.cancel(),n=c,i=e(c),i?We(()=>s()):r.resolve(n)})}else r.resolve(n)};return r.registerSkipController(new G(()=>(i&&i.abort(),t))),i=e(t),i?We(()=>s()):We(()=>r.resolve(n)),r}get status(){return this._status}isSettled(){return this._status!=="pending"}isResolved(){return this._status==="resolved"}isCancelled(){return this._status==="cancelled"}isFailed(){return this._status==="failed"}onResolved(e){this._onResolved.push(e)}onCancelled(e){this._onCancelled.push(e)}onFailed(e){this._onFailed.push(e)}onSettled(e){this.isSettled()?We(e):(this.onResolved(e),this.onCancelled(e),this.onFailed(e))}abort(){this.isSettled()||(this.awaitable.abort(),this.setStatus("cancelled",this.emitEvents.bind(this)),this.children.forEach(e=>e.abort()))}attachChild(e){if(!this._ableToAttach)throw new x(`Attaching to this timeline violates the timeline's state.
8
8
  Timeline attaching is only allowed synchronously after the timeline is created.
9
- Current _ableToAttach: `+this._ableToAttach);let t=g.isAwaitable(e)?new o(e,this.guard):e;return this.children.push(t),this.guard&&t.setGuard(this.guard),t.onSettled(()=>{this.resolveStatus()}),this}setGuard(e){return this.guard=e,this}catSettled(){return this.children.reduce(([e,t],n)=>(n.isResolved()?e.push(n):n.isCancelled()&&t.push(n),[e,t]),[[],[]])}onTimelineRegistered(e){return this._onTimelineRegistered.push(e),this}resolveStatus(){this.awaitable.solved&&this.children.every(e=>e.isSettled())?this.setStatus("resolved",this.emitEvents.bind(this)):this.awaitable.skipController?.isAborted()&&this.setStatus("cancelled",this.emitEvents.bind(this))}emitEvents(){this.isResolved()?this._onResolved.forEach(e=>e()):this.isCancelled()&&this._onCancelled.forEach(e=>e()),this._onResolved=[],this._onCancelled=[]}setStatus(e,t){if(this.isSettled()){this.guard&&this.guard.warn("unexpectedTimelineStatusChange",`Trying to resolve a settled timeline: ${this._status} -> ${e}`);return}e!==this._status&&t?(this._status=e,t()):this._status=e}preventAttach(){this._ableToAttach=!1,this._onTimelineRegistered.forEach(e=>e())}},ni=class{constructor(e){this.guard=e;this.timelines=[]}attachTimeline(e){this.cleanupSettled();let t=e instanceof fe?e:new fe(e);return this.timelines.push(t),this.guard&&t.setGuard(this.guard),t}abortAll(){for(let e of this.timelines)e.abort();this.cleanupSettled()}cleanupSettled(){this.timelines=this.timelines.filter(e=>!e.isSettled())}};var Xt=class Xt extends U{static getVoice(e,t){let n=e.getLastScene();if(!n)throw new Error("No scene found when trying to play voice");let{voiceId:i,voice:r}=t.config;return!i&&!r?null:Z.toSound(n.getVoice(i)||r)}static endVoiceWithPreference(e,t){let{voiceEndMode:n,voiceFadeDuration:i}=e.game.preference.getPreferences();if(n==="none")return null;let r=n==="fade"?Math.max(0,i):0;return e.audioManager.stop(t,r)}executeAction(e,t){if(this.type===Bt.say){let n=null,i="",r=null,s=new g(y=>y).registerSkipController(new M(()=>{n?.()})),a=new fe(s),c=this.contentNode.getContent(),l=e.isNvlMode(),u=e.getLiveGame(),m=e.createPresentationSnapshot(),p=u.lastDialog?{sentence:u.lastDialog.sentence,speaker:u.lastDialog.speaker}:null,h=Xt.getVoice(e,c);if(h){let y=e.audioManager.play(h);a.attachChild(y)}let d=h?e.events.on(w.EventTypes["event:state.player.lineEnd"],()=>{let y=Xt.endVoiceWithPreference(e,h);y&&e.timelines.attachTimeline(y),d?.cancel()}):null;if(l){let y=this.getId(),f=(e.getActiveNvlDialogForAction(y)||e.getLatestNvlDialogForAction(y))?.id||e.allocateNvlDialogId(y),S=c.evaluate(re.getCtx({gameState:e}));i=F.getText(S),u.events.emit(rt.EventTypes["event:character.prompt"],{character:c.config.character,sentence:c,text:i});let N=!1,q=()=>{N||(N=!0,e.events.emit(w.EventTypes["event:state.player.lineEnd"]),e.gameHistory.resolvePending(T),s.resolve({type:this.type,node:this.contentNode.getChild()}))},{created:ae}=e.ensureNvlDialog({id:f,actionId:y,character:this.callee,sentence:c,text:i});r=f;let Ve=e.consumeNvlTypingSuppression(),Te=ae&&!Ve?"typing":"awaitAdvance";e.activateNvlDialog(f,Te,!ae);let ke=e.waitForNvlAdvance(f,()=>{e.settleNvlDialog(f),q()});n=()=>{ke.cancel()}}else{let y=e.idManager.generateId(),x=e.createDialog(y,c,()=>{e.gameHistory.resolvePending(T),s.resolve({type:this.type,node:this.contentNode.getChild()})});i=x.text,n=x.cancel}u.setLastDialog(i,this.callee.state.name),e.timelines.attachTimeline(a);let{id:T}=e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:a},()=>{if(d?.cancel(),h&&e.audioManager.isPlaying(h)){let y=Xt.endVoiceWithPreference(e,h);y&&a.attachChild(y)}n?.(),r&&(e.removeNvlDialog(r),e.settleNvlDialog(r)),e.restorePresentationSnapshot(m),p?u.setLastDialog(p.sentence,p.speaker):u.lastDialog=null});return e.gameHistory.push({token:T,action:this,element:{type:"say",text:i,voice:h?h.getSrc():null,character:this.callee.state.name},isPending:!0}),s}else if(this.type===Bt.setName){let n=this.callee.state.name;return this.callee.state.name=this.contentNode.getContent()[0],e.actionHistory.push({action:this,stackModel:t.stackModel},i=>{this.callee.state.name=i},[n]),super.executeAction(e,t)}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("CharacterAction")}};Xt.ActionTypes=Bt;var Ye=Xt;var yn=class yn extends X{constructor(e,t={}){super(),this.config=I(yn.defaultConfig,t),this.state={name:e||""};let n=this,i=function(r,s,...a){return n.call(r,s,...a)};return new Proxy(i,{get(r,s){return n[s]},set(r,s,a){return n[s]=a,!0},has(r,s){return s in n}})}say(e,t,...n){if(Array.isArray(e)&&e.every(c=>typeof c=="string")&&[t,...n].length>0&&[t,...n].every(c=>ne.isSingleWord(c))){let c=e,l=ne.format([t,...n]),u=new ne(Zo(c,l),{character:this}),m=new Ye(this.chain(),Ye.ActionTypes.say,new v().setContent(u));return this.chain(m)}let i=t||{},r=e,s=Array.isArray(r)?new ne(r,{...i,character:this}):(ne.isSentence(r)?r:new ne(r,{...i,character:this})).copy();s.setCharacter(this);let a=new Ye(this.chain(),Ye.ActionTypes.say,new v().setContent(s));return this.chain(a)}setName(e){let t=new Ye(this.chain(),Ye.ActionTypes.setName,new v().setContent([e]));return this.chain(t)}apply(e,t,...n){return this.say.apply(this,[e,t,...n])}call(e,t,...n){return Array.isArray(e)&&"raw"in e?t&&ne.isSingleWord(t)?this.say(e,t,...n):this.say(e):typeof e=="string"?this.say(e,t):ne.isSentence(e)?this.say(e):this.say(e,t)}};yn.defaultCharacterColor="#000",yn.defaultConfig={};var ii=yn,wt=new ii(null);var R=class o{static isLambda(e){return e instanceof o&&"handler"in e}static isLambdaHandler(e){return typeof e=="function"}static from(e){return o.isLambda(e)?e:new o(e)}static not(e){return new o(t=>!e.evaluate(t).value)}constructor(e){this.handler=e}evaluate({gameState:e}){return{value:this.handler(this.getCtx({gameState:e}))}}getCtx({gameState:e}){let t=e.game.getLiveGame(),n=t.getStorable();return{gameState:e,game:e.game,liveGame:t,storable:n,$:i=>n.getNamespace(i)}}toString(){return`Lambda(${this.handler.toString()})`}},Zi=class o extends X{constructor(){super();this.conditions={If:{condition:null,action:null},ElseIf:[],Else:{action:null}}}static getInitialState(){return{If:{condition:null,action:null},ElseIf:[],Else:{action:null}}}static If(t,n){return new o().createIfCondition(t,n)}ElseIf(t,n){if(this.conditions.Else.action)throw new ye(`ELSE condition already set
10
- You are trying to set an ELSE-IF condition after an ELSE condition`);return this.conditions.ElseIf.push({condition:R.from(t),action:this.construct(Array.isArray(n)?n:[n])}),this.chain()}Else(t){if(this.conditions.Else.action)throw new ye(`ELSE condition already set
11
- You are trying to set multiple ELSE conditions for the same condition`);return this.conditions.Else.action=this.construct(Array.isArray(t)?t:[t]),this.chain()}evaluate(t,{gameState:n}){let i={gameState:n};if(t.If.condition?.evaluate(i)?.value)return t.If.action||null;for(let s of t.ElseIf)if(s.condition?.evaluate(i)?.value)return s.action||null;return t.Else.action||null}fromChained(t){return[Reflect.construct(tt,[this,tt.ActionTypes.action,new v().setContent(t.conditions)])]}construct(t,n,i){let r=this.narrativeToActions(t);for(let s=0;s<r.length;s++){let a=r[s].contentNode,c=r[s+1]?.contentNode;c&&a.setChild(c),s===r.length-1&&n&&a.setChild(n),s===0&&i&&i.setChild(a)}return r}_getFutureActions(){return ge.toActions([this.conditions.If.action?.[0]||[],...this.conditions.ElseIf.flatMap(t=>t.action?.[0]||[]),this.conditions.Else.action?.[0]||[]])}createIfCondition(t,n){this.conditions.If.condition=R.from(t),this.conditions.If.action=this.construct(n);let i=this.chain(),r=new tt(i,tt.ActionTypes.action,new v().setContent(this.conditions));return i.chain(r)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?wt.say(n).getActions():ge.toActions([n]))}};var oi=class oi extends X{constructor(e,t){super(),this.namespace=this.prefix(e),this.defaultContent=t}init(e){e.hasNamespace(this.namespace)||e.addNamespace(new nt(this.namespace,this.defaultContent))}getNamespace(e){return e.getNamespace(this.namespace)}set(e,t){return this.chain(this.createAction(ln.set,[e,t]))}assign(e){return this.chain(this.createAction(ln.assign,[e]))}equals(e,t){return new R(n=>{let i=n.storable.getNamespace(this.namespace),r=R.isLambda(t)||R.isLambdaHandler(t)?R.from(t).evaluate(n).value:t;return i.equals(e,r)})}notEquals(e,t){return new R(n=>{let i=n.storable.getNamespace(this.namespace),r=R.isLambda(t)||R.isLambdaHandler(t)?R.from(t).evaluate(n).value:t;return!i.equals(e,r)})}isTrue(e){return new R(({storable:t})=>t.getNamespace(this.namespace).equals(e,!0))}isFalse(e){return new R(({storable:t})=>t.getNamespace(this.namespace).equals(e,!1))}isNotNull(e){return new R(({storable:t})=>{let n=t.getNamespace(this.namespace).get(e);return n!=null})}toWord(e){return new F(({storable:t})=>[String(t.getNamespace(this.namespace).get(e))])}get(e){return this.toWord(e)}conditional(e,t,n){return new F(i=>R.from(e).evaluate(i).value?t:n)}evaluate(e,t){return new R(({storable:n})=>t(n.getNamespace(this.namespace).get(e)))}getNamespaceName(){return this.namespace}prefix(e,t=oi.NamespacePrefix){return t+":"+String(e)}createAction(e,t){return new ei(this.chain(),e,v.create(t))}};oi.NamespacePrefix="persistent";var Yt=oi,ri=class ri extends Yt{constructor(e){super(e,{}),this.namespace=this.prefix(e,ri.LocalNamespacePrefix)}init(e){e.removeNamespace(this.namespace).addNamespace(new nt(this.namespace,this.defaultContent))}};ri.LocalNamespacePrefix="local";var Jt=ri;var Zt=class extends U{executeAction(e,t){if(this.type===It.action)return super.executeAction(e,t);if(this.type===It.setZIndex){let[n]=this.contentNode.getContent(),i=this.callee.state.zIndex;return this.callee.state.zIndex=n,e.actionHistory.push({action:this,stackModel:t.stackModel},r=>{this.callee.state.zIndex=r},[i]),e.stage.update(),super.executeAction(e,t)}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("LayerAction")}};Zt.ActionTypes=It;var je=class je extends it{constructor(e,t={}){super();let n=je.DefaultUserConfig.create(t),i=je.DefaultConfig.create({...n.get(),name:e});this.userConfig=n,this.config=i.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState()}include(e){return(Array.isArray(e)?e:[e]).forEach(n=>{n.useLayer(this)}),this}setZIndex(e){return this.chain(new Zt(this.chain(),It.setZIndex,new v().setContent([e])))}toData(){return{state:je.StateSerializer.serialize(this.state)}}fromData(e){return this.state=je.StateSerializer.deserialize(e.state),this}copy(){return new je(this.config.name,this.userConfig.get())}setName(e){return this.config.name=e,this}_init(e){return[new Zt(this.chain(),It.action,new v),new Se(this.chain(),he.init,new v().setContent([e,null,!1]))]}getInitialState(){return je.DefaultState.create({zIndex:this.config.zIndex}).get()}getInitialTransformState(){let[e]=this.userConfig.extract(me.DefaultTransformState.keys());return new me(me.DefaultTransformState.create(e.get()).get())}};je.DefaultUserConfig=new K({zIndex:0,...me.DefaultTransformState.getDefaultConfig(),opacity:1}),je.DefaultConfig=new K({name:"(anonymous)",zIndex:0}),je.StateSerializer=new Le,je.DefaultState=new K({zIndex:0});var _t=je;var Sn=class extends X{constructor(e){super(),this.scene=e}show(e){let t=new O(this.scene.chain(),H.nvlShow,new v().setContent([e]));return this.chain(t)}hide(e){let t=new O(this.scene.chain(),H.nvlHide,new v().setContent([e]));return this.chain(t)}end(){let e=new O(this.scene.chain(),H.nvlEnd,new v().setContent([]));return this.chain(e)}};var De=class De extends Qt{constructor(t,n){super();this.srcManager=new Ae;this.events=new W;this.actions=[];this._futureActions_=[];let i=De.DefaultSceneConfig.getDefaultConfig().defaultBackgroundLayer.copy().setName("[[Background Layer of "+t+"]]"),r=De.DefaultSceneConfig.getDefaultConfig().defaultDisplayableLayer.copy().setName("[[Displayable Layer of "+t+"]]"),s=De.DefaultUserConfig.create(n),a=De.DefaultSceneConfig.create({...s.get(),name:t,layers:[...s.get().layers,i,r],defaultBackgroundLayer:i,defaultDisplayableLayer:r});this.userConfig=s,this.config=a.get(),this.state=this.getInitialState(),this.localPersistent=new Jt(t)}static validateVoice(t){if(t.config.type!=="voice"&&t.config.type!=="sound")throw new ye(`Voice must be a voice, but got ${t.config.type}.
12
- To prevent unintended behavior and unexpected results, the sound have to be marked as voice. Please use \`Sound.voice()\` to create the sound.`)}static isScene(t){return t instanceof De}static getScene(t,n){return typeof n=="string"?t.getScene(n):n}static getStateSerializer(t){return new Le({backgroundImage:n=>n.toData(),backgroundMusic:n=>n?.toData()||null},{backgroundImage:n=>t.state.backgroundImage.fromData(n),backgroundMusic:n=>t.state.backgroundMusic&&n?t.state.backgroundMusic.fromData(n):null})}get __futureActions__(){return this._futureActions_}get local(){return this.localPersistent}get background(){return this.state.backgroundImage}get backgroundLayer(){return this.config.defaultBackgroundLayer}get displayableLayer(){return this.config.defaultDisplayableLayer}setBackground(t,n){return this.chain().chain(He.do([this.background.char(t,n)]))}jumpTo(t,n={}){return this.combineActions(new He({allowFutureScene:!1}),i=>{let s=I({},n instanceof ot?{transition:n}:n);return i.chain(new O(i,"scene:preUnmount",new v().setContent([]))).chain(this._initScene(t))._transitionToScene(s.transition,t.state.backgroundImage.state.currentSrc).chain(this._exit()),i})._jumpTo(t)}setBackgroundMusic(t,n){return this.chain(new O(this.chain(),H.setBackgroundMusic,new v().setContent([t,n])))}nvl(t,n){let i,r;n!==void 0?(i=t,r=n):(i=void 0,r=t);let s=new Sn(this),a=typeof r=="function"?r(s):r,c=this.narrativeToActions(a),l={showTransition:i,hideTransition:i},u=new O(this.chain(),H.nvlEnd,new v().setContent([l])),m=[...c,u];super.constructNodes(m);let p=new O(this.chain(),H.nvlBlock,new v().setContent([m,l]));return this.chain(p)}action(t){return this.actions=t,this}preloadImage(t){if(!A.isImageSrc(t))throw new Error("Invalid image source: "+t);return(Array.isArray(t)?t:[t]).forEach(i=>{this.srcManager.register({type:"image",src:i})}),this}toData(){return{state:De.getStateSerializer(this).serialize(this.state)}}fromData(t){return this.state=De.getStateSerializer(this).deserialize(t.state),this}constructSceneRoot(t){this.sceneRoot=new O(this.chain(),"scene:action",new v);let n=this.actions,r=this.narrativeToActions(typeof n=="function"?n(this):n).map(d=>ge.isChained(d)?d.fromChained(d):d).flat(2),s=[],a=[];this.getAllChildrenElements(t,r,{allowFutureScene:!1}).forEach(d=>{ge.isChained(d)||(d instanceof G?s.push(d):d instanceof Gt&&a.push(d))});let c=[],l=[],u=new Map;s.forEach(d=>{d.config.isWearable?l.push(d):d.config.autoInit&&c.push(d);for(let T of d.config.wearables){if(u.get(T)&&u.get(T)!==d)throw new Error(`Wearable image cannot be used multiple times
9
+ Current _ableToAttach: `+this._ableToAttach);let t=y.isAwaitable(e)?new o(e,this.guard):e;return this.children.push(t),this.guard&&t.setGuard(this.guard),t.onSettled(()=>{this.resolveStatus()}),this}setGuard(e){return this.guard=e,this}catSettled(){return this.children.reduce(([e,t],n)=>(n.isResolved()?e.push(n):n.isCancelled()&&t.push(n),[e,t]),[[],[]])}onTimelineRegistered(e){return this._onTimelineRegistered.push(e),this}resolveStatus(){let e=this.children.find(t=>t.isFailed());this.awaitable.failed||e?this.setStatus("failed",this.emitEvents.bind(this)):this.awaitable.solved&&this.children.every(t=>t.isSettled())?this.setStatus("resolved",this.emitEvents.bind(this)):this.awaitable.skipController?.isAborted()&&this.setStatus("cancelled",this.emitEvents.bind(this))}emitEvents(){if(this.isResolved())this._onResolved.forEach(e=>e());else if(this.isCancelled())this._onCancelled.forEach(e=>e());else if(this.isFailed()){let e=this.children.find(t=>t.isFailed());this._onFailed.forEach(t=>t(this.awaitable.error??e?.awaitable.error))}this._onResolved=[],this._onCancelled=[],this._onFailed=[]}setStatus(e,t){if(this.isSettled()){this.guard&&this.guard.warn("unexpectedTimelineStatusChange",`Trying to resolve a settled timeline: ${this._status} -> ${e}`);return}e!==this._status&&t?(this._status=e,t()):this._status=e}preventAttach(){this._ableToAttach=!1,this._onTimelineRegistered.forEach(e=>e())}},ai=class{constructor(e){this.guard=e;this.timelines=[]}attachTimeline(e){this.cleanupSettled();let t=e instanceof Te?e:new Te(e);return this.timelines.push(t),this.guard&&t.setGuard(this.guard),t}abortAll(){for(let e of this.timelines)e.abort();this.cleanupSettled()}cleanupSettled(){this.timelines=this.timelines.filter(e=>!e.isSettled())}};var nn=class nn extends O{static getVoice(e,t){let n=e.getLastScene();if(!n)throw new Error("No scene found when trying to play voice");let{voiceId:i,voice:r}=t.config;return!i&&!r?null:re.toSound(n.getVoice(i)||r)}static endVoiceWithPreference(e,t){let{voiceEndMode:n,voiceFadeDuration:i}=e.game.preference.getPreferences();if(n==="none")return null;let r=n==="fade"?Math.max(0,i):0;return e.audioManager.stop(t,r)}executeAction(e,t){if(this.type===Jt.say){let n=null,i="",r=null,s=new y(g=>g).registerSkipController(new G(()=>{n?.()})),a=new Te(s),c=this.contentNode.getContent(),l=e.isNvlMode(),p=e.getLiveGame(),u=e.createPresentationSnapshot(),d=p.lastDialog?{sentence:p.lastDialog.sentence,speaker:p.lastDialog.speaker}:null,h=nn.getVoice(e,c);if(h){let g=e.audioManager.play(h);a.attachChild(g)}let m=h?e.events.on(k.EventTypes["event:state.player.lineEnd"],()=>{let g=nn.endVoiceWithPreference(e,h);g&&e.timelines.attachTimeline(g),m?.cancel()}):null;if(l){let g=this.getId(),f=(e.getActiveNvlDialogForAction(g)||e.getLatestNvlDialogForAction(g))?.id||e.allocateNvlDialogId(g),T=c.evaluate(ue.getCtx({gameState:e}));i=W.getText(T),p.events.emit(lt.EventTypes["event:character.prompt"],{character:c.config.character,sentence:c,text:i});let C=!1,I=()=>{C||(C=!0,e.events.emit(k.EventTypes["event:state.player.lineEnd"]),e.gameHistory.resolvePending(v),s.resolve({type:this.type,node:this.contentNode.getChild()}))},{created:N}=e.ensureNvlDialog({id:f,actionId:g,character:this.callee,sentence:c,text:i});r=f;let X=e.consumeNvlTypingSuppression(),he=N&&!X?"typing":"awaitAdvance";e.activateNvlDialog(f,he,!N);let ge=e.waitForNvlAdvance(f,()=>{e.settleNvlDialog(f),I()});n=()=>{ge.cancel()}}else{let g=e.idManager.generateId(),S=e.createDialog(g,c,()=>{e.gameHistory.resolvePending(v),s.resolve({type:this.type,node:this.contentNode.getChild()})});i=S.text,n=S.cancel}p.setLastDialog(i,this.callee.state.name),e.timelines.attachTimeline(a);let{id:v}=e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:a},()=>{if(m?.cancel(),h&&e.audioManager.isPlaying(h)){let g=nn.endVoiceWithPreference(e,h);g&&a.attachChild(g)}n?.(),r&&(e.removeNvlDialog(r),e.settleNvlDialog(r)),e.restorePresentationSnapshot(u),d?p.setLastDialog(d.sentence,d.speaker):p.lastDialog=null});return e.gameHistory.push({token:v,action:this,element:{type:"say",text:i,voice:h?h.getSrc():null,character:this.callee.state.name},isPending:!0}),s}else if(this.type===Jt.setName){let n=this.callee.state.name;return this.callee.state.name=this.contentNode.getContent()[0],e.actionHistory.push({action:this,stackModel:t.stackModel},i=>{this.callee.state.name=i},[n]),super.executeAction(e,t)}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("CharacterAction")}};nn.ActionTypes=Jt;var Ze=nn;var wn=class wn extends te{constructor(e,t={}){super(),this.config=H(wn.defaultConfig,t),this.state={name:e||""};let n=this,i=function(r,s,...a){return n.call(r,s,...a)};return new Proxy(i,{get(r,s){return n[s]},set(r,s,a){return n[s]=a,!0},has(r,s){return s in n}})}say(e,t,...n){if(Array.isArray(e)&&e.every(c=>typeof c=="string")&&[t,...n].length>0&&[t,...n].every(c=>ie.isSingleWord(c))){let c=e,l=ie.format([t,...n]),p=new ie(pr(c,l),{character:this}),u=new Ze(this.chain(),Ze.ActionTypes.say,new b().setContent(p));return this.chain(u)}let i=t||{},r=e,s=Array.isArray(r)?new ie(r,{...i,character:this}):(ie.isSentence(r)?r:new ie(r,{...i,character:this})).copy();s.setCharacter(this);let a=new Ze(this.chain(),Ze.ActionTypes.say,new b().setContent(s));return this.chain(a)}setName(e){let t=new Ze(this.chain(),Ze.ActionTypes.setName,new b().setContent([e]));return this.chain(t)}setAvatar(e){return this.config.avatar=e===null?null:e,this}addPortrait(e,t={}){return this.config.portraits.push({image:e,avatar:t.avatar}),this}setPortraits(e){return this.config.portraits=[...e],this}apply(e,t,...n){return this.say.apply(this,[e,t,...n])}call(e,t,...n){return Array.isArray(e)&&"raw"in e?t&&ie.isSingleWord(t)?this.say(e,t,...n):this.say(e):typeof e=="string"?this.say(e,t):ie.isSentence(e)?this.say(e):this.say(e,t)}};wn.defaultCharacterColor="#000",wn.defaultConfig={portraits:[]};var ci=wn,St=new ci(null);var F=class o{static isLambda(e){return e instanceof o&&"handler"in e}static isLambdaHandler(e){return typeof e=="function"}static from(e){return o.isLambda(e)?e:new o(e)}static not(e){return new o(t=>!e.evaluate(t).value)}constructor(e){this.handler=e}evaluate({gameState:e}){return{value:this.handler(this.getCtx({gameState:e}))}}getCtx({gameState:e}){let t=e.game.getLiveGame(),n=t.getStorable();return{gameState:e,game:e.game,liveGame:t,storable:n,$:i=>n.getNamespace(i)}}toString(){return`Lambda(${this.handler.toString()})`}},oo=class o extends te{constructor(){super();this.conditions={If:{condition:null,action:null},ElseIf:[],Else:{action:null}}}static getInitialState(){return{If:{condition:null,action:null},ElseIf:[],Else:{action:null}}}static If(t,n){return new o().createIfCondition(t,n)}ElseIf(t,n){if(this.conditions.Else.action)throw new Se(`ELSE condition already set
10
+ You are trying to set an ELSE-IF condition after an ELSE condition`);return this.conditions.ElseIf.push({condition:F.from(t),action:this.construct(Array.isArray(n)?n:[n])}),this.chain()}Else(t){if(this.conditions.Else.action)throw new Se(`ELSE condition already set
11
+ You are trying to set multiple ELSE conditions for the same condition`);return this.conditions.Else.action=this.construct(Array.isArray(t)?t:[t]),this.chain()}evaluate(t,{gameState:n}){let i={gameState:n};if(t.If.condition?.evaluate(i)?.value)return t.If.action||null;for(let s of t.ElseIf)if(s.condition?.evaluate(i)?.value)return s.action||null;return t.Else.action||null}fromChained(t){return[Reflect.construct(rt,[this,rt.ActionTypes.action,new b().setContent(t.conditions)])]}construct(t,n,i){let r=this.narrativeToActions(t);for(let s=0;s<r.length;s++){let a=r[s].contentNode,c=r[s+1]?.contentNode;c&&a.setChild(c),s===r.length-1&&n&&a.setChild(n),s===0&&i&&i.setChild(a)}return r}_getFutureActions(){return Ae.toActions([this.conditions.If.action?.[0]||[],...this.conditions.ElseIf.flatMap(t=>t.action?.[0]||[]),this.conditions.Else.action?.[0]||[]])}createIfCondition(t,n){this.conditions.If.condition=F.from(t),this.conditions.If.action=this.construct(n);let i=this.chain(),r=new rt(i,rt.ActionTypes.action,new b().setContent(this.conditions));return i.chain(r)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?St.say(n).getActions():Ae.toActions([n]))}};var li=class li extends te{constructor(e,t){super(),this.namespace=this.prefix(e),this.defaultContent=t}init(e){e.hasNamespace(this.namespace)||e.addNamespace(new st(this.namespace,this.defaultContent))}getNamespace(e){return e.getNamespace(this.namespace)}set(e,t){return this.chain(this.createAction(yn.set,[e,t]))}assign(e){return this.chain(this.createAction(yn.assign,[e]))}equals(e,t){return new F(n=>{let i=n.storable.getNamespace(this.namespace),r=F.isLambda(t)||F.isLambdaHandler(t)?F.from(t).evaluate(n).value:t;return i.equals(e,r)})}notEquals(e,t){return new F(n=>{let i=n.storable.getNamespace(this.namespace),r=F.isLambda(t)||F.isLambdaHandler(t)?F.from(t).evaluate(n).value:t;return!i.equals(e,r)})}isTrue(e){return new F(({storable:t})=>t.getNamespace(this.namespace).equals(e,!0))}isFalse(e){return new F(({storable:t})=>t.getNamespace(this.namespace).equals(e,!1))}isNotNull(e){return new F(({storable:t})=>{let n=t.getNamespace(this.namespace).get(e);return n!=null})}toWord(e){return new W(({storable:t})=>[String(t.getNamespace(this.namespace).get(e))])}get(e){return this.toWord(e)}conditional(e,t,n){return new W(i=>F.from(e).evaluate(i).value?t:n)}evaluate(e,t){return new F(({storable:n})=>t(n.getNamespace(this.namespace).get(e)))}getNamespaceName(){return this.namespace}prefix(e,t=li.NamespacePrefix){return t+":"+String(e)}createAction(e,t){return new ri(this.chain(),e,b.create(t))}};li.NamespacePrefix="persistent";var on=li,ui=class ui extends on{constructor(e){super(e,{}),this.namespace=this.prefix(e,ui.LocalNamespacePrefix)}init(e){e.removeNamespace(this.namespace).addNamespace(new st(this.namespace,this.defaultContent))}};ui.LocalNamespacePrefix="local";var rn=ui;var sn=class extends O{executeAction(e,t){if(this.type===Ut.action)return super.executeAction(e,t);if(this.type===Ut.setZIndex){let[n]=this.contentNode.getContent(),i=this.callee.state.zIndex;return this.callee.state.zIndex=n,e.actionHistory.push({action:this,stackModel:t.stackModel},r=>{this.callee.state.zIndex=r},[i]),e.stage.update(),super.executeAction(e,t)}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("LayerAction")}};sn.ActionTypes=Ut;var Qe=class Qe extends at{constructor(e,t={}){super();let n=Qe.DefaultUserConfig.create(t),i=Qe.DefaultConfig.create({...n.get(),name:e});this.userConfig=n,this.config=i.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState()}include(e){return(Array.isArray(e)?e:[e]).forEach(n=>{n.useLayer(this)}),this}setZIndex(e){return this.chain(new sn(this.chain(),Ut.setZIndex,new b().setContent([e])))}toData(){return{state:Qe.StateSerializer.serialize(this.state),transformState:this.transformState.serialize()}}fromData(e){return this.state=Qe.StateSerializer.deserialize(e.state),this.transformState=me.deserialize(e.transformState),this}copy(){return new Qe(this.config.name,this.userConfig.get())}setName(e){return this.config.name=e,this}_init(e){return[new sn(this.chain(),Ut.action,new b),new Ce(this.chain(),be.init,new b().setContent([e,null,!1]))]}getInitialState(){return Qe.DefaultState.create({zIndex:this.config.zIndex}).get()}getInitialTransformState(){let[e]=this.userConfig.extract(me.DefaultTransformState.keys());return new me(me.DefaultTransformState.create(e.get()).get())}};Qe.DefaultUserConfig=new j({zIndex:0,...me.DefaultTransformState.getDefaultConfig(),opacity:1}),Qe.DefaultConfig=new j({name:"(anonymous)",zIndex:0}),Qe.StateSerializer=new He,Qe.DefaultState=new j({zIndex:0});var an=Qe;var kn=class extends te{constructor(e){super(),this.scene=e}show(e){let t=new Y(this.scene.chain(),V.nvlShow,new b().setContent([e]));return this.chain(t)}hide(e){let t=new Y(this.scene.chain(),V.nvlHide,new b().setContent([e]));return this.chain(t)}end(){let e=new Y(this.scene.chain(),V.nvlEnd,new b().setContent([]));return this.chain(e)}};var Me=class Me extends tn{constructor(t,n){super();this.srcManager=new De;this.events=new J;this.actions=[];this._futureActions_=[];let i=Me.DefaultSceneConfig.getDefaultConfig().defaultBackgroundLayer.copy().setName("[[Background Layer of "+t+"]]"),r=Me.DefaultSceneConfig.getDefaultConfig().defaultDisplayableLayer.copy().setName("[[Displayable Layer of "+t+"]]"),s=Me.DefaultUserConfig.create(n),a=Me.DefaultSceneConfig.create({...s.get(),name:t,layers:[...s.get().layers,i,r],defaultBackgroundLayer:i,defaultDisplayableLayer:r});this.userConfig=s,this.config=a.get(),this.state=this.getInitialState(),this.localPersistent=new rn(t)}static validateVoice(t){if(t.config.type!=="voice"&&t.config.type!=="sound")throw new Se(`Voice must be a voice, but got ${t.config.type}.
12
+ To prevent unintended behavior and unexpected results, the sound have to be marked as voice. Please use \`Sound.voice()\` to create the sound.`)}static isScene(t){return t instanceof Me}static getScene(t,n){return typeof n=="string"?t.getScene(n):n}static getStateSerializer(t){return new He({backgroundImage:n=>n.toData(),backgroundMusic:n=>n?.toData()||null},{backgroundImage:n=>t.state.backgroundImage.fromData(n),backgroundMusic:n=>t.state.backgroundMusic&&n?t.state.backgroundMusic.fromData(n):null})}get __futureActions__(){return this._futureActions_}get local(){return this.localPersistent}get background(){return this.state.backgroundImage}get backgroundLayer(){return this.config.defaultBackgroundLayer}get displayableLayer(){return this.config.defaultDisplayableLayer}setBackground(t,n){return this.chain().chain(xe.do([this.background.char(t,n)]))}jumpTo(t,n={}){return this.combineActions(new xe({allowFutureScene:!1}),i=>{let s=H({},n instanceof ct?{transition:n}:n);return i.chain(new Y(i,"scene:preUnmount",new b().setContent([]))).chain(this._initScene(t))._transitionToScene(s.transition,t.state.backgroundImage.state.currentSrc).chain(this._exit()),i})._jumpTo(t)}setBackgroundMusic(t,n){return this.chain(new Y(this.chain(),V.setBackgroundMusic,new b().setContent([t,n])))}nvl(t,n){let i,r;n!==void 0?(i=t,r=n):(i=void 0,r=t);let s=new kn(this),a=typeof r=="function"?r(s):r,c=this.narrativeToActions(a),l={showTransition:i,hideTransition:i},p=new Y(this.chain(),V.nvlEnd,new b().setContent([l])),u=[...c,p];super.constructNodes(u);let d=new Y(this.chain(),V.nvlBlock,new b().setContent([u,l]));return this.chain(d)}action(t){return this.actions=t,this}preloadImage(t){if(!A.isImageSrc(t))throw new Error("Invalid image source: "+t);return(Array.isArray(t)?t:[t]).forEach(i=>{this.srcManager.register({type:"image",src:i})}),this}toData(){return{state:Me.getStateSerializer(this).serialize(this.state)}}fromData(t){return this.state=Me.getStateSerializer(this).deserialize(t.state),this}constructSceneRoot(t){this.sceneRoot=new Y(this.chain(),"scene:action",new b);let n=this.actions,r=this.narrativeToActions(typeof n=="function"?n(this):n).map(m=>Ae.isChained(m)?m.fromChained(m):m).flat(2),s=[],a=[];this.getAllChildrenElements(t,r,{allowFutureScene:!1}).forEach(m=>{Ae.isChained(m)||(m instanceof U?s.push(m):m instanceof Vt&&a.push(m))});let c=[],l=[],p=new Map;s.forEach(m=>{m.config.isWearable?l.push(m):m.config.autoInit&&c.push(m);for(let v of m.config.wearables){if(p.get(v)&&p.get(v)!==m)throw new Error(`Wearable image cannot be used multiple times
13
13
  Maybe you bind the same wearable image to multiple parent images
14
- Parent Conflict (src: `+u.get(T)?.state.currentSrc+`)
15
- Current Parent (src: `+d.state.currentSrc+")");u.set(T,d)}});let m=[...this._initScene(this),...c.map(d=>d._init(this)),...l.map(d=>{if(!u.has(d))throw new Error("Wearable image must have a parent image");return u.get(d)._initWearable(d)}),...a.map(d=>d._init()),...r],p=super.constructNodes(m),h=new v(this.sceneRoot,void 0,p||void 0).setContent(this);return p?.setParent(h),this.sceneRoot?.setContentNode(h),this._futureActions_=m,this}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?wt.say(n).getActions():ge.toActions([n]))}isSceneRootConstructed(){return!!this.sceneRoot}registerSrc(t,n=new Set){if(!this.sceneRoot)return;let i=new Set,r=new Set,s=[this.sceneRoot],a=new Set;for(;s.length;){let c=s.shift();if(!i.has(c)){if(i.add(c),c instanceof O){let l=c.callee;if(A.isImageSrc(l.state.backgroundImage.state.currentSrc)&&this.srcManager.register({type:"image",src:A.srcToURL(l.state.backgroundImage.state.currentSrc)}),c.type===H.jumpTo){let u=c,m=De.getScene(t,u.contentNode.getContent()[0]);if(!m)throw c._sceneNotFoundError(c.getSceneName(u.contentNode.getContent()[0]));let p=Ae.getPreloadableSrc(t,c);if(p&&this.srcManager.register(p),r.has(u)||n.has(m))continue;r.add(u),a.add(m),n.add(m)}}else if(c instanceof Y){let l=Ae.getPreloadableSrc(t,c);l&&this.srcManager.register(l)}else if(c instanceof Re)this.srcManager.register(c.callee);else if(c instanceof _){let u=c.getFutureActions(t,{allowFutureScene:!0});s.push(...u)}else c instanceof Se&&this.srcManager.register(c.callee.srcManager.getSrc());s.push(...c.getFutureActions(t,{allowFutureScene:!0}))}}a.forEach(c=>{c.registerSrc(t,n),this.srcManager.registerFuture(c.srcManager)})}assignActionId(t){this.getAllChildren(t,this.sceneRoot||[],{allowFutureScene:!0}).forEach((i,r)=>{i.setId(`a-${r}`)})}assignElementId(t){this.getAllChildrenElements(t,this.sceneRoot||[]).forEach((i,r)=>{i.setId(`e-${r}`)})}getVoice(t){if(!t)return null;let n=this.config.voices;if(n){if(typeof n=="function"){let r=n(t);return typeof r=="string"?Z.voice(r):(De.validateVoice(r),r)}let i=n[t];return typeof i=="string"?Z.voice(i):i||null}return null}getSceneRoot(){if(!this.sceneRoot)throw new Error("Scene root is not constructed");return this.sceneRoot}stringify(t,n,i){return super.getAllChildren(t,this.sceneRoot||[],{allowFutureScene:!0}).map(r=>r.stringify(t,n,i)).join(";")}reset(){this.state.backgroundImage.reset(),this.state.backgroundMusic?.reset(),this.state=this.getInitialState()}getInitialState(){let t=this.userConfig.get();if(t.backgroundMusic&&t.backgroundMusic.config.type!=="bgm")throw new ye(`[Scene: ${this.config.name}] Background music must be a bgm, but got ${t.backgroundMusic.config.type}.
16
- To prevent unintended behavior and unexpected results, the sound have to be marked as bgm. Please use \`Sound.bgm()\` to create the sound.`);let n=this.state?.backgroundImage?this.state.backgroundImage.reset():new G({src:t.background,opacity:1,autoFit:!0,name:`[[Background Image of ${this.config.name}]]`,layer:this.config.defaultBackgroundLayer})._setIsBackground(!0),i=t.backgroundMusic?this.state?.backgroundMusic?this.state.backgroundMusic.reset():t.backgroundMusic:null;return{backgroundImage:n,backgroundMusic:i}}_jumpTo(t){return this.chain(new O(this.chain(),"scene:jumpTo",new v().setContent([t])))}_exit(){return new O(this.chain(),"scene:exit",new v().setContent([]))}_transitionToScene(t,n){let i=this.chain();if(t&&n){let r=this.state.backgroundImage.char(n,t);i.chain(r.getActions())}return i}_init(t){return new O(this.chain(),"scene:init",new v().setContent([t]))}_initScene(t){return[t._init(t),...t.config.layers.flatMap(n=>n._init(t)),...t._initBackground(t,t.config.defaultBackgroundLayer)]}_initBackground(t,n){return[t.state.backgroundImage._init(t,n)]}};De.EventTypes={"event:scene.remove":"event:scene.remove","event:scene.load":"event:scene.load","event:scene.unload":"event:scene.unload","event:scene.mount":"event:scene.mount","event:scene.unmount":"event:scene.unmount","event:scene.preUnmount":"event:scene.preUnmount","event:scene.imageLoaded":"event:scene.imageLoaded"},De.DefaultUserConfig=new K({backgroundMusic:null,backgroundMusicFade:0,voices:void 0,background:"#fff",layers:[]}),De.DefaultSceneConfig=new K({name:"",backgroundMusicFade:0,voices:null,layers:[],defaultBackgroundLayer:new _t("[[Background Layer]]",{zIndex:-1}),defaultDisplayableLayer:new _t("[[Displayable Layer]]",{zIndex:0})},{voices:t=>{let n=r=>typeof r=="object"&&r!==null,i=r=>typeof r=="function";if(!t)return null;if(n(t)&&Object.values(t).forEach(r=>{Z.isSound(r)&&De.validateVoice(r)}),i(t))return t;throw new ye(`Invalid voices config: ${t}`)}});var Ue=De;import*as hr from"howler";var si=class{constructor(e,t){this.game=e,this.prefix=t}log(e,...t){this.isEnabled("log")&&console.log(...this.colorLog("gray",e,...t))}info(e,...t){this.isEnabled("info")&&console.info(...this._log(e,...t))}warn(e,...t){this.isEnabled("warn")&&console.warn(...this._log(e,...t))}error(e,...t){this.isEnabled("error")&&console.error(...this._log(e,...t))}debug(e,...t){this.isEnabled("debug")&&console.debug(...this.colorLog("gray",e,...t))}trace(e,...t){this.isEnabled("trace")&&console.trace(this._log(e,...t))}weakWarn(e,...t){this.isEnabled("warn")&&console.log(...this.colorLog("yellow",e,...t))}weakError(e,...t){this.isEnabled("error")&&console.log(...this.colorLog("red",e,...t))}verbose(e,...t){this.isEnabled("verbose")&&console.log(...this.colorLog("gray",e,...t))}group(e,t=!1){let n=this._log(e).join(" ");return this.isEnabled("info")&&(t?console.groupCollapsed(n):console.group(n)),{end:()=>{this.isEnabled("info")&&console.groupEnd()}}}isEnabled(e){return typeof this.game.config.app.logger=="boolean"?this.game.config.app.logger:this.game.config.app.logger[e]}_log(e,...t){return t.length===0?[this.prefix||"",e]:[`${this.prefix||""} [${e}]`,...t]}colorLog(e,t,...n){if(n.length===0)return[`%c${this.prefix||""} ${t}`,`color: ${e}`];let i=[],r=[],s=[];return this.prefix?(i.push(`%c${this.prefix} [${t}]`),r.push(`color: ${e}`)):(i.push(`%c[${t}]`),r.push(`color: ${e}`)),n.forEach(a=>{typeof a=="string"?(i.push(`%c${a}`),r.push(`color: ${e}`)):(i.push("%O"),s.push(a),r.push(""))}),[i.join(" ")].concat(r,s)}};var Us={volume:1,limit:1/0},Fs=class dr{constructor(e,t,n,i){this.subChannels=new Map,this.tokens=new Set,this.tokenQueue=[],this.muted=!1,this.removed=!1,this.name=e,this.audioProvider=t,this.parentChannel=i??null,this.options={...Us,...n},this.volume=this.options.volume;let r=this.audioProvider.getAudioContext();this.gainNode=r.createGain(),this.gainNode.gain.value=this.muted?0:this.volume,this.connectToParent()}connectToParent(){this.parentChannel?this.gainNode.connect(this.parentChannel.getGainNode()):this.gainNode.connect(this.audioProvider.getAudioContext().destination)}getGainNode(){return this.gainNode}ensureNotRemoved(){if(this.removed)throw new Error(`Channel "${this.name}" has been removed and cannot be used.`)}getName(){return this.name}async play(e,t){if(this.ensureNotRemoved(),this.tokens.size>=this.options.limit){let r=this.tokenQueue.shift();r&&r.stop()}let n=await this.audioProvider.createToken(e,t,this.gainNode);this.tokens.add(n),this.tokenQueue.push(n);let i=()=>{this.tokens.delete(n);let r=this.tokenQueue.indexOf(n);r!==-1&&this.tokenQueue.splice(r,1)};return n.once("ended",i),n.once("stop",i),n}createChannel(e,t){if(this.ensureNotRemoved(),this.subChannels.has(e))throw new Error(`Channel "${e}" already exists under "${this.name}".`);this.audioProvider.checkChannelLimit();let n=new dr(e,this.audioProvider,t,this);return this.subChannels.set(e,n),this.audioProvider.registerChannel(n),n}getChannel(e){return this.ensureNotRemoved(),this.subChannels.get(e)??null}getChannels(){return this.ensureNotRemoved(),Array.from(this.subChannels.values())}setVolume(e){return this.ensureNotRemoved(),this.volume=Math.max(0,Math.min(1,e)),this.muted||(this.gainNode.gain.value=this.volume),this}getVolume(){return this.volume}mute(e){return this.ensureNotRemoved(),this.muted=e!==void 0?e:!0,this.gainNode.gain.value=this.muted?0:this.volume,this}unmute(){return this.mute(!1)}isMuted(){return this.muted}remove(){if(this.removed)return this;this.removed=!0;for(let t of this.tokens)t.stop();this.tokens.clear();let e=Array.from(this.subChannels.values());this.subChannels.clear();for(let t of e)t.remove();try{this.gainNode.disconnect()}catch(t){console.warn("Failed to disconnect Channel gain node during remove().",t)}return this.audioProvider.unregisterChannel(this),this.parentChannel&&this.parentChannel.removeSubChannel(this.name),this}removeSubChannel(e){this.subChannels.delete(e)}getTokens(){this.ensureNotRemoved();let e=[...this.tokenQueue];for(let t of this.subChannels.values())e.push(...t.getTokens());return e}isRemoved(){return this.removed}getParent(){return this.parentChannel}getOptions(){return{...this.options}}},mr=!1;function Ks(o){mr=o}function kt(o,e){mr||(e!==void 0?console.warn(o,e):console.warn(o))}var Vs=class{constructor(o,e){this.currentSource=null,this.mediaElementSource=null,this.endedHandler=null,this.eventListeners=new Map,this.audioContext=o,this.gainNode=e}setSource(o){this.disconnectSource(),this.currentSource=o,o instanceof AudioBufferSourceNode?o.connect(this.gainNode):o instanceof HTMLAudioElement&&(this.mediaElementSource=this.audioContext.createMediaElementSource(o),this.mediaElementSource.connect(this.gainNode)),this.setupEventListeners()}getSource(){return this.currentSource}refreshSource(o){let e=new Map(this.eventListeners);this.disconnectSource(),this.currentSource=o,o instanceof AudioBufferSourceNode?o.connect(this.gainNode):o instanceof HTMLAudioElement&&(this.mediaElementSource=this.audioContext.createMediaElementSource(o),this.mediaElementSource.connect(this.gainNode)),this.eventListeners=e,this.setupEventListeners()}disconnectSource(){if(this.currentSource){if(this.removeAllEventListeners(),this.currentSource instanceof AudioBufferSourceNode)try{this.currentSource.disconnect()}catch(o){kt("Failed to disconnect AudioBufferSourceNode in disconnectSource().",o)}else this.currentSource instanceof HTMLAudioElement&&(this.currentSource.pause(),this.currentSource.src="",this.currentSource.load());if(this.mediaElementSource){try{this.mediaElementSource.disconnect()}catch(o){kt("Failed to disconnect MediaElementAudioSourceNode in disconnectSource().",o)}this.mediaElementSource=null}this.currentSource=null}}setupEventListeners(){this.currentSource&&(this.endedHandler=o=>{this.emit("ended")},this.currentSource instanceof HTMLAudioElement?this.currentSource.addEventListener("ended",this.endedHandler):this.currentSource instanceof AudioBufferSourceNode&&this.currentSource.addEventListener("ended",this.endedHandler))}removeAllEventListeners(){!this.currentSource||!this.endedHandler||(this.currentSource instanceof HTMLAudioElement?this.currentSource.removeEventListener("ended",this.endedHandler):this.currentSource instanceof AudioBufferSourceNode&&this.currentSource.removeEventListener("ended",this.endedHandler),this.endedHandler=null)}emit(o){let e=this.eventListeners.get(o);e&&[...e].forEach((t,n)=>{try{t.callback()}catch(i){console.error(`Error in event listener for '${o}':`,i)}t.once&&e.splice(e.indexOf(t),1)})}on(o,e){this.eventListeners.has(o)||this.eventListeners.set(o,[]),this.eventListeners.get(o).push({callback:e,once:!1})}off(o,e){let t=this.eventListeners.get(o);if(!t)return;let n=t.findIndex(i=>i.callback===e);n!==-1&&t.splice(n,1)}once(o,e){this.eventListeners.has(o)||this.eventListeners.set(o,[]),this.eventListeners.get(o).push({callback:e,once:!0})}stop(){if(this.currentSource){if(this.currentSource instanceof HTMLAudioElement)this.currentSource.pause(),this.currentSource.currentTime=0;else if(this.currentSource instanceof AudioBufferSourceNode)try{this.currentSource.stop()}catch(o){kt("Failed to stop AudioBufferSourceNode in stop().",o)}}}destroy(){this.disconnectSource(),this.eventListeners.clear()}start(o=0,e=0){this.currentSource instanceof AudioBufferSourceNode?this.currentSource.start(o,e):this.currentSource instanceof HTMLAudioElement&&this.currentSource.play()}pause(){this.currentSource instanceof HTMLAudioElement?this.currentSource.pause():this.currentSource instanceof AudioBufferSourceNode&&this.stop()}},pr=class{constructor(o,e){this.token=o,this.endVolume=e,this.cancelled=!1,this.finishedInternal=!1,this._finished=new Promise(t=>{this.resolveFinished=t})}get finished(){return this._finished}cancel(){this.cancelled||this.finishedInternal||(this.cancelled=!0,this.resolveFinished())}finish(){this.finishedInternal||(this.finishedInternal=!0,this.token.setVolume(this.endVolume),this.resolveFinished())}isCancelled(){return this.cancelled}isFinished(){return this.finishedInternal}getTargetVolume(){return this.endVolume}},Os=class{constructor(o,e,t={},n){this._isPlaying=!1,this._isPaused=!1,this._isMuted=!1,this.volume=1,this.rate=1,this.contextStartTime=0,this.startOffset=0,this.pauseOffset=0,this.duration=0,this.currentFade=null,this.audioContext=o,this.volume=t.volume??1,this.rate=t.rate??1,this.startOffset=t.startOffset??0,this.duration=t.duration??0,this.outputNode=n??o.destination,this.gainNode=o.createGain(),this.gainNode.gain.value=this.volume,this.gainNode.connect(this.outputNode),this.sourceController=new Vs(o,this.gainNode),this.sourceController.setSource(e);let i=this.startOffset;this.sourceController.start(0,i),this.contextStartTime=this.audioContext.currentTime,this._isPlaying=!0,this.duration>0&&setTimeout(()=>{this._isPlaying&&this.stop()},this.duration*1e3)}emit(o){if(this.sourceController.emit(o),o==="ended"){this._isPlaying=!1;try{this.gainNode.disconnect()}catch(e){kt("Failed to disconnect gain node on natural end.",e)}}}setVolume(o){return this.currentFade&&(this.currentFade.cancel(),this.currentFade=null),o=Math.max(0,Math.min(1,o)),this.volume=o,this._isMuted||(this.gainNode.gain.cancelScheduledValues(this.audioContext.currentTime),this.gainNode.gain.value=o),this}getVolume(){return this.volume}mute(o){let e=o!==void 0?o:!0;if(this._isMuted=e,this.currentFade&&!this.currentFade.isFinished()&&!this.currentFade.isCancelled()){let t=this.currentFade.getTargetVolume();this.gainNode.gain.cancelScheduledValues(this.audioContext.currentTime),this.volume=t,this.gainNode.gain.value=e?0:t,this.currentFade.finish(),this.currentFade=null}else this.gainNode.gain.cancelScheduledValues(this.audioContext.currentTime),this.gainNode.gain.value=e?0:this.volume;return this}unmute(){return this.mute(!1)}isMuted(){return this._isMuted}pause(){if(!this._isPlaying||this._isPaused)return this;let o=this.sourceController.getSource();return o instanceof HTMLAudioElement?(o.pause(),this.pauseOffset=o.currentTime):o instanceof AudioBufferSourceNode&&(this.pauseOffset=this.getCurrentTime(),this.sourceController.stop()),this._isPlaying=!1,this._isPaused=!0,this.emit("pause"),this}resume(){if(!this._isPaused)return this;let o=this.sourceController.getSource();if(o instanceof HTMLAudioElement){let e=o.play();e&&typeof e.catch=="function"&&e.catch(()=>{this._isPlaying=!1,this._isPaused=!0})}else if(o instanceof AudioBufferSourceNode){let e=this.audioContext.createBufferSource();e.buffer=o.buffer,e.playbackRate.value=this.rate,e.loop=o.loop,e.loopStart=o.loopStart,e.loopEnd=o.loopEnd,this.sourceController.refreshSource(e),this.startOffset=this.pauseOffset,this.contextStartTime=this.audioContext.currentTime,this.sourceController.start(0,this.pauseOffset)}return this._isPlaying=!0,this._isPaused=!1,this.emit("resume"),this}isPlaying(){return this._isPlaying}isPaused(){return this._isPaused}stop(o={}){let{fadeDuration:e=0}=o;return e>0?this.fade(this.getVolume(),0,e).finished.then(()=>{this.doStop()}):this.doStop(),this}doStop(){this.sourceController.stop(),this._isPlaying=!1,this._isPaused=!1,this.emit("stop"),this.sourceController.destroy();try{this.gainNode.disconnect()}catch(o){kt("Failed to disconnect gain node on stop().",o)}}setRate(o){o=Math.max(.001,o),this.rate=o;let e=this.sourceController.getSource();return e instanceof HTMLAudioElement?e.playbackRate=o:e instanceof AudioBufferSourceNode&&(e.playbackRate.value=o),this}getRate(){return this.rate}seek(o){o=Math.max(0,o);let e=this.sourceController.getSource();if(e instanceof HTMLAudioElement)e.currentTime=o,this.emit("seek");else if(e instanceof AudioBufferSourceNode){let t=this.getCurrentTime();if(Math.abs(o-t)>.01){if(this._isPlaying){this.sourceController.stop();let n=this.audioContext.createBufferSource();n.buffer=e.buffer,n.playbackRate.value=this.rate,n.loop=e.loop,n.loopStart=e.loopStart,n.loopEnd=e.loopEnd,this.sourceController.refreshSource(n),this.startOffset=this.audioContext.currentTime-o,this.sourceController.start(0,o)}else this._isPaused&&(this.pauseOffset=o);this.emit("seek")}}return this}getCurrentTime(){let o=this.sourceController.getSource();if(o instanceof HTMLAudioElement)return o.currentTime;if(o instanceof AudioBufferSourceNode){if(this._isPaused)return this.pauseOffset;if(this._isPlaying)return(this.audioContext.currentTime-this.contextStartTime)*this.rate+this.startOffset}return 0}getDuration(){let o=this.sourceController.getSource();return o instanceof HTMLAudioElement?o.duration||0:o instanceof AudioBufferSourceNode&&o.buffer?o.buffer.duration:this.duration}fade(o,e,t){if(this.currentFade&&this.currentFade.cancel(),o=Math.max(0,Math.min(1,o)),e=Math.max(0,Math.min(1,e)),t=Math.max(0,t),t===0){this.setVolume(e);let r=new pr(this,e);return r.finish(),r}this.volume=o,this._isMuted||(this.gainNode.gain.value=o);let n=new pr(this,e);this.currentFade=n;let i=this.audioContext.currentTime;return this.gainNode.gain.setValueAtTime(o,i),this.gainNode.gain.linearRampToValueAtTime(e,i+t/1e3),setTimeout(()=>{!n.isCancelled()&&!n.isFinished()&&(this.volume=e,n.finish(),this.currentFade=null)},t),n}on(o,e){return this.sourceController.on(o,e),this}off(o,e){return this.sourceController.off(o,e),this}once(o,e){return this.sourceController.once(o,e),this}},Ws=class{constructor(o){this.alive=!0,this.refCount=0,this.audioBuffer=o}addRef(){this.refCount++}releaseRef(){this.refCount>0&&this.refCount--}getRefCount(){return this.refCount}async unload(){this.refCount>0||(this.alive=!1)}async forceUnload(){this.alive=!1,this.refCount=0}isAlive(){return this.alive}raw(){if(!this.alive)throw new Error("CachedAudio has been unloaded.");return this.audioBuffer}},zs=10*1024*1024,Bs=class{constructor(o){this.cache=new Map,this.loadingPromises=new Map,this.audioContext=o}async load(o){let e=this.cache.get(o);if(e&&e.isAlive())return e;let t=this.loadingPromises.get(o);if(t)return t;let n=this.doLoad(o);this.loadingPromises.set(o,n);try{let i=await n;return this.cache.set(o,i),i}finally{this.loadingPromises.delete(o)}}async doLoad(o){let e=await(await fetch(o)).arrayBuffer(),t=await this.audioContext.decodeAudioData(e);return new Ws(t)}clear(){for(let o of this.cache.values())o.forceUnload();this.cache.clear(),this.loadingPromises.clear()}getStats(){return{cached:this.cache.size,loading:this.loadingPromises.size}}},$s={volume:1,latencyHint:"interactive",sampleRate:44100,maxChannels:128,silent:!1},fr=class{constructor(o){this.registeredChannels=new Set,this.isReady=!1,this.readyPromise=null,this.destroyed=!1,this.unlockHandler=null,this.options={...$s,...o},Ks(!!this.options.silent),this.audioContext=new AudioContext({latencyHint:this.options.latencyHint,sampleRate:this.options.sampleRate}),this.audioCache=new Bs(this.audioContext),this.masterChannel=new Fs("__master__",this,{volume:this.options.volume},null),this.initialize()}async onceReady(){return this.readyPromise?(await this.readyPromise,this):this}initialize(){this.isReady||(this.readyPromise=this.waitForUnlock())}waitForUnlock(){return typeof document>"u"?(this.isReady=!0,Promise.resolve()):this.audioContext.state==="running"?(this.isReady=!0,Promise.resolve()):new Promise(o=>{let e=()=>{if(this.destroyed){this.clearUnlockHandler(),o();return}this.audioContext.resume().then(()=>{this.audioContext.state==="running"&&(this.clearUnlockHandler(),this.isReady=!0,o())}).catch(t=>{kt("Failed to resume AudioContext while unlocking.",t)})};this.unlockHandler=e,document.addEventListener("click",e),document.addEventListener("touchstart",e),document.addEventListener("keydown",e)})}clearUnlockHandler(){if(!this.unlockHandler||typeof document>"u")return;let o=this.unlockHandler;this.unlockHandler=null,document.removeEventListener("click",o),document.removeEventListener("touchstart",o),document.removeEventListener("keydown",o)}ensureNotDestroyed(){if(this.destroyed)throw new Error("Sound instance has been destroyed and cannot be used.")}ensureReady(){if(!this.isReady)throw new Error("Audio context is not ready. Call onceReady() and wait for it to resolve before creating channels or playing audio.")}getAudioContext(){return this.audioContext}async createToken(o,e,t){this.ensureNotDestroyed(),this.ensureReady();let{volume:n=1,rate:i=1,startTime:r=0,endTime:s,load:a="auto",loop:c=!1}=e??{},l,u=null;if(typeof o=="string")if(await this.resolveLoadMode(o,a)==="stream")l=this.createStreamSource(o);else{u=await this.audioCache.load(o),u.addRef?.();let p=this.audioContext.createBufferSource();p.buffer=u.raw(),l=p}else{u=o,u.addRef?.();let p=this.audioContext.createBufferSource();p.buffer=o.raw(),l=p}let m=new Os(this.audioContext,l,{volume:n,rate:i,startOffset:r,duration:s?s-r:0},t);if(l instanceof AudioBufferSourceNode?(l.loop=c,c&&s!==void 0&&(l.loopStart=r,l.loopEnd=s)):l instanceof HTMLAudioElement&&(l.loop=c),u){let p=!1,h=()=>{p||(p=!0,u.releaseRef?.())};m.once("ended",h),m.once("stop",h)}return m}async resolveLoadMode(o,e){if(e==="stream"||e==="full")return e;try{let t=await fetch(o,{method:"HEAD"});if(!t.ok)return"stream";let n=t.headers.get("Content-Length");if(!n)return"stream";let i=parseInt(n,10);return isNaN(i)?"stream":i<zs?"full":"stream"}catch(t){return kt("Failed to resolve load mode via HEAD request, falling back to 'stream'.",t),"stream"}}createStreamSource(o){let e=new Audio(o);return e.crossOrigin="anonymous",e}checkChannelLimit(){if(this.registeredChannels.size+1>=this.options.maxChannels)throw new Error(`Maximum number of channels (${this.options.maxChannels}) reached.`)}registerChannel(o){this.registeredChannels.add(o)}unregisterChannel(o){this.registeredChannels.delete(o)}setVolume(o){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.setVolume(o),this}getVolume(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.getVolume()}mute(o){return this.ensureNotDestroyed(),this.ensureReady(),o===void 0?this.masterChannel.mute():this.masterChannel.mute(o),this}unmute(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.unmute(),this}isMuted(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.isMuted()}createChannel(o,e){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.createChannel(o,e)}getChannel(o){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.getChannel(o)}getChannels(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.getChannels()}async load(o){return this.ensureNotDestroyed(),this.ensureReady(),this.audioCache.load(o)}async play(o,e){this.ensureNotDestroyed(),this.ensureReady();let t=this.masterChannel.getTokens();for(let n of t)try{n.stop()}catch{}return this.masterChannel.play(o,e)}getTokens(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.getTokens()}destroy(){this.destroyed||(this.destroyed=!0,this.clearUnlockHandler(),this.audioCache.clear(),this.masterChannel.remove(),this.registeredChannels.clear(),this.audioContext.close().catch(o=>{kt("Failed to close AudioContext during destroy().",o)}))}isDestroyed(){return this.destroyed}};var ai=class{constructor(e){this.gameState=e;this.state=new Map;this.channels=new Map;this.channelVolumes=new Map;this.globalVolume=1;this.ready=Promise.resolve();this.isReady=!1;Object.values(Ct).forEach(t=>{this.channelVolumes.set(t,1)})}initialize(){this.isReady||(this.sound=new fr,this.ready=this.sound.onceReady().then(()=>{this.sound.setVolume(this.globalVolume),Object.values(Ct).forEach(e=>{let t=this.channelVolumes.get(e)??1,n=this.sound.createChannel(e,{volume:t});this.channels.set(e,n)}),this.isReady=!0,this.setupGroupVolume()}))}play(e,t={end:1,duration:0}){let n=new g;return this.ready.then(async()=>{this.state.has(e)&&this.state.get(e).token.stop();try{let i=this.channels.get(e.config.type),r=await this.sound.load(e.config.src),s=await i.play(r,{volume:0,startTime:e.config.seek,loop:e.config.loop,rate:1}),a=e.state.muted??!1;s.mute(a),e.state.muted=a,this.state.set(e,{token:s,cachedAudio:r,originalVolume:t.end}),t.duration>0?await s.fade(0,t.end,t.duration).finished:s.setVolume(t.end),e.state.volume=t.end,e.state.paused=!1,e.config.loop||await new Promise(c=>{s.once("ended",()=>c())}),n.resolve()}catch(i){this.gameState.logger.error("AudioManager",`Failed to play sound (src: "${e.config.src}")`,i),n.resolve()}}),n}async playSoundToken(e,t={end:1,duration:0}){await this.ready,this.state.has(e)&&this.state.get(e).token.stop();try{let n=this.channels.get(e.config.type);if(!n)throw new b(`Channel not found for sound type: "${e.config.type}"`);let i=await this.sound.load(e.config.src),r=await n.play(i,{volume:0,startTime:e.config.seek,loop:e.config.loop,rate:1}),s=e.state.muted??!1;return r.mute(s),e.state.muted=s,this.state.set(e,{token:r,cachedAudio:i,originalVolume:t.end}),t.duration>0?r.fade(0,t.end,t.duration):r.setVolume(t.end),e.state.volume=t.end,e.state.paused=!1,r}catch(n){throw this.gameState.logger.error("AudioManager",`Failed to play sound (src: "${e.config.src}")`,n),n}}stop(e,t=0){let n=new g;if(!this.state.has(e))return n.resolve(),n;let i=this.state.get(e);return t===0?(i.token.stop(),this.state.delete(e),n.resolve()):i.token.fade(i.token.getVolume(),0,t).finished.then(()=>{i.token.stop(),this.state.delete(e),n.resolve()}),n}setVolume(e,t,n=0){let i=new g;if(!this.state.has(e))return i.resolve(),i;let r=this.state.get(e);return r.originalVolume=t,n===0?(r.token.setVolume(t),e.state.volume=t,i.resolve()):r.token.fade(r.token.getVolume(),t,n).finished.then(()=>{e.state.volume=t,i.resolve()}),i}mute(e,t=!0){let n=new g;return e.state.muted=t,this.state.has(e)?(this.state.get(e).token.mute(t),n.resolve(),n):(n.resolve(),n)}pause(e,t=0){let n=new g;if(!this.state.has(e))return n.resolve(),n;let i=this.state.get(e);return t===0?(i.pausePosition=i.token.getCurrentTime(),i.token.pause(),e.state.paused=!0,n.resolve()):i.token.fade(i.token.getVolume(),0,t).finished.then(()=>{i.pausePosition=i.token.getCurrentTime(),i.token.pause(),i.token.setVolume(i.originalVolume),e.state.paused=!0,n.resolve()}),n}resume(e,t=0){let n=new g;if(!this.state.has(e))return n.resolve(),n;let i=this.state.get(e);return t===0?(i.pausePosition!==void 0&&i.token.seek(i.pausePosition),i.token.resume(),e.state.paused=!1,n.resolve()):(i.token.setVolume(0),i.pausePosition!==void 0&&i.token.seek(i.pausePosition),i.token.resume(),i.token.fade(0,i.originalVolume,t).finished.then(()=>{e.state.paused=!1,n.resolve()})),n}setRate(e,t){return this.state.has(e)?(this.state.get(e).token.setRate(t),e.state.rate=t,g.resolve(void 0)):g.resolve(void 0)}getPosition(e){return this.state.has(e)?this.state.get(e).token.getCurrentTime():0}isPlaying(e){return this.isManaged(e)?this.state.get(e).token.isPlaying():!1}getToken(e){return this.state.get(e)?.token??null}toData(){return{sounds:[...this.state.entries()].map(([e,t])=>[e.getId(),{isPlaying:t.token.isPlaying(),position:t.token.getCurrentTime()}]),groups:[...this.channelVolumes.entries()].map(([e,t])=>[e,t])}}fromData(e,t){return e.groups?.forEach(([n,i])=>{this.setGroupVolume(n,i)}),e.sounds.forEach(([n,i])=>{let r=t.get(n);if(!r)throw new b(`Sound not found (id: "${n}")
17
- NarraLeaf cannot find the element with the id from the saved game`);this.soundFromData(r,i)}),this}soundFromData(e,t){this.state.has(e)&&this.state.get(e).token.stop(),this.ready.then(async()=>{try{let n=this.channels.get(e.config.type),i=await this.sound.load(e.config.src),r=await n.play(i,{volume:e.state.volume,startTime:t.position,loop:e.config.loop,rate:1});this.state.set(e,{token:r,cachedAudio:i,originalVolume:e.state.volume});let s=e.state.muted??!1;r.mute(s),e.state.muted=s,e.state.paused?r.pause():t.isPlaying||r.stop()}catch(n){this.gameState.logger.error("AudioManager",`Failed to restore sound (src: "${e.config.src}")`,n)}})}isManaged(e){return this.state.has(e)}reset(){this.state.forEach(e=>{e.token.stop()}),this.state.clear(),this.globalVolume=1,this.isReady&&this.sound.setVolume(1),Object.values(Ct).forEach(e=>{if(this.channelVolumes.set(e,1),this.isReady){let t=this.channels.get(e);t&&t.setVolume(1)}}),this.setupGroupVolume()}setGroupVolume(e,t){if(this.channelVolumes.set(e,t),this.isReady){let n=this.channels.get(e);n&&n.setVolume(t)}}setGlobalVolume(e){this.globalVolume=e,this.isReady&&this.sound.setVolume(e)}getGlobalVolume(){return this.globalVolume}getGroupVolume(e){return this.channelVolumes.get(e)??1}destroy(){this.reset(),this.sound.destroy()}setupGroupVolume(){let{soundVolume:e,bgmVolume:t,voiceVolume:n}=this.gameState.game.preference.getPreferences();this.setGroupVolume("sound",e),this.setGroupVolume("bgm",t),this.setGroupVolume("voice",n)}};import*as js from"html-to-image";var ci=class{constructor(e,t){this.gameState=e;this.notifications=t;this.events=new W}addNotification(e){this.notifications.push(e),this.flush()}removeNotification(e){this.notifications=this.notifications.filter(t=>t!==e),this.flush()}clearNotifications(){this.notifications=[],this.flush()}consume(e){let t=new g,n=new fe(t);return t.registerSkipController(new M(()=>{this.removeNotification(e)})),this.addNotification(e),e.duration&&this.gameState.schedule(()=>{t.resolve(),this.removeNotification(e)},e.duration),this.gameState.timelines.attachTimeline(n),t}onFlush(e){return this.events.on("event:notifications.flush",e)}toArray(){return[...this.notifications]}flush(){this.events.emit("event:notifications.flush")}};var li=class{constructor(e=100,t){this.liveGame=t;this.history=[];this.hooks={onUndo:[],onHistoryLimit:[]};this.maxHistorySize=e}push(e,t,n){let i=ir(6),{action:r,timeline:s,stackModel:a}=e,c=this.liveGame.getStackModelForce().serialize(!1);if(this.history.push({action:r,id:i,args:n||[],undo:t,timeline:s,rootStackSnapshot:c,stackModel:a}),this.history.length>this.maxHistorySize){let l=this.history.splice(0,this.history.length-this.maxHistorySize);this.hooks.onHistoryLimit.forEach(u=>u(l))}return{id:i}}undoUntil(e){let t=-1;for(let r=this.history.length-1;r>=0;r--)if(this.history[r].id===e){t=r;break}if(t===-1)return null;let n=[];for(let r=this.history.length-1;r>=t;r--)this.history[r].timeline&&!this.history[r].timeline.isSettled()&&this.history[r].timeline.abort(),console.log("NarraLeaf-React [ActionHistory] Undoing",this.history[r].action.type,this.history[r]),this.history[r].undo?.(...this.history[r].args||[]),n.push(this.history[r]);this.history.length=t,this.hooks.onUndo.forEach(r=>r(n));let i=this.liveGame.getStackModelForce().serialize();if(i){let[r]=this.liveGame.constructMaps();this.liveGame.getStackModelForce().deserialize(i,r)}return n[n.length-1]||null}undo(e){if(!this.ableToUndo(e))return null;let t=e.getHistory(),n;for(let i=t.length-1;i>=0;i--)if(t[i].isPending!==!0){n=t[i];break}return n?this.undoUntil(n.token):null}ableToUndo(e){return this.history.length>0&&e.getHistory().some(t=>t.isPending!==!0)}onUndo(e){return this.hooks.onUndo.push(e),{cancel:()=>this.offUndo(e)}}offUndo(e){this.hooks.onUndo=this.hooks.onUndo.filter(t=>t!==e)}getHistory(){return this.history}onHistoryLimit(e){return this.hooks.onHistoryLimit.push(e),{cancel:()=>this.offHistoryLimit(e)}}offHistoryLimit(e){this.hooks.onHistoryLimit=this.hooks.onHistoryLimit.filter(t=>t!==e)}reset(){this.history.forEach(e=>{e.timeline&&!e.timeline.isSettled()&&e.timeline.abort()}),this.history=[]}};var ui=class{constructor(e){this.history=[];this.actionHistoryMgr=e,this.actionHistoryMgr.onUndo(t=>{this.crossFilter(t)}),this.actionHistoryMgr.onHistoryLimit(t=>{this.crossFilter(t)})}push(e){return this.history.push(e),this}getHistory(){return this.history}reset(){this.history=[]}updateByToken(e,t){let n=this.history.find(i=>i.token===e);t(n||null)}resolvePending(e){let t=this.history.find(n=>n.token===e);t&&(t.isPending=!1)}crossFilter(e){let t=new Set(e.map(n=>n.id));this.history=this.history.filter(n=>!t.has(n.token))}};var Ht=class extends U{executeAction(e,t){let n=new g().registerSkipController(new M(()=>{c.cancel()})),i=e.timelines.attachTimeline(n),r=this.contentNode.getContent(),s=e.createPresentationSnapshot(),a=null,c=e.createMenu(r,u=>{let m=e.getLiveGame().createStackModel([{type:this.type,node:u.action[0]?.contentNode??null}]);n.resolve({type:this.type,node:null,wait:{type:"all",stackModels:[m]}}),a=()=>{m.reset()},e.gameHistory.updateByToken(l,p=>{p&&p.element.type==="menu"&&(p.element.selected=u.evaluated,p.isPending=!1)})}),{id:l}=e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:i},()=>{c.cancel(),a?.(),e.restorePresentationSnapshot(s)});return e.gameHistory.push({token:l,action:this,element:{type:"menu",text:c.prompt,selected:null},isPending:!0}),[{type:this.type,node:this.contentNode.getChild()},n]}getFutureActions(e,t){let n=this.contentNode.getContent();return[...this.callee._getFutureActions(n.choices),...super.getFutureActions(e,t)]}stringify(e,t,n){let i=this.contentNode.getContent(),r=i.choices.map(s=>`{${s.action.map(c=>c.stringify(e,t,n)).join(";")}}`);return super.stringifyWithContent("Menu",`(${i.prompt}) {[${r.join(",")}]}`)}};Ht.ActionTypes=Qo;var Ut=class Ut extends X{constructor(t,n={}){super();this.choices=[];this.prompt=ne.isSentence(t)?t:t===null?null:new ne(t),this.config=I(Ut.defaultConfig,n)}static prompt(t,n={}){return new Ut(t!==void 0?t:null,n)}static choose(t,n){return new Ut(null,{}).choose(t,n)}choose(t,n){let i=this.chain();return ne.isSentence(t)&&n?i.choices.push({prompt:ne.toSentence(t),action:this.narrativeToActions(n),config:{}}):(F.isWord(t)||Array.isArray(t)||typeof t=="string")&&n?i.choices.push({prompt:ne.toSentence(t),action:this.narrativeToActions(n),config:{}}):typeof t=="object"&&"prompt"in t&&"action"in t?i.choices.push({prompt:ne.toSentence(t.prompt),action:this.narrativeToActions(t.action),config:{disabled:t.config?.disabled?R.from(t.config.disabled):void 0,hidden:t.config?.hidden?R.from(t.config.hidden):void 0}}):console.warn("No valid choice added to menu, ",{arg0:t,arg1:n}),i}hideIf(t){let n=this.choices[this.choices.length-1];if(!n)throw new ye("Trying to configure the last choice of a menu, but no choice added. This may be caused by calling `menu.hideIf` before `menu.choose`");return n.config.hidden=R.from(t),this.chain()}disableIf(t){let n=this.choices[this.choices.length-1];if(!n)throw new ye("Trying to configure the last choice of a menu, but no choice added. This may be caused by calling `menu.disableIf` before `menu.choose`");return n.config.disabled=R.from(t),this.chain()}enableWhen(t,n,i){return this.choose({prompt:n,action:i,config:{disabled:R.not(R.from(t))}})}showWhen(t,n,i){return this.choose({prompt:n,action:i,config:{hidden:R.not(R.from(t))}})}fromChained(t){return[new Ht(this.chain(),Ht.ActionTypes.action,new v().setContent({prompt:this.prompt,choices:t.constructChoices()}))]}_getFutureActions(t){return t.map(n=>n.action[0]||null).filter(n=>n!==null)}narrativeToActions(t){return this.constructNodes(t.flatMap(n=>typeof n=="string"?wt.say(n).getActions():ge.toActions([n])))}constructNodes(t,n,i){for(let r=0;r<t.length;r++){let s=t[r].contentNode,a=t[r+1]?.contentNode;a&&s.setChild(a),r===this.choices.length-1&&n&&s.setChild(n),r===0&&i&&i.setChild(s)}return t}constructChoices(){return this.choices.map(t=>({action:this.constructNodes(t.action),prompt:t.prompt,config:t.config??{}}))}};Ut.defaultConfig={},Ut.targetAction=Ht;var _i=Ut;var ft=class ft extends Qt{constructor(t,n=ft.defaultConfig){super();this.entryScene=null;this.scenes=new Map;this.persistent=[];this.services=new Map;this.name=t,this.config=I(ft.defaultConfig,n)}static empty(){return new ft("empty").entry(new Ue("empty"))}entry(t){return this.entryScene=t,this}registerPersistent(t){return this.persistent.push(t),this}createPersistent(t,n){let i=new Yt(t,n);return this.registerPersistent(i),i}registerService(t,n){return this.services.set(t,n),this}getService(t){let n=this.services.get(t);if(!n)throw new ye(`Trying to access service ${t} before it's registered, please use "story.registerService" to register the service`);return n}hash(t=!1){return sr(this.stringify(t))}stringify(t=!1){return this.entryScene?.stringify(this,new Set,t)||""}serializeServices(){let t={};return this.services.forEach((n,i)=>{if(!n.serialize||typeof n.serialize!="function")return;let r=n.serialize();if(r!==null){{if(r instanceof Promise)throw new te(`Service ${i} serialize method should not return a promise`);if(!Qi(r))throw new te(`Service ${i} serialize method should return a pure object.
14
+ Parent Conflict (src: `+p.get(v)?.state.currentSrc+`)
15
+ Current Parent (src: `+m.state.currentSrc+")");p.set(v,m)}});let u=[...this._initScene(this),...c.map(m=>m._init(this)),...l.map(m=>{if(!p.has(m))throw new Error("Wearable image must have a parent image");return p.get(m)._initWearable(m)}),...a.map(m=>m._init()),...r],d=super.constructNodes(u),h=new b(this.sceneRoot,void 0,d||void 0).setContent(this);return d?.setParent(h),this.sceneRoot?.setContentNode(h),this._futureActions_=u,this}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?St.say(n).getActions():Ae.toActions([n]))}isSceneRootConstructed(){return!!this.sceneRoot}registerSrc(t,n=new Set){if(!this.sceneRoot)return;let i=new Set,r=new Set,s=[this.sceneRoot],a=new Set;for(;s.length;){let c=s.shift();if(!i.has(c)){if(i.add(c),c instanceof Y){let l=c.callee;if(A.isImageSrc(l.state.backgroundImage.state.currentSrc)&&this.srcManager.register({type:"image",src:A.srcToURL(l.state.backgroundImage.state.currentSrc)}),c.type===V.jumpTo){let p=c,u=Me.getScene(t,p.contentNode.getContent()[0]);if(!u)throw c._sceneNotFoundError(c.getSceneName(p.contentNode.getContent()[0]));let d=De.getPreloadableSrc(t,c);if(d&&this.srcManager.register(d),r.has(p)||n.has(u))continue;r.add(p),a.add(u),n.add(u)}}else if(c instanceof ne){let l=De.getPreloadableSrc(t,c);l&&this.srcManager.register(l)}else if(c instanceof Fe)this.srcManager.register(c.callee);else if(c instanceof se){let p=c.getFutureActions(t,{allowFutureScene:!0});s.push(...p)}else c instanceof Ce&&this.srcManager.register(c.callee.srcManager.getSrc());s.push(...c.getFutureActions(t,{allowFutureScene:!0}))}}a.forEach(c=>{c.registerSrc(t,n),this.srcManager.registerFuture(c.srcManager)})}assignActionId(t){let n=this.getAllChildren(t,this.sceneRoot||[],{allowFutureScene:!0}),i=new Set;n.forEach(a=>{let c=a.getStaticId();if(c){if(i.has(c))throw new Se(`Duplicate static action id: ${c}`);i.add(c)}});let r=0,s=()=>{let a=`a-${r++}`;for(;i.has(a);)a=`a-${r++}`;return i.add(a),a};n.forEach(a=>{let c=a.getStaticId();a.resolveId(c||s())})}assignElementId(t){this.getAllChildrenElements(t,this.sceneRoot||[]).forEach((i,r)=>{i.setId(`e-${r}`)})}getVoice(t){if(!t)return null;let n=this.config.voices;if(n){if(typeof n=="function"){let r=n(t);return typeof r=="string"?re.voice(r):(Me.validateVoice(r),r)}let i=n[t];return typeof i=="string"?re.voice(i):i||null}return null}getSceneRoot(){if(!this.sceneRoot)throw new Error("Scene root is not constructed");return this.sceneRoot}stringify(t,n,i){return super.getAllChildren(t,this.sceneRoot||[],{allowFutureScene:!0}).map(r=>r.stringify(t,n,i)).join(";")}reset(){this.state.backgroundImage.reset(),this.state.backgroundMusic?.reset(),this.state=this.getInitialState()}getInitialState(){let t=this.userConfig.get();if(t.backgroundMusic&&t.backgroundMusic.config.type!=="bgm")throw new Se(`[Scene: ${this.config.name}] Background music must be a bgm, but got ${t.backgroundMusic.config.type}.
16
+ To prevent unintended behavior and unexpected results, the sound have to be marked as bgm. Please use \`Sound.bgm()\` to create the sound.`);let n=this.state?.backgroundImage?this.state.backgroundImage.reset():new U({src:t.background,opacity:1,autoFit:!0,name:`[[Background Image of ${this.config.name}]]`,layer:this.config.defaultBackgroundLayer})._setIsBackground(!0),i=t.backgroundMusic?this.state?.backgroundMusic?this.state.backgroundMusic.reset():t.backgroundMusic:null;return{backgroundImage:n,backgroundMusic:i}}_jumpTo(t){return this.chain(new Y(this.chain(),"scene:jumpTo",new b().setContent([t])))}_exit(){return new Y(this.chain(),"scene:exit",new b().setContent([]))}_transitionToScene(t,n){let i=this.chain();if(t&&n){let r=this.state.backgroundImage.char(n,t);i.chain(r.getActions())}return i}_init(t){return new Y(this.chain(),"scene:init",new b().setContent([t]))}_initScene(t){return[t._init(t),...t.config.layers.flatMap(n=>n._init(t)),...t._initBackground(t,t.config.defaultBackgroundLayer)]}_initBackground(t,n){return[t.state.backgroundImage._init(t,n)]}};Me.EventTypes={"event:scene.remove":"event:scene.remove","event:scene.load":"event:scene.load","event:scene.unload":"event:scene.unload","event:scene.mount":"event:scene.mount","event:scene.unmount":"event:scene.unmount","event:scene.preUnmount":"event:scene.preUnmount","event:scene.imageLoaded":"event:scene.imageLoaded"},Me.DefaultUserConfig=new j({backgroundMusic:null,backgroundMusicFade:0,voices:void 0,background:"#fff",layers:[]}),Me.DefaultSceneConfig=new j({name:"",backgroundMusicFade:0,voices:null,layers:[],defaultBackgroundLayer:new an("[[Background Layer]]",{zIndex:-1}),defaultDisplayableLayer:new an("[[Displayable Layer]]",{zIndex:0})},{voices:t=>{let n=r=>typeof r=="object"&&r!==null,i=r=>typeof r=="function";if(!t)return null;if(n(t)&&Object.values(t).forEach(r=>{re.isSound(r)&&Me.validateVoice(r)}),i(t))return t;throw new Se(`Invalid voices config: ${t}`)}});var ze=Me;import*as Ir from"howler";var pi=class{constructor(e,t){this.game=e,this.prefix=t}log(e,...t){this.isEnabled("log")&&console.log(...this.colorLog("gray",e,...t))}info(e,...t){this.isEnabled("info")&&console.info(...this._log(e,...t))}warn(e,...t){this.isEnabled("warn")&&console.warn(...this._log(e,...t))}error(e,...t){this.isEnabled("error")&&console.error(...this._log(e,...t))}debug(e,...t){this.isEnabled("debug")&&console.debug(...this.colorLog("gray",e,...t))}trace(e,...t){this.isEnabled("trace")&&console.trace(this._log(e,...t))}weakWarn(e,...t){this.isEnabled("warn")&&console.log(...this.colorLog("yellow",e,...t))}weakError(e,...t){this.isEnabled("error")&&console.log(...this.colorLog("red",e,...t))}verbose(e,...t){this.isEnabled("verbose")&&console.log(...this.colorLog("gray",e,...t))}group(e,t=!1){let n=this._log(e).join(" ");return this.isEnabled("info")&&(t?console.groupCollapsed(n):console.group(n)),{end:()=>{this.isEnabled("info")&&console.groupEnd()}}}isEnabled(e){return typeof this.game.config.app.logger=="boolean"?this.game.config.app.logger:this.game.config.app.logger[e]}_log(e,...t){return t.length===0?[this.prefix||"",e]:[`${this.prefix||""} [${e}]`,...t]}colorLog(e,t,...n){if(n.length===0)return[`%c${this.prefix||""} ${t}`,`color: ${e}`];let i=[],r=[],s=[];return this.prefix?(i.push(`%c${this.prefix} [${t}]`),r.push(`color: ${e}`)):(i.push(`%c[${t}]`),r.push(`color: ${e}`)),n.forEach(a=>{typeof a=="string"?(i.push(`%c${a}`),r.push(`color: ${e}`)):(i.push("%O"),s.push(a),r.push(""))}),[i.join(" ")].concat(r,s)}};var ea={volume:1,limit:1/0},ta=class wr{constructor(e,t,n,i){this.subChannels=new Map,this.tokens=new Set,this.tokenQueue=[],this.muted=!1,this.removed=!1,this.name=e,this.audioProvider=t,this.parentChannel=i??null,this.options={...ea,...n},this.volume=this.options.volume;let r=this.audioProvider.getAudioContext();this.gainNode=r.createGain(),this.gainNode.gain.value=this.muted?0:this.volume,this.connectToParent()}connectToParent(){this.parentChannel?this.gainNode.connect(this.parentChannel.getGainNode()):this.gainNode.connect(this.audioProvider.getAudioContext().destination)}getGainNode(){return this.gainNode}ensureNotRemoved(){if(this.removed)throw new Error(`Channel "${this.name}" has been removed and cannot be used.`)}getName(){return this.name}async play(e,t){if(this.ensureNotRemoved(),this.tokens.size>=this.options.limit){let r=this.tokenQueue.shift();r&&r.stop()}let n=await this.audioProvider.createToken(e,t,this.gainNode);this.tokens.add(n),this.tokenQueue.push(n);let i=()=>{this.tokens.delete(n);let r=this.tokenQueue.indexOf(n);r!==-1&&this.tokenQueue.splice(r,1)};return n.once("ended",i),n.once("stop",i),n}createChannel(e,t){if(this.ensureNotRemoved(),this.subChannels.has(e))throw new Error(`Channel "${e}" already exists under "${this.name}".`);this.audioProvider.checkChannelLimit();let n=new wr(e,this.audioProvider,t,this);return this.subChannels.set(e,n),this.audioProvider.registerChannel(n),n}getChannel(e){return this.ensureNotRemoved(),this.subChannels.get(e)??null}getChannels(){return this.ensureNotRemoved(),Array.from(this.subChannels.values())}setVolume(e){return this.ensureNotRemoved(),this.volume=Math.max(0,Math.min(1,e)),this.muted||(this.gainNode.gain.value=this.volume),this}getVolume(){return this.volume}mute(e){return this.ensureNotRemoved(),this.muted=e!==void 0?e:!0,this.gainNode.gain.value=this.muted?0:this.volume,this}unmute(){return this.mute(!1)}isMuted(){return this.muted}remove(){if(this.removed)return this;this.removed=!0;for(let t of this.tokens)t.stop();this.tokens.clear();let e=Array.from(this.subChannels.values());this.subChannels.clear();for(let t of e)t.remove();try{this.gainNode.disconnect()}catch(t){console.warn("Failed to disconnect Channel gain node during remove().",t)}return this.audioProvider.unregisterChannel(this),this.parentChannel&&this.parentChannel.removeSubChannel(this.name),this}removeSubChannel(e){this.subChannels.delete(e)}getTokens(){this.ensureNotRemoved();let e=[...this.tokenQueue];for(let t of this.subChannels.values())e.push(...t.getTokens());return e}isRemoved(){return this.removed}getParent(){return this.parentChannel}getOptions(){return{...this.options}}},kr=!1;function na(o){kr=o}function Lt(o,e){kr||(e!==void 0?console.warn(o,e):console.warn(o))}var ia=class{constructor(o,e){this.currentSource=null,this.mediaElementSource=null,this.endedHandler=null,this.eventListeners=new Map,this.audioContext=o,this.gainNode=e}setSource(o){this.disconnectSource(),this.currentSource=o,o instanceof AudioBufferSourceNode?o.connect(this.gainNode):o instanceof HTMLAudioElement&&(this.mediaElementSource=this.audioContext.createMediaElementSource(o),this.mediaElementSource.connect(this.gainNode)),this.setupEventListeners()}getSource(){return this.currentSource}refreshSource(o){let e=new Map(this.eventListeners);this.disconnectSource(),this.currentSource=o,o instanceof AudioBufferSourceNode?o.connect(this.gainNode):o instanceof HTMLAudioElement&&(this.mediaElementSource=this.audioContext.createMediaElementSource(o),this.mediaElementSource.connect(this.gainNode)),this.eventListeners=e,this.setupEventListeners()}disconnectSource(){if(this.currentSource){if(this.removeAllEventListeners(),this.currentSource instanceof AudioBufferSourceNode)try{this.currentSource.disconnect()}catch(o){Lt("Failed to disconnect AudioBufferSourceNode in disconnectSource().",o)}else this.currentSource instanceof HTMLAudioElement&&(this.currentSource.pause(),this.currentSource.src="",this.currentSource.load());if(this.mediaElementSource){try{this.mediaElementSource.disconnect()}catch(o){Lt("Failed to disconnect MediaElementAudioSourceNode in disconnectSource().",o)}this.mediaElementSource=null}this.currentSource=null}}setupEventListeners(){this.currentSource&&(this.endedHandler=o=>{this.emit("ended")},this.currentSource instanceof HTMLAudioElement?this.currentSource.addEventListener("ended",this.endedHandler):this.currentSource instanceof AudioBufferSourceNode&&this.currentSource.addEventListener("ended",this.endedHandler))}removeAllEventListeners(){!this.currentSource||!this.endedHandler||(this.currentSource instanceof HTMLAudioElement?this.currentSource.removeEventListener("ended",this.endedHandler):this.currentSource instanceof AudioBufferSourceNode&&this.currentSource.removeEventListener("ended",this.endedHandler),this.endedHandler=null)}emit(o){let e=this.eventListeners.get(o);e&&[...e].forEach((t,n)=>{try{t.callback()}catch(i){console.error(`Error in event listener for '${o}':`,i)}t.once&&e.splice(e.indexOf(t),1)})}on(o,e){this.eventListeners.has(o)||this.eventListeners.set(o,[]),this.eventListeners.get(o).push({callback:e,once:!1})}off(o,e){let t=this.eventListeners.get(o);if(!t)return;let n=t.findIndex(i=>i.callback===e);n!==-1&&t.splice(n,1)}once(o,e){this.eventListeners.has(o)||this.eventListeners.set(o,[]),this.eventListeners.get(o).push({callback:e,once:!0})}stop(){if(this.currentSource){if(this.currentSource instanceof HTMLAudioElement)this.currentSource.pause(),this.currentSource.currentTime=0;else if(this.currentSource instanceof AudioBufferSourceNode)try{this.currentSource.stop()}catch(o){Lt("Failed to stop AudioBufferSourceNode in stop().",o)}}}destroy(){this.disconnectSource(),this.eventListeners.clear()}start(o=0,e=0){this.currentSource instanceof AudioBufferSourceNode?this.currentSource.start(o,e):this.currentSource instanceof HTMLAudioElement&&this.currentSource.play()}pause(){this.currentSource instanceof HTMLAudioElement?this.currentSource.pause():this.currentSource instanceof AudioBufferSourceNode&&this.stop()}},xr=class{constructor(o,e){this.token=o,this.endVolume=e,this.cancelled=!1,this.finishedInternal=!1,this._finished=new Promise(t=>{this.resolveFinished=t})}get finished(){return this._finished}cancel(){this.cancelled||this.finishedInternal||(this.cancelled=!0,this.resolveFinished())}finish(){this.finishedInternal||(this.finishedInternal=!0,this.token.setVolume(this.endVolume),this.resolveFinished())}isCancelled(){return this.cancelled}isFinished(){return this.finishedInternal}getTargetVolume(){return this.endVolume}},oa=class{constructor(o,e,t={},n){this._isPlaying=!1,this._isPaused=!1,this._isMuted=!1,this.volume=1,this.rate=1,this.contextStartTime=0,this.startOffset=0,this.pauseOffset=0,this.duration=0,this.currentFade=null,this.audioContext=o,this.volume=t.volume??1,this.rate=t.rate??1,this.startOffset=t.startOffset??0,this.duration=t.duration??0,this.outputNode=n??o.destination,this.gainNode=o.createGain(),this.gainNode.gain.value=this.volume,this.gainNode.connect(this.outputNode),this.sourceController=new ia(o,this.gainNode),this.sourceController.setSource(e);let i=this.startOffset;this.sourceController.start(0,i),this.contextStartTime=this.audioContext.currentTime,this._isPlaying=!0,this.duration>0&&setTimeout(()=>{this._isPlaying&&this.stop()},this.duration*1e3)}emit(o){if(this.sourceController.emit(o),o==="ended"){this._isPlaying=!1;try{this.gainNode.disconnect()}catch(e){Lt("Failed to disconnect gain node on natural end.",e)}}}setVolume(o){return this.currentFade&&(this.currentFade.cancel(),this.currentFade=null),o=Math.max(0,Math.min(1,o)),this.volume=o,this._isMuted||(this.gainNode.gain.cancelScheduledValues(this.audioContext.currentTime),this.gainNode.gain.value=o),this}getVolume(){return this.volume}mute(o){let e=o!==void 0?o:!0;if(this._isMuted=e,this.currentFade&&!this.currentFade.isFinished()&&!this.currentFade.isCancelled()){let t=this.currentFade.getTargetVolume();this.gainNode.gain.cancelScheduledValues(this.audioContext.currentTime),this.volume=t,this.gainNode.gain.value=e?0:t,this.currentFade.finish(),this.currentFade=null}else this.gainNode.gain.cancelScheduledValues(this.audioContext.currentTime),this.gainNode.gain.value=e?0:this.volume;return this}unmute(){return this.mute(!1)}isMuted(){return this._isMuted}pause(){if(!this._isPlaying||this._isPaused)return this;let o=this.sourceController.getSource();return o instanceof HTMLAudioElement?(o.pause(),this.pauseOffset=o.currentTime):o instanceof AudioBufferSourceNode&&(this.pauseOffset=this.getCurrentTime(),this.sourceController.stop()),this._isPlaying=!1,this._isPaused=!0,this.emit("pause"),this}resume(){if(!this._isPaused)return this;let o=this.sourceController.getSource();if(o instanceof HTMLAudioElement){let e=o.play();e&&typeof e.catch=="function"&&e.catch(()=>{this._isPlaying=!1,this._isPaused=!0})}else if(o instanceof AudioBufferSourceNode){let e=this.audioContext.createBufferSource();e.buffer=o.buffer,e.playbackRate.value=this.rate,e.loop=o.loop,e.loopStart=o.loopStart,e.loopEnd=o.loopEnd,this.sourceController.refreshSource(e),this.startOffset=this.pauseOffset,this.contextStartTime=this.audioContext.currentTime,this.sourceController.start(0,this.pauseOffset)}return this._isPlaying=!0,this._isPaused=!1,this.emit("resume"),this}isPlaying(){return this._isPlaying}isPaused(){return this._isPaused}stop(o={}){let{fadeDuration:e=0}=o;return e>0?this.fade(this.getVolume(),0,e).finished.then(()=>{this.doStop()}):this.doStop(),this}doStop(){this.sourceController.stop(),this._isPlaying=!1,this._isPaused=!1,this.emit("stop"),this.sourceController.destroy();try{this.gainNode.disconnect()}catch(o){Lt("Failed to disconnect gain node on stop().",o)}}setRate(o){o=Math.max(.001,o),this.rate=o;let e=this.sourceController.getSource();return e instanceof HTMLAudioElement?e.playbackRate=o:e instanceof AudioBufferSourceNode&&(e.playbackRate.value=o),this}getRate(){return this.rate}seek(o){o=Math.max(0,o);let e=this.sourceController.getSource();if(e instanceof HTMLAudioElement)e.currentTime=o,this.emit("seek");else if(e instanceof AudioBufferSourceNode){let t=this.getCurrentTime();if(Math.abs(o-t)>.01){if(this._isPlaying){this.sourceController.stop();let n=this.audioContext.createBufferSource();n.buffer=e.buffer,n.playbackRate.value=this.rate,n.loop=e.loop,n.loopStart=e.loopStart,n.loopEnd=e.loopEnd,this.sourceController.refreshSource(n),this.startOffset=this.audioContext.currentTime-o,this.sourceController.start(0,o)}else this._isPaused&&(this.pauseOffset=o);this.emit("seek")}}return this}getCurrentTime(){let o=this.sourceController.getSource();if(o instanceof HTMLAudioElement)return o.currentTime;if(o instanceof AudioBufferSourceNode){if(this._isPaused)return this.pauseOffset;if(this._isPlaying)return(this.audioContext.currentTime-this.contextStartTime)*this.rate+this.startOffset}return 0}getDuration(){let o=this.sourceController.getSource();return o instanceof HTMLAudioElement?o.duration||0:o instanceof AudioBufferSourceNode&&o.buffer?o.buffer.duration:this.duration}fade(o,e,t){if(this.currentFade&&this.currentFade.cancel(),o=Math.max(0,Math.min(1,o)),e=Math.max(0,Math.min(1,e)),t=Math.max(0,t),t===0){this.setVolume(e);let r=new xr(this,e);return r.finish(),r}this.volume=o,this._isMuted||(this.gainNode.gain.value=o);let n=new xr(this,e);this.currentFade=n;let i=this.audioContext.currentTime;return this.gainNode.gain.setValueAtTime(o,i),this.gainNode.gain.linearRampToValueAtTime(e,i+t/1e3),setTimeout(()=>{!n.isCancelled()&&!n.isFinished()&&(this.volume=e,n.finish(),this.currentFade=null)},t),n}on(o,e){return this.sourceController.on(o,e),this}off(o,e){return this.sourceController.off(o,e),this}once(o,e){return this.sourceController.once(o,e),this}},ra=class{constructor(o){this.alive=!0,this.refCount=0,this.audioBuffer=o}addRef(){this.refCount++}releaseRef(){this.refCount>0&&this.refCount--}getRefCount(){return this.refCount}async unload(){this.refCount>0||(this.alive=!1)}async forceUnload(){this.alive=!1,this.refCount=0}isAlive(){return this.alive}raw(){if(!this.alive)throw new Error("CachedAudio has been unloaded.");return this.audioBuffer}},sa=10*1024*1024,aa=class{constructor(o){this.cache=new Map,this.loadingPromises=new Map,this.audioContext=o}async load(o){let e=this.cache.get(o);if(e&&e.isAlive())return e;let t=this.loadingPromises.get(o);if(t)return t;let n=this.doLoad(o);this.loadingPromises.set(o,n);try{let i=await n;return this.cache.set(o,i),i}finally{this.loadingPromises.delete(o)}}async doLoad(o){let e=await(await fetch(o)).arrayBuffer(),t=await this.audioContext.decodeAudioData(e);return new ra(t)}clear(){for(let o of this.cache.values())o.forceUnload();this.cache.clear(),this.loadingPromises.clear()}getStats(){return{cached:this.cache.size,loading:this.loadingPromises.size}}},ca={volume:1,latencyHint:"interactive",sampleRate:44100,maxChannels:128,silent:!1},Pr=class{constructor(o){this.registeredChannels=new Set,this.isReady=!1,this.readyPromise=null,this.destroyed=!1,this.unlockHandler=null,this.options={...ca,...o},na(!!this.options.silent),this.audioContext=new AudioContext({latencyHint:this.options.latencyHint,sampleRate:this.options.sampleRate}),this.audioCache=new aa(this.audioContext),this.masterChannel=new ta("__master__",this,{volume:this.options.volume},null),this.initialize()}async onceReady(){return this.readyPromise?(await this.readyPromise,this):this}initialize(){this.isReady||(this.readyPromise=this.waitForUnlock())}waitForUnlock(){return typeof document>"u"?(this.isReady=!0,Promise.resolve()):this.audioContext.state==="running"?(this.isReady=!0,Promise.resolve()):new Promise(o=>{let e=()=>{if(this.destroyed){this.clearUnlockHandler(),o();return}this.audioContext.resume().then(()=>{this.audioContext.state==="running"&&(this.clearUnlockHandler(),this.isReady=!0,o())}).catch(t=>{Lt("Failed to resume AudioContext while unlocking.",t)})};this.unlockHandler=e,document.addEventListener("click",e),document.addEventListener("touchstart",e),document.addEventListener("keydown",e)})}clearUnlockHandler(){if(!this.unlockHandler||typeof document>"u")return;let o=this.unlockHandler;this.unlockHandler=null,document.removeEventListener("click",o),document.removeEventListener("touchstart",o),document.removeEventListener("keydown",o)}ensureNotDestroyed(){if(this.destroyed)throw new Error("Sound instance has been destroyed and cannot be used.")}ensureReady(){if(!this.isReady)throw new Error("Audio context is not ready. Call onceReady() and wait for it to resolve before creating channels or playing audio.")}getAudioContext(){return this.audioContext}async createToken(o,e,t){this.ensureNotDestroyed(),this.ensureReady();let{volume:n=1,rate:i=1,startTime:r=0,endTime:s,load:a="auto",loop:c=!1}=e??{},l,p=null;if(typeof o=="string")if(await this.resolveLoadMode(o,a)==="stream")l=this.createStreamSource(o);else{p=await this.audioCache.load(o),p.addRef?.();let d=this.audioContext.createBufferSource();d.buffer=p.raw(),l=d}else{p=o,p.addRef?.();let d=this.audioContext.createBufferSource();d.buffer=o.raw(),l=d}let u=new oa(this.audioContext,l,{volume:n,rate:i,startOffset:r,duration:s?s-r:0},t);if(l instanceof AudioBufferSourceNode?(l.loop=c,c&&s!==void 0&&(l.loopStart=r,l.loopEnd=s)):l instanceof HTMLAudioElement&&(l.loop=c),p){let d=!1,h=()=>{d||(d=!0,p.releaseRef?.())};u.once("ended",h),u.once("stop",h)}return u}async resolveLoadMode(o,e){if(e==="stream"||e==="full")return e;try{let t=await fetch(o,{method:"HEAD"});if(!t.ok)return"stream";let n=t.headers.get("Content-Length");if(!n)return"stream";let i=parseInt(n,10);return isNaN(i)?"stream":i<sa?"full":"stream"}catch(t){return Lt("Failed to resolve load mode via HEAD request, falling back to 'stream'.",t),"stream"}}createStreamSource(o){let e=new Audio(o);return e.crossOrigin="anonymous",e}checkChannelLimit(){if(this.registeredChannels.size+1>=this.options.maxChannels)throw new Error(`Maximum number of channels (${this.options.maxChannels}) reached.`)}registerChannel(o){this.registeredChannels.add(o)}unregisterChannel(o){this.registeredChannels.delete(o)}setVolume(o){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.setVolume(o),this}getVolume(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.getVolume()}mute(o){return this.ensureNotDestroyed(),this.ensureReady(),o===void 0?this.masterChannel.mute():this.masterChannel.mute(o),this}unmute(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.unmute(),this}isMuted(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.isMuted()}createChannel(o,e){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.createChannel(o,e)}getChannel(o){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.getChannel(o)}getChannels(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.getChannels()}async load(o){return this.ensureNotDestroyed(),this.ensureReady(),this.audioCache.load(o)}async play(o,e){this.ensureNotDestroyed(),this.ensureReady();let t=this.masterChannel.getTokens();for(let n of t)try{n.stop()}catch{}return this.masterChannel.play(o,e)}getTokens(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.getTokens()}destroy(){this.destroyed||(this.destroyed=!0,this.clearUnlockHandler(),this.audioCache.clear(),this.masterChannel.remove(),this.registeredChannels.clear(),this.audioContext.close().catch(o=>{Lt("Failed to close AudioContext during destroy().",o)}))}isDestroyed(){return this.destroyed}};var di=class{constructor(e){this.gameState=e;this.state=new Map;this.channels=new Map;this.channelVolumes=new Map;this.globalVolume=1;this.ready=Promise.resolve();this.isReady=!1;this.isInitializing=!1;Object.values(kt).forEach(t=>{this.channelVolumes.set(t,1)})}initialize(){if(this.isReady||this.isInitializing)return;let e=new Pr;this.sound=e,this.isInitializing=!0,this.ready=e.onceReady().then(()=>{e.setVolume(this.globalVolume),Object.values(kt).forEach(t=>{let n=this.channelVolumes.get(t)??1,i=e.getChannel(t)??e.createChannel(t,{volume:n});i.setVolume(n),this.channels.set(t,i)}),this.isReady=!0,this.isInitializing=!1,this.setupGroupVolume()}).catch(t=>{throw this.isInitializing=!1,this.gameState.logger.error("AudioManager","Failed to initialize audio subsystem",t),t})}play(e,t={end:1,duration:0}){let n=new y;return this.ready.then(async()=>{this.state.has(e)&&this.state.get(e).token.stop();try{let i=this.channels.get(e.config.type),r=await this.sound.load(e.config.src),s=await i.play(r,{volume:0,startTime:e.config.seek,loop:e.config.loop,rate:1}),a=e.state.muted??!1;s.mute(a),e.state.muted=a,this.state.set(e,{token:s,cachedAudio:r,originalVolume:t.end}),t.duration>0?await s.fade(0,t.end,t.duration).finished:s.setVolume(t.end),e.state.volume=t.end,e.state.paused=!1,e.config.loop||await new Promise(c=>{s.once("ended",()=>c())}),n.resolve()}catch(i){this.gameState.logger.error("AudioManager",`Failed to play sound (src: "${e.config.src}")`,i),n.resolve()}}),n}async playSoundToken(e,t={end:1,duration:0}){await this.ready,this.state.has(e)&&this.state.get(e).token.stop();try{let n=this.channels.get(e.config.type);if(!n)throw new x(`Channel not found for sound type: "${e.config.type}"`);let i=await this.sound.load(e.config.src),r=await n.play(i,{volume:0,startTime:e.config.seek,loop:e.config.loop,rate:1}),s=e.state.muted??!1;return r.mute(s),e.state.muted=s,this.state.set(e,{token:r,cachedAudio:i,originalVolume:t.end}),t.duration>0?r.fade(0,t.end,t.duration):r.setVolume(t.end),e.state.volume=t.end,e.state.paused=!1,r}catch(n){throw this.gameState.logger.error("AudioManager",`Failed to play sound (src: "${e.config.src}")`,n),n}}stop(e,t=0){let n=new y;if(!this.state.has(e))return n.resolve(),n;let i=this.state.get(e);return t===0?(i.token.stop(),this.state.delete(e),n.resolve()):i.token.fade(i.token.getVolume(),0,t).finished.then(()=>{i.token.stop(),this.state.delete(e),n.resolve()}),n}setVolume(e,t,n=0){let i=new y;if(!this.state.has(e))return i.resolve(),i;let r=this.state.get(e);return r.originalVolume=t,n===0?(r.token.setVolume(t),e.state.volume=t,i.resolve()):r.token.fade(r.token.getVolume(),t,n).finished.then(()=>{e.state.volume=t,i.resolve()}),i}mute(e,t=!0){let n=new y;return e.state.muted=t,this.state.has(e)?(this.state.get(e).token.mute(t),n.resolve(),n):(n.resolve(),n)}pause(e,t=0){let n=new y;if(!this.state.has(e))return n.resolve(),n;let i=this.state.get(e);return t===0?(i.pausePosition=i.token.getCurrentTime(),i.token.pause(),e.state.paused=!0,n.resolve()):i.token.fade(i.token.getVolume(),0,t).finished.then(()=>{i.pausePosition=i.token.getCurrentTime(),i.token.pause(),i.token.setVolume(i.originalVolume),e.state.paused=!0,n.resolve()}),n}resume(e,t=0){let n=new y;if(!this.state.has(e))return n.resolve(),n;let i=this.state.get(e);return t===0?(i.pausePosition!==void 0&&i.token.seek(i.pausePosition),i.token.resume(),e.state.paused=!1,n.resolve()):(i.token.setVolume(0),i.pausePosition!==void 0&&i.token.seek(i.pausePosition),i.token.resume(),i.token.fade(0,i.originalVolume,t).finished.then(()=>{e.state.paused=!1,n.resolve()})),n}setRate(e,t){return this.state.has(e)?(this.state.get(e).token.setRate(t),e.state.rate=t,y.resolve(void 0)):y.resolve(void 0)}getPosition(e){return this.state.has(e)?this.state.get(e).token.getCurrentTime():0}isPlaying(e){return this.isManaged(e)?this.state.get(e).token.isPlaying():!1}getToken(e){return this.state.get(e)?.token??null}toData(){return{sounds:[...this.state.entries()].map(([e,t])=>[e.getId(),{isPlaying:t.token.isPlaying(),position:t.token.getCurrentTime()}]),groups:[...this.channelVolumes.entries()].map(([e,t])=>[e,t])}}fromData(e,t){return e.groups?.forEach(([n,i])=>{this.setGroupVolume(n,i)}),e.sounds.forEach(([n,i])=>{let r=t.get(n);if(!r)throw new x(`Sound not found (id: "${n}")
17
+ NarraLeaf cannot find the element with the id from the saved game`);this.soundFromData(r,i)}),this}soundFromData(e,t){this.state.has(e)&&this.state.get(e).token.stop(),this.ready.then(async()=>{try{let n=this.channels.get(e.config.type),i=await this.sound.load(e.config.src),r=await n.play(i,{volume:e.state.volume,startTime:t.position,loop:e.config.loop,rate:1});this.state.set(e,{token:r,cachedAudio:i,originalVolume:e.state.volume});let s=e.state.muted??!1;r.mute(s),e.state.muted=s,e.state.paused?r.pause():t.isPlaying||r.stop()}catch(n){this.gameState.logger.error("AudioManager",`Failed to restore sound (src: "${e.config.src}")`,n)}})}isManaged(e){return this.state.has(e)}reset(){this.state.forEach(e=>{e.token.stop()}),this.state.clear(),this.globalVolume=1,this.isReady&&this.sound.setVolume(1),Object.values(kt).forEach(e=>{if(this.channelVolumes.set(e,1),this.isReady){let t=this.channels.get(e);t&&t.setVolume(1)}}),this.setupGroupVolume()}setGroupVolume(e,t){if(this.channelVolumes.set(e,t),this.isReady){let n=this.channels.get(e);n&&n.setVolume(t)}}setGlobalVolume(e){this.globalVolume=e,this.isReady&&this.sound.setVolume(e)}getGlobalVolume(){return this.globalVolume}getGroupVolume(e){return this.channelVolumes.get(e)??1}destroy(){this.reset(),this.sound.destroy()}setupGroupVolume(){let{soundVolume:e,bgmVolume:t,voiceVolume:n}=this.gameState.game.preference.getPreferences();this.setGroupVolume("sound",e),this.setGroupVolume("bgm",t),this.setGroupVolume("voice",n)}};import*as la from"html-to-image";var mi=class{constructor(e,t){this.gameState=e;this.notifications=t;this.events=new J}addNotification(e){this.notifications.push(e),this.flush()}removeNotification(e){this.notifications=this.notifications.filter(t=>t!==e),this.flush()}clearNotifications(){this.notifications=[],this.flush()}consume(e){let t=new y,n=new Te(t);return t.registerSkipController(new G(()=>{this.removeNotification(e)})),this.addNotification(e),e.duration&&this.gameState.schedule(()=>{t.resolve(),this.removeNotification(e)},e.duration),this.gameState.timelines.attachTimeline(n),t}onFlush(e){return this.events.on("event:notifications.flush",e)}toArray(){return[...this.notifications]}flush(){this.events.emit("event:notifications.flush")}};var fi=class{constructor(e=100,t){this.liveGame=t;this.history=[];this.hooks={onUndo:[],onHistoryLimit:[]};this.maxHistorySize=e}push(e,t,n){let i=gr(6),{action:r,timeline:s,stackModel:a}=e,c=this.liveGame.getStackModelForce().serialize(!1);if(this.history.push({action:r,id:i,args:n||[],undo:t,timeline:s,rootStackSnapshot:c,stackModel:a}),this.history.length>this.maxHistorySize){let l=this.history.splice(0,this.history.length-this.maxHistorySize);this.hooks.onHistoryLimit.forEach(p=>p(l))}return{id:i}}undoUntil(e){let t=-1;for(let r=this.history.length-1;r>=0;r--)if(this.history[r].id===e){t=r;break}if(t===-1)return null;let n=[];for(let r=this.history.length-1;r>=t;r--)this.history[r].timeline&&!this.history[r].timeline.isSettled()&&this.history[r].timeline.abort(),console.log("NarraLeaf-React [ActionHistory] Undoing",this.history[r].action.type,this.history[r]),this.history[r].undo?.(...this.history[r].args||[]),n.push(this.history[r]);this.history.length=t,this.hooks.onUndo.forEach(r=>r(n));let i=this.liveGame.getStackModelForce().serialize();if(i){let[r]=this.liveGame.constructMaps();this.liveGame.getStackModelForce().deserialize(i,r)}return n[n.length-1]||null}undo(e){if(!this.ableToUndo(e))return null;let t=e.getHistory(),n;for(let i=t.length-1;i>=0;i--)if(t[i].isPending!==!0){n=t[i];break}return n?this.undoUntil(n.token):null}ableToUndo(e){return this.history.length>0&&e.getHistory().some(t=>t.isPending!==!0)}onUndo(e){return this.hooks.onUndo.push(e),{cancel:()=>this.offUndo(e)}}offUndo(e){this.hooks.onUndo=this.hooks.onUndo.filter(t=>t!==e)}getHistory(){return this.history}onHistoryLimit(e){return this.hooks.onHistoryLimit.push(e),{cancel:()=>this.offHistoryLimit(e)}}offHistoryLimit(e){this.hooks.onHistoryLimit=this.hooks.onHistoryLimit.filter(t=>t!==e)}reset(){this.history.forEach(e=>{e.timeline&&!e.timeline.isSettled()&&e.timeline.abort()}),this.history=[]}};var hi=class{constructor(e){this.history=[];this.actionHistoryMgr=e,this.actionHistoryMgr.onUndo(t=>{this.crossFilter(t)}),this.actionHistoryMgr.onHistoryLimit(t=>{this.crossFilter(t)})}push(e){return this.history.push(e),this}getHistory(){return this.history}reset(){this.history=[]}updateByToken(e,t){let n=this.history.find(i=>i.token===e);t(n||null)}resolvePending(e){let t=this.history.find(n=>n.token===e);t&&(t.isPending=!1)}crossFilter(e){let t=new Set(e.map(n=>n.id));this.history=this.history.filter(n=>!t.has(n.token))}};var Ot=class extends O{executeAction(e,t){let n=new y().registerSkipController(new G(()=>{c.cancel()})),i=e.timelines.attachTimeline(n),r=this.contentNode.getContent(),s=e.createPresentationSnapshot(),a=null,c=e.createMenu(r,p=>{let u=e.getLiveGame().createStackModel([{type:this.type,node:p.action[0]?.contentNode??null}]);n.resolve({type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[u]}}),a=()=>{u.reset()},e.gameHistory.updateByToken(l,d=>{d&&d.element.type==="menu"&&(d.element.selected=p.evaluated,d.isPending=!1)})}),{id:l}=e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:i},()=>{c.cancel(),a?.(),e.restorePresentationSnapshot(s)});return e.gameHistory.push({token:l,action:this,element:{type:"menu",text:c.prompt,selected:null},isPending:!0}),n}getFutureActions(e,t){let n=this.contentNode.getContent();return[...this.callee._getFutureActions(n.choices),...super.getFutureActions(e,t)]}stringify(e,t,n){let i=this.contentNode.getContent(),r=i.choices.map(s=>`{${s.action.map(c=>c.stringify(e,t,n)).join(";")}}`);return super.stringifyWithContent("Menu",`(${i.prompt}) {[${r.join(",")}]}`)}};Ot.ActionTypes=ar;var Wt=class Wt extends te{constructor(t,n={}){super();this.choices=[];this.prompt=ie.isSentence(t)?t:t===null?null:new ie(t),this.config=H(Wt.defaultConfig,n)}static prompt(t,n={}){return new Wt(t!==void 0?t:null,n)}static choose(t,n){return new Wt(null,{}).choose(t,n)}choose(t,n){let i=this.chain();return ie.isSentence(t)&&n?i.choices.push({prompt:ie.toSentence(t),action:this.narrativeToActions(n),config:{}}):(W.isWord(t)||Array.isArray(t)||typeof t=="string")&&n?i.choices.push({prompt:ie.toSentence(t),action:this.narrativeToActions(n),config:{}}):typeof t=="object"&&"prompt"in t&&"action"in t?i.choices.push({prompt:ie.toSentence(t.prompt),action:this.narrativeToActions(t.action),config:{disabled:t.config?.disabled?F.from(t.config.disabled):void 0,hidden:t.config?.hidden?F.from(t.config.hidden):void 0}}):console.warn("No valid choice added to menu, ",{arg0:t,arg1:n}),i}hideIf(t){let n=this.choices[this.choices.length-1];if(!n)throw new Se("Trying to configure the last choice of a menu, but no choice added. This may be caused by calling `menu.hideIf` before `menu.choose`");return n.config.hidden=F.from(t),this.chain()}disableIf(t){let n=this.choices[this.choices.length-1];if(!n)throw new Se("Trying to configure the last choice of a menu, but no choice added. This may be caused by calling `menu.disableIf` before `menu.choose`");return n.config.disabled=F.from(t),this.chain()}enableWhen(t,n,i){return this.choose({prompt:n,action:i,config:{disabled:F.not(F.from(t))}})}showWhen(t,n,i){return this.choose({prompt:n,action:i,config:{hidden:F.not(F.from(t))}})}fromChained(t){return[new Ot(this.chain(),Ot.ActionTypes.action,new b().setContent({prompt:this.prompt,choices:t.constructChoices()}))]}_getFutureActions(t){return t.map(n=>n.action[0]||null).filter(n=>n!==null)}narrativeToActions(t){return this.constructNodes(t.flatMap(n=>typeof n=="string"?St.say(n).getActions():Ae.toActions([n])))}constructNodes(t,n,i){for(let r=0;r<t.length;r++){let s=t[r].contentNode,a=t[r+1]?.contentNode;a&&s.setChild(a),r===this.choices.length-1&&n&&s.setChild(n),r===0&&i&&i.setChild(s)}return t}constructChoices(){return this.choices.map(t=>({action:this.constructNodes(t.action),prompt:t.prompt,config:t.config??{}}))}};Wt.defaultConfig={},Wt.targetAction=Ot;var ro=Wt;var Tt=class Tt extends tn{constructor(t,n=Tt.defaultConfig){super();this.entryScene=null;this.scenes=new Map;this.persistent=[];this.services=new Map;this.name=t,this.config=H(Tt.defaultConfig,n)}static empty(){return new Tt("empty").entry(new ze("empty"))}entry(t){return this.entryScene=t,this}registerPersistent(t){return this.persistent.push(t),this}createPersistent(t,n){let i=new on(t,n);return this.registerPersistent(i),i}registerService(t,n){return this.services.set(t,n),this}getService(t){let n=this.services.get(t);if(!n)throw new Se(`Trying to access service ${t} before it's registered, please use "story.registerService" to register the service`);return n}hash(t=!1){return Sr(this.stringify(t))}stringify(t=!1){return this.entryScene?.stringify(this,new Set,t)||""}serializeServices(){let t={};return this.services.forEach((n,i)=>{if(!n.serialize||typeof n.serialize!="function")return;let r=n.serialize();if(r!==null){{if(r instanceof Promise)throw new ce(`Service ${i} serialize method should not return a promise`);if(!eo(r))throw new ce(`Service ${i} serialize method should return a pure object.
18
18
  A pure object should:
19
19
  1. be an object literal
20
20
  2. not have any prototype
21
21
  3. no circular reference
22
22
  4. sub objects should also be pure objects or serializable data
23
23
  Return null if nothing needs to be saved. For more information, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#description
24
- Returned value ${r} violates the above rules`)}t[i]=r}}),t}deserializeServices(t){this.services.forEach((n,i)=>{!n.deserialize||typeof n.deserialize!="function"||t[i]&&n.deserialize(t[i])})}getScene(t,n=!1,i){if(Ue.isScene(t))return t;let r=this.scenes.get(t)||null;if(!r&&n)throw Reflect.construct(i||te,[`Scene with name ${t} not found`]);return r}constructStory(){let t=this.entryScene;if(!t)throw new Error("Story must have an entry scene");return this.constructSceneRoots(t),t.registerSrc(this),t.assignActionId(this),t.assignElementId(this),this.runStaticCheck(t),this}getAllElementStates(){return this.getAllChildrenElements(this,this.entryScene?.getSceneRoot()||[]).map(n=>({id:n.getId(),data:n.toData()})).filter(n=>!!n.data)}constructSceneRoots(t){let n=new Set,i=[],r=0;for(t.constructSceneRoot(this),i.push(t.getSceneRoot());i.length;){if(r++,r>ft.MAX_DEPTH)throw new Error(`Max depth reached while constructing scene roots (max depth: ${ft.MAX_DEPTH})`);let s=i.shift();if(Ue.isScene(s.callee)){if(n.has(s.callee))continue;s.callee.isSceneRootConstructed()||s.callee.constructSceneRoot(this),n.add(s.callee)}let a=s.getFutureActions(this,{allowFutureScene:!0});i.push(...a)}return this}initPersistent(t){return this.persistent.forEach(n=>{n.init(t)}),this}getInversionConfig(){let{origin:t}=this.config;return{invertY:t==="bottom left"||t==="bottom right",invertX:t==="bottom right"||t==="top right"}}runStaticCheck(t){return new pi(t).run(this)}};ft.defaultConfig={origin:"bottom left"},ft.MAX_DEPTH=32767;var vn=ft;var di=class extends U{executeAction(e,t){let[n,i]=this.contentNode.getContent(),r=this.callee.triggerAction(re.getCtx({gameState:e}),n,i);return g.isAwaitable(r)?g.forward(r,{type:this.type,node:this.contentNode?.getChild()}):super.executeAction(e,t)}stringify(e,t,n){return super.stringifyWithName("ServiceAction")}};var eo=class extends X{constructor(){super(...arguments);this._handlers={}}on(t,n){return this._registerActionHandler(t,n),this}trigger(t,...n){let i=this.chain();return i.chain(this._createAction(i,t,n))}triggerAction(t,n,i){let r=this._handlers[n];if(!r){t.gameState.logger.warn(`(in User-Defined Service) Trying to trigger action ${n} before it's registered, please use "service.on" to register the action`);return}if(nr(r)){let s=[],a=new g().registerSkipController(new M(()=>{for(let l of s)l?.()}));return r({...t,onAbort:l=>{s.push(l)}},...i).then(()=>a.resolve()),a}r({...t,onAbort:()=>{}},...i)}_registerActionHandler(t,n){this._handlers[t]=n}_createAction(t,n,i){return new di(t,"service:action",new v().setContent([n,i]))}},to=class extends eo{},Tn=class extends to{};var st=class st extends U{executeAction(e,t){let n=this,i=this.callee,r={action:n,stackModel:t.stackModel};if(n.is(st,"video:play"))return this.changeStateAsync(e,s=>s.play(),t);if(n.is(st,"video:pause"))return this.changeState(e,s=>s.pause(),t);if(n.is(st,"video:stop"))return this.changeState(e,s=>s.stop(),t);if(n.is(st,"video:seek"))return this.changeState(e,s=>s.seek(n.contentNode.getContent()[0]),t);if(n.is(st,"video:show")){let s=i.state.display;return e.isVideoAdded(i)||(e.addVideo(i),e.stage.update()),i.state.display=!0,e.actionHistory.push(r,a=>{i.state.display=a},[s]),this.changeState(e,a=>a.show(),t)}else if(n.is(st,"video:hide")){let s=i.state.display;return this.changeState(e,a=>{i.state.display=!1,e.actionHistory.push(r,c=>{i.state.display=c},[s]),a.hide(),e.removeVideo(i),e.stage.update()},t)}else if(n.is(st,"video:resume"))return this.changeState(e,s=>s.resume(),t);throw this.unknownTypeError()}changeStateBase(e,t,n){if(!e.isVideoAdded(this.callee))throw new b(`Video is being used before it is added to the game
25
- Use video.show() to add the video to the game`);let i=this.callee,r=new g,s=e.getExposedStateAsync(i,async a=>{e.logger.debug("Video Component state exposed",a),await t(a),r.resolve(super.executeAction(e,n))});return r.registerSkipController(new M(s.cancel)),r}changeState(e,t,n){return this.changeStateBase(e,t,n)}changeStateAsync(e,t,n){return this.changeStateBase(e,t,n)}stringify(e,t,n){return super.stringifyWithName("VideoAction")}};st.ActionTypes=$t;var mi=st;var en=class en extends X{constructor(e){super();let t=en.DefaultVideoConfig.create(e);if(this.config=t.get(),this.state=this.getInitialState(),!this.config.src)throw new te("Video must have a src")}show(){return this.chain(this.createAction($t.show,[]))}hide(){return this.chain(this.createAction($t.hide,[]))}play(){return this.chain(this.createAction($t.play,[]))}toData(){return{state:{display:this.state.display}}}fromData(e){let{state:t}=e;return this.state={display:t.display},this}reset(){return this.state=this.getInitialState(),this}getInitialState(){return en.DefaultVideoState.create().get()}createAction(e,t){return new mi(this.chain(),e,v.create(t))}};en.DefaultVideoConfig=new K({src:"",muted:!1}),en.DefaultVideoState=new K({display:!1});var no=en;var ee=class ee{constructor(e,t){this.state={sounds:[],videos:[],srcManagers:[],elements:[]};this.nvlState={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1};this._suppressNextNvlTyping=!1;this.currentHandling=null;this.playerCurrent=null;this.mainContentNode=null;this.exposedState=new Map;this.preloadingScene=null;this.flushDep=0;this.rollLock=new un;this.htmlToImage=js;this.pageRouter=null;this.stageClickBuffer=null;this.nvlAdvanceWaiters=new Map;this.stage=t,this.game=e,this.events=new W,this.logger=new si(e,"NarraLeaf-React"),this.audioManager=new ai(this),this.guard=new ti(e.config.app.guard).observe(this),this.timelines=new ni(this.guard),this.notificationMgr=new ci(this,[]),this.idManager=new Bn,this.actionHistory=new li(e.config.maxActionHistory,this.game.getLiveGame()),this.gameHistory=new ui(this.actionHistory)}get deps(){return this.flushDep}addVideo(e){return this.state.videos.push(e),this}removeVideo(e){let t=this.state.videos.indexOf(e);return t===-1?(this.logger.weakWarn("Video not found when removing",e.getId()),this):(this.state.videos.splice(t,1),this)}isVideoAdded(e){return this.state.videos.includes(e)}getVideos(){return this.state.videos}findElementByScene(e){return this.state.elements.find(t=>t.scene===e)||null}findElementByDisplayable(e,t=null){return this.state.elements.find(n=>{if(t)return n.layers.get(t)?.includes(e)||!1;for(let i of n.layers.values())if(i.includes(e))return!0;return!1})||null}getLiveGame(){return this.game.getLiveGame()}removeElement(e){let t=this.state.elements.indexOf(e);return t===-1?(this.logger.weakWarn("Element not found when removing",e.scene.getId()),this):(this.logger.debug("GameState","Removing element",e.scene.getId()),this.state.elements.splice(t,1),this)}preloadScene(e){let t=Ue.isScene(e)?e:e.entryScene;if(!t)throw new b("Trying to preload a story but the story is not loaded");return this.preloadingScene=t,this.events.emit(ee.EventTypes["event:state:flushPreloadedScenes"]),this}getPreloadingScene(){return this.preloadingScene}addElement(e){return this.state.elements.push(e),this.logger.debug("GameState","Adding element",e.scene.getId()),this}addScene(e){return this.sceneExists(e)?this:(this.state.elements.unshift({scene:e,texts:[],menus:[],layers:new Map(e.config.layers.map(t=>[t,[]]))}),this.logger.debug("GameState","Adding scene",e.getId()),this)}flush(){return this.stage.update(),this}popScene(){let e=this.state.elements.pop();return e?(this.removeElements(e.scene),this.logger.debug("GameState","Popping scene",e.scene.getId()),this):this}removeScene(e){return this.removeElements(e),this.logger.debug("GameState","Removing scene",e.getId()),this}getSceneElements(){return this.state.elements}getLastScene(){return this.state.elements[this.state.elements.length-1]?.scene||null}getCurrentScene(){return this.state.elements[0]?.scene||null}sceneExists(e){return e?this.state.elements.some(t=>t.scene===e):!!this.getLastScene()}isSceneActive(e){for(let{scene:t}of this.state.elements)if(t===e)return!0;return!1}wait(e){return new Promise(t=>setTimeout(t,e))}schedule(e,t){let n=[],i=setTimeout(()=>{e({retry:()=>{this.schedule(e,0)},onCleanup:r=>{n.push(r)}})},t);return()=>{n.forEach(r=>r()),clearTimeout(i)}}notify(e){this.notificationMgr.addNotification(e)}handle(e){if(this.currentHandling===e)return this;switch(this.currentHandling=e,e.type){case"condition:action":break}return this}createDialog(e,t,n,i){let r=this.findElementByScene(this.getLastSceneIfNot(i))?.texts;if(!r)throw this.sceneNotFound();let s=t.evaluate(re.getCtx({gameState:this}));this.game.getLiveGame().events.emit(rt.EventTypes["event:character.prompt"],{character:t.config.character,sentence:t,text:F.getText(s)});let a=this.createWaitableAction({character:t.config.character,sentence:t,id:e,words:s},()=>{r.splice(r.indexOf(a),1),n&&n()});return r.push(a),this.stage.update(),{cancel:()=>{let c=r.indexOf(a);c!==-1&&r.splice(c,1)},text:F.getText(s)}}createMenu(e,t,n){if(!e.choices.length)throw new Error("Menu must have at least one choice");let i=this.findElementByScene(this.getLastSceneIfNot(n))?.menus;if(!i)throw this.sceneNotFound();let r=e.prompt?.evaluate(re.getCtx({gameState:this}))||null,s=this.createWaitableAction({...e,words:r},a=>{i.splice(i.indexOf(s),1),t&&t(a),this.game.getLiveGame().events.emit(rt.EventTypes["event:menu.choose"],{sentence:a.prompt,text:a.evaluated})});return i.push(s),{cancel:()=>{let a=i.indexOf(s);a!==-1&&i.splice(a,1)},prompt:r?F.getText(r):null}}enterNvlMode(e){let t=this.idManager.generateId();return this.nvlState={active:!0,visible:!0,sessionId:t,dialogs:[],options:e||null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},this.events.emit(ee.EventTypes["event:state.nvl.enter"],t,e||null),this.events.emit(ee.EventTypes["event:state.nvl.visibilityChange"],!0,e?.showTransition),this.emitNvlStateChange(),this}exitNvlMode(e){let t=e?.hideTransition||this.nvlState.options?.hideTransition;return this.nvlState={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},this.nvlAdvanceWaiters.clear(),this.events.emit(ee.EventTypes["event:state.nvl.visibilityChange"],!1,t),this.events.emit(ee.EventTypes["event:state.nvl.exit"]),this.emitNvlStateChange(),this}setNvlVisibility(e,t){return this.nvlState={...this.nvlState,visible:e},this.events.emit(ee.EventTypes["event:state.nvl.visibilityChange"],e,t),this.emitNvlStateChange(),this}appendNvlDialog(e){return this.nvlState.dialogs=[...this.nvlState.dialogs,e],this.events.emit(ee.EventTypes["event:state.nvl.dialogAppend"],e),this.emitNvlStateChange(),this}removeNvlDialog(e){let t=this.nvlState.dialogs.findIndex(r=>r.id===e);if(t===-1)return this;let n=[...this.nvlState.dialogs],[i]=n.splice(t,1);return this.nvlState.dialogs=n,this.events.emit(ee.EventTypes["event:state.nvl.dialogAppend"],i),this.nvlState.activeDialogId===e&&(this.nvlState.activeDialogId=null,this.nvlState.phase="idle",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState()),this.emitNvlStateChange(),this}getNvlDialogs(){return this.nvlState.dialogs}isNvlMode(){return this.nvlState.active}getNvlState(){return this.nvlState}createNvlSnapshot(){return{active:this.nvlState.active,visible:this.nvlState.visible,sessionId:this.nvlState.sessionId,dialogs:this.nvlState.dialogs.map(e=>({...e})),options:this.nvlState.options?{...this.nvlState.options}:null,activeDialogId:this.nvlState.activeDialogId,phase:this.nvlState.phase,pendingAdvance:this.nvlState.pendingAdvance,isTyping:this.nvlState.isTyping}}createPresentationSnapshot(){return{scenes:this.state.elements.map(({scene:e})=>O.createSceneSnapshot(e,this)),nvlState:this.createNvlSnapshot()}}restoreNvlSnapshot(e){let t=e.activeDialogId&&e.dialogs.some(n=>n.id===e.activeDialogId)?e.activeDialogId:null;return this.nvlState={active:e.active,visible:e.visible,sessionId:e.sessionId,dialogs:e.dialogs.map(n=>({...n})),options:e.options?{...e.options}:null,activeDialogId:t,phase:t?"awaitAdvance":"idle",pendingAdvance:!1,isTyping:!1},this.syncNvlDerivedState(),this.nvlState.active?(this.events.emit(ee.EventTypes["event:state.nvl.enter"],this.nvlState.sessionId||"",this.nvlState.options),this.events.emit(ee.EventTypes["event:state.nvl.visibilityChange"],this.nvlState.visible,this.nvlState.visible?this.nvlState.options?.showTransition:this.nvlState.options?.hideTransition)):(this.events.emit(ee.EventTypes["event:state.nvl.visibilityChange"],!1,this.nvlState.options?.hideTransition),this.events.emit(ee.EventTypes["event:state.nvl.exit"])),this.emitNvlStateChange(),this}restorePresentationSnapshot(e){return e.scenes.forEach(t=>{O.restoreSceneSnapshot(t,this)}),this.restoreNvlSnapshot(e.nvlState),this}clearNvlDialogs(){return this.nvlState.dialogs=[],this.emitNvlStateChange(),this}setNvlActiveDialog(e,t){return this.nvlState.activeDialogId=e,this.nvlState.phase=e?t?"typing":"awaitAdvance":"idle",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.emitNvlStateChange(),this}setNvlTyping(e){return this.nvlState.phase=e?"typing":this.nvlState.activeDialogId?"awaitAdvance":"idle",this.syncNvlDerivedState(),this.emitNvlStateChange(),this}getNvlDialog(e){return this.nvlState.dialogs.find(t=>t.id===e)||null}getActiveNvlDialogForAction(e){if(!this.nvlState.activeDialogId)return null;let t=this.getNvlDialog(this.nvlState.activeDialogId);return!t||t.actionId!==e?null:t}getLatestNvlDialogForAction(e){for(let t=this.nvlState.dialogs.length-1;t>=0;t--){let n=this.nvlState.dialogs[t];if(n.actionId===e)return n}return null}allocateNvlDialogId(e){let t=-1;for(let n of this.nvlState.dialogs){if(n.actionId!==e)continue;let i=n.id.startsWith(`${e}:`)?Number.parseInt(n.id.slice(e.length+1),10):Number.NaN;Number.isNaN(i)||(t=Math.max(t,i))}return`${e}:${t+1}`}ensureNvlDialog(e){let t=this.getNvlDialog(e.id);return t?(t.character=e.character,t.sentence=e.sentence,t.text=e.text,this.events.emit(ee.EventTypes["event:state.nvl.dialogAppend"],t),this.emitNvlStateChange(),{created:!1,entry:t}):(this.appendNvlDialog(e),{created:!0,entry:e})}activateNvlDialog(e,t="typing",n=!0){return n&&this.nvlState.activeDialogId===e&&this.nvlState.phase!=="idle"||(this.nvlState.activeDialogId=e,this.nvlState.phase=t,this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.emitNvlStateChange()),this}waitForNvlAdvance(e,t){return this.nvlAdvanceWaiters.set(e,t),{cancel:()=>{this.nvlAdvanceWaiters.get(e)===t&&this.nvlAdvanceWaiters.delete(e)}}}requestNvlAdvance(e){return!this.nvlState.active||this.nvlState.activeDialogId!==e?"ignore":this.nvlState.phase==="typing"?"typing":this.nvlState.phase==="awaitAdvance"?(this.resolveNvlAdvance(e),"advance"):"ignore"}requestNvlSkip(e){return this.requestNvlAdvance(e)}completeNvlTyping(e){return!this.nvlState.active||this.nvlState.activeDialogId!==e?!1:(this.nvlState.phase="awaitAdvance",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.events.emit(ee.EventTypes["event:state.nvl.dialogComplete"],e),this.emitNvlStateChange(),!0)}settleNvlDialog(e){return this.nvlState.activeDialogId===e&&(this.nvlState.activeDialogId=null,this.nvlState.phase="idle",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.emitNvlStateChange()),this}suppressNextNvlTyping(){return this._suppressNextNvlTyping=!0,this}consumeNvlTypingSuppression(){return this._suppressNextNvlTyping?(this._suppressNextNvlTyping=!1,!0):!1}recordStageClick(){return this.stageClickBuffer={timestamp:Date.now()},this}consumeStageClick(e=200){if(!this.stageClickBuffer)return!1;let{timestamp:t}=this.stageClickBuffer,n=Date.now()-t;return this.stageClickBuffer=null,n>=0&&n<=e}createDisplayable(e,t=null,n=null){let i=this.getLastSceneIfNot(t),r=this.findElementByScene(i);if(!r)throw this.sceneNotFound();let s=r.layers.get(n||i.config.defaultDisplayableLayer);if(!s)throw this.layerNotFound();return s.push(e),this}disposeDisplayable(e,t=null,n=null){let i=this.getLastSceneIfNot(t),r=this.findElementByScene(i)?.layers.get(n||i.config.defaultDisplayableLayer);if(!r)throw this.layerNotFound();let s=r.indexOf(e);if(s===-1)throw new b(`Displayables not found when disposing. (disposing: ${e.getId()})`);return r.splice(s,1),this}forceReset(){this.state.elements.forEach(({scene:e})=>{this.offSrcManager(e.srcManager),this.removeScene(e),e.events.clear()}),this.state.elements=[],this.state.srcManagers=[],this.state.videos=[],this.nvlState={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},this.nvlAdvanceWaiters.clear(),this.audioManager.reset(),this.timelines.abortAll(),this.gameHistory.reset(),this.actionHistory.reset(),this.logger.debug("GameState","Force reset")}getHowl(){return hr.Howl}registerSrcManager(e){return this.state.srcManagers.push(e),this}offSrcManager(e){return this.state.srcManagers=this.state.srcManagers.filter(t=>t!==e),this}getStorable(){return this.game.getLiveGame().getStorable()}getSceneByName(e){return this.game.getLiveGame().story?.getScene(e)||null}getStory(){if(!this.game.getLiveGame().story)throw new b("Story not loaded");return this.game.getLiveGame().story}setInterval(e,t){return setInterval(e,t)}clearInterval(e){clearInterval(e)}setTimeout(e,t){return setTimeout(e,t)}clearTimeout(e){clearTimeout(e)}forceAnimation(){let[e,t]=fe.proxy(g.nothing),n=[];return Array.from(this.exposedState.keys()).forEach(i=>{i instanceof it&&n.push(i)}),n.forEach(i=>{let r=this.getExposedStateForce(i),s=r.applyTransform(z.immediate({}),()=>{});t.attachChild(s),r.updateStyleSync()}),this.timelines.attachTimeline(t),e}mountState(e,t){if(this.exposedState.has(e))throw new xe("State already mounted");if(!e)throw new xe("Invalid state key");return this.exposedState.set(e,t),this.events.emit(ee.EventTypes["event.state.onExpose"],e,t),{unMount:()=>{this.unMountState(e)}}}unMountState(e){return this.exposedState.has(e)||this.guard.warn("invalidExposedStateUnmounting","State not found when unmounting"),this.exposedState.delete(e),this}initVideo(e){return this.state.videos.push(e),this}isStateMounted(e){return this.exposedState.has(e)}getExposedState(e){return this.exposedState.get(e)||null}getExposedStateForce(e){let t=this.getExposedState(e);if(!t)throw new b("State not found, key: "+e);return t}getExposedStateAsync(e,t){let n=this.getExposedState(e);if(n)return{cancel:this.schedule(()=>{t(n)},0)};{let i=this.events.on(ee.EventTypes["event.state.onExpose"],(r,s)=>{r===e&&(t(s),i.cancel())});return i}}dispose(){this.forceReset()}toData(){return{scenes:this.state.elements.map(e=>({sceneId:e.scene.getId(),elements:{layers:Object.fromEntries(Array.from(e.layers.entries()).map(([t,n])=>[t.getId(),n.map(i=>i.getId())]))}})),audio:this.audioManager.toData(),videos:this.state.videos.map(e=>[e.getId(),e.toData()]),nvlState:{active:this.nvlState.active,visible:this.nvlState.visible,sessionId:this.nvlState.sessionId,options:this.nvlState.options?{...this.nvlState.options}:null,activeDialogId:this.nvlState.activeDialogId,phase:this.nvlState.phase,pendingAdvance:this.nvlState.pendingAdvance,dialogIds:this.nvlState.dialogs.map(e=>e.id),dialogs:this.nvlState.dialogs.map(e=>({id:e.id,actionId:e.actionId,text:e.text,characterId:e.character?e.character.getId():null}))}}}loadData(e,t){if(this.state.elements=[],!this.game.getLiveGame().story)throw new Error("No story loaded");let{scenes:i,audio:r,videos:s}=e;if(i.forEach(({sceneId:a,elements:c})=>{this.logger.debug("Loading scene: "+a);let l=t.get(a);if(!l)throw new b("Scene not found, id: "+a+`
26
- NarraLeaf cannot find the element with the id from the saved game`);let u={scene:l,layers:this.constructLayerMap(c.layers,t),menus:[],texts:[]};this.state.elements.push(u),this.registerSrcManager(l.srcManager),this.getExposedStateAsync(l,m=>{O.initBackgroundMusic(l,m)})}),this.audioManager.fromData(r,t),this.state.videos=s.map(([a,c])=>{let l=t.get(a);if(!l)throw new b("Video not found, id: "+a+`
27
- NarraLeaf cannot find the element with the id from the saved game`);return l.fromData(c),l}),e.nvlState){let a=(e.nvlState.dialogs||[]).map(c=>{let l=c.characterId&&t.get(c.characterId)||null,u=c.text||"";return{id:c.id,actionId:c.actionId||c.id,character:l,sentence:new ne(u,{character:l}),text:u}});this.nvlState={active:e.nvlState.active,visible:e.nvlState.visible,sessionId:e.nvlState.sessionId,dialogs:a,options:e.nvlState.options||null,activeDialogId:e.nvlState.activeDialogId||null,phase:e.nvlState.phase||(e.nvlState.activeDialogId?"awaitAdvance":"idle"),pendingAdvance:e.nvlState.pendingAdvance||!1,isTyping:!1},this.syncNvlDerivedState(),this.nvlState.active&&this.events.emit(ee.EventTypes["event:state.nvl.enter"],this.nvlState.sessionId||"",this.nvlState.options),this.nvlState.visible&&this.events.emit(ee.EventTypes["event:state.nvl.visibilityChange"],!0,this.nvlState.options?.showTransition),this.emitNvlStateChange()}}getLastSceneIfNot(e){let t=e||this.getLastScene();if(!t||!this.sceneExists(t))throw new b('Scene not found, please call "scene.activate()" first.');return t}createElementSnapshot(e){return{scene:e.scene,layers:new Map(Array.from(e.layers.entries()).map(([t,n])=>[t,n.map(i=>[i,i.toData()])]))}}fromElementSnapshot(e){return{scene:e.scene,layers:new Map(Array.from(e.layers.entries()).map(([t,n])=>[t,n.map(([i,r])=>(i.fromData(r),i))])),texts:[],menus:[]}}removeElements(e){let t=this.state.elements.findIndex(n=>n.scene===e);return t===-1?(this.logger.weakWarn("Scene not found when removing elements",e.getId()),this):(this.resetLayers(this.state.elements[t].layers),this.state.elements.splice(t,1),this.logger.debug("GameState","Removing elements",e.getId()),this)}resetLayers(e){e.forEach(t=>{t.forEach(n=>{n.reset()})})}syncNvlDerivedState(){this.nvlState.isTyping=this.nvlState.phase==="typing",this.nvlState.activeDialogId||(this.nvlState.phase="idle",this.nvlState.pendingAdvance=!1,this.nvlState.isTyping=!1)}emitNvlStateChange(){this.syncNvlDerivedState(),this.events.emit(ee.EventTypes["event:state.nvl.change"],this.getNvlState()),this.stage.update()}resolveNvlAdvance(e){let t=this.nvlAdvanceWaiters.get(e);return t?(this.nvlAdvanceWaiters.delete(e),this.nvlState.activeDialogId=null,this.nvlState.phase="idle",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.emitNvlStateChange(),t(),!0):!1}createWaitableAction(e,t){return{action:e,onClick:i=>{t&&t(i)}}}sceneNotFound(){return new b("Scene not found, target scene may not be activated. This is an internal error, please report this to the developer.")}layerNotFound(){return new b("Layer not found, target layer may not be activated. You may forget to add the layer to the scene config")}constructLayerMap(e,t){return new Map(Object.entries(e).map(([n,i])=>{let r=t.get(n);if(!r)throw new b("Layer not found, id: "+n+`
28
- NarraLeaf cannot find the element with the id from the saved game`);return[r,i.map(s=>{if(!t.has(s))throw new b("Displayable not found, id: "+s+`
24
+ Returned value ${r} violates the above rules`)}t[i]=r}}),t}deserializeServices(t){this.services.forEach((n,i)=>{!n.deserialize||typeof n.deserialize!="function"||t[i]&&n.deserialize(t[i])})}getScene(t,n=!1,i){if(ze.isScene(t))return t;let r=this.scenes.get(t)||null;if(!r&&n)throw Reflect.construct(i||ce,[`Scene with name ${t} not found`]);return r}constructStory(){let t=this.entryScene;if(!t)throw new Error("Story must have an entry scene");return this.constructSceneRoots(t),t.registerSrc(this),t.assignActionId(this),t.assignElementId(this),this.runStaticCheck(t),this}getAllElementStates(){return this.getAllChildrenElements(this,this.entryScene?.getSceneRoot()||[]).map(n=>({id:n.getId(),data:n.toData()})).filter(n=>!!n.data)}constructSceneRoots(t){let n=new Set,i=[],r=0;for(t.constructSceneRoot(this),i.push(t.getSceneRoot());i.length;){if(r++,r>Tt.MAX_DEPTH)throw new Error(`Max depth reached while constructing scene roots (max depth: ${Tt.MAX_DEPTH})`);let s=i.shift();if(ze.isScene(s.callee)){if(n.has(s.callee))continue;s.callee.isSceneRootConstructed()||s.callee.constructSceneRoot(this),n.add(s.callee)}let a=s.getFutureActions(this,{allowFutureScene:!0});i.push(...a)}return this}initPersistent(t){return this.persistent.forEach(n=>{n.init(t)}),this}getInversionConfig(){let{origin:t}=this.config;return{invertY:t==="bottom left"||t==="bottom right",invertX:t==="bottom right"||t==="top right"}}runStaticCheck(t){return new gi(t).run(this)}};Tt.defaultConfig={origin:"bottom left"},Tt.MAX_DEPTH=32767;var Pn=Tt;var yi=class extends O{executeAction(e,t){let[n,i]=this.contentNode.getContent(),r=this.callee.triggerAction(ue.getCtx({gameState:e}),n,i);return y.isAwaitable(r)?y.forward(r,{type:this.type,node:this.contentNode?.getChild()}):super.executeAction(e,t)}stringify(e,t,n){return super.stringifyWithName("ServiceAction")}};var so=class extends te{constructor(){super(...arguments);this._handlers={}}on(t,n){return this._registerActionHandler(t,n),this}trigger(t,...n){let i=this.chain();return i.chain(this._createAction(i,t,n))}triggerAction(t,n,i){let r=this._handlers[n];if(!r){t.gameState.logger.warn(`(in User-Defined Service) Trying to trigger action ${n} before it's registered, please use "service.on" to register the action`);return}if(hr(r)){let s=[],a=new y().registerSkipController(new G(()=>{for(let l of s)l?.()}));return r({...t,onAbort:l=>{s.push(l)}},...i).then(()=>a.resolve()),a}r({...t,onAbort:()=>{}},...i)}_registerActionHandler(t,n){this._handlers[t]=n}_createAction(t,n,i){return new yi(t,"service:action",new b().setContent([n,i]))}},ao=class extends so{},En=class extends ao{};var ut=class ut extends O{executeAction(e,t){let n=this,i=this.callee,r={action:n,stackModel:t.stackModel};if(n.is(ut,"video:play"))return this.changeStateAsync(e,s=>s.play(),t);if(n.is(ut,"video:pause"))return this.changeState(e,s=>s.pause(),t);if(n.is(ut,"video:stop"))return this.changeState(e,s=>s.stop(),t);if(n.is(ut,"video:seek"))return this.changeState(e,s=>s.seek(n.contentNode.getContent()[0]),t);if(n.is(ut,"video:show")){let s=i.state.display;return e.isVideoAdded(i)||(e.addVideo(i),e.stage.update()),i.state.display=!0,e.actionHistory.push(r,a=>{i.state.display=a},[s]),this.changeState(e,a=>a.show(),t)}else if(n.is(ut,"video:hide")){let s=i.state.display;return this.changeState(e,a=>{i.state.display=!1,e.actionHistory.push(r,c=>{i.state.display=c},[s]),a.hide(),e.removeVideo(i),e.stage.update()},t)}else if(n.is(ut,"video:resume"))return this.changeState(e,s=>s.resume(),t);throw this.unknownTypeError()}changeStateBase(e,t,n){if(!e.isVideoAdded(this.callee))throw new x(`Video is being used before it is added to the game
25
+ Use video.show() to add the video to the game`);let i=this.callee,r=new y,s=e.getExposedStateAsync(i,async a=>{e.logger.debug("Video Component state exposed",a),await t(a),r.resolve(super.executeAction(e,n))});return r.registerSkipController(new G(s.cancel)),r}changeState(e,t,n){return this.changeStateBase(e,t,n)}changeStateAsync(e,t,n){return this.changeStateBase(e,t,n)}stringify(e,t,n){return super.stringifyWithName("VideoAction")}};ut.ActionTypes=Zt;var vi=ut;var cn=class cn extends te{constructor(e){super();let t=cn.DefaultVideoConfig.create(e);if(this.config=t.get(),this.state=this.getInitialState(),!this.config.src)throw new ce("Video must have a src")}show(){return this.chain(this.createAction(Zt.show,[]))}hide(){return this.chain(this.createAction(Zt.hide,[]))}play(){return this.chain(this.createAction(Zt.play,[]))}toData(){return{state:{display:this.state.display}}}fromData(e){let{state:t}=e;return this.state={display:t.display},this}reset(){return this.state=this.getInitialState(),this}getInitialState(){return cn.DefaultVideoState.create().get()}createAction(e,t){return new vi(this.chain(),e,b.create(t))}};cn.DefaultVideoConfig=new j({src:"",muted:!1}),cn.DefaultVideoState=new j({display:!1});var co=cn;function Dr(o){return"image"in o?{image:o.image,avatar:o.avatar}:{image:o}}function Lr(o){let{sentenceAvatar:e,portraitAvatar:t,characterAvatar:n}=o;if(!o.character||!o.character.state.name||e===!1)return Er(o);let i=lo(e,o);if(i.resolved)return{source:i.source,character:o.character,portrait:o.portrait};let r=lo(t,o);if(r.resolved)return{source:r.source,character:o.character,portrait:o.portrait};let s=lo(n,o);return s.resolved?{source:s.source,character:o.character,portrait:o.portrait}:{source:null,character:o.character,portrait:o.portrait}}function lo(o,e){if(o===!1||typeof o>"u")return{resolved:!1,source:null};if(typeof o=="function"){let t=o(e);return{resolved:typeof t<"u",source:t??null}}return{resolved:!0,source:o}}function Er(o){return{source:null,character:o.character||null,portrait:o.portrait||null}}var ae=class ae{constructor(e,t){this.state={sounds:[],videos:[],srcManagers:[],elements:[]};this.nvlState={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1};this._suppressNextNvlTyping=!1;this.currentHandling=null;this.playerCurrent=null;this.mainContentNode=null;this.exposedState=new Map;this.preloadingScene=null;this.flushDep=0;this.rollLock=new vn;this.htmlToImage=la;this.pageRouter=null;this.stageClickBuffer=null;this.nvlAdvanceWaiters=new Map;this.stage=t,this.game=e,this.events=new J,this.logger=new pi(e,"NarraLeaf-React"),this.audioManager=new di(this),this.guard=new si(e.config.app.guard).observe(this),this.timelines=new ai(this.guard),this.notificationMgr=new mi(this,[]),this.idManager=new Xn,this.actionHistory=new fi(e.config.maxActionHistory,this.game.getLiveGame()),this.gameHistory=new hi(this.actionHistory)}get deps(){return this.flushDep}addVideo(e){return this.state.videos.push(e),this}removeVideo(e){let t=this.state.videos.indexOf(e);return t===-1?(this.logger.weakWarn("Video not found when removing",e.getId()),this):(this.state.videos.splice(t,1),this)}isVideoAdded(e){return this.state.videos.includes(e)}getVideos(){return this.state.videos}findElementByScene(e){return this.state.elements.find(t=>t.scene===e)||null}findElementByDisplayable(e,t=null){return this.state.elements.find(n=>{if(t)return n.layers.get(t)?.includes(e)||!1;for(let i of n.layers.values())if(i.includes(e))return!0;return!1})||null}getLiveGame(){return this.game.getLiveGame()}removeElement(e){let t=this.state.elements.indexOf(e);return t===-1?(this.logger.weakWarn("Element not found when removing",e.scene.getId()),this):(this.logger.debug("GameState","Removing element",e.scene.getId()),this.state.elements.splice(t,1),this)}preloadScene(e){let t=ze.isScene(e)?e:e.entryScene;if(!t)throw new x("Trying to preload a story but the story is not loaded");return this.preloadingScene=t,this.events.emit(ae.EventTypes["event:state:flushPreloadedScenes"]),this}getPreloadingScene(){return this.preloadingScene}addElement(e){return this.state.elements.push(e),this.logger.debug("GameState","Adding element",e.scene.getId()),this}addScene(e){return this.sceneExists(e)?this:(this.state.elements.unshift({scene:e,texts:[],menus:[],layers:new Map(e.config.layers.map(t=>[t,[]]))}),this.logger.debug("GameState","Adding scene",e.getId()),this)}flush(){return this.stage.update(),this}popScene(){let e=this.state.elements.pop();return e?(this.removeElements(e.scene),this.logger.debug("GameState","Popping scene",e.scene.getId()),this):this}removeScene(e){return this.removeElements(e),this.logger.debug("GameState","Removing scene",e.getId()),this}getSceneElements(){return this.state.elements}getLastScene(){return this.state.elements[this.state.elements.length-1]?.scene||null}getCurrentScene(){return this.state.elements[0]?.scene||null}findCurrentPortraitForCharacter(e){let t=(e.config.portraits||[]).map(Dr);if(!t.length)return null;let n=this.getLastScene(),i=n?this.findElementByScene(n):null;if(!i)return null;let r=new Map(t.map(a=>[a.image,a])),s=Array.from(i.layers.values());for(let a=s.length-1;a>=0;a--){let c=s[a];for(let l=c.length-1;l>=0;l--){let p=c[l],u=r.get(p);if(u&&this.isDisplayableVisible(p))return u}}return null}sceneExists(e){return e?this.state.elements.some(t=>t.scene===e):!!this.getLastScene()}isSceneActive(e){for(let{scene:t}of this.state.elements)if(t===e)return!0;return!1}wait(e){return new Promise(t=>setTimeout(t,e))}schedule(e,t){let n=[],i=setTimeout(()=>{e({retry:()=>{this.schedule(e,0)},onCleanup:r=>{n.push(r)}})},t);return()=>{n.forEach(r=>r()),clearTimeout(i)}}notify(e){this.notificationMgr.addNotification(e)}handle(e){if(this.currentHandling===e)return this;switch(this.currentHandling=e,e.type){case"condition:action":break}return this}createDialog(e,t,n,i){let r=this.findElementByScene(this.getLastSceneIfNot(i))?.texts;if(!r)throw this.sceneNotFound();let s=t.evaluate(ue.getCtx({gameState:this}));this.game.getLiveGame().events.emit(lt.EventTypes["event:character.prompt"],{character:t.config.character,sentence:t,text:W.getText(s)});let a=this.createWaitableAction({character:t.config.character,sentence:t,id:e,words:s},()=>{let c=r.indexOf(a);c!==-1&&r.splice(c,1),n&&n()});return r.push(a),this.stage.update(),{cancel:()=>{let c=r.indexOf(a);c!==-1&&r.splice(c,1)},text:W.getText(s)}}createMenu(e,t,n){if(!e.choices.length)throw new Error("Menu must have at least one choice");let i=this.findElementByScene(this.getLastSceneIfNot(n))?.menus;if(!i)throw this.sceneNotFound();let r=e.prompt?.evaluate(ue.getCtx({gameState:this}))||null,s=this.createWaitableAction({...e,words:r},a=>{i.splice(i.indexOf(s),1),t&&t(a),this.game.getLiveGame().events.emit(lt.EventTypes["event:menu.choose"],{sentence:a.prompt,text:a.evaluated})});return i.push(s),{cancel:()=>{let a=i.indexOf(s);a!==-1&&i.splice(a,1)},prompt:r?W.getText(r):null}}enterNvlMode(e){let t=this.idManager.generateId();return this.nvlState={active:!0,visible:!0,sessionId:t,dialogs:[],options:e||null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},this.events.emit(ae.EventTypes["event:state.nvl.enter"],t,e||null),this.events.emit(ae.EventTypes["event:state.nvl.visibilityChange"],!0,e?.showTransition),this.emitNvlStateChange(),this}exitNvlMode(e){let t=e?.hideTransition||this.nvlState.options?.hideTransition;return this.nvlState={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},this.nvlAdvanceWaiters.clear(),this.events.emit(ae.EventTypes["event:state.nvl.visibilityChange"],!1,t),this.events.emit(ae.EventTypes["event:state.nvl.exit"]),this.emitNvlStateChange(),this}setNvlVisibility(e,t){return this.nvlState={...this.nvlState,visible:e},this.events.emit(ae.EventTypes["event:state.nvl.visibilityChange"],e,t),this.emitNvlStateChange(),this}appendNvlDialog(e){return this.nvlState.dialogs=[...this.nvlState.dialogs,e],this.events.emit(ae.EventTypes["event:state.nvl.dialogAppend"],e),this.emitNvlStateChange(),this}removeNvlDialog(e){let t=this.nvlState.dialogs.findIndex(r=>r.id===e);if(t===-1)return this;let n=[...this.nvlState.dialogs],[i]=n.splice(t,1);return this.nvlState.dialogs=n,this.events.emit(ae.EventTypes["event:state.nvl.dialogAppend"],i),this.nvlState.activeDialogId===e&&(this.nvlState.activeDialogId=null,this.nvlState.phase="idle",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState()),this.emitNvlStateChange(),this}getNvlDialogs(){return this.nvlState.dialogs}isNvlMode(){return this.nvlState.active}getNvlState(){return this.nvlState}createNvlSnapshot(){return{active:this.nvlState.active,visible:this.nvlState.visible,sessionId:this.nvlState.sessionId,dialogs:this.nvlState.dialogs.map(e=>({...e})),options:this.nvlState.options?{...this.nvlState.options}:null,activeDialogId:this.nvlState.activeDialogId,phase:this.nvlState.phase,pendingAdvance:this.nvlState.pendingAdvance,isTyping:this.nvlState.isTyping}}createPresentationSnapshot(){return{scenes:this.state.elements.map(({scene:e})=>Y.createSceneSnapshot(e,this)),nvlState:this.createNvlSnapshot()}}restoreNvlSnapshot(e){let t=e.activeDialogId&&e.dialogs.some(n=>n.id===e.activeDialogId)?e.activeDialogId:null;return this.nvlState={active:e.active,visible:e.visible,sessionId:e.sessionId,dialogs:e.dialogs.map(n=>({...n})),options:e.options?{...e.options}:null,activeDialogId:t,phase:t?"awaitAdvance":"idle",pendingAdvance:!1,isTyping:!1},this.syncNvlDerivedState(),this.nvlState.active?(this.events.emit(ae.EventTypes["event:state.nvl.enter"],this.nvlState.sessionId||"",this.nvlState.options),this.events.emit(ae.EventTypes["event:state.nvl.visibilityChange"],this.nvlState.visible,this.nvlState.visible?this.nvlState.options?.showTransition:this.nvlState.options?.hideTransition)):(this.events.emit(ae.EventTypes["event:state.nvl.visibilityChange"],!1,this.nvlState.options?.hideTransition),this.events.emit(ae.EventTypes["event:state.nvl.exit"])),this.emitNvlStateChange(),this}restorePresentationSnapshot(e){return e.scenes.forEach(t=>{Y.restoreSceneSnapshot(t,this)}),this.restoreNvlSnapshot(e.nvlState),this}clearNvlDialogs(){return this.nvlState.dialogs=[],this.emitNvlStateChange(),this}setNvlActiveDialog(e,t){return this.nvlState.activeDialogId=e,this.nvlState.phase=e?t?"typing":"awaitAdvance":"idle",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.emitNvlStateChange(),this}setNvlTyping(e){return this.nvlState.phase=e?"typing":this.nvlState.activeDialogId?"awaitAdvance":"idle",this.syncNvlDerivedState(),this.emitNvlStateChange(),this}getNvlDialog(e){return this.nvlState.dialogs.find(t=>t.id===e)||null}getActiveNvlDialogForAction(e){if(!this.nvlState.activeDialogId)return null;let t=this.getNvlDialog(this.nvlState.activeDialogId);return!t||t.actionId!==e?null:t}getLatestNvlDialogForAction(e){for(let t=this.nvlState.dialogs.length-1;t>=0;t--){let n=this.nvlState.dialogs[t];if(n.actionId===e)return n}return null}allocateNvlDialogId(e){let t=-1;for(let n of this.nvlState.dialogs){if(n.actionId!==e)continue;let i=n.id.startsWith(`${e}:`)?Number.parseInt(n.id.slice(e.length+1),10):Number.NaN;Number.isNaN(i)||(t=Math.max(t,i))}return`${e}:${t+1}`}ensureNvlDialog(e){let t=this.getNvlDialog(e.id);return t?(t.character=e.character,t.sentence=e.sentence,t.text=e.text,this.events.emit(ae.EventTypes["event:state.nvl.dialogAppend"],t),this.emitNvlStateChange(),{created:!1,entry:t}):(this.appendNvlDialog(e),{created:!0,entry:e})}activateNvlDialog(e,t="typing",n=!0){return n&&this.nvlState.activeDialogId===e&&this.nvlState.phase!=="idle"||(this.nvlState.activeDialogId=e,this.nvlState.phase=t,this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.emitNvlStateChange()),this}waitForNvlAdvance(e,t){return this.nvlAdvanceWaiters.set(e,t),{cancel:()=>{this.nvlAdvanceWaiters.get(e)===t&&this.nvlAdvanceWaiters.delete(e)}}}requestNvlAdvance(e){return!this.nvlState.active||this.nvlState.activeDialogId!==e?"ignore":this.nvlState.phase==="typing"?"typing":this.nvlState.phase==="awaitAdvance"?(this.resolveNvlAdvance(e),"advance"):"ignore"}requestNvlSkip(e){return this.requestNvlAdvance(e)}completeNvlTyping(e){return!this.nvlState.active||this.nvlState.activeDialogId!==e?!1:(this.nvlState.phase="awaitAdvance",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.events.emit(ae.EventTypes["event:state.nvl.dialogComplete"],e),this.emitNvlStateChange(),!0)}settleNvlDialog(e){return this.nvlState.activeDialogId===e&&(this.nvlState.activeDialogId=null,this.nvlState.phase="idle",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.emitNvlStateChange()),this}suppressNextNvlTyping(){return this._suppressNextNvlTyping=!0,this}consumeNvlTypingSuppression(){return this._suppressNextNvlTyping?(this._suppressNextNvlTyping=!1,!0):!1}recordStageClick(){return this.stageClickBuffer={timestamp:Date.now()},this}consumeStageClick(e=200){if(!this.stageClickBuffer)return!1;let{timestamp:t}=this.stageClickBuffer,n=Date.now()-t;return this.stageClickBuffer=null,n>=0&&n<=e}createDisplayable(e,t=null,n=null){let i=this.getLastSceneIfNot(t),r=this.findElementByScene(i);if(!r)throw this.sceneNotFound();let s=r.layers.get(n||i.config.defaultDisplayableLayer);if(!s)throw this.layerNotFound();return s.push(e),this}disposeDisplayable(e,t=null,n=null){let i=this.getLastSceneIfNot(t),r=this.findElementByScene(i)?.layers.get(n||i.config.defaultDisplayableLayer);if(!r)throw this.layerNotFound();let s=r.indexOf(e);if(s===-1)throw new x(`Displayables not found when disposing. (disposing: ${e.getId()})`);return r.splice(s,1),this}forceReset(){[...this.state.elements].forEach(({scene:t})=>{this.offSrcManager(t.srcManager),this.removeScene(t),t.events.clear()}),this.state.elements=[],this.state.srcManagers=[],this.state.videos=[],this.nvlState={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},this.nvlAdvanceWaiters.clear(),this.audioManager.reset(),this.timelines.abortAll(),this.gameHistory.reset(),this.actionHistory.reset(),this.logger.debug("GameState","Force reset")}getHowl(){return Ir.Howl}registerSrcManager(e){return this.state.srcManagers.push(e),this}offSrcManager(e){return this.state.srcManagers=this.state.srcManagers.filter(t=>t!==e),this}getStorable(){return this.game.getLiveGame().getStorable()}getSceneByName(e){return this.game.getLiveGame().story?.getScene(e)||null}getStory(){if(!this.game.getLiveGame().story)throw new x("Story not loaded");return this.game.getLiveGame().story}setInterval(e,t){return setInterval(e,t)}clearInterval(e){clearInterval(e)}setTimeout(e,t){return setTimeout(e,t)}clearTimeout(e){clearTimeout(e)}forceAnimation(){let[e,t]=Te.proxy(y.nothing),n=[];return Array.from(this.exposedState.keys()).forEach(i=>{i instanceof at&&n.push(i)}),n.forEach(i=>{let r=this.getExposedStateForce(i),s=r.applyTransform(q.immediate({}),()=>{});t.attachChild(s),r.updateStyleSync()}),this.timelines.attachTimeline(t),e}mountState(e,t){if(this.exposedState.has(e))throw new Le("State already mounted");if(!e)throw new Le("Invalid state key");return this.exposedState.set(e,t),this.events.emit(ae.EventTypes["event.state.onExpose"],e,t),{unMount:()=>{this.unMountState(e)}}}unMountState(e){return this.exposedState.has(e)||this.guard.warn("invalidExposedStateUnmounting","State not found when unmounting"),this.exposedState.delete(e),this}initVideo(e){return this.state.videos.push(e),this}isStateMounted(e){return this.exposedState.has(e)}getExposedState(e){return this.exposedState.get(e)||null}getExposedStateForce(e){let t=this.getExposedState(e);if(!t)throw new x("State not found, key: "+e);return t}getExposedStateAsync(e,t){let n=this.getExposedState(e);if(n)return{cancel:this.schedule(()=>{t(n)},0)};{let i=this.events.on(ae.EventTypes["event.state.onExpose"],(r,s)=>{r===e&&(t(s),i.cancel())});return i}}dispose(){this.forceReset()}toData(){return{scenes:this.state.elements.map(e=>({sceneId:e.scene.getId(),elements:{layers:Object.fromEntries(Array.from(e.layers.entries()).map(([t,n])=>[t.getId(),n.map(i=>i.getId())]))}})),audio:this.audioManager.toData(),videos:this.state.videos.map(e=>[e.getId(),e.toData()]),nvlState:{active:this.nvlState.active,visible:this.nvlState.visible,sessionId:this.nvlState.sessionId,options:this.nvlState.options?{...this.nvlState.options}:null,activeDialogId:this.nvlState.activeDialogId,phase:this.nvlState.phase,pendingAdvance:this.nvlState.pendingAdvance,dialogIds:this.nvlState.dialogs.map(e=>e.id),dialogs:this.nvlState.dialogs.map(e=>({id:e.id,actionId:e.actionId,text:e.text,characterId:e.character?e.character.getId():null}))}}}loadData(e,t){if(this.state.elements=[],!this.game.getLiveGame().story)throw new Error("No story loaded");let{scenes:i,audio:r,videos:s}=e;if(i.forEach(({sceneId:a,elements:c})=>{this.logger.debug("Loading scene: "+a);let l=t.get(a);if(!l)throw new x("Scene not found, id: "+a+`
26
+ NarraLeaf cannot find the element with the id from the saved game`);let p={scene:l,layers:this.constructLayerMap(c.layers,t),menus:[],texts:[]};this.state.elements.push(p),this.registerSrcManager(l.srcManager),this.getExposedStateAsync(l,u=>{Y.initBackgroundMusic(l,u)})}),this.audioManager.fromData(r,t),this.state.videos=s.map(([a,c])=>{let l=t.get(a);if(!l)throw new x("Video not found, id: "+a+`
27
+ NarraLeaf cannot find the element with the id from the saved game`);return l.fromData(c),l}),e.nvlState){let a=(e.nvlState.dialogs||[]).map(c=>{let l=c.characterId&&t.get(c.characterId)||null,p=c.text||"";return{id:c.id,actionId:c.actionId||c.id,character:l,sentence:new ie(p,{character:l}),text:p}});this.nvlState={active:e.nvlState.active,visible:e.nvlState.visible,sessionId:e.nvlState.sessionId,dialogs:a,options:e.nvlState.options||null,activeDialogId:e.nvlState.activeDialogId||null,phase:e.nvlState.phase||(e.nvlState.activeDialogId?"awaitAdvance":"idle"),pendingAdvance:e.nvlState.pendingAdvance||!1,isTyping:!1},this.syncNvlDerivedState(),this.nvlState.active&&this.events.emit(ae.EventTypes["event:state.nvl.enter"],this.nvlState.sessionId||"",this.nvlState.options),this.nvlState.visible&&this.events.emit(ae.EventTypes["event:state.nvl.visibilityChange"],!0,this.nvlState.options?.showTransition),this.emitNvlStateChange()}}getLastSceneIfNot(e){let t=e||this.getLastScene();if(!t||!this.sceneExists(t))throw new x('Scene not found, please call "scene.activate()" first.');return t}createElementSnapshot(e){return{scene:e.scene,layers:new Map(Array.from(e.layers.entries()).map(([t,n])=>[t,n.map(i=>[i,i.toData()])]))}}fromElementSnapshot(e){return{scene:e.scene,layers:new Map(Array.from(e.layers.entries()).map(([t,n])=>[t,n.map(([i,r])=>(i.fromData(r),i))])),texts:[],menus:[]}}removeElements(e){let t=this.state.elements.findIndex(n=>n.scene===e);return t===-1?(this.logger.weakWarn("Scene not found when removing elements",e.getId()),this):(this.resetLayers(this.state.elements[t].layers),this.state.elements.splice(t,1),this.logger.debug("GameState","Removing elements",e.getId()),this)}resetLayers(e){e.forEach(t=>{t.forEach(n=>{n.reset()})})}syncNvlDerivedState(){this.nvlState.isTyping=this.nvlState.phase==="typing",this.nvlState.activeDialogId||(this.nvlState.phase="idle",this.nvlState.pendingAdvance=!1,this.nvlState.isTyping=!1)}emitNvlStateChange(){this.syncNvlDerivedState(),this.events.emit(ae.EventTypes["event:state.nvl.change"],this.getNvlState()),this.stage.update()}resolveNvlAdvance(e){let t=this.nvlAdvanceWaiters.get(e);return t?(this.nvlAdvanceWaiters.delete(e),this.nvlState.activeDialogId=null,this.nvlState.phase="idle",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.emitNvlStateChange(),t(),!0):!1}isDisplayableVisible(e){return(e.transformState.get().opacity??0)>0}createWaitableAction(e,t){return{action:e,onClick:(i=>{t&&t(i)})}}sceneNotFound(){return new x("Scene not found, target scene may not be activated. This is an internal error, please report this to the developer.")}layerNotFound(){return new x("Layer not found, target layer may not be activated. You may forget to add the layer to the scene config")}constructLayerMap(e,t){return new Map(Object.entries(e).map(([n,i])=>{let r=t.get(n);if(!r)throw new x("Layer not found, id: "+n+`
28
+ NarraLeaf cannot find the element with the id from the saved game`);return[r,i.map(s=>{if(!t.has(s))throw new x("Displayable not found, id: "+s+`
29
29
  NarraLeaf cannot find the element with the id from the saved game
30
- This may be caused by the damage of the saved game file or the change of the story file`);return t.get(s)})]}))}};ee.EventTypes={"event:state.end":"event:state.end","event:state.player.skip":"event:state.player.skip","event:state.player.lineEnd":"event:state.player.lineEnd","event:state.player.requestFlush":"event:state.player.requestFlush","event:state.player.stageClick":"event:state.player.stageClick","event.state.onExpose":"event.state.onExpose","event:state.onRender":"event:state.onRender","event:state:flushPreloadedScenes":"event:state:flushPreloadedScenes","event:state.nvl.enter":"event:state.nvl.enter","event:state.nvl.exit":"event:state.nvl.exit","event:state.nvl.dialogComplete":"event:state.nvl.dialogComplete","event:state.nvl.dialogAppend":"event:state.nvl.dialogAppend","event:state.nvl.visibilityChange":"event:state.nvl.visibilityChange","event:state.nvl.change":"event:state.nvl.change"};var w=ee;var gr=32767,qs=1e3,we=class o{constructor(e,t=void 0){this.liveGame=e;this.__tag=void 0;this.waitingAction=null;this.loopConfig=null;this.loopBodyActions=[];this.loopCondition=null;this.loopStartTime=0;this.loopDebugCheckpoint=0;this.__tag=t,this.stack=new jn().addPushValidator(n=>{let i=this.stack.peek();if(n===i)throw new xe("StackModel: Unexpected self-push in stack.");if(o.isCalledActionResult(i)){if(i.wait&&o.isStackModelsAwaiting(i.wait.type,i.wait.stackModels))throw new xe("StackModel: Unexpected waiting action in stack. (is calledActionResult: true, wait: true)")}else if(g.isAwaitable(i)&&!i.isSettled())throw new xe("StackModel: Unexpected unsettled Awaitable in stack.");if(!o.isCalledActionResult(n)&&!g.isAwaitable(n))throw new xe("StackModel: Unexpected non-CalledActionResult or Awaitable in stack.");return!0})}static isStackModel(e){return e instanceof o}static createStackModel(e,t,n){let i=new o(e);return i.deserialize(t,n),i}static createCountLoop(e,t,n){let i=new o(e,"loop:count");return i.initLoop({type:"count",counter:0,limit:t,bodyActionIds:n.map(r=>r.getId()),broken:!1},n,null),i}static createConditionLoop(e,t,n,i){let r=new o(e,"loop:condition");return r.initLoop({type:"condition",counter:0,conditionActionId:n,bodyActionIds:i.map(s=>s.getId()),broken:!1},i,t),r}static isCalledActionResult(e){return!!e&&!this.isStackModel(e)&&!g.isAwaitable(e)&&"type"in e}static fromAction(e){return{type:e.type,node:e.contentNode}}static executeStackModelGroup(e,t){return e==="any"?g.any(...t.map(n=>n.execute())):g.all(...t.map(n=>n.execute()))}static isStackModelsAwaiting(e,t){if(t.length===0)throw new Error("StackModel: StackModels are empty.");return e==="any"?t.every(n=>!n.isEmpty()):t.some(n=>!n.isEmpty())}initLoop(e,t,n){this.loopConfig=e,this.loopBodyActions=t,this.loopCondition=n,this.loopStartTime=Date.now(),this.loopDebugCheckpoint=0,this.shouldContinueLoop(this.liveGame.getGameStateForce())&&this.pushLoopBody()}shouldContinueLoop(e){return!this.loopConfig||this.loopConfig.broken?!1:this.loopConfig.type==="count"?this.loopConfig.counter<(this.loopConfig.limit??0):this.loopCondition?this.loopCondition.evaluate({gameState:e}).value:!1}pushLoopBody(){if(this.loopBodyActions.length!==0)for(let e=this.loopBodyActions.length-1;e>=0;e--)this.stack.push(o.fromAction(this.loopBodyActions[e]))}onIterationComplete(){!this.loopConfig||this.loopConfig.broken||(this.loopConfig.counter++,this.liveGame.game.config.app.debug&&this.checkInfiniteLoop(),this.shouldContinueLoop(this.liveGame.getGameStateForce())&&this.pushLoopBody())}checkInfiniteLoop(){if(!this.loopConfig)return;let e=this.loopConfig.counter;if(e>0&&e%gr===0){let t=Date.now()-this.loopStartTime;if(e-this.loopDebugCheckpoint>=gr&&t<qs){let i=new b(`[NarraLeaf] Potential infinite loop detected!
30
+ This may be caused by the damage of the saved game file or the change of the story file`);return t.get(s)})]}))}};ae.EventTypes={"event:state.end":"event:state.end","event:state.player.skip":"event:state.player.skip","event:state.player.lineEnd":"event:state.player.lineEnd","event:state.player.requestFlush":"event:state.player.requestFlush","event:state.player.stageClick":"event:state.player.stageClick","event.state.onExpose":"event.state.onExpose","event:state.onRender":"event:state.onRender","event:state:flushPreloadedScenes":"event:state:flushPreloadedScenes","event:state.nvl.enter":"event:state.nvl.enter","event:state.nvl.exit":"event:state.nvl.exit","event:state.nvl.dialogComplete":"event:state.nvl.dialogComplete","event:state.nvl.dialogAppend":"event:state.nvl.dialogAppend","event:state.nvl.visibilityChange":"event:state.nvl.visibilityChange","event:state.nvl.change":"event:state.nvl.change"};var k=ae;var Rr=32767,ua=1e3,Ie=class o{constructor(e,t=void 0){this.liveGame=e;this.__tag=void 0;this.waitingAction=null;this.loopConfig=null;this.loopBodyActions=[];this.loopCondition=null;this.loopStartTime=0;this.loopDebugCheckpoint=0;this.__tag=t,this.stack=new Jn().addPushValidator(n=>{let i=this.stack.peek();if(n===i)throw new Le("StackModel: Unexpected self-push in stack.");if(o.isCalledActionResult(i)){if(i.wait&&o.isStackModelsAwaiting(i.wait.type,i.wait.stackModels))throw new Le("StackModel: Unexpected waiting action in stack. (is calledActionResult: true, wait: true)")}else if(y.isAwaitable(i)&&!i.isSettled())throw new Le("StackModel: Unexpected unsettled Awaitable in stack.");if(!o.isCalledActionResult(n)&&!y.isAwaitable(n))throw new Le("StackModel: Unexpected non-CalledActionResult or Awaitable in stack.");return!0})}static isStackModel(e){return e instanceof o}static createStackModel(e,t,n){let i=new o(e);return i.deserialize(t,n),i}static createCountLoop(e,t,n){let i=new o(e,"loop:count");return i.initLoop({type:"count",counter:0,limit:t,bodyActionIds:n.map(r=>r.getId()),broken:!1},n,null),i}static createConditionLoop(e,t,n,i){let r=new o(e,"loop:condition");return r.initLoop({type:"condition",counter:0,conditionActionId:n,bodyActionIds:i.map(s=>s.getId()),broken:!1},i,t),r}static isCalledActionResult(e){return!!e&&!this.isStackModel(e)&&!y.isAwaitable(e)&&"type"in e}static fromAction(e){return{type:e.type,node:e.contentNode}}static executeStackModelGroup(e,t){return e==="any"?y.any(...t.map(n=>n.execute())):y.all(...t.map(n=>n.execute()))}static isStackModelsAwaiting(e,t){if(t.length===0)throw new Error("StackModel: StackModels are empty.");return e==="any"?t.every(n=>!n.isEmpty()):t.some(n=>!n.isEmpty())}initLoop(e,t,n){this.loopConfig=e,this.loopBodyActions=t,this.loopCondition=n,this.loopStartTime=Date.now(),this.loopDebugCheckpoint=0,this.shouldContinueLoop(this.liveGame.getGameStateForce())&&this.pushLoopBody()}shouldContinueLoop(e){return!this.loopConfig||this.loopConfig.broken?!1:this.loopConfig.type==="count"?this.loopConfig.counter<(this.loopConfig.limit??0):this.loopCondition?this.loopCondition.evaluate({gameState:e}).value:!1}pushLoopBody(){if(this.loopBodyActions.length!==0)for(let e=this.loopBodyActions.length-1;e>=0;e--)this.stack.push(o.fromAction(this.loopBodyActions[e]))}onIterationComplete(){!this.loopConfig||this.loopConfig.broken||(this.loopConfig.counter++,this.liveGame.game.config.app.debug&&this.checkInfiniteLoop(),this.shouldContinueLoop(this.liveGame.getGameStateForce())&&this.pushLoopBody())}checkInfiniteLoop(){if(!this.loopConfig)return;let e=this.loopConfig.counter;if(e>0&&e%Rr===0){let t=Date.now()-this.loopStartTime;if(e-this.loopDebugCheckpoint>=Rr&&t<ua){let i=new x(`[NarraLeaf] Potential infinite loop detected!
31
31
  Loop has executed ${e} iterations in ${t}ms.
32
32
  This is likely a bug in your game script. Check your loop conditions.
33
- Loop type: ${this.loopConfig.type}, broken: ${this.loopConfig.broken}`);throw this.liveGame.getGameStateForce().logger.error("StackModel",i.message),i}this.loopDebugCheckpoint=e,this.loopStartTime=Date.now()}}breakLoop(){if(!this.loopConfig)throw new b("Cannot break: StackModel is not a loop");this.loopConfig.broken=!0,this.stack.clear()}isLoop(){return this.loopConfig!==null}rollNext(){if(this.stack.isEmpty())return null;let e=this.stack.peek();if(g.isAwaitable(e)&&!e.isSettled())return e;if(o.isCalledActionResult(e)&&e.wait){let n=e.wait.stackModels;if(!n.length)throw new Error("StackModel: Waiting action contains empty stackModels.");if(o.isStackModelsAwaiting(e.wait.type,n))return n.forEach(i=>i.rollNext()),e}this.waitingAction=null;let t=this.stack.pop();if(g.isAwaitable(t)){let n=t.result;if(n)return this.stack.push(n),this.liveGame.getGameStateForce().logger.debug("next action (resolved awaitable)",n.node?.action),n}else return this.waitingAction=t,this.executeActions(t);return null}execute(){let e=new g,t=null,n=!1;return(async()=>{let r=0;for(;!n;){if(r++>this.liveGame.game.config.maxStackModelLoop)throw new Error("StackModel: Suspiciously long waiting loop.");if(this.stack.isEmpty()){if(this.loopConfig&&!this.loopConfig.broken&&(this.onIterationComplete(),!this.stack.isEmpty()))continue;n=!0;break}let s=this.rollNext();if(s){if(g.isAwaitable(s)){if(s.isSettled())continue;t=s,await s}else if(o.isCalledActionResult(s))if(s.wait)t=o.executeStackModelGroup(s.wait.type,s.wait.stackModels),await t;else continue}}})().then(()=>e.resolve()),e.onSkipControllerRegister(r=>{r.onAbort(()=>{t&&(n=!0,t.abort())})}),e}abortStackTop(){if(this.stack.isEmpty())return null;let e=this.stack.peek();return e&&g.isAwaitable(e)?(this.stack.pop().abort(),this.waitingAction=null):o.isCalledActionResult(e)&&e.wait&&(e.wait.stackModels.forEach(t=>t.abortStackTop()),this.waitingAction=null),this.waitingAction}getTopSync(){if(this.stack.isEmpty())return null;let e=!1;for(let t=this.stack.size()-1;t>=0;t--){let n=this.stack.get(t);if(n){if(o.isCalledActionResult(n))return n;if(e)throw new xe("StackModel: Unexpected non-CalledActionResult in stack.")}else return null;e=!0}return null}executeActions(e){if(!e.node?.action)return null;let t=this.liveGame.executeAction(this.liveGame.getGameStateForce(),e.node.action,{stackModel:this}),n=i=>i?g.isAwaitable(i)?(this.liveGame.getGameStateForce().logger.debug("next action (executed awaitable)",i),this.stack.push(i),i):i.node?.action?(this.liveGame.getGameStateForce().logger.debug("next action (executed)",i),this.stack.push(i),i):null:null;if(Array.isArray(t)){let i=null;for(let r of t){let s=n(r);s&&(i=s)}return i}else{let i=n(t);if(i)return i}return null}isWaiting(){let e=this.stack.peek();return e?g.isAwaitable(e)?!e.isSettled():o.isCalledActionResult(e)&&e.wait?o.isStackModelsAwaiting(e.wait.type,e.wait.stackModels):!1:!1}serialize(e=!0){let t=r=>{if(o.isCalledActionResult(r)){let s=r.node?.action?.getId()??null,a=r.node?.action?.type??null;return r.wait?.stackModels?{type:"link",actionType:a,action:s,stacks:r.wait.stackModels.map(c=>c.serialize()),stackWaitType:r.wait.type}:{type:"action",actionType:a,action:s}}return null},n=this.stack.map(t).filter(function(r){return r!==null});if(e&&this.waitingAction){let r=t(this.waitingAction);r&&n.push(r)}let i={items:n};return this.loopConfig&&(i.loop={type:this.loopConfig.type,counter:this.loopConfig.counter,limit:this.loopConfig.limit,conditionActionId:this.loopConfig.conditionActionId,bodyActionIds:this.loopConfig.bodyActionIds,broken:this.loopConfig.broken}),i}reset(){this.stack.forEach(e=>{o.isCalledActionResult(e)?e.wait?.stackModels.forEach(t=>t.reset()):g.isAwaitable(e)&&e.abort()}),this.waitingAction&&this.waitingAction.wait?.stackModels.forEach(e=>e.reset()),this.waitingAction=null,this.stack.clear(),this.loopConfig=null,this.loopBodyActions=[],this.loopCondition=null,this.loopStartTime=0,this.loopDebugCheckpoint=0}deserialize(e,t){this.reset();let n=e.items;for(let i of n)if(i.type==="action"){if(!i.action)continue;let{actionType:r,action:s}=i,a=t.get(s);if(!a)throw new Error(`Action not found: ${s}`);this.stack.push({type:r,node:a.contentNode,wait:null})}else if(i.type==="link"){let{actionType:r,action:s,stacks:a,stackWaitType:c}=i;if(c==null)throw new Error(`Missing stackWaitType for link action: ${s}`);this.stack.push({type:r,node:s?t.get(s)?.contentNode??null:null,wait:{type:c,stackModels:a.map(l=>o.createStackModel(this.liveGame,l,t))}})}if(e.loop){let i=e.loop,r=[];for(let a of i.bodyActionIds){let c=t.get(a);if(!c)throw new Error(`Loop body action not found: ${a}`);r.push(c)}let s=null;if(i.type==="condition"&&i.conditionActionId){let a=t.get(i.conditionActionId);if(a){let c=a.contentNode.getContent();Array.isArray(c)&&c.length>=2&&R.isLambda(c[1])&&(s=c[1])}}this.loopConfig={type:i.type,counter:i.counter,limit:i.limit,conditionActionId:i.conditionActionId,bodyActionIds:i.bodyActionIds,broken:i.broken},this.loopBodyActions=r,this.loopCondition=s,this.loopStartTime=Date.now(),this.loopDebugCheckpoint=i.counter}return this}isEmpty(){return this.stack.isEmpty()}push(...e){return this.stack.push(...e),this}};var ht=class ht{constructor(e){this.events=new W;this.story=null;this.gameLock=new jt;this.currentSavedGame=null;this.gameState=void 0;this.stackModel=null;this.asyncStackModels=new Set;this.lastDialog=null;this.mapCache=null;this.game=e,this._storable=new fn,this.initNamespaces()}initNamespaces(){return this._storable.clear().addNamespace(new nt(ht.GameSpacesKey.game,ht.DefaultNamespaces.game)),this.story&&this.story.initPersistent(this._storable),this}getStorable(){return this._storable}get storable(){return this._storable}loadStory(e){return this.story=e.constructStory(),this}serialize(){this.assertGameState();let e=this.gameState,t=this.story;if(!t)throw new Error("No story loaded");if(!this.currentSavedGame||!this.stackModel)throw new Error("Failed when trying to serialize the game: The game has not started");let n=this._storable.toData(),i=e.toData(),r=t.getAllElementStates(),s=this.stackModel.serialize(),a=Array.from(this.asyncStackModels).map(c=>c.serialize());return{name:this.currentSavedGame.name,meta:{created:this.currentSavedGame.meta.created,updated:Date.now(),id:this.currentSavedGame.meta.id,lastSentence:this.lastDialog?.sentence||null,lastSpeaker:this.lastDialog?.speaker||null,storyHash:t.hash()},game:{store:n,stage:i,elementStates:r,stackModel:s,asyncStackModels:a,services:t.serializeServices()}}}deserialize(e){if(!e)throw new Error("No saved game provided when trying to deserialize game state");this.assertGameState();let t=this.gameState,n=this.story;if(!n)throw new Error("No story loaded");this.game.hooks.trigger("beforeRestore",[]),t.rollLock.lock(),this.reset(),t.stage.forceRemount();let{game:{store:i,stage:r,elementStates:s,services:a,stackModel:c,asyncStackModels:l}}=e,[u,m]=this.constructMaps();this._storable.clear().load(i),s.forEach(({id:p,data:h})=>{t.logger.debug("restore element",p);let d=m.get(p);if(!d)throw new Error("Element not found, id: "+p+`
34
- NarraLeaf cannot find the element with the id from the saved game`);d.reset(),d.fromData(h)}),this.currentSavedGame=e,t.loadData(r,m),this.stackModel.deserialize(c,u),l.forEach(p=>this.asyncStackModels.add(we.createStackModel(this,p,u))),this.asyncStackModels.forEach(p=>t.timelines.attachTimeline(p.execute())),n.deserializeServices(a),this.game.hooks.trigger("afterRestore",[]),t.events.once(w.EventTypes["event:state.onRender"],()=>{t.schedule(()=>{t.rollLock.unlock(),t.stage.next()},0)}),t.stage.forceUpdate()}getHistory(){return this.assertGameState(),this.gameState.gameHistory.getHistory()}undo(e){if(this.assertGameState(),!this.gameState.actionHistory.ableToUndo(this.gameState.gameHistory)){this.gameState.logger.warn("LiveGame.undo","No action to undo");return}let t=this.gameLock.register().lock();this.stackModel.abortStackTop();let n=e?this.gameState.actionHistory.undoUntil(e):this.gameState.actionHistory.undo(this.gameState.gameHistory);if(n){let[i]=this.constructMaps(),{rootStackSnapshot:r,stackModel:s}=n;n.action.type===Bt.say&&this.gameState.isNvlMode()&&this.gameState.suppressNextNvlTyping(),this.stackModel.deserialize(r,i),s===this.stackModel&&this.stackModel.push(we.fromAction(n.action)),this.gameLock.off(t.unlock()),this.gameState.logger.info("LiveGame.undo","Undo until",e,"action",n),this.gameState.stage.forceUpdate(),this.gameState.stage.next(),this.gameState.schedule(()=>{this.gameState&&this.gameState.forceAnimation()},0)}else this.gameState.logger.warn("LiveGame.undo","No action found"),this.gameLock.off(t.unlock())}dispose(){this.events.clear(),this.gameState?.dispose()}notify(e,t=3e3){this.assertGameState();let n=this.gameState.idManager.generateId(),i=this.gameState.notificationMgr.consume({id:n,message:e,duration:t}),r=g.toPromiseForce(i);return{cancel:()=>{i.abort()},promise:r}}playSound(e){this.assertGameState();let t=e instanceof URL?e.toString():e,n=typeof t=="string"?new Z({src:t}):t;return this.gameState.audioManager.playSoundToken(n)}skipDialog(){this.assertGameState(),this.gameState.events.emit(w.EventTypes["event:state.player.skip"],!0)}assertScreenshot(){this.assertGameState(),this.assertPlayerElement()}capturePng(){return this.assertScreenshot(),this.gameState.htmlToImage.toPng(this.gameState.mainContentNode,this.getScreenshotOptions())}captureJpeg(){return this.assertScreenshot(),this.gameState.htmlToImage.toJpeg(this.gameState.mainContentNode,this.getScreenshotOptions())}captureSvg(){return this.assertScreenshot(),this.gameState.htmlToImage.toSvg(this.gameState.mainContentNode,this.getScreenshotOptions())}capturePngBlob(){return this.assertScreenshot(),this.assertGameState(),this.assertPlayerElement(),this.gameState.htmlToImage.toBlob(this.gameState.mainContentNode,this.getScreenshotOptions())}onCharacterPrompt(e){return this.events.on(ht.EventTypes["event:character.prompt"],e)}onMenuChoose(e){return this.events.on(ht.EventTypes["event:menu.choose"],e)}newGame(){this.assertGameState();let e=this.gameState,t=e.logger.group("LiveGame (newGame)",!0);this.reset(),this.initNamespaces();let n=this.getNewSavedGame();n.name="NewGame-"+Date.now(),this.currentSavedGame=n;let i=this.story?.entryScene?.getSceneRoot();i?this.stackModel.push(we.fromAction(i)):e.logger.warn("No scene root found");let r=this.story?.getAllElementMap(this.story,this.story?.entryScene?.getSceneRoot()||[]);return r?r.forEach(s=>{e.logger.debug("reset element",s),s.reset()}):e.logger.warn("No elements found"),e.stage.forceUpdate(),e.stage.next(),t.end(),this}waitForRouterExit(){let e=null;return{promise:new Promise(t=>{e=this.game.router.onceExitComplete(()=>{t()})}),cancel:()=>{e&&e.cancel()}}}waitForPageMount(){let e=null;return{promise:new Promise(t=>{e=this.game.router.oncePageMount(()=>{t()})}),cancel:()=>{e&&e.cancel()}}}requestFullScreen(e){this.assertGameState();let t="LiveGame.requestFullScreen";try{let n=this.gameState.playerCurrent;if(!n){this.gameState.logger.warn(t,"No player element found");return}if(n.requestFullscreen)return n.requestFullscreen(e);this.gameState.logger.warn(t,"Fullscreen is not supported")}catch(n){this.gameState.logger.error(t,n)}}exitFullScreen(){this.assertGameState();let e="LiveGame.exitFullScreen";try{if(document.exitFullscreen)return document.exitFullscreen();this.gameState.logger.warn(e,"Fullscreen is not supported")}catch(t){this.gameState.logger.error(e,t)}}constructMaps(){let e=this.story;if(!e)throw new Error("No story loaded");if(this.mapCache)return this.mapCache;let t=new Map,n=new Map;return e.forEachChild(e,e.entryScene?.getSceneRoot()||[],i=>{t.set(i.getId(),i),n.set(i.callee.getId(),i.callee)},{allowFutureScene:!0}),this.mapCache=[t,n],this.mapCache}getScreenshotOptions(){return{quality:this.game.config.screenshotQuality}}onPlayerEvent(e,t,n){this.assertPlayerElement();let i=this.gameState.playerCurrent;return i?(i.addEventListener(e,t,n),{cancel:()=>i.removeEventListener(e,t,n)}):(this.gameState.logger.warn("LiveGame.onEvent","No player element found"),{cancel:()=>{}})}onWindowEvent(e,t,n){return window.addEventListener(e,t,n),{cancel:()=>window.removeEventListener(e,t,n)}}reset(){this.assertGameState();let e=this.gameState;this.resetStackModels(),this.stackModel.reset(),this.currentSavedGame=null,this.lastDialog=null,e.forceReset()}next(){this.assertGameState();let e=this.gameState;if(this.gameLock.isLocked())return this.gameLock;if(!this.story)throw new Error("No story loaded");return this.stackModel.isEmpty()?(e.logger.weakWarn("Game Actions","Action stack is empty"),this.currentSavedGame?e.events.emit("event:state.end"):this.currentSavedGame=null,null):this.stackModel.rollNext()}setLastDialog(e,t){this.lastDialog={sentence:e,speaker:t}}requestAsyncStackModel(e){this.assertGameState();let t=new we(this);return this.asyncStackModels.add(t),t.push(...e),t}createStackModel(e){let t=new we(this);return t.push(...e),t}resetStackModels(){this.asyncStackModels.forEach(e=>e.reset()),this.asyncStackModels.clear()}isPlaying(){return this.stackModel&&!this.stackModel.isEmpty()}executeAction(e,t,n){if(!this.stackModel)throw new Error("Stack model is not initialized");let i=t.executeAction(e,n);return g.isAwaitable(i)?i:i||null}setGameState(e){if(e&&this.gameState)throw new xe("GameState already set");return this.gameState=e,e&&!this.stackModel&&(this.stackModel=new we(this,"$root")),this}getGameState(){return this.gameState}getGameStateForce(){if(!this.gameState)throw new xe("GameState not set");return this.gameState}getAllPredictableActions(e,t,n){let i=t?.contentNode||null,r=[],s=[],a=new Set;for(;(i||s.length)&&!(n&&r.length>=n);){if(i||(i=s.pop().contentNode),[tt].some(c=>i?.action&&i.action instanceof c)){i=null;continue}if(i.action&&i.action.is(O,H.jumpTo)){let[c]=i.action.contentNode.getContent(),l=e.getScene(c);if(!l)throw i.action._sceneNotFoundError(i.action.getSceneName(c));if(a.has(l)){i=null;continue}a.add(l),i=l.getSceneRoot()?.contentNode||null;continue}else if(i.action&&i.action.is(_,pe.do)){let[c]=i.action.contentNode.getContent();i.getChild()?.action&&s.push(i.getChild().action),i=c[0]?.contentNode||null}i.action&&r.push(i.action),i=i.getChild()}return r}clearMainStack(){if(!this.stackModel)throw new xe("No stack model found");return this.stackModel.reset(),this}getStackModelForce(){if(!this.stackModel)throw new xe("No stack model found");return this.stackModel}getNewSavedGame(){return{name:"",meta:{created:Date.now(),updated:Date.now(),id:or(),lastSentence:null,lastSpeaker:null,storyHash:this.story?.hash()||""},game:{store:{},stage:{scenes:[],audio:{sounds:[],groups:[]},videos:[]},elementStates:[],services:{},stackModel:{items:[]},asyncStackModels:[]}}}assertGameState(){if(!this.gameState)throw new b("No game state found, make sure you call this method in effect hooks or event handlers")}assertPlayerElement(){if(this.assertGameState(),!this.gameState.playerCurrent)throw new b("Player Element Not Mounted")}};ht.DefaultNamespaces={game:{}},ht.GameSpacesKey={game:"game"},ht.EventTypes={"event:character.prompt":"event:character.prompt","event:menu.choose":"event:menu.choose"};var rt=ht;var bn=class bn{constructor(e){this.settings=e;this.events=new W;this.events.setMaxListeners(64)}setPreference(e,t){this.settings[e]=t,this.events.emit(bn.EventTypes["event:game.preference.change"],e,t)}getPreference(e){return this.settings[e]}getPreferences(){return this.settings}onPreferenceChange(e,t){return this.events.on(bn.EventTypes["event:game.preference.change"],(n,i)=>{typeof e=="string"?e===n&&t&&t(i):e(n,i)})}importPreferences(e){for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&this.setPreference(t,e[t])}exportPreferences(){let e={};for(let t in this.settings)Object.prototype.hasOwnProperty.call(this.settings,t)&&(e[t]=this.settings[t]);return e}togglePreference(e){if(typeof this.settings[e]!="boolean")throw new Error(`Preference ${e} is not a boolean`);this.setPreference(e,!this.getPreference(e))}};bn.EventTypes={"event:game.preference.change":"event:game.preference.change"};var Cn=bn;import"client-only";import Yr,{useEffect as Cc,useRef as Ao}from"react";import"client-only";import yr,{useContext as Qs,useState as Xs}from"react";var Sr=yr.createContext(null);function vr({children:o,game:e}){"use client";let t=new B({}),[n]=Xs(e||t);return yr.createElement(Sr,{value:n},o)}function C(){let o=Qs(Sr);if(!o)throw new Error("useGame must be used within a GameProvider");return o}import Ys,{createContext as Js,useContext as Tr}from"react";var br="/",fi=class fi{constructor(e,t=fi.rootPath){this.events=new W;this.currentPath="";this.currentQuery={};this.history=[];this.historyIndex=-1;this.mountedPaths=new Set;this.defaultHandlerPaths=new Set;this.unmountingPaths=new Set;this.updateSyncHooks=new Set;this.transitioning=!1;this.game=e;let{path:n,query:i}=this.parseUrl(t);this.currentPath=n,this.currentQuery=i,this.history.push(t),this.historyIndex=0}getCurrentPath(){return this.currentPath}getPathname(){return this.currentPath}getCurrentQuery(){return{...this.currentQuery}}getQueryParams(){return this.getCurrentQuery()}getCurrentUrl(){return this.buildUrl(this.currentPath,this.currentQuery)}parseUrl(e){let[t,n]=e.split("?"),i={};if(n){let r=n.split("&");for(let s of r){let[a,c]=s.split("=");a&&(i[decodeURIComponent(a)]=c?decodeURIComponent(c):"")}}return{path:t||"/",query:i}}buildUrl(e,t){if(Object.keys(t).length===0)return e;let n=Object.entries(t).map(([i,r])=>`${encodeURIComponent(i)}=${encodeURIComponent(r)}`).join("&");return`${e}?${n}`}getQueryParam(e){return this.currentQuery[e]}setQueryParam(e,t){return this.currentQuery[e]=t,this.updateHistory(),this.emitOnChange(),this}setQueryParams(e){return Object.assign(this.currentQuery,e),this.updateHistory(),this.emitOnChange(),this}removeQueryParam(e){return delete this.currentQuery[e],this.updateHistory(),this.emitOnChange(),this}clearQueryParams(){return this.currentQuery={},this.updateHistory(),this.emitOnChange(),this}hasQueryParam(e){return e in this.currentQuery}getQueryParamKeys(){return Object.keys(this.currentQuery)}getQueryParamCount(){return Object.keys(this.currentQuery).length}getHistory(){return[...this.history]}getHistoryIndex(){return this.historyIndex}canGoBack(){return this.historyIndex>0}canGoForward(){return this.historyIndex<this.history.length-1}navigate(e,t){let{path:n,query:i}=this.parseUrl(e),r=this.resolvePath(n),s={...i,...t};if(this.currentPath===r)return this.currentQuery=s,this.historyIndex>=0&&(this.history[this.historyIndex]=this.buildUrl(r,s)),this.emitOnChange(),this;this.historyIndex<this.history.length-1&&(this.history.length=this.historyIndex+1);let a=this.buildUrl(r,s);return this.history.push(a),this.history.length>this.game.config.maxRouterHistory&&(this.history.shift(),this.historyIndex--),this.historyIndex++,this.currentPath=r,this.currentQuery=s,this.emitOnChange(),this.requestPageTransition(),this}back(){if(this.canGoBack()){this.historyIndex--;let{path:e,query:t}=this.parseUrl(this.history[this.historyIndex]);this.currentPath=e,this.currentQuery=t,this.emitOnChange(),this.requestPageTransition()}return this}forward(){if(this.canGoForward()){this.historyIndex++;let{path:e,query:t}=this.parseUrl(this.history[this.historyIndex]);this.currentPath=e,this.currentQuery=t,this.emitOnChange(),this.requestPageTransition()}return this}replace(e,t){let{path:n,query:i}=this.parseUrl(e),r=this.resolvePath(n),s={...i,...t};return this.currentPath=r,this.currentQuery=s,this.historyIndex>=0?this.history[this.historyIndex]=this.buildUrl(r,s):(this.history.push(this.buildUrl(r,s)),this.historyIndex=0),this.emitOnChange(),this}clear(){return this.currentPath="",this.currentQuery={},this.history=[],this.historyIndex=-1,this.emitOnChange(),this.requestPageTransition(),this}cleanHistory(){return this.history=this.currentPath?[this.buildUrl(this.currentPath,this.currentQuery)]:[],this.historyIndex=this.currentPath?0:-1,this}parsePath(e){return e.split("/").filter(t=>t.length>0)}buildPath(e){return"/"+e.join("/")}getParentPath(e){let t=this.parsePath(e);return t.length<=1?"":this.buildPath(t.slice(0,-1))}matchPath(e,t){let n=this.parsePath(e),i=this.parsePath(t);if(n.length<i.length)return!1;for(let r=0;r<i.length;r++){let s=n[r],a=i[r];if(a!=="*"){if(a.startsWith(":"))continue;if(s!==a)return!1}}return!0}exactMatch(e,t){let n=this.parsePath(e),i=this.parsePath(t);if(n.length!==i.length)return!1;for(let r=0;r<i.length;r++){let s=n[r],a=i[r];if(a!=="*"){if(a.startsWith(":"))continue;if(s!==a)return!1}}return!0}extractParams(e,t){let n={},i=this.parsePath(e),r=this.parsePath(t);if(i.length!==r.length)return n;for(let s=0;s<r.length;s++){let a=r[s];if(a.startsWith(":")){let c=a.slice(1);n[c]=i[s]}}return n}onExitComplete(e){return this.events.on("event:router.onExitComplete",e)}onceExitComplete(e){return this.events.once("event:router.onExitComplete",e)}onPageMount(e){return this.events.on("event:router.onPageMount",e)}oncePageMount(e){return this.events.once("event:router.onPageMount",e)}onUpdate(e){return this.updateSyncHooks.add(e),{cancel:()=>{this.updateSyncHooks.delete(e)}}}emitUpdateSync(){this.updateSyncHooks.forEach(e=>e())}mount(e){if(this.mountedPaths.has(e))throw new b(`Path ${e} is already mounted. This may be caused by multiple capture segments in the same path.`);return this.mountedPaths.add(e),{cancel:()=>{this.unmount(e)}}}unmount(e){this.mountedPaths.delete(e)}mountDefaultHandler(e){if(this.defaultHandlerPaths.has(e))throw new b(`Default handler path ${e} is already mounted.`);return this.defaultHandlerPaths.add(e),{cancel:()=>{this.unmountDefaultHandler(e)}}}unmountDefaultHandler(e){this.defaultHandlerPaths.delete(e)}emitOnPageMount(){this.events.emit("event:router.onPageMount")}onRootExitComplete(e){return this.events.on("event:router.onExitComplete",e)}isActive(){return this.currentPath!==""}onChange(e){return this.events.on("event:router.onChange",e)}emitOnChange(){this.events.emit("event:router.onChange")}resolvePath(e){let t=e.split("?")[0];if(t.startsWith("/"))return t;if(t==="")return this.currentPath;let n=this.parsePath(this.currentPath),i=t.split("/"),r=[];r.push(...n);for(let s=0;s<i.length;s++){let a=i[s];a===""||a==="."||(a===".."?r.length>0&&r.pop():r.push(a))}return this.buildPath(r)}normalizePath(e){let t=e.replace(/\/\/+/g,"/").replace(/\/$/,"");return t===""?"/":(t.startsWith("/"),t)}joinPath(e,...t){let n=this.normalizePath(e),s=[n.startsWith("/")?n:"/"+n,...t.filter(a=>a.length>0)].join("/");return this.normalizePath(s)}updateHistory(){this.historyIndex>=0&&(this.history[this.historyIndex]=this.buildUrl(this.currentPath,this.currentQuery))}requestPageTransition(){let e=()=>{this.transitioning=!0,this.emitUpdateSync(),this.emitOnChange()},t=()=>{this.events.emit("event:router.onTransitionEnd"),this.transitioning=!1,this.emitUpdateSync(),this.emitOnChange(),this.events.emit("event:router.onExitComplete")};if(e(),this.isPathsUnmounting()){let n=this.events.on("event:router.onPathUnmount",()=>{this.isPathsUnmounting()||(n.cancel(),ze(()=>{t()}))})}else ze(()=>{t()})}registerUnmountingPath(e){this.unmountingPaths.add(e)}isPathsUnmounting(){return this.unmountingPaths.size>0}unregisterUnmountingPath(e){this.unmountingPaths.delete(e),this.events.emit("event:router.onPathUnmount")}isTransitioning(){return this.transitioning}createToken(e){return Symbol(e)}};fi.rootPath=br;var Et=fi,io=Js(null);function Cr({children:o}){let e=C();return Ys.createElement(io,{value:{router:e.router}},o)}function at(){if(!Tr(io))throw new Error("useRouter must be used within a RouterProvider");return Tr(io).router}import xr from"react";import oa from"clsx";import Zs,{createContext as _s,useContext as ea,useLayoutEffect as ta,useReducer as na,useState as ia}from"react";var gt=class gt{constructor(){this.state={width:0,height:0,minWidth:800,minHeight:450,paused:!1,scale:0};this.events=new W().setMaxListeners(1/0);this.lockers=[];this.updater=null}update(e,t,n){this.state.width=e,this.state.height=t,this.state.scale=n,this.events.emit(gt.EventTypes["event:aspectRatio.update"],e,t)}updateMin(e,t){this.state.minWidth=e,this.state.minHeight=t}lock(){let e=Symbol();return this.lockers.push(e),e}unlock(e){if(e&&!this.lockers.includes(e))throw new Error("Locker not found");return this.lockers=this.lockers.filter(t=>t!==e),this.triggerUpdate(),null}isLocked(){return!!this.lockers.length}getStyle(){return{width:`${this.state.width}px`,height:`${this.state.height}px`}}setUpdate(e){this.updater=e}pause(){this.state.paused=!0,this.events.emit(gt.EventTypes["event:aspectRatio.pause"])}resume(){this.state.paused=!1,this.events.emit(gt.EventTypes["event:aspectRatio.resume"])}onUpdate(e){return this.events.on(gt.EventTypes["event:aspectRatio.update"],e).cancel}requestUpdate(){this.events.emit(gt.EventTypes["event:aspectRatio.requestUpdate"])}onRequestedUpdate(e){return this.events.on(gt.EventTypes["event:aspectRatio.requestUpdate"],e).cancel}triggerUpdate(){this.updater&&this.updater()}};gt.EventTypes={"event:aspectRatio.update":"event:aspectRatio.update","event:aspectRatio.pause":"event:aspectRatio.pause","event:aspectRatio.resume":"event:aspectRatio.resume","event:aspectRatio.requestUpdate":"event:aspectRatio.requestUpdate"};var oo=gt,ro=_s(null);function Ar({children:o}){"use client";let[e]=ia(()=>new oo);return Zs.createElement(ro,{value:{ratio:e}},o)}function se(){let o=ea(ro),[,e]=na(n=>n+1,0);if(!ro||!o)throw new Error("useRatio must be used within a RatioProvider");let{ratio:t}=o;return ta(()=>(e(),t.onUpdate(()=>{e()})),[t]),o}function ct({children:o,className:e,style:t,ref:n,...i}){let{ratio:r}=se(),s=r.getStyle();return xr.createElement("div",{className:oa("inset-0",e),style:{width:"100%",height:"100%",minWidth:`${r.state.minWidth}px`,minHeight:`${r.state.minHeight}px`},...i},xr.createElement("div",{style:{...s,position:"relative",...t||{}},...i||{},ref:n},o))}import ra,{useEffect as sa}from"react";function Je(o){let e=C(),[t,n]=ra.useState(e.preference.getPreference(o)),i=r=>{e.preference.setPreference(o,r),n(r)};return sa(()=>e.preference.onPreferenceChange(o,n).cancel,[o,e.preference,n]),[t,i]}import so from"react";import hi from"react";import wr from"clsx";function gi({children:o,className:e,style:t,...n}){let{ratio:i}=se(),r=C();return hi.createElement(ct,{className:wr("absolute pointer-events-none w-full h-full"),style:{transform:`scale(${i.state.scale})`,transformOrigin:"left top",width:r.config.width,height:r.config.height,pointerEvents:"none"},"data-element-type":"full",...n},hi.createElement("div",{className:"absolute inset-0 w-full h-full"},hi.createElement("div",{className:"inset-0 w-full h-full"},hi.createElement("div",{className:wr("pointer-events-auto-rest",e),style:t},o))))}function aa({children:o,className:e,style:t}){return so.createElement(so.Fragment,null,so.createElement(gi,{style:t,className:e,"data-element-type":"stage","data-code-source":"Stage.tsx"},o))}import kr from"clsx";import Er from"react";function yi({className:o,children:e,...t}){let{ratio:n}=se();return Er.createElement("div",{style:{transform:`scale(${n.state.scale})`,transformOrigin:"left top"},className:kr("w-full h-full")},Er.createElement("div",{className:kr("z-20",o),...t},e))}import qe,{useState as Pr}from"react";import{motion as ca}from"motion/react";function Si({children:o,border:e="solid",color:t="red",tag:n,borderWidth:i=1,as:r="div",ref:s,...a}){let c=C(),[l,u]=Pr(!1);if(!c.config.app.inspector)return qe.createElement(r,{...a,ref:s},o);let m={...a,onMouseEnter:()=>u(!0),onMouseLeave:()=>u(!1),style:{...a.style||{},outline:`${i}px ${e} ${t}`,zIndex:l?1e3:"auto"}};return qe.createElement(r,{...m,ref:s},n&&l&&qe.createElement("span",{className:"absolute top-0 left-0 bg-white text-black border-2 border-black text-sm"},n),o)}function la({border:o="solid",color:e="red",tag:t,borderWidth:n=1,as:i="img",...r}){let s=C(),[a,c]=Pr(!1);if(!s.config.app.inspector)return qe.createElement(i,{...r});let l={...r,onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),style:{...r.style||{},outline:`${o} ${n}px ${e}`,zIndex:a?1e3:"auto"}};return qe.createElement("div",null,qe.createElement(i,{...l}),t&&a&&qe.createElement("span",{className:"absolute top-0 left-0 bg-white text-black border-2 border-black"},t))}function ua(o){return qe.createElement(Si,{...o,as:"div"})}function pa(o){return qe.createElement(Si,{...o,as:"span"})}function da(o){return qe.createElement(la,{...o,as:"img"})}function ma(o){return qe.createElement(Si,{...o,as:"button"})}function fa(o){return qe.createElement(Si,{...o,as:ca.div,ref:o.ref,layout:o.layout})}var ha={Div:ua,Span:pa,Button:ma,Img:da,mDiv:fa},Ft=ha;import Ir from"clsx";import lt,{useEffect as ao,useRef as Aa,useState as xa}from"react";import{useEffect as ga,useState as ya}from"react";function $(o){let[e,t]=ya(0);ga(()=>{n()},o??[]);function n(){t(i=>i+1)}return[n,e]}import Dr from"react";var Kt=Dr.createContext(null);function yt(){let o=Dr.useContext(Kt);if(!o)throw new Error("useDialogContext must be used within a DialogContext");return o}import vi,{useLayoutEffect as Lr,useMemo as Sa,useState as va}from"react";var Ze=class Ze{constructor(e){this.events=new W;this._forceSkipped=!1;this._idle=!1;this.config=e,this._state="pending",this.autoForwardScheduler=new Wn,this._count=0}get state(){return this._state}get deps(){return[this._count]}isIdle(){return this._idle}setIdle(e){this._idle=e}requestComplete(){this.state==="ended"?this.safeEmit(Ze.Events.complete):this.safeEmit(Ze.Events.requestComplete)}forceSkip(){this.state==="ended"?this.emitComplete():(this._forceSkipped=!0,this.safeEmit(Ze.Events.forceSkip))}dispatchComplete(){if(this.state==="ended"){this.config.gameState.logger.weakWarn("DialogState","Dialog is already ended. Cannot dispatch complete.");return}if(!this.events.hasListeners(Ze.Events.complete)){this.config.gameState.logger.weakWarn("DialogState","No listener for complete event. Cannot dispatch complete.");return}let e=this.config.gameState.game.preference;return this._state="ended",e.getPreference(B.Preferences.autoForward)&&this.scheduleAutoForward(),this.emitComplete(),this}emitComplete(){return this.safeEmit(Ze.Events.complete),this.emitFlush(),this}isEnded(){return this.state==="ended"}setPause(e){this.isEnded()||(e?this._state="paused":this._state="pending")}isForceSkipped(){return this._forceSkipped}tryScheduleAutoForward(){this.isEnded()&&this.scheduleAutoForward()}cancelAutoForward(){this.autoForwardScheduler.cancelTask()}emitFlush(){return this._count++,this.events.emit(Ze.Events.onFlush),this}onFlush(e){return this.events.on(Ze.Events.onFlush,e)}safeEmit(e,...t){return this.events.emit(e,...t)===0&&this.config.gameState.logger.weakWarn("DialogState",`Failed to emit event: ${e}. Target Component is not mounted.`),this}scheduleAutoForward(){let e=this.config.gameState.game.preference;!e.getPreference(B.Preferences.autoForward)||this.state!=="ended"||this.autoForwardScheduler.cancelTask().scheduleTask(()=>{this.events.emit(Ze.Events.simulateClick)},this.config.gameState.game.config.autoForwardDelay/e.getPreference(B.Preferences.gameSpeed))}};Ze.Events={requestComplete:"event:dialog.requestComplete",complete:"event:dialog.complete",forceSkip:"event:dialog.forceSkip",onFlush:"event:dialog.onFlush",simulateClick:"event:dialog.simulateClick"};var le=Ze;function An({action:o,onFinished:e,useTypeEffect:t=!0,gameState:n}){let i=Sa(()=>o.sentence?.evaluate(re.getCtx({gameState:n})),[o.sentence,n]),[r]=va(()=>new le({useTypeEffect:t,action:o,evaluatedWords:i||[],gameState:n})),s=n.game.config.dialog;return Lr(()=>(n.logger.debug("NarraLeaf-React: Say","dialogState",r),r.events.on(le.Events.complete,a=>{n.logger.log("NarraLeaf-React: Say","Complete",r.isIdle()),r.isIdle()||a?e?.(!1):r.setIdle(!0)}).cancel),[r]),Lr(()=>n.events.on(w.EventTypes["event:state.player.skip"],a=>{a?(r.setIdle(!0),r.forceSkip()):r.isIdle()?e?.(!0):r.forceSkip()}).cancel,[r]),vi.createElement(vi.Fragment,null,vi.createElement(Kt,{value:r,key:o.id},vi.createElement(s,null)))}import{useEffect as Ti,useState as Ca}from"react";import{useEffect as Ta,useState as ba}from"react";function Vt(o){let e=C(),[t,n]=ba(e.keyMap.getKeyBinding(o)),i=r=>{e.keyMap.setKeyBinding(o,r),n(r)};return Ta(()=>e.keyMap.onKeyBindingChange(o,n).cancel,[o,e.keyMap,n]),[t,i]}var tn=(t=>(t.skipAction="skipAction",t.nextAction="nextAction",t))(tn||{});function bi({entry:o,gameState:e,words:t,isActive:n,useTypeEffect:i}){let r=C(),[s]=Vt("nextAction"),[a]=Ca(()=>new le({useTypeEffect:i,action:{sentence:o.sentence,character:o.character,words:t,id:o.id},evaluatedWords:t,gameState:e}));return Ti(()=>{if(!n)return;let c=()=>{e.requestNvlAdvance(o.id)==="typing"&&a.requestComplete()},l=()=>{e.requestNvlSkip(o.id)==="typing"&&a.forceSkip()},u=e.events.on(w.EventTypes["event:state.player.stageClick"],c),m=e.events.on(w.EventTypes["event:state.player.skip"],l);return()=>{u.cancel(),m.cancel()}},[a,o.id,e,n]),Ti(()=>{if(!n)return;let c=u=>{if(!r.keyMap.match("nextAction",u.key))return;e.requestNvlAdvance(o.id)==="typing"&&a.requestComplete()};if(r.config.useWindowListener){let u=r.getLiveGame().onWindowEvent("keyup",c);return()=>{u.cancel()}}let l=r.getLiveGame().onPlayerEvent("keyup",c);return()=>{l.cancel()}},[a,o.id,r,e,n,s]),Ti(()=>{let c=a.events.on(le.Events.complete,l=>{n&&(e.completeNvlTyping(o.id),!a.isIdle()&&!l&&a.setIdle(!0))});return()=>{c.cancel()}},[a,o.id,e,n]),Ti(()=>{let c=a.events.on(le.Events.simulateClick,()=>{if(!n)return;e.requestNvlAdvance(o.id)==="typing"&&a.requestComplete()});return()=>{c.cancel()}},[a,n]),a}function*Rr(o){let e=[...o];for(let t=0;t<e.length;t++){let n=e[t];if(Pe.isPause(n.text)){yield Pe.from(n.text);continue}for(let i=0;i<n.text.length;i++){let r=n.text[i];r===`
33
+ Loop type: ${this.loopConfig.type}, broken: ${this.loopConfig.broken}`);throw this.liveGame.getGameStateForce().logger.error("StackModel",i.message),i}this.loopDebugCheckpoint=e,this.loopStartTime=Date.now()}}breakLoop(){if(!this.loopConfig)throw new x("Cannot break: StackModel is not a loop");this.loopConfig.broken=!0,this.stack.clear()}isLoop(){return this.loopConfig!==null}rollNext(){if(this.stack.isEmpty())return null;let e=this.stack.peek();if(y.isAwaitable(e)&&!e.isSettled())return e;if(o.isCalledActionResult(e)&&e.wait){let n=e.wait.stackModels;if(!n.length)throw new Error("StackModel: Waiting action contains empty stackModels.");if(o.isStackModelsAwaiting(e.wait.type,n))return n.forEach(i=>i.rollNext()),e}this.waitingAction=null;let t=this.stack.pop();if(y.isAwaitable(t)){if(t.isFailed())throw t.error;let n=t.result;if(n)return this.stack.push(n),this.liveGame.getGameStateForce().logger.debug("next action (resolved awaitable)",n.node?.action),n}else return this.waitingAction=t,this.executeActions(t);return null}execute(){let e=null,t=!1,n=new y().registerSkipController(new G(()=>{t=!0,e?.abort()}));return(async()=>{let r=0;for(;!t;){if(r++>this.liveGame.game.config.maxStackModelLoop)throw new Error("StackModel: Suspiciously long waiting loop.");if(this.stack.isEmpty()){if(this.loopConfig&&!this.loopConfig.broken&&(this.onIterationComplete(),!this.stack.isEmpty()))continue;t=!0;break}let s=this.rollNext();if(s){if(y.isAwaitable(s)){if(s.isFailed())throw s.error;if(s.isSettled())continue;e=s,await s}else if(o.isCalledActionResult(s))if(s.wait)e=o.executeStackModelGroup(s.wait.type,s.wait.stackModels),await e;else continue}}})().then(()=>n.resolve()).catch(r=>n.fail(r)),n}abortStackTop(){if(this.stack.isEmpty())return null;let e=this.stack.peek();return e&&y.isAwaitable(e)?(this.stack.pop().abort(),this.waitingAction=null):o.isCalledActionResult(e)&&e.wait&&(e.wait.stackModels.forEach(t=>t.abortStackTop()),this.waitingAction=null),this.waitingAction}getTopSync(){if(this.stack.isEmpty())return null;let e=!1;for(let t=this.stack.size()-1;t>=0;t--){let n=this.stack.get(t);if(n){if(o.isCalledActionResult(n))return n;if(e)throw new Le("StackModel: Unexpected non-CalledActionResult in stack.")}else return null;e=!0}return null}executeActions(e){if(!e.node?.action)return null;let t=this.liveGame.executeAction(this.liveGame.getGameStateForce(),e.node.action,{stackModel:this}),n=i=>i?y.isAwaitable(i)?(this.liveGame.getGameStateForce().logger.debug("next action (executed awaitable)",i),this.stack.push(i),i):i.node?.action?(this.liveGame.getGameStateForce().logger.debug("next action (executed)",i),this.stack.push(i),i):null:null;if(Array.isArray(t)){let i=null;for(let r of t){let s=n(r);s&&(i=s)}return i}else{let i=n(t);if(i)return i}return null}isWaiting(){let e=this.stack.peek();return e?y.isAwaitable(e)?!e.isSettled():o.isCalledActionResult(e)&&e.wait?o.isStackModelsAwaiting(e.wait.type,e.wait.stackModels):!1:!1}serialize(e=!0){let t=r=>{if(o.isCalledActionResult(r)){let s=r.node?.action?.getId()??null,a=r.node?.action?.type??null;return r.wait?.stackModels?{type:"link",actionType:a,action:s,stacks:r.wait.stackModels.map(c=>c.serialize()),stackWaitType:r.wait.type}:{type:"action",actionType:a,action:s}}return null},n=this.stack.map(t).filter(function(r){return r!==null});if(e&&this.waitingAction){let r=t(this.waitingAction);r&&n.push(r)}let i={items:n};return this.loopConfig&&(i.loop={type:this.loopConfig.type,counter:this.loopConfig.counter,limit:this.loopConfig.limit,conditionActionId:this.loopConfig.conditionActionId,bodyActionIds:this.loopConfig.bodyActionIds,broken:this.loopConfig.broken}),i}reset(){this.stack.forEach(e=>{o.isCalledActionResult(e)?e.wait?.stackModels.forEach(t=>t.reset()):y.isAwaitable(e)&&e.abort()}),this.waitingAction&&this.waitingAction.wait?.stackModels.forEach(e=>e.reset()),this.waitingAction=null,this.stack.clear(),this.loopConfig=null,this.loopBodyActions=[],this.loopCondition=null,this.loopStartTime=0,this.loopDebugCheckpoint=0}deserialize(e,t){this.reset();let n=e.items;for(let i of n)if(i.type==="action"){if(!i.action)continue;let{actionType:r,action:s}=i,a=t.get(s);if(!a)throw new Error(`Action not found: ${s}`);this.stack.push({type:r,node:a.contentNode,wait:null})}else if(i.type==="link"){let{actionType:r,action:s,stacks:a,stackWaitType:c}=i;if(c==null)throw new Error(`Missing stackWaitType for link action: ${s}`);this.stack.push({type:r,node:s?t.get(s)?.contentNode??null:null,wait:{type:c,stackModels:a.map(l=>o.createStackModel(this.liveGame,l,t))}})}if(e.loop){let i=e.loop,r=[];for(let a of i.bodyActionIds){let c=t.get(a);if(!c)throw new Error(`Loop body action not found: ${a}`);r.push(c)}let s=null;if(i.type==="condition"&&i.conditionActionId){let a=t.get(i.conditionActionId);if(a){let c=a.contentNode.getContent();Array.isArray(c)&&c.length>=2&&F.isLambda(c[1])&&(s=c[1])}}this.loopConfig={type:i.type,counter:i.counter,limit:i.limit,conditionActionId:i.conditionActionId,bodyActionIds:i.bodyActionIds,broken:i.broken},this.loopBodyActions=r,this.loopCondition=s,this.loopStartTime=Date.now(),this.loopDebugCheckpoint=i.counter}return this}isEmpty(){return this.stack.isEmpty()}push(...e){return this.stack.push(...e),this}};var bt=class bt{constructor(e){this.events=new J;this.story=null;this.gameLock=new _t;this.currentSavedGame=null;this.gameState=void 0;this.stackModel=null;this.asyncStackModels=new Set;this.lastDialog=null;this.mapCache=null;this.game=e,this._storable=new An,this.initNamespaces()}initNamespaces(){return this._storable.clear().addNamespace(new st(bt.GameSpacesKey.game,bt.DefaultNamespaces.game)),this.story&&this.story.initPersistent(this._storable),this}getStorable(){return this._storable}get storable(){return this._storable}loadStory(e){return this.story=e.constructStory(),this}serialize(){this.assertGameState();let e=this.gameState,t=this.story;if(!t)throw new Error("No story loaded");if(!this.currentSavedGame||!this.stackModel)throw new Error("Failed when trying to serialize the game: The game has not started");let n=this._storable.toData(),i=e.toData(),r=t.getAllElementStates(),s=this.stackModel.serialize(),a=Array.from(this.asyncStackModels).map(c=>c.serialize());return{name:this.currentSavedGame.name,meta:{created:this.currentSavedGame.meta.created,updated:Date.now(),id:this.currentSavedGame.meta.id,lastSentence:this.lastDialog?.sentence||null,lastSpeaker:this.lastDialog?.speaker||null,storyHash:t.hash()},game:{store:n,stage:i,elementStates:r,stackModel:s,asyncStackModels:a,services:t.serializeServices()}}}deserialize(e){if(!e)throw new Error("No saved game provided when trying to deserialize game state");this.assertGameState();let t=this.gameState,n=this.story;if(!n)throw new Error("No story loaded");this.game.hooks.trigger("beforeRestore",[]),t.rollLock.lock(),this.reset(),t.stage.forceRemount();let{game:{store:i,stage:r,elementStates:s,services:a,stackModel:c,asyncStackModels:l}}=e,[p,u]=this.constructMaps();this._storable.clear().load(i),s.forEach(({id:d,data:h})=>{t.logger.debug("restore element",d);let m=u.get(d);if(!m)throw new Error("Element not found, id: "+d+`
34
+ NarraLeaf cannot find the element with the id from the saved game`);m.reset(),m.fromData(h)}),this.currentSavedGame=e,t.loadData(r,u),this.stackModel.deserialize(c,p),l.forEach(d=>{let h=Ie.createStackModel(this,d,p);this.asyncStackModels.add(h),t.timelines.attachTimeline(this.executeAsyncStackModel(h))}),n.deserializeServices(a),this.game.hooks.trigger("afterRestore",[]),t.events.once(k.EventTypes["event:state.onRender"],()=>{t.schedule(()=>{t.rollLock.unlock(),t.stage.next()},0)}),t.stage.forceUpdate()}getHistory(){return this.assertGameState(),this.gameState.gameHistory.getHistory()}undo(e){if(this.assertGameState(),!this.gameState.actionHistory.ableToUndo(this.gameState.gameHistory)){this.gameState.logger.warn("LiveGame.undo","No action to undo");return}let t=this.gameLock.register().lock();this.stackModel.abortStackTop();let n=e?this.gameState.actionHistory.undoUntil(e):this.gameState.actionHistory.undo(this.gameState.gameHistory);if(n){let[i]=this.constructMaps(),{rootStackSnapshot:r,stackModel:s}=n;n.action.type===Jt.say&&this.gameState.isNvlMode()&&this.gameState.suppressNextNvlTyping(),this.stackModel.deserialize(r,i),s===this.stackModel&&this.stackModel.push(Ie.fromAction(n.action)),this.gameLock.off(t.unlock()),this.gameState.logger.info("LiveGame.undo","Undo until",e,"action",n),this.gameState.stage.forceUpdate(),this.gameState.stage.next(),this.gameState.schedule(()=>{this.gameState&&this.gameState.forceAnimation()},0)}else this.gameState.logger.warn("LiveGame.undo","No action found"),this.gameLock.off(t.unlock())}dispose(){this.events.clear(),this.gameState?.dispose()}notify(e,t=3e3){this.assertGameState();let n=this.gameState.idManager.generateId(),i=this.gameState.notificationMgr.consume({id:n,message:e,duration:t}),r=y.toPromiseForce(i);return{cancel:()=>{i.abort()},promise:r}}playSound(e){this.assertGameState();let t=e instanceof URL?e.toString():e,n=typeof t=="string"?new re({src:t}):t;return this.gameState.audioManager.playSoundToken(n)}skipDialog(){this.assertGameState(),this.gameState.events.emit(k.EventTypes["event:state.player.skip"],!0)}assertScreenshot(){this.assertGameState(),this.assertPlayerElement()}capturePng(){return this.assertScreenshot(),this.gameState.htmlToImage.toPng(this.gameState.mainContentNode,this.getScreenshotOptions())}captureJpeg(){return this.assertScreenshot(),this.gameState.htmlToImage.toJpeg(this.gameState.mainContentNode,this.getScreenshotOptions())}captureSvg(){return this.assertScreenshot(),this.gameState.htmlToImage.toSvg(this.gameState.mainContentNode,this.getScreenshotOptions())}capturePngBlob(){return this.assertScreenshot(),this.assertGameState(),this.assertPlayerElement(),this.gameState.htmlToImage.toBlob(this.gameState.mainContentNode,this.getScreenshotOptions())}onCharacterPrompt(e){return this.events.on(bt.EventTypes["event:character.prompt"],e)}onMenuChoose(e){return this.events.on(bt.EventTypes["event:menu.choose"],e)}newGame(){this.assertGameState();let e=this.gameState,t=e.logger.group("LiveGame (newGame)",!0);this.reset(),this.initNamespaces();let n=this.getNewSavedGame();n.name="NewGame-"+Date.now(),this.currentSavedGame=n;let i=this.story?.entryScene?.getSceneRoot();i?this.stackModel.push(Ie.fromAction(i)):e.logger.warn("No scene root found");let r=this.story?.getAllElementMap(this.story,this.story?.entryScene?.getSceneRoot()||[]);return r?r.forEach(s=>{e.logger.debug("reset element",s),s.reset()}):e.logger.warn("No elements found"),e.stage.forceUpdate(),e.stage.next(),t.end(),this}waitForRouterExit(){let e=null;return{promise:new Promise(t=>{e=this.game.router.onceExitComplete(()=>{t()})}),cancel:()=>{e&&e.cancel()}}}waitForPageMount(){let e=null;return{promise:new Promise(t=>{e=this.game.router.oncePageMount(()=>{t()})}),cancel:()=>{e&&e.cancel()}}}requestFullScreen(e){this.assertGameState();let t="LiveGame.requestFullScreen";try{let n=this.gameState.playerCurrent;if(!n){this.gameState.logger.warn(t,"No player element found");return}if(n.requestFullscreen)return n.requestFullscreen(e);this.gameState.logger.warn(t,"Fullscreen is not supported")}catch(n){this.gameState.logger.error(t,n)}}exitFullScreen(){this.assertGameState();let e="LiveGame.exitFullScreen";try{if(document.exitFullscreen)return document.exitFullscreen();this.gameState.logger.warn(e,"Fullscreen is not supported")}catch(t){this.gameState.logger.error(e,t)}}constructMaps(){let e=this.story;if(!e)throw new Error("No story loaded");if(this.mapCache)return this.mapCache;let t=new Map,n=new Map;return e.forEachChild(e,e.entryScene?.getSceneRoot()||[],i=>{t.set(i.getId(),i),n.set(i.callee.getId(),i.callee)},{allowFutureScene:!0}),this.mapCache=[t,n],this.mapCache}getScreenshotOptions(){return{quality:this.game.config.screenshotQuality}}onPlayerEvent(e,t,n){this.assertPlayerElement();let i=this.gameState.playerCurrent;return i?(i.addEventListener(e,t,n),{cancel:()=>i.removeEventListener(e,t,n)}):(this.gameState.logger.warn("LiveGame.onEvent","No player element found"),{cancel:()=>{}})}onWindowEvent(e,t,n){return window.addEventListener(e,t,n),{cancel:()=>window.removeEventListener(e,t,n)}}reset(){this.assertGameState();let e=this.gameState;this.resetStackModels(),this.stackModel.reset(),this.currentSavedGame=null,this.lastDialog=null,e.forceReset()}next(){this.assertGameState();let e=this.gameState;if(this.gameLock.isLocked())return this.gameLock;if(!this.story)throw new Error("No story loaded");return this.stackModel.isEmpty()?(e.logger.weakWarn("Game Actions","Action stack is empty"),this.currentSavedGame?e.events.emit("event:state.end"):this.currentSavedGame=null,null):this.stackModel.rollNext()}setLastDialog(e,t){this.lastDialog={sentence:e,speaker:t}}requestAsyncStackModel(e){this.assertGameState();let t=new Ie(this);return this.asyncStackModels.add(t),t.push(...e),t}executeAsyncStackModel(e){this.assertGameState();let t=e.execute();return t.onFailed(n=>{this.gameState.logger.error("Async StackModel",n)}),t.onSettled(()=>{this.asyncStackModels.delete(e)}),t}createStackModel(e){let t=new Ie(this);return t.push(...e),t}resetStackModels(){this.asyncStackModels.forEach(e=>e.reset()),this.asyncStackModels.clear()}isPlaying(){return this.stackModel&&!this.stackModel.isEmpty()}executeAction(e,t,n){if(!this.stackModel)throw new Error("Stack model is not initialized");let i=t.executeAction(e,n);return y.isAwaitable(i)?i:i||null}setGameState(e){if(e&&this.gameState)throw new Le("GameState already set");return this.gameState=e,e&&!this.stackModel&&(this.stackModel=new Ie(this,"$root")),this}getGameState(){return this.gameState}getGameStateForce(){if(!this.gameState)throw new Le("GameState not set");return this.gameState}getAllPredictableActions(e,t,n){let i=t?.contentNode||null,r=[],s=[],a=new Set;for(;(i||s.length)&&!(n&&r.length>=n);){if(i||(i=s.pop().contentNode),[rt].some(c=>i?.action&&i.action instanceof c)){i=null;continue}if(i.action&&i.action.is(Y,V.jumpTo)){let[c]=i.action.contentNode.getContent(),l=e.getScene(c);if(!l)throw i.action._sceneNotFoundError(i.action.getSceneName(c));if(a.has(l)){i=null;continue}a.add(l),i=l.getSceneRoot()?.contentNode||null;continue}else if(i.action&&i.action.is(se,ve.do)){let[c]=i.action.contentNode.getContent();i.getChild()?.action&&s.push(i.getChild().action),i=c[0]?.contentNode||null}i.action&&r.push(i.action),i=i.getChild()}return r}clearMainStack(){if(!this.stackModel)throw new Le("No stack model found");return this.stackModel.reset(),this}getStackModelForce(){if(!this.stackModel)throw new Le("No stack model found");return this.stackModel}getNewSavedGame(){return{name:"",meta:{created:Date.now(),updated:Date.now(),id:yr(),lastSentence:null,lastSpeaker:null,storyHash:this.story?.hash()||""},game:{store:{},stage:{scenes:[],audio:{sounds:[],groups:[]},videos:[]},elementStates:[],services:{},stackModel:{items:[]},asyncStackModels:[]}}}assertGameState(){if(!this.gameState)throw new x("No game state found, make sure you call this method in effect hooks or event handlers")}assertPlayerElement(){if(this.assertGameState(),!this.gameState.playerCurrent)throw new x("Player Element Not Mounted")}};bt.DefaultNamespaces={game:{}},bt.GameSpacesKey={game:"game"},bt.EventTypes={"event:character.prompt":"event:character.prompt","event:menu.choose":"event:menu.choose"};var lt=bt;var Dn=class Dn{constructor(e){this.settings=e;this.events=new J;this.events.setMaxListeners(64)}setPreference(e,t){this.settings[e]=t,this.events.emit(Dn.EventTypes["event:game.preference.change"],e,t)}getPreference(e){return this.settings[e]}getPreferences(){return this.settings}onPreferenceChange(e,t){return this.events.on(Dn.EventTypes["event:game.preference.change"],(n,i)=>{typeof e=="string"?e===n&&t&&t(i):e(n,i)})}importPreferences(e){for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&this.setPreference(t,e[t])}exportPreferences(){let e={};for(let t in this.settings)Object.prototype.hasOwnProperty.call(this.settings,t)&&(e[t]=this.settings[t]);return e}togglePreference(e){if(typeof this.settings[e]!="boolean")throw new Error(`Preference ${e} is not a boolean`);this.setPreference(e,!this.getPreference(e))}};Dn.EventTypes={"event:game.preference.change":"event:game.preference.change"};var Ln=Dn;import"client-only";import gs,{useEffect as Bc,useRef as Mo}from"react";import"client-only";import Nr,{useContext as Mr,useState as pa}from"react";var uo=Nr.createContext(null);function Gr({children:o,game:e}){"use client";let t=new Q({}),[n]=pa(e||t);return Nr.createElement(uo,{value:n},o)}function w(){let o=Mr(uo);if(!o)throw new Error("useGame must be used within a GameProvider");return o}function Hr(){return Mr(uo)}import da,{createContext as ma,useContext as Ur}from"react";var Fr="/",Si=class Si{constructor(e,t=Si.rootPath){this.events=new J;this.currentPath="";this.currentQuery={};this.history=[];this.historyIndex=-1;this.mountedPaths=new Set;this.defaultHandlerPaths=new Set;this.unmountingPaths=new Set;this.updateSyncHooks=new Set;this.transitioning=!1;this.game=e;let{path:n,query:i}=this.parseUrl(t);this.currentPath=n,this.currentQuery=i,this.history.push(t),this.historyIndex=0}getCurrentPath(){return this.currentPath}getPathname(){return this.currentPath}getCurrentQuery(){return{...this.currentQuery}}getQueryParams(){return this.getCurrentQuery()}getCurrentUrl(){return this.buildUrl(this.currentPath,this.currentQuery)}parseUrl(e){let[t,n]=e.split("?"),i={};if(n){let r=n.split("&");for(let s of r){let[a,c]=s.split("=");a&&(i[decodeURIComponent(a)]=c?decodeURIComponent(c):"")}}return{path:t||"/",query:i}}buildUrl(e,t){if(Object.keys(t).length===0)return e;let n=Object.entries(t).map(([i,r])=>`${encodeURIComponent(i)}=${encodeURIComponent(r)}`).join("&");return`${e}?${n}`}getQueryParam(e){return this.currentQuery[e]}setQueryParam(e,t){return this.currentQuery[e]=t,this.updateHistory(),this.emitOnChange(),this}setQueryParams(e){return Object.assign(this.currentQuery,e),this.updateHistory(),this.emitOnChange(),this}removeQueryParam(e){return delete this.currentQuery[e],this.updateHistory(),this.emitOnChange(),this}clearQueryParams(){return this.currentQuery={},this.updateHistory(),this.emitOnChange(),this}hasQueryParam(e){return e in this.currentQuery}getQueryParamKeys(){return Object.keys(this.currentQuery)}getQueryParamCount(){return Object.keys(this.currentQuery).length}getHistory(){return[...this.history]}getHistoryIndex(){return this.historyIndex}canGoBack(){return this.historyIndex>0}canGoForward(){return this.historyIndex<this.history.length-1}navigate(e,t){let{path:n,query:i}=this.parseUrl(e),r=this.resolvePath(n),s={...i,...t};if(this.currentPath===r)return this.currentQuery=s,this.historyIndex>=0&&(this.history[this.historyIndex]=this.buildUrl(r,s)),this.emitOnChange(),this;this.historyIndex<this.history.length-1&&(this.history.length=this.historyIndex+1);let a=this.buildUrl(r,s);return this.history.push(a),this.history.length>this.game.config.maxRouterHistory&&(this.history.shift(),this.historyIndex--),this.historyIndex++,this.currentPath=r,this.currentQuery=s,this.emitOnChange(),this.requestPageTransition(),this}back(){if(this.canGoBack()){this.historyIndex--;let{path:e,query:t}=this.parseUrl(this.history[this.historyIndex]);this.currentPath=e,this.currentQuery=t,this.emitOnChange(),this.requestPageTransition()}return this}forward(){if(this.canGoForward()){this.historyIndex++;let{path:e,query:t}=this.parseUrl(this.history[this.historyIndex]);this.currentPath=e,this.currentQuery=t,this.emitOnChange(),this.requestPageTransition()}return this}replace(e,t){let{path:n,query:i}=this.parseUrl(e),r=this.resolvePath(n),s={...i,...t};return this.currentPath=r,this.currentQuery=s,this.historyIndex>=0?this.history[this.historyIndex]=this.buildUrl(r,s):(this.history.push(this.buildUrl(r,s)),this.historyIndex=0),this.emitOnChange(),this}clear(){return this.currentPath="",this.currentQuery={},this.history=[],this.historyIndex=-1,this.emitOnChange(),this.requestPageTransition(),this}cleanHistory(){return this.history=this.currentPath?[this.buildUrl(this.currentPath,this.currentQuery)]:[],this.historyIndex=this.currentPath?0:-1,this}parsePath(e){return e.split("/").filter(t=>t.length>0)}buildPath(e){return"/"+e.join("/")}getParentPath(e){let t=this.parsePath(e);return t.length<=1?"":this.buildPath(t.slice(0,-1))}matchPath(e,t){let n=this.parsePath(e),i=this.parsePath(t);if(n.length<i.length)return!1;for(let r=0;r<i.length;r++){let s=n[r],a=i[r];if(a!=="*"){if(a.startsWith(":"))continue;if(s!==a)return!1}}return!0}exactMatch(e,t){let n=this.parsePath(e),i=this.parsePath(t);if(n.length!==i.length)return!1;for(let r=0;r<i.length;r++){let s=n[r],a=i[r];if(a!=="*"){if(a.startsWith(":"))continue;if(s!==a)return!1}}return!0}extractParams(e,t){let n={},i=this.parsePath(e),r=this.parsePath(t);if(i.length!==r.length)return n;for(let s=0;s<r.length;s++){let a=r[s];if(a.startsWith(":")){let c=a.slice(1);n[c]=i[s]}}return n}onExitComplete(e){return this.events.on("event:router.onExitComplete",e)}onceExitComplete(e){return this.events.once("event:router.onExitComplete",e)}onPageMount(e){return this.events.on("event:router.onPageMount",e)}oncePageMount(e){return this.events.once("event:router.onPageMount",e)}onUpdate(e){return this.updateSyncHooks.add(e),{cancel:()=>{this.updateSyncHooks.delete(e)}}}emitUpdateSync(){this.updateSyncHooks.forEach(e=>e())}mount(e){if(this.mountedPaths.has(e))throw new x(`Path ${e} is already mounted. This may be caused by multiple capture segments in the same path.`);return this.mountedPaths.add(e),{cancel:()=>{this.unmount(e)}}}unmount(e){this.mountedPaths.delete(e)}mountDefaultHandler(e){if(this.defaultHandlerPaths.has(e))throw new x(`Default handler path ${e} is already mounted.`);return this.defaultHandlerPaths.add(e),{cancel:()=>{this.unmountDefaultHandler(e)}}}unmountDefaultHandler(e){this.defaultHandlerPaths.delete(e)}emitOnPageMount(){this.events.emit("event:router.onPageMount")}onRootExitComplete(e){return this.events.on("event:router.onExitComplete",e)}isActive(){return this.currentPath!==""}onChange(e){return this.events.on("event:router.onChange",e)}emitOnChange(){this.events.emit("event:router.onChange")}resolvePath(e){let t=e.split("?")[0];if(t.startsWith("/"))return t;if(t==="")return this.currentPath;let n=this.parsePath(this.currentPath),i=t.split("/"),r=[];r.push(...n);for(let s=0;s<i.length;s++){let a=i[s];a===""||a==="."||(a===".."?r.length>0&&r.pop():r.push(a))}return this.buildPath(r)}normalizePath(e){let t=e.replace(/\/\/+/g,"/").replace(/\/$/,"");return t===""?"/":(t.startsWith("/"),t)}joinPath(e,...t){let n=this.normalizePath(e),s=[n.startsWith("/")?n:"/"+n,...t.filter(a=>a.length>0)].join("/");return this.normalizePath(s)}updateHistory(){this.historyIndex>=0&&(this.history[this.historyIndex]=this.buildUrl(this.currentPath,this.currentQuery))}requestPageTransition(){let e=()=>{this.transitioning=!0,this.emitUpdateSync(),this.emitOnChange()},t=()=>{this.events.emit("event:router.onTransitionEnd"),this.transitioning=!1,this.emitUpdateSync(),this.emitOnChange(),this.events.emit("event:router.onExitComplete")};if(e(),this.isPathsUnmounting()){let n=this.events.on("event:router.onPathUnmount",()=>{this.isPathsUnmounting()||(n.cancel(),We(()=>{t()}))})}else We(()=>{t()})}registerUnmountingPath(e){this.unmountingPaths.add(e)}isPathsUnmounting(){return this.unmountingPaths.size>0}unregisterUnmountingPath(e){this.unmountingPaths.delete(e),this.events.emit("event:router.onPathUnmount")}isTransitioning(){return this.transitioning}createToken(e){return Symbol(e)}};Si.rootPath=Fr;var It=Si,po=ma(null);function Kr({children:o}){let e=w();return da.createElement(po,{value:{router:e.router}},o)}function pt(){if(!Ur(po))throw new Error("useRouter must be used within a RouterProvider");return Ur(po).router}import Or from"react";import Ta from"clsx";import fa,{createContext as ha,useContext as ga,useLayoutEffect as ya,useReducer as va,useState as Sa}from"react";var At=class At{constructor(){this.state={width:0,height:0,minWidth:800,minHeight:450,paused:!1,scale:0};this.events=new J().setMaxListeners(1/0);this.lockers=[];this.updater=null}update(e,t,n){this.state.width=e,this.state.height=t,this.state.scale=n,this.events.emit(At.EventTypes["event:aspectRatio.update"],e,t)}updateMin(e,t){this.state.minWidth=e,this.state.minHeight=t}lock(){let e=Symbol();return this.lockers.push(e),e}unlock(e){if(e&&!this.lockers.includes(e))throw new Error("Locker not found");return this.lockers=this.lockers.filter(t=>t!==e),this.triggerUpdate(),null}isLocked(){return!!this.lockers.length}getStyle(){return{width:`${this.state.width}px`,height:`${this.state.height}px`}}setUpdate(e){this.updater=e}pause(){this.state.paused=!0,this.events.emit(At.EventTypes["event:aspectRatio.pause"])}resume(){this.state.paused=!1,this.events.emit(At.EventTypes["event:aspectRatio.resume"])}onUpdate(e){return this.events.on(At.EventTypes["event:aspectRatio.update"],e).cancel}requestUpdate(){this.events.emit(At.EventTypes["event:aspectRatio.requestUpdate"])}onRequestedUpdate(e){return this.events.on(At.EventTypes["event:aspectRatio.requestUpdate"],e).cancel}triggerUpdate(){this.updater&&this.updater()}};At.EventTypes={"event:aspectRatio.update":"event:aspectRatio.update","event:aspectRatio.pause":"event:aspectRatio.pause","event:aspectRatio.resume":"event:aspectRatio.resume","event:aspectRatio.requestUpdate":"event:aspectRatio.requestUpdate"};var mo=At,fo=ha(null);function Vr({children:o}){"use client";let[e]=Sa(()=>new mo);return fa.createElement(fo,{value:{ratio:e}},o)}function pe(){let o=ga(fo),[,e]=va(n=>n+1,0);if(!fo||!o)throw new Error("useRatio must be used within a RatioProvider");let{ratio:t}=o;return ya(()=>(e(),t.onUpdate(()=>{e()})),[t]),o}function dt({children:o,className:e,style:t,ref:n,...i}){let{ratio:r}=pe(),s=r.getStyle();return Or.createElement("div",{className:Ta("inset-0",e),style:{width:"100%",height:"100%",minWidth:`${r.state.minWidth}px`,minHeight:`${r.state.minHeight}px`},...i},Or.createElement("div",{style:{...s,position:"relative",...t||{}},...i||{},ref:n},o))}import ba,{useEffect as Aa}from"react";function _e(o){let e=w(),[t,n]=ba.useState(e.preference.getPreference(o)),i=r=>{e.preference.setPreference(o,r),n(r)};return Aa(()=>e.preference.onPreferenceChange(o,n).cancel,[o,e.preference,n]),[t,i]}import ho from"react";import Ti from"react";import Wr from"clsx";function bi({children:o,className:e,style:t,...n}){let{ratio:i}=pe(),r=w();return Ti.createElement(dt,{className:Wr("absolute pointer-events-none w-full h-full"),style:{transform:`scale(${i.state.scale})`,transformOrigin:"left top",width:r.config.width,height:r.config.height,pointerEvents:"none"},"data-element-type":"full",...n},Ti.createElement("div",{className:"absolute inset-0 w-full h-full"},Ti.createElement("div",{className:"inset-0 w-full h-full"},Ti.createElement("div",{className:Wr("pointer-events-auto-rest",e),style:t},o))))}function Ca({children:o,className:e,style:t}){return ho.createElement(ho.Fragment,null,ho.createElement(bi,{style:t,className:e,"data-element-type":"stage","data-code-source":"Stage.tsx"},o))}import zr from"clsx";import Br from"react";function Ai({className:o,children:e,...t}){let{ratio:n}=pe();return Br.createElement("div",{style:{transform:`scale(${n.state.scale})`,transformOrigin:"left top"},className:zr("w-full h-full")},Br.createElement("div",{className:zr("z-20",o),...t},e))}import Xe,{useState as $r}from"react";import{motion as xa}from"motion/react";function Ci({children:o,border:e="solid",color:t="red",tag:n,borderWidth:i=1,as:r="div",ref:s,...a}){let c=w(),[l,p]=$r(!1);if(!c.config.app.inspector)return Xe.createElement(r,{...a,ref:s},o);let u={...a,onMouseEnter:()=>p(!0),onMouseLeave:()=>p(!1),style:{...a.style||{},outline:`${i}px ${e} ${t}`,zIndex:l?1e3:"auto"}};return Xe.createElement(r,{...u,ref:s},n&&l&&Xe.createElement("span",{className:"absolute top-0 left-0 bg-white text-black border-2 border-black text-sm"},n),o)}function wa({border:o="solid",color:e="red",tag:t,borderWidth:n=1,as:i="img",...r}){let s=w(),[a,c]=$r(!1);if(!s.config.app.inspector)return Xe.createElement(i,{...r});let l={...r,onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),style:{...r.style||{},outline:`${o} ${n}px ${e}`,zIndex:a?1e3:"auto"}};return Xe.createElement("div",null,Xe.createElement(i,{...l}),t&&a&&Xe.createElement("span",{className:"absolute top-0 left-0 bg-white text-black border-2 border-black"},t))}function ka(o){return Xe.createElement(Ci,{...o,as:"div"})}function Pa(o){return Xe.createElement(Ci,{...o,as:"span"})}function Ea(o){return Xe.createElement(wa,{...o,as:"img"})}function Da(o){return Xe.createElement(Ci,{...o,as:"button"})}function La(o){return Xe.createElement(Ci,{...o,as:xa.div,ref:o.ref,layout:o.layout})}var Ia={Div:ka,Span:Pa,Button:Da,Img:Ea,mDiv:La},zt=Ia;import Pi from"clsx";import Pe,{useEffect as un,useRef as Yr,useState as go}from"react";import{useEffect as Ra,useState as Na}from"react";function Z(o){let[e,t]=Na(0);Ra(()=>{n()},o??[]);function n(){t(i=>i+1)}return[n,e]}import jr from"react";var Bt=jr.createContext(null);function et(){let o=jr.useContext(Bt);if(!o)throw new Error("useDialogContext must be used within a DialogContext");return o}import xi,{useCallback as Ma,useLayoutEffect as In,useMemo as qr,useRef as Qr}from"react";import{useIsPresent as Ga}from"motion/react";var tt=class tt{constructor(e){this.events=new J;this._forceSkipped=!1;this._idle=!1;this._active=!0;this.config=e,this._state="pending",this.autoForwardScheduler=new qn,this._count=0}get state(){return this._state}get deps(){return[this._count]}isIdle(){return this._idle}setIdle(e){this._idle=e}isActive(){return this._active}setActive(e){return this._active=e,e||this.cancelAutoForward(),this}requestComplete(){this._active&&(this.state==="ended"?this.safeEmit(tt.Events.complete):this.safeEmit(tt.Events.requestComplete))}forceSkip(){this._active&&(this.state==="ended"?this.emitComplete():(this._forceSkipped=!0,this.safeEmit(tt.Events.forceSkip)))}dispatchComplete(){if(this.state==="ended"){this.config.gameState.logger.weakWarn("DialogState","Dialog is already ended. Cannot dispatch complete.");return}if(!this.events.hasListeners(tt.Events.complete)){this.config.gameState.logger.weakWarn("DialogState","No listener for complete event. Cannot dispatch complete.");return}let e=this.config.gameState.game.preference;return this._state="ended",e.getPreference(Q.Preferences.autoForward)&&this.scheduleAutoForward(),this.emitComplete(),this}emitComplete(){return this.safeEmit(tt.Events.complete),this.emitFlush(),this}isEnded(){return this.state==="ended"}setPause(e){this.isEnded()||(e?this._state="paused":this._state="pending")}isForceSkipped(){return this._forceSkipped}tryScheduleAutoForward(){this.isEnded()&&this.scheduleAutoForward()}cancelAutoForward(){this.autoForwardScheduler.cancelTask()}emitFlush(){return this._count++,this.events.emit(tt.Events.onFlush),this}onFlush(e){return this.events.on(tt.Events.onFlush,e)}safeEmit(e,...t){return this.events.emit(e,...t)===0&&this.config.gameState.logger.weakWarn("DialogState",`Failed to emit event: ${e}. Target Component is not mounted.`),this}scheduleAutoForward(){let e=this.config.gameState.game.preference;!this._active||!e.getPreference(Q.Preferences.autoForward)||this.state!=="ended"||this.autoForwardScheduler.cancelTask().scheduleTask(()=>{this.events.emit(tt.Events.simulateClick)},this.config.gameState.game.config.autoForwardDelay/e.getPreference(Q.Preferences.gameSpeed))}};tt.Events={requestComplete:"event:dialog.requestComplete",complete:"event:dialog.complete",forceSkip:"event:dialog.forceSkip",onFlush:"event:dialog.onFlush",simulateClick:"event:dialog.simulateClick"};var fe=tt;function Rn({action:o,onFinished:e,useTypeEffect:t=!0,gameState:n,active:i=!0}){let r=Ga(),s=i&&r,a=Qr(!1),c=Qr(o),l=c.current!==o,p=qr(()=>o.sentence?.evaluate(ue.getCtx({gameState:n})),[o.sentence,n]),u=qr(()=>new fe({useTypeEffect:t,action:o,evaluatedWords:p||[],gameState:n,suppressInitialAnimation:l}),[o,n,t,p]),d=n.game.config.dialog,h=Ma(m=>{!s||a.current||(a.current=!0,e?.(m))},[s,e]);return In(()=>{a.current=!1},[u]),In(()=>{c.current=o},[o]),In(()=>(u.setActive(s),()=>{u.setActive(!1)}),[u,s]),In(()=>(n.logger.debug("NarraLeaf-React: Say","dialogState",u),u.events.on(fe.Events.complete,m=>{n.logger.log("NarraLeaf-React: Say","Complete",u.isIdle()),s&&(u.isIdle()||m?h(!1):u.setIdle(!0))}).cancel),[u,h,n,s]),In(()=>n.events.on(k.EventTypes["event:state.player.skip"],m=>{s&&(m?(u.setIdle(!0),u.forceSkip()):u.isIdle()?h(!0):u.forceSkip())}).cancel,[u,h,n,s]),xi.createElement(xi.Fragment,null,xi.createElement(Bt,{value:u},xi.createElement(d,null)))}import{useEffect as wi,useState as Fa}from"react";import{useEffect as Ha,useState as Ua}from"react";function $t(o){let e=w(),[t,n]=Ua(e.keyMap.getKeyBinding(o)),i=r=>{e.keyMap.setKeyBinding(o,r),n(r)};return Ha(()=>e.keyMap.onKeyBindingChange(o,n).cancel,[o,e.keyMap,n]),[t,i]}var ln=(t=>(t.skipAction="skipAction",t.nextAction="nextAction",t))(ln||{});function ki({entry:o,gameState:e,words:t,isActive:n,useTypeEffect:i}){let r=w(),[s]=$t("nextAction"),[a]=Fa(()=>new fe({useTypeEffect:i,action:{sentence:o.sentence,character:o.character,words:t,id:o.id},evaluatedWords:t,gameState:e}));return wi(()=>{if(!n)return;let c=()=>{e.requestNvlAdvance(o.id)==="typing"&&a.requestComplete()},l=()=>{e.requestNvlSkip(o.id)==="typing"&&a.forceSkip()},p=e.events.on(k.EventTypes["event:state.player.stageClick"],c),u=e.events.on(k.EventTypes["event:state.player.skip"],l);return()=>{p.cancel(),u.cancel()}},[a,o.id,e,n]),wi(()=>{if(!n)return;let c=p=>{if(!r.keyMap.match("nextAction",p.key))return;e.requestNvlAdvance(o.id)==="typing"&&a.requestComplete()};if(r.config.useWindowListener){let p=r.getLiveGame().onWindowEvent("keyup",c);return()=>{p.cancel()}}let l=r.getLiveGame().onPlayerEvent("keyup",c);return()=>{l.cancel()}},[a,o.id,r,e,n,s]),wi(()=>{let c=a.events.on(fe.Events.complete,l=>{n&&(e.completeNvlTyping(o.id),!a.isIdle()&&!l&&a.setIdle(!0))});return()=>{c.cancel()}},[a,o.id,e,n]),wi(()=>{let c=a.events.on(fe.Events.simulateClick,()=>{if(!n)return;e.requestNvlAdvance(o.id)==="typing"&&a.requestComplete()});return()=>{c.cancel()}},[a,n]),a}function*vo(o){let e=[...o];for(let t=0;t<e.length;t++){let n=e[t];if(we.isPause(n.text)){yield we.from(n.text);continue}for(let i=0;i<n.text.length;i++){let r=n.text[i];r===`
35
35
  `?yield`
36
- `:yield{text:r,config:n.config,tag:t,tag2:i,cps:n.config.cps}}}}function co({defaultColor:o,className:e,style:t,dialog:n,...i}){let r=C(),s=r.getLiveGame().getGameState(),a=Aa(null),[c,l]=xa(()=>n&&!n.config.useTypeEffect?h(n.config.evaluatedWords):[]),[u,m]=$();if(!n)throw new Error("Dialog state is required");ao(()=>{if(!(!n.config.action.sentence||a.current))return s.logger.info("Initializing the sentence",n,a.current),s.schedule(({onCleanup:f})=>{if(!n.config.useTypeEffect){n.dispatchComplete();return}l([]),a.current=p(),u(),a.current.onComplete(()=>{n.dispatchComplete()}),f(()=>{a.current?.timeline?.abort()})},0)},[]),ao(()=>n.events.depends([n.events.on(le.Events.requestComplete,()=>{a.current?.interact()}),n.events.on(le.Events.forceSkip,()=>{n.isEnded()||a.current?.forceSkip()})]).cancel,[n,m]),ao(()=>r.preference.events.depends([r.preference.onPreferenceChange(B.Preferences.gameSpeed,()=>{a.current?.update()}),r.preference.onPreferenceChange(B.Preferences.autoForward,()=>{a.current?.update()}),r.preference.onPreferenceChange(B.Preferences.cps,()=>{a.current?.update()})]).cancel,[]);function p(){let f=new g,S=new fe(f).setGuard(s.guard),N=new Set,q=new Set,ae=new Set,Ve=Rr(n.config.evaluatedWords),Te=null,ke=[],be=[],Oe=()=>{ke.forEach(D=>D()),ke.length=0},Qe=()=>{if(be.length!==0)return{done:!1,value:be.shift()};let{done:D,value:L}=Ve.next();return{done:D,value:L}},ue=D=>{let L=ie=>{D(ie),q.delete(L)};return q.add(L),{cancel:()=>{q.delete(L)}}},P=D=>{l(L=>{let ie=L[L.length-1];return ie&&ie!==`
37
- `&&D!==`
38
- `&&ie.tag===D.tag?[...L.slice(0,-1),{...D,text:ie.text+D.text,config:D.config}]:[...L,D]})},Q=(D=!1)=>{let L=!1;for(;!L;){let{done:ie,value:J}=Qe();if(ie){L=!0;break}if(Pe.isPause(J)){if(D)continue;L=!0,be.push(J);break}else J===`
39
- `?l(Ce=>[...Ce,J]):typeof J=="object"&&"text"in J&&!N.has(J)&&(N.add(J),P(J))}Te&&!Te.isSettled()?Te.abort():(ae.forEach(ie=>ie()),f.resolve())};return s.schedule(async D=>{let L=!1,ie=!1;for(;!L;){let{done:J,value:Ce}=Qe();if(J){L=ie=!0;break}let Hn=new g;if(s.timelines.attachTimeline(Hn),Hn.registerSkipController(new M(()=>{Oe(),L=!0,D.retry()})),Hn.onSettled(()=>{Oe()}),Te=Hn,Pe.isPause(Ce)){let Un=Pe.from(Ce),Fn=r.preference.getPreference(B.Preferences.gameSpeed);if(Un.config.duration){let Kn=Un.config.duration/Fn;await Qn(Kn)}else{let Kn=r.preference.getPreference(B.Preferences.autoForward),Vn=g.race([g.create(Is=>{let Rs=ue(Ns=>{Ns(),Is.resolve()});ke.push(()=>Rs.cancel())}),...Kn?[g.delay(r.config.autoForwardDefaultPause/Fn)]:[]]);s.timelines.attachTimeline(Vn),await g.wait(Vn)}}else{if(Ce!==`
40
- `&&N.has(Ce))continue;N.add(Ce),P(Ce);let{gameSpeed:Un,cps:Fn}=r.preference.getPreferences(),Vn=1e3/((typeof Ce=="object"&&"cps"in Ce&&Ce.cps!==void 0?Ce.cps:Fn)*Un);await Qn(Vn)}}ie&&(ae.forEach(J=>J()),f.resolve())},0),{getToken:()=>f,interact:()=>{let D=!1;q.forEach(L=>L(()=>D=!0)),!D&&Q()},update:()=>{Te&&Te.abort()},forceSkip:()=>{Q(!0)},timeline:S,onComplete:D=>(ae.add(D),{cancel:()=>{ae.delete(D)}})}}function h(f){let S=Rr(f),N=[];for(let q of S)Pe.isPause(q)||N.push(q);return N}let d=n.config.action.sentence;if(!d)return null;let T={fontWeight:d.config.bold?r.config.fontWeightBold:r.config.fontWeight,fontSize:d.config.fontSize??r.config.fontSize,color:mt(d.config.color??r.config.defaultTextColor),fontFamily:d.config.fontFamily??r.config.fontFamily,fontStyle:d.config.italic?"italic":void 0},y=f=>({fontWeight:f.config.bold||d.config.bold?r.config.fontWeightBold:r.config.fontWeight,fontSize:f.config.fontSize??d.config.fontSize??r.config.fontSize,color:mt(f.config.color??d.config.color??o??r.config.defaultTextColor),fontFamily:f.config.fontFamily??d.config.fontFamily??r.config.fontFamily,fontStyle:f.config.italic??d.config.italic?"italic":void 0}),x=(f,S)=>f===`
41
- `?lt.createElement("br",{key:S}):lt.createElement(Ft.Span,{tag:`say.word.${S}`,key:S,style:{...y(f),...Xn(r.config.app.debug,{outline:"1px dashed red"})},className:Ir("inline-block break-all",f.config.className)},f.config.ruby?lt.createElement("ruby",{className:"align-bottom inline-block"},lt.createElement("rt",{className:"block text-center"},f.config.ruby),f.text):f.text);return lt.createElement("div",{...i,className:Ir("whitespace-pre-wrap",e),style:{...t,...T}},c.map(x))}function Nr(o){return lt.createElement(co,{...o,key:o.dialog?.config.action.id})}function wa({entry:o,gameState:e,words:t,useTypeEffect:n,isActive:i,...r}){let s=bi({entry:o,gameState:e,words:t,useTypeEffect:n,isActive:i});return lt.createElement(co,{...r,dialog:s,key:s.config.action.id})}function ka(o){let e=yt();return lt.createElement(co,{...o,dialog:e,key:e.config.action.id})}function Pt(o){return"entry"in o&&o.entry&&"gameState"in o&&o.gameState&&"words"in o&&o.words?lt.createElement(wa,{...o}):lt.createElement(ka,{...o})}var Ea=Pt;import Ai,{useEffect as Pa,useLayoutEffect as Da,useMemo as Hr,useRef as La,useState as Ia}from"react";import Ci from"react";var lo=Ci.createContext(null);function Mr(){let o=Ci.useContext(lo);if(!o)throw new Error("useUIMenuContext must be used within a UIMenuContext");return o}var uo=Ci.createContext(null);function Gr(){let o=Ci.useContext(uo);if(!o)throw new Error("useUIListContext must be used within a UIListContext");return o}function xi({className:o,style:e,bindKey:t}){let n=La(null),{register:i,unregister:r,getIndex:s}=Gr(),[a,c]=Ia(-1),{choose:l,evaluated:u,gameState:m}=Mr(),p=a===-1?null:u[a],h=Hr(()=>re.getCtx({gameState:m}),[m]),{hidden:d,disabled:T}=Hr(()=>{if(!p)return{hidden:!1,disabled:!1};let f=p.config.hidden?.evaluate(h)?.value??!1,S=!f&&(p.config.disabled?.evaluate(h)?.value??!1);return{hidden:f,disabled:S}},[p,h]);Da(()=>{if(!n.current)return;let f=n;i(f);let S=s(f);return c(S),n.current.dataset.index=S.toString(),()=>r(f)},[i,r,s]),Pa(()=>{if(!t)return;let f=S=>{S.key.toLowerCase()===t.toLowerCase()&&!S.ctrlKey&&!S.metaKey&&(S.preventDefault(),S.stopPropagation(),y())};return window.addEventListener("keydown",f,!0),()=>{window.removeEventListener("keydown",f,!0)}},[t]);function y(){if(a===-1||!u[a]||d||T)return;let f=u[a];l({...f,evaluated:F.getText(f.words||[])})}let x=p&&!d;return Ai.createElement(Ai.Fragment,null,Ai.createElement("button",{className:o,style:{...e,display:x?e?.display??void 0:"none"},onClick:y,ref:n,disabled:T},x&&Ai.createElement(Nr,{dialog:new le({useTypeEffect:!1,action:{sentence:p.prompt,words:p.words,character:null},gameState:m,evaluatedWords:p.words})})))}import wi from"react";import{AnimatePresence as Ra}from"motion/react";function ki({children:o,...e}){let t=Ra;return wi.createElement(wi.Fragment,null,wi.createElement("div",{...e},wi.createElement(t,null,o)))}import xn from"react";function Dt({entry:o,character:e,...t}){let n=xn.useContext(Kt),i=C(),r=e??o?.character??n?.config.action.character??null;return xn.createElement(xn.Fragment,null,xn.createElement("div",{...t},xn.createElement("span",{style:{color:mt(r?.config.color||i.config.defaultNametagColor)}},r?.state.name)))}import{useEffect as Na}from"react";function Ma(){let o=yt(),[e]=$(o.deps),t=F.getText(o.config.evaluatedWords);return Na(()=>o.events.on(le.Events.onFlush,()=>{e()}).cancel,[o]),{done:o.isEnded(),text:t,isNarrator:o.config.action.character===null||o.config.action.character.state.name===""}}import{useCallback as Ei,useEffect as po,useMemo as Ga,useRef as Ha,useState as Ur}from"react";function Ua(){let o=yt(),[e]=$(o.deps),[t,n]=Ur(!0),[i,r]=Ur(!0),s=Ha(null),a=o.config.gameState,c=o.config.action.sentence,l=c?.config.voiceId??null;po(()=>o.events.on(le.Events.onFlush,()=>{e()}).cancel,[o]);let u=Ga(()=>{if(!c)return null;try{return Ye.getVoice(a,c)}catch{return null}},[a,c,l,c?.config.voice]);po(()=>{s.current=null,r(!0)},[c]),po(()=>{let T=!1,y=null,x=null,f=null;if(!u){n(!0);return}n(!1);let S=()=>{T||n(!0)};y=a.audioManager.getToken(u),y&&(y.isPlaying()||n(!0),x=()=>S(),f=()=>S(),y.once("ended",x),y.once("stop",f));let N=a.events.on(w.EventTypes["event:state.player.lineEnd"],()=>{S()});return()=>{T=!0,N.cancel(),y&&x&&y.off("ended",x),y&&f&&y.off("stop",f)}},[a,u]);let m=Ei(async T=>{let y=T??u;if(!y)return r(!0),null;s.current?.isPlaying()&&s.current.stop(),r(!1);let x=y instanceof URL?Z.voice(y.toString()):typeof y=="string"?Z.voice(y):y,f=await a.getLiveGame().playSound(x);s.current=f;let S=()=>{r(!0)};return f.once("ended",S),f.once("stop",S),f},[a,u]),p=Ei(()=>u,[u]),h=Ei(()=>l,[l]),d=Ei(()=>u?.getSrc()??null,[u]);return{done:t&&i,voice:u,playVoice:m,getVoice:p,getVoiceId:h,getVoiceSrc:d}}import mo,{createContext as Xa,useContext as Ya,useEffect as Vr,useRef as Ja}from"react";import{useState as Fa}from"react";function Pi(o){let[e]=Fa(o);return e}import{AnimatePresence as Ka}from"motion/react";var Di=Ka;import Pn,{createContext as Ba,useContext as $a,useEffect as ja,useRef as qa}from"react";import{useEffect as wn,useLayoutEffect as Va}from"react";function Oa(){let o=at(),[e]=$();return wn(()=>o.onChange(e).cancel,[]),o.getPathname()}function Wa(){let{router:o,path:e}=En(),[t]=$();return wn(()=>o.onChange(t).cancel,[]),o.extractParams(o.getCurrentPath(),e)}function za(){let o=at(),[e]=$();return wn(()=>o.onChange(e).cancel,[]),o.getQueryParams()}function Li(o,e){let t=at();Va(()=>t.onUpdate(()=>o(t)).cancel,e),wn(()=>{o(t)},[])}function kn(){let o=at(),[e]=$();return wn(()=>o.onChange(e).cancel,[]),e}var Fr=Ba(null);function Dn({children:o,path:e,consumedBy:t}){let i={router:at(),path:e,consumedBy:t};return Pn.createElement(Fr,{value:i},o)}function En(){let o=$a(Fr);if(!o)throw new Error("useLayout must be used within a LayoutRouterProvider");if(o.path===null)throw new b(`Invalid useLayout call: Trying to access layout without a parent.
42
- This is likely caused by a nested Layout component or using Page inside a Page. `);return o}function Qa({children:o,name:e,propagate:t}){let n=C(),[i]=$(),{path:r,router:s,consumedBy:a}=En(),c=s.joinPath(r,e),l=Pi(()=>s.createToken(c+"@layout")),u=s.getCurrentPath(),m=qa(!1),p=d=>{m.current=d,i()},h=s.matchPath(u,c);if(kn(),Li(d=>{let T=d.matchPath(d.getCurrentPath(),c);if(m.current&&!T){if(!o){p(!1);return}d.registerUnmountingPath(l)}T&&d.isPathsUnmounting()&&d.unregisterUnmountingPath(l),T&&!m.current&&!d.isTransitioning()&&p(!0)},[h,o]),ja(()=>{if(!h)return;let d=s.mount(c);return()=>{d.cancel()}},[c,s,h]),a)throw new b("[PageRouter] Layout is consumed by a different layout. This is likely caused by a nested layout inside a layout.");return Pn.createElement(Dn,{path:c},Pn.createElement(Di,{mode:"wait",propagate:t??n.config.animationPropagate,onExitComplete:()=>{s.unregisterUnmountingPath(l),p(!1)}},h&&m.current&&o))}function Kr({children:o}){return kn(),Pn.createElement(Dn,{path:Et.rootPath},Pn.createElement(gi,{"data-layout-path":Et.rootPath,key:Et.rootPath},o))}var fo=Xa(null);function Za(){return Ya(fo)}function _a({children:o,name:e}){let[t]=$(),{path:n,router:i,consumedBy:r}=En(),s=Za(),a=s?.name??e,c=a??n+"@default",l=a?i.joinPath(n,a):n,u=Pi(()=>i.createToken(l+"@page")),m=i.getCurrentPath(),p=!a,h=Ja(!1),d=f=>{h.current=f,t()},T=p&&i.exactMatch(m,n)||i.exactMatch(m,l);if(r&&r!==c)throw new b("[PageRouter] Layout Context is consumed by a different page. This is likely caused by a nested page/layout inside a page.");kn(),Li(f=>{let S=p&&f.exactMatch(f.getCurrentPath(),n)||f.exactMatch(f.getCurrentPath(),l);if(h.current&&!S){if(!o){d(!1);return}f.registerUnmountingPath(u)}S&&f.isPathsUnmounting()&&f.unregisterUnmountingPath(u),S&&!h.current&&!f.isTransitioning()&&d(!0)},[T,o]),Vr(()=>{if(!T)return;let f=p?i.mountDefaultHandler(l):i.mount(l);return i.emitOnPageMount(),()=>{f.cancel()}},[l,T]),Vr(()=>()=>{i.unregisterUnmountingPath(u),d(!1)},[]);let y=mo.createElement(Dn,{path:n,consumedBy:c},mo.createElement(Di,{mode:"wait",onExitComplete:()=>{i.unregisterUnmountingPath(u),d(!1)}},T&&h.current&&o));return(f=>s?mo.createElement(fo,{value:{name:null}},f):f)(y)}import ho,{useCallback as ec,useEffect as go,useImperativeHandle as tc,useMemo as Or,useRef as yo,useState as nc}from"react";var ic=50,oc={position:"relative",width:"100%",height:"100%",overflow:"hidden"},Wr={margin:"auto",position:"absolute",top:0,bottom:0,left:0,right:0,display:"flex",alignItems:"center",justifyContent:"center"};function rc(o){return o?Object.entries(o).reduce((e,[t,n])=>(e[`data-${t}`]=n,e),{}):{}}function zr(o,e){return e==null?o:Math.max(o,e)}function sc(o,e,t){return o<=0||e<=0||t<=0?{width:o,height:e}:o/e>t?{width:e*t,height:e}:{width:o,height:o/t}}var Br=ho.forwardRef(function({aspectRatio:e,baseWidth:t,minWidth:n,minHeight:i,debounceMs:r,className:s,style:a,id:c,dataAttributes:l,onUpdate:u,children:m},p){let h=yo(null),[d,T]=nc({...Wr,width:"0px",height:"0px"}),y=yo(u),x=yo(null);go(()=>{y.current=u},[u]);let f=ec(()=>{let q=h.current;if(!q)return;let ae=q.clientWidth,Ve=q.clientHeight;if(ae<=0||Ve<=0||e<=0)return;let Te=sc(ae,Ve,e),ke=zr(Te.width,n),be=zr(Te.height,i),Oe=x.current;(!Oe||Oe.width!==ke||Oe.height!==be)&&(x.current={width:ke,height:be},T({...Wr,width:`${ke}px`,height:`${be}px`}));let Qe=t>0?ke/t:1;y.current?.({width:ke,height:be,scale:Qe,containerWidth:ae,containerHeight:Ve})},[e,t,n,i]),S=Or(()=>Jo(f,typeof r=="number"?r:ic),[f,r]);go(()=>{f()},[f]),go(()=>{let q=new ResizeObserver(()=>{S()});h.current&&q.observe(h.current);let ae=()=>{S()};return window.addEventListener("resize",ae),()=>{q.disconnect(),window.removeEventListener("resize",ae)}},[S]),tc(p,()=>({requestUpdate:f}),[f]);let N=Or(()=>rc(l),[l]);return ho.createElement("div",{id:c,ref:h,style:oc,...N},ho.createElement("div",{className:s,style:{...d,...a}},m))}),$r=Br;function ac(){return C().getLiveGame()}import To from"react";import cc,{createContext as lc,useContext as uc,useEffect as pc,useState as jr}from"react";var dc={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},qr=lc({state:dc,dialogs:[],isActive:!1,isVisible:!1,transitionOptions:null});function ut(){return uc(qr)}function So(){let{dialogs:o}=ut();return o}function mc(){let{isActive:o}=ut();return o}function fc(){let{isVisible:o}=ut();return o}function vo({children:o}){let t=C().getLiveGame().getGameState(),[n,i]=jr(()=>({...t.getNvlState(),dialogs:[...t.getNvlState().dialogs]})),[r,s]=jr(null);pc(()=>{let c=d=>({...d,dialogs:[...d.dialogs]}),l=t.events.on(w.EventTypes["event:state.nvl.enter"],(d,T)=>{i(c(t.getNvlState())),s(T?.showTransition||null)}),u=t.events.on(w.EventTypes["event:state.nvl.exit"],()=>{i(c(t.getNvlState())),s(null)}),m=t.events.on(w.EventTypes["event:state.nvl.dialogAppend"],()=>{i(c(t.getNvlState()))}),p=t.events.on(w.EventTypes["event:state.nvl.visibilityChange"],(d,T)=>{i(c(t.getNvlState())),s(T||null)}),h=t.events.on(w.EventTypes["event:state.nvl.change"],d=>{i(c(d))});return()=>{l.cancel(),u.cancel(),m.cancel(),p.cancel(),h.cancel()}},[t]);let a={state:n,dialogs:n.dialogs,isActive:n.active,isVisible:n.visible,transitionOptions:r};return cc.createElement(qr.Provider,{value:a},o)}import{AnimatePresence as hc,motion as gc}from"motion/react";import yc from"clsx";function bo({children:o,className:e,style:t}){let{isVisible:n,transitionOptions:i}=ut(),{ratio:r}=se(),s=C(),a=i?.duration?i.duration/1e3:.3;return To.createElement(hc,null,n&&To.createElement("div",{className:"absolute inset-0 p-6","data-element-type":"nvl-container-wrapper"},To.createElement(gc.div,{key:"nvl-container",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:a},"data-element-type":"nvl-container",className:yc("w-full h-full overflow-auto",e),style:{transform:s.config.useAspectScale?`scale(${r.state.scale})`:void 0,transformOrigin:"top left",width:s.config.useAspectScale?s.config.width:"100%",height:s.config.useAspectScale?s.config.height:"100%",...t}},o)))}import Ot from"react";function Co({renderDialogItem:o,dialogs:e}){return Ot.createElement(bo,{className:"bg-black/80 text-white p-16 inset-8"},Ot.createElement("div",{"data-element-type":"nvl-dialog-list",className:"flex flex-col space-y-4 p-4"},(e??[]).map((n,i)=>{let r=n.entry.character?Ot.createElement(Dt,{className:"nvl-character-name font-bold mr-2",entry:n.entry}):null,s=Ot.createElement(Pt,{className:"nvl-dialog-text",entry:n.entry,gameState:n.gameState,words:n.words,useTypeEffect:n.useTypeEffect,isActive:n.isActive});return Ot.createElement("div",{key:`${n.entry.id}:${n.isActive?"active":"idle"}`,"data-element-type":"nvl-dialog-item","data-dialog-index":i,className:"nvl-dialog-item"},o?o({entry:n.entry,index:i,isActive:n.isActive,nametag:r,texts:s}):Ot.createElement(Ot.Fragment,null,r,s))})))}import Fe,{useMemo as Sc}from"react";import Qr from"clsx";function vc({children:o,className:e,style:t,renderDialogItem:n}){let i=So(),{state:r}=ut();return Fe.createElement("div",{"data-element-type":"nvl-dialog-list",className:Qr("flex flex-col space-y-4 p-4",e),style:t},i.map((s,a)=>Fe.createElement("div",{key:`${s.id}:${r.activeDialogId===s.id?r.phase:"idle"}`},Fe.createElement(Tc,{entry:s},n?n({entry:s,index:a,isActive:r.activeDialogId===s.id,nametag:s.character?Fe.createElement(Dt,{className:"nvl-character-name font-bold mr-2"}):null,texts:Fe.createElement(Pt,{className:"nvl-dialog-text"})}):o?Fe.Children.map(o,c=>Fe.isValidElement(c)?Fe.cloneElement(c,{entry:s,index:a}):c):Fe.createElement(Xr,{entry:s,index:a})))))}function Xr({entry:o,index:e,className:t,style:n,texts:i}){let r=C(),s=o.character?.state.name||null,a=mt(o.character?.config.color||r.config.defaultTextColor),c=i??Fe.createElement(Pt,{className:"nvl-dialog-text"});return Fe.createElement("div",{"data-element-type":"nvl-dialog-item","data-dialog-index":e,className:Qr("nvl-dialog-item",t),style:n},s&&Fe.createElement("span",{className:"nvl-character-name font-bold mr-2",style:{color:a}},s,":"),c)}function Tc({entry:o,children:e}){let n=C().getLiveGame().getGameState(),i=Sc(()=>o.sentence.evaluate(re.getCtx({gameState:n})),[o.sentence,n]),r=n.getNvlState(),s=r.activeDialogId===o.id,a=s&&r.phase==="typing",c=bi({entry:o,gameState:n,words:i,isActive:s,useTypeEffect:a});return Fe.createElement(Kt,{value:c},e)}function Jr({state:o}){let e=C(),t=at(),n=Ao(null),i=Ao(null),r=Ao(!1),[s]=Je(B.Preferences.skipDelay),[a]=Je(B.Preferences.skipInterval),[c]=Vt("skipAction");return Cc(()=>{if(!e.getLiveGame().gameState.playerCurrent){o.logger.warn("KeyEventAnnouncer","Failed to listen to playerElement events");return}if(!window){o.logger.warn("KeyEventAnnouncer","Failed to listen to window events");return}let u=()=>{i.current&&(clearTimeout(i.current),i.current=null),n.current&&(clearInterval(n.current),n.current=null),r.current=!1},m=h=>{if(e.keyMap.match("skipAction",h.key)&&e.preference.getPreference(B.Preferences.skip)&&!r.current){o.logger.verbose("KeyEventAnnouncer","Skipping");let d=()=>{n.current=setInterval(()=>{o.events.emit(w.EventTypes["event:state.player.skip"],!1)},a)};u(),o.events.emit(w.EventTypes["event:state.player.skip"],!1),r.current=!0,s===0?d():i.current=setTimeout(d,s)}},p=h=>{e.keyMap.match("skipAction",h.key)&&u()};if(e.config.useWindowListener){let h=e.getLiveGame().onWindowEvent("keydown",m).cancel,d=e.getLiveGame().onWindowEvent("keyup",p).cancel;return()=>{u(),h(),d()}}else{let h=e.getLiveGame().onPlayerEvent("keydown",m).cancel,d=e.getLiveGame().onPlayerEvent("keyup",p).cancel;return()=>{u(),h(),d()}}},[t,s,a,c]),Yr.createElement(Yr.Fragment,null)}import Zr,{useEffect as Ac}from"react";function xc(o){let e=o;for(;e;){if(e.hasAttribute("data-layout-path"))return!0;e=e.parentElement}return!1}var _r=['[data-element-type="nvl-container"]','[data-element-type="nvl-dialog-list"]','[data-element-type="nvl-dialog-item"]'],wc=["[data-layout-path]",'[data-element-type="menu"]','[data-element-type="notification"]'];function kc(o,e){return!o||e&&_r.some(t=>!!o.closest(t))?!1:[...wc,..._r].some(t=>!!o.closest(t))}function es(o,e){if(!e)return!1;let t=e.getBoundingClientRect();return o.clientX>=t.left&&o.clientX<=t.right&&o.clientY>=t.top&&o.clientY<=t.bottom}function ts({state:o}){let e=C();return Ac(()=>{let t=e.getLiveGame().gameState?.playerCurrent;if(!t){o.logger.warn("StageClickAnnouncer","Failed to listen to playerElement events");return}let n=i=>{let r=i.target;if(!r||!t.contains(r)||!es(i,t))return;let s=o.mainContentNode;s&&(!s.contains(r)||!es(i,s))||xc(r)||kc(r,o.isNvlMode())||(o.events.emit(w.EventTypes["event:state.player.stageClick"]),o.recordStageClick())};if(e.config.useWindowListener){let i=e.getLiveGame().onWindowEvent("click",n);return()=>{i.cancel()}}else{let i=e.getLiveGame().onPlayerEvent("click",n);return()=>{i.cancel()}}},[e,o]),Zr.createElement(Zr.Fragment,null)}import{useEffect as Ln}from"react";function xo({gameState:o}){let e=o.audioManager,[t]=Je("voiceVolume"),[n]=Je("bgmVolume"),[i]=Je("soundVolume"),[r,s]=Je("globalVolume");return Ln(()=>{s(e.getGlobalVolume())},[]),Ln(()=>{e.setGroupVolume("voice",t)},[t]),Ln(()=>{e.setGroupVolume("bgm",n)},[n]),Ln(()=>{e.setGroupVolume("sound",i)},[i]),Ln(()=>{e.setGlobalVolume(r)},[r]),null}import{useEffect as Ri,useRef as Dc}from"react";import wo,{createContext as Ec,useContext as Pc,useState as ns}from"react";var Wt=class Wt{constructor(){this.preloaded=[];this.events=new W}add(e){let t=this.getSrc(e);return t&&this.has(t)?this:(this.preloaded.push(e),this.events.emit(Wt.EventTypes["event:preloaded.add"],e),this.events.emit(Wt.EventTypes["event:preloaded.change"]),this)}get(e){return this.preloaded.find(t=>this.getSrc(t)===e)}has(e){return Array.isArray(e)?e.every(t=>this.has(t)):this.preloaded.some(t=>this.getSrc(t)===e)}remove(e){if(Array.isArray(e)){let n=e.map(i=>this.getSrc(i));return this.preloaded=this.preloaded.filter(i=>!n.includes(this.getSrc(i))),this}let t=this.getSrc(e);return this.preloaded=this.preloaded.filter(n=>this.getSrc(n)!==t),this.events.emit(Wt.EventTypes["event:preloaded.remove"],e),this.events.emit(Wt.EventTypes["event:preloaded.change"]),this}clear(){return this.preloaded=[],this}getSrc(e){return Ae.getSrc(e)}};Wt.EventTypes={"event:preloaded.add":"event:preloaded.add","event:preloaded.remove":"event:preloaded.remove","event:preloaded.change":"event:preloaded.change","event:preloaded.mount":"event:preloaded.mount","event:preloaded.ready":"event:preloaded.ready","event:preloaded.unmount":"event:preloaded.unmount"};var Ke=Wt;var Ii=class o{constructor(e){this.game=e;this.src=new Map;this.preloadTasks=new Map;this.game.addSideEffect(()=>{this.abortAll(),this.src.clear()})}static getImage(e,t,n){return _o(e,{...n,signal:t})}has(e){return this.src.has(e)}add(e,t){return this.src.set(e,t),this}remove(e){return this.src.delete(e),this}get(e){return this.src.get(e)}clear(){return this.src.clear(),this}size(){return this.src.size}isPreloading(e){return this.preloadTasks.has(e)}preload(e,t){if(this.src.has(t)||this.preloadTasks.has(t)){let m={abort:()=>{},onFinished:()=>m,onErrored:()=>m};return m}let n=t,i={};this.game.hooks.rawTrigger("preloadImage",()=>[n,(m,p)=>{n=m,i={...i,...p}}]);let r=new AbortController,s=r.signal,a=[],l={promise:o.getImage(n,s,i).then(m=>{this.preloadTasks.delete(t),m&&this.add(t,m)}).catch(m=>{e.logger.error("ImageCacheManager",`Failed to preload image: ${t}`,`Reason: ${m}`),a.forEach(p=>p(m))}),controller:r};this.preloadTasks.set(t,l);let u={abort:()=>{r.abort(),this.preloadTasks.delete(t)},onFinished:m=>(l.promise.then(m),u),onErrored:m=>(a.push(m),u)};return u}abortAll(){this.preloadTasks.forEach(e=>{e.controller.abort()}),this.preloadTasks.clear()}abort(e){let t=this.preloadTasks.get(e);t&&(t.controller.abort(),this.preloadTasks.delete(e))}preloadedSrc(){return Array.from(this.src.values())}filter(e){for(let t of this.src.keys())e.includes(t)||this.src.delete(t);return this}};var ko=Ec(null);function is({children:o}){let e=C(),[t]=ns(()=>new Ke),[n]=ns(()=>new Ii(e));return wo.createElement(wo.Fragment,null,wo.createElement(ko,{value:{preloaded:t,cacheManager:n}},o))}function nn(){if(!ko)throw new Error("usePreloaded must be used within a PreloadedProvider");return Pc(ko)}function os({state:o}){let{preloaded:e,cacheManager:t}=nn(),n=C(),i=Dc(new Set),[r]=$(),s="Preload",a=o.getLastScene()||o.getPreloadingScene(),c=n.getLiveGame().stackModel?.getTopSync()?.node?.action||null,l=n.getLiveGame().story;function u(){o.logger.debug(s,"Preload unmounted"),e.events.emit(Ke.EventTypes["event:preloaded.unmount"])}return Ri(()=>o.events.on(w.EventTypes["event:state:flushPreloadedScenes"],()=>{r()}).cancel,[]),Ri(()=>{if(typeof fetch>"u")return e.events.emit(Ke.EventTypes["event:preloaded.ready"]),o.logger.warn(s,"Fetch is not supported in this environment, skipping preload"),u;if(!n.config.preloadAllImages)return e.events.emit(Ke.EventTypes["event:preloaded.ready"]),o.logger.debug(s,"Preload all images is disabled, skipping preload"),u;if(n.config.forceClearCache&&(t.clear(),o.logger.weakWarn(s,"Cache cleared")),!l||!a)return o.logger.weakWarn(s,"Story/Scene not found, skipping preload"),u;let m=performance.now(),p=Ae.catSrc([...a.srcManager?.src||[],...a.srcManager?.getFutureSrc()||[]]),h=new pn(n.config.preloadConcurrency,n.config.preloadDelay),d=[],T=o.logger.group(s,!0),y=[];o.logger.debug(s,"preloading:",p,a);for(let x of p.image){let f=Ae.getSrc(x);if(f){if(d.push(f),t.has(f)||t.isPreloading(f)||y.includes(f)){o.logger.debug(s,`Image already loaded (${p.image.indexOf(x)+1}/${p.image.length})`,f),y.push(f);continue}y.push(f),h.addTask(()=>new Promise(S=>{t.preload(o,f).onFinished(()=>{o.logger.debug(s,`Image loaded (${p.image.indexOf(x)+1}/${p.image.length})`,f),S()}).onErrored(()=>{o.logger.weakError(s,`Failed to preload image (${p.image.indexOf(x)+1}/${p.image.length})`,f),S()})}))}}return T.end(),h.start().then(()=>{o.logger.info(s,"Image preload",`loaded ${t.size()} images in ${performance.now()-m}ms`),n.config.waitForPreload&&e.events.emit(Ke.EventTypes["event:preloaded.ready"]),t.filter(d)}),n.config.waitForPreload||e.events.emit(Ke.EventTypes["event:preloaded.ready"]),e.events.emit(Ke.EventTypes["event:preloaded.mount"]),u},[a,l]),Ri(()=>{i.current.clear()},[a]),Ri(()=>{if(typeof fetch>"u"||n.config.preloadAllImages)return;if(!l){o.logger.weakWarn(s,"Story not found, skipping preload");return}let m=performance.now(),p=n.getLiveGame().getAllPredictableActions(l,c,n.config.maxPreloadActions).map(f=>Ae.getPreloadableSrc(l,f)).filter(function(f){return f!==null});p.filter(function(f){return f?.activeType==="scene"}).forEach(f=>{i.current.has(f)||i.current.add(f)});let d=Ae.catSrc([...i.current,...p]),T=new pn(n.config.preloadConcurrency,n.config.preloadDelay),y=[],x=o.logger.group(s);o.logger.debug(s,"preloading:",d);for(let f of d.image){let S=Ae.getSrc(f);if(S){if(y.push(S),t.has(S)||t.isPreloading(S)){o.logger.debug(s,`Image already loaded (${d.image.indexOf(f)+1}/${d.image.length})`,S);continue}T.addTask(()=>new Promise(N=>{t.preload(o,S).onFinished(()=>{o.logger.debug(s,`Image loaded (${d.image.indexOf(f)+1}/${d.image.length})`,S),N()}).onErrored(()=>{o.logger.weakError(s,`Failed to preload image (${d.image.indexOf(f)+1}/${d.image.length})`,S),N()})}))}}x.end(),T.start().then(()=>{o.logger.info(s,"Image preload (quick reload)",`loaded ${t.size()} images in ${performance.now()-m}ms`),t.filter(y)})},[c,l]),null}import Lc from"clsx";import pt,{useCallback as Eo,useMemo as Ic,useRef as Rc}from"react";function Po({prompt:o,choices:e,afterChoose:t,state:n,words:i}){let r=C(),s=Rc([]),a=Eo(h=>(s.current.push(h),s.current.indexOf(h)),[]),c=Eo(h=>{let d=s.current.indexOf(h);d!==-1&&s.current.splice(d,1)},[]),l=Eo(h=>s.current.indexOf(h),[]),u=r.config.menu,m=Ic(()=>e.map(h=>({...h,words:h.prompt.evaluate(re.getCtx({gameState:n}))})),[]);function p(h){t(h)}return pt.createElement(pt.Fragment,null,pt.createElement(lo,{value:{evaluated:m,choose:p,gameState:n}},pt.createElement(uo,{value:{register:a,unregister:c,getIndex:l}},pt.createElement(ct,{className:"absolute"},o&&pt.createElement(An,{gameState:n,action:{sentence:o,words:i,character:null},useTypeEffect:!1})),pt.createElement(Ft.Div,{color:"green",border:"dashed",className:Lc("absolute"),style:{width:`${r.config.width}px`,height:`${r.config.height}px`}},pt.createElement(u,{items:m.map((h,d)=>d)})))))}function rs({items:o}){return pt.createElement(yi,{className:"absolute flex flex-col items-center justify-center min-w-full w-full h-full"},o.map(e=>pt.createElement(xi,{key:e,className:"bg-white text-black p-2 mt-2 w-1/2"})))}import Ui from"react";import Ni from"react";import Do,{useEffect as ss,useLayoutEffect as as,useRef as cs,useState as Lo}from"react";function on({element:o,state:e,skipTransform:t,skipTransition:n,overwriteDefinition:i,onTransform:r,onTransition:s,transitionsProps:a=[],propOverwrite:c}){let[l,u]=Lo(null),[m,p]=Lo(null),h=Do.useRef(null),[d]=Lo(()=>new zn("displayable.refGroup")),T=cs(d.next()),y=cs(Qe()),f=C().getLiveGame().getGameState(),S=typeof a=="function"?a(l):a,[N]=$([m,l,y]);ss(()=>f.events.depends([f.events.on(w.EventTypes["event:state.player.skip"],Oe)]).cancel,[m,l,y]),as(()=>{if(q(),!l)return;if(y.current.some(([ce])=>!ce.current))throw new b("Displayable: Trying to access transition groups before they are mounted");let{controller:P,task:Q}=l;return P.onUpdate(ce=>{y.current.forEach(([We],et)=>{let D=Q.resolve[et],L=typeof D=="function"?D:D.resolver;if(!L)throw new b(`Displayable: Trying to resolve element props but found no resolver. (reading: transitionTask.task.resolve[${et}])`);let ie=L(...ce),J=I(S[et]||S[S.length-1]||{},ie);Ve(We,c?c(J):J)})}).cancel},[l]),ss(()=>{if(!h.current)throw new Error(`Scope not ready. Using element: ${o.constructor.name}`)},[]),as(()=>{let P=e.toStyle(f,i);Object.assign(h.current.style,P),f.logger.debug("Displayable","Initial style applied",h.current,P)},[]);function q(){let P=typeof a=="function"?a(l):a;if(!y.current||!y.current.length)throw new b("Displayable: Transition group refs are not initialized correctly");if(y.current.some(([Q])=>!Q.current))throw new b("Displayable: Trying to access transition groups before they are mounted");y.current.forEach(([Q],E)=>{if(!Q.current)throw new b("Displayable: Trying to assign properties to unmounted element");Ve(Q,P[E]||P[P.length-1]||{})})}function ae(P){f.logger.debug("Displayable","Transform applied",e.toStyle(f,i),h.current),N(),r?.(P)}function Ve(P,Q){if(!P.current)throw new b("Displayable: Trying to assign properties to unmounted element");let E=P.current,ce={},We={};Object.keys(Q).forEach(D=>{let L=D;L==="style"&&Q.style?Object.assign(ce,Q.style):Q[L]!==void 0&&L!=="key"&&(We[L]=Q[L])}),Object.keys(ce).length>0&&Object.assign(E.style,ce);let et=c?c(We):We;for(let[D,L]of Object.entries(et))E.getAttribute(D)!==L&&E.setAttribute(D,L)}function Te(P,Q){m&&(m.abort(),p(null));let E=P.animate(e,{gameState:f,ref:h,overwrites:i}),ce=new fe(E);return f.timelines.attachTimeline(ce),E.onSkipControllerRegister(We=>{We.onAbort(()=>{ce.abort(),p(null)})}),p(E),E.then(()=>{p(null),ae(P),Q()}),ce}function ke(P,Q){l&&l.controller.complete();let E=P.createTask(f),ce=P.requestAnimations(E.animations),We=new g().registerSkipController(new M(ce.cancel)),et=new fe(We);We.skipController.onAbort(()=>{ce.cancel()}),ce.onCanceled(()=>{et.abort(),u(null),f.logger.debug("Displayable","Transition cancelled",P)}),f.timelines.attachTimeline(et),u({task:E,controller:ce,transition:P,resolve:Q});let D;if(y.current=E.resolve.map(ie=>{let J=Do.createRef(),Ce=typeof ie=="function"?void 0:ie.key;if(!Ce)return[J,d.next()];if(Ce==="target")return D=d.next(),[J,D];if(Ce==="current")return[J,T.current];throw new b("Displayable: Invalid key type")}),!D)throw new b("Displayable: No target key found");T.current=D;let L=y.current.map(([ie])=>{let J=ie.current;return J?.waitForLoad?J.waitForLoad():Promise.resolve()});return Promise.all(L).then(()=>{ce.start(),ce.onComplete(()=>{ue(),u(null),s?.(P),Q(),We.resolve()})}),et}function be(P){return f.logger.debug("initDisplayable",o),Te(z.immediate(e.get()),P)}function Oe(){t&&m&&(m.abort(),p(null),f.logger.debug("transform skipped")),n&&l&&(l.controller.complete(),f.logger.debug("transition skipped"))}function Qe(){return[[Do.createRef(),T.current]]}function ue(){y.current.forEach(([P])=>{P.current=null}),y.current=Qe()}return{transformRef:h,transitionRefs:y.current,isTransforming:!!m,transitionTask:l,initDisplayable:be,applyTransform:Te,applyTransition:ke,updateStyleSync:q,deps:[m,l,y]}}import{useEffect as Nc}from"react";function Lt(o,e,t=[]){let i=C().getLiveGame().getGameState();return Nc(()=>{let r=typeof e=="function"?e():e;return i.mountState(o,r).unMount},[...t]),[]}function Io({state:o,text:e}){let{ratio:t}=se(),[n]=$(),{transformRef:i,transitionRefs:r,initDisplayable:s,applyTransform:a,applyTransition:c,updateStyleSync:l,deps:u,isTransforming:m}=on({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipTextTransform,skipTransition:o.game.config.allowSkipTextTransition,overwriteDefinition:{overwrite:p=>({width:"fit-content",transform:z.propToCSSTransform(o,p,{translate:[e.config.alignX==="left"?"0%":e.config.alignX==="right"?"-100%":void 0,e.config.alignY==="top"?"100%":e.config.alignY==="bottom"?"0%":void 0]})})},transitionsProps:[{style:{width:"fit-content",whiteSpace:"nowrap",transform:`scale(${t.state.scale})`,transformOrigin:`${e.config.alignX} ${e.config.alignY}`,fontSize:`${e.state.fontSize}px`}}]});return Lt(e,{initDisplayable:s,applyTransform:a,applyTransition:c,flush:n,updateStyleSync:l},[...u]),Ni.createElement(Ft.Div,{"data-element-type":"text"},Ni.createElement(Ft.mDiv,{tag:"text.container",color:"green",border:"dashed",layout:m,ref:i,className:"absolute"},r.map(([p,h])=>Ni.createElement("span",{key:h,ref:p,className:e.config.className},Ni.createElement("span",null,e.state.text)))))}import rn,{useRef as ps,useState as ds}from"react";import Mi,{useEffect as Ro,useRef as Gi,forwardRef as Mc}from"react";var ls=Mc(({onSizeChanged:o,onLoad:e,autoFit:t=!1},n)=>{let i=Gi(null),{ratio:r}=se(),[s,a]=Mi.useState(()=>r.state.width),[c,l]=Mi.useState(()=>r.state.height),u=C(),m=Gi(!1),p=Gi(null),h=Gi(null);Mi.useImperativeHandle(n,()=>i.current,[]),Ro(()=>{i.current&&Object.defineProperties(i.current,{isLoaded:{value:()=>m.current,configurable:!0},waitForLoad:{value:()=>m.current?Promise.resolve():(p.current||(p.current=new Promise(y=>{h.current=y})),p.current),configurable:!0}})},[]),Ro(()=>(d(),r.onUpdate(d)),[o]),Ro(()=>{let y=new MutationObserver(x=>{x.forEach(f=>{f.type==="attributes"&&f.attributeName==="src"&&i.current&&d()})});return i.current&&y.observe(i.current,{attributes:!0}),()=>{y.disconnect()}},[o]);function d(){if(i.current&&i.current.naturalWidth)if(i.current.naturalWidth*i.current.naturalHeight===1){let y=r.state.width,x=r.state.height,f=`${y} / ${x}`;a(y),l(x),i.current.style.aspectRatio=f,o&&o(y,x)}else{let y=t?u.config.width/i.current.naturalWidth:1,x=i.current.naturalWidth*r.state.scale*y,f=i.current.naturalHeight*r.state.scale*y;a(x),l(f),i.current.style.aspectRatio="auto",o&&o(x,f)}}function T(){d(),m.current=!0,h.current&&(h.current(),h.current=null,p.current=null),e&&e()}return Mi.createElement("img",{ref:i,onLoad:T,width:s,height:c,alt:""})});ls.displayName="AspectScaleImage";var us=ls;import ms from"clsx";import{motion as Gc}from"motion/react";function Hi({image:o,state:e}){let[t]=ds(()=>new W),[n,i]=ds([]),{cacheManager:r}=nn(),s=ps([]),a=ps(null),{transformRef:c,transitionRefs:l,isTransforming:u,initDisplayable:m,applyTransition:p,applyTransform:h,updateStyleSync:d,deps:T}=on({element:o,state:o.transformState,skipTransform:e.game.config.allowSkipImageTransform,skipTransition:e.game.config.allowSkipImageTransition,transitionsProps:f=>{let S=f?f.transition._getCurrentSrc():o.state.currentSrc;return[{style:{willChange:"filter",position:"absolute",transformOrigin:"center",backgroundColor:A.isColor(S)?A.colorToString(S):void 0,transform:"none",top:"auto",left:"auto",right:"auto",bottom:"auto",filter:`brightness(${1-o.state.darkness})`},src:A.isImageSrc(S)?A.srcToURL(S):G.DefaultImagePlaceholder},{style:{willChange:"filter",position:"absolute",transformOrigin:"center",transform:"translate(-50%, -50%)",top:"50%",left:"50%",right:"auto",bottom:"auto",maxWidth:"none",maxHeight:"none",filter:"brightness(1)"}}]},propOverwrite:f=>f.src?(!A.isDataURI(f.src)&&!r.has(f.src)&&!r.isPreloading(f.src)&&!s.current.includes(f.src)&&(e.game.getLiveGame().getGameState()?.logger.warn("Image",`Image not preloaded: "${f.src}".
36
+ `:yield{text:r,config:n.config,tag:t,tag2:i,cps:n.config.cps}}}}function yo(o){let e=vo(o),t=[];for(let n of e)we.isPause(n)||t.push(n);return t}function Jr(o,e){o(t=>{let n=t[t.length-1];return n&&n!==`
37
+ `&&e!==`
38
+ `&&n.tag===e.tag?[...t.slice(0,-1),{...e,text:n.text+e.text,config:e.config}]:[...t,e]})}function Ka(o,e,t){return t||(o!==void 0?ie.formatStaticWord(o):e?e.text.flatMap(n=>typeof n.text=="function"?[]:new W(n.text,n.config)):[])}function Va(o,e,t){let n=Math.max(0,e??t);return typeof o=="object"?{enabled:o.enabled??!0,delay:Math.max(0,o.delay??n)}:{enabled:o??!0,delay:n}}function Xr(o,e){let t=Math.max(.01,o),n=Math.max(.01,e);return 1e3/(t*n)}function So({defaultColor:o,className:e,style:t,dialog:n,...i}){let r=w(),s=r.getLiveGame().getGameState(),a=Yr(null),[c,l]=go(()=>n&&!n.config.useTypeEffect?yo(n.config.evaluatedWords):[]),[p,u]=Z();if(!n)throw new Error("Dialog state is required");un(()=>{if(!(!n.config.action.sentence||a.current))return s.logger.info("Initializing the sentence",n,a.current),s.schedule(({onCleanup:S})=>{if(!n.config.useTypeEffect){n.dispatchComplete();return}l([]),a.current=d(),p(),a.current.onComplete(()=>{n.dispatchComplete()}),S(()=>{a.current?.timeline?.abort()})},0)},[]),un(()=>n.events.depends([n.events.on(fe.Events.requestComplete,()=>{a.current?.interact()}),n.events.on(fe.Events.forceSkip,()=>{n.isEnded()||a.current?.forceSkip()})]).cancel,[n,u]),un(()=>r.preference.events.depends([r.preference.onPreferenceChange(Q.Preferences.gameSpeed,()=>{a.current?.update()}),r.preference.onPreferenceChange(Q.Preferences.autoForward,()=>{a.current?.update()}),r.preference.onPreferenceChange(Q.Preferences.cps,()=>{a.current?.update()})]).cancel,[]);function d(){let S=new y,f=new Te(S).setGuard(s.guard),T=new Set,C=new Set,I=new Set,N=vo(n.config.evaluatedWords),X=null,he=[],ge=[],ye=()=>{he.forEach(M=>M()),he.length=0},Re=()=>{if(ge.length!==0)return{done:!1,value:ge.shift()};let{done:M,value:K}=N.next();return{done:M,value:K}},Ne=M=>{let K=ee=>{M(ee),C.delete(K)};return C.add(K),{cancel:()=>{C.delete(K)}}},ot=M=>{Jr(l,M)},R=(M=!1)=>{let K=!1;for(;!K;){let{done:ee,value:oe}=Re();if(ee){K=!0;break}if(we.isPause(oe)){if(M)continue;K=!0,ge.push(oe);break}else oe===`
39
+ `?l(E=>[...E,oe]):typeof oe=="object"&&"text"in oe&&!T.has(oe)&&(T.add(oe),ot(oe))}X&&!X.isSettled()?X.abort():(I.forEach(ee=>ee()),S.resolve())};return s.schedule(async M=>{let K=!1,ee=!1;for(;!K;){let{done:oe,value:E}=Re();if(oe){K=ee=!0;break}let Ge=new y;if(s.timelines.attachTimeline(Ge),Ge.registerSkipController(new G(()=>{ye(),K=!0,M.retry()})),Ge.onSettled(()=>{ye()}),X=Ge,we.isPause(E)){let Yt=we.from(E),gt=r.preference.getPreference(Q.Preferences.gameSpeed);if(Yt.config.duration){let Gt=Yt.config.duration/gt;await _n(Gt)}else{let Gt=r.preference.getPreference(Q.Preferences.autoForward),hn=y.race([y.create(Ht=>{let gn=Ne(yt=>{yt(),Ht.resolve()});he.push(()=>gn.cancel())}),...Gt?[y.delay(r.config.autoForwardDefaultPause/gt)]:[]]);s.timelines.attachTimeline(hn),await y.wait(hn)}}else{if(E!==`
40
+ `&&T.has(E))continue;T.add(E),ot(E);let{gameSpeed:Yt,cps:gt}=r.preference.getPreferences(),hn=1e3/((typeof E=="object"&&"cps"in E&&E.cps!==void 0?E.cps:gt)*Yt);await _n(hn)}}ee&&(I.forEach(oe=>oe()),S.resolve())},0),{getToken:()=>S,interact:()=>{let M=!1;C.forEach(K=>K(()=>M=!0)),!M&&R()},update:()=>{X&&X.abort()},forceSkip:()=>{R(!0)},timeline:f,onComplete:M=>(I.add(M),{cancel:()=>{I.delete(M)}})}}let h=n.config.action.sentence;if(!h)return null;let m={fontWeight:h.config.bold?r.config.fontWeightBold:r.config.fontWeight,fontSize:h.config.fontSize??r.config.fontSize,color:Ye(h.config.color??r.config.defaultTextColor),fontFamily:h.config.fontFamily??r.config.fontFamily,fontStyle:h.config.italic?"italic":void 0},v=S=>({fontWeight:S.config.bold||h.config.bold?r.config.fontWeightBold:r.config.fontWeight,fontSize:S.config.fontSize??h.config.fontSize??r.config.fontSize,color:Ye(S.config.color??h.config.color??o??r.config.defaultTextColor),fontFamily:S.config.fontFamily??h.config.fontFamily??r.config.fontFamily,fontStyle:S.config.italic??h.config.italic?"italic":void 0}),g=(S,f)=>S===`
41
+ `?Pe.createElement("br",{key:f}):Pe.createElement(zt.Span,{tag:`say.word.${f}`,key:f,style:{...v(S),...ei(r.config.app.debug,{outline:"1px dashed red"})},className:Pi("inline-block break-all",S.config.className)},S.config.ruby?Pe.createElement("ruby",{className:"align-bottom inline-block"},Pe.createElement("rt",{className:"block text-center"},S.config.ruby),S.text):S.text);return Pe.createElement("div",{...i,className:Pi("whitespace-pre-wrap",e),style:{...t,...m}},c.map(g))}function Oa({text:o,sentence:e,words:t,useTypeEffect:n=!0,loop:i=!0,restartDelay:r,cps:s,gameSpeed:a,pauseDuration:c,defaultColor:l,className:p,style:u,fontSize:d,fontWeight:h,fontWeightBold:m,fontFamily:v,onCompleted:g,...S}){let f=Hr(),[,T]=go(0),C=f?.config??Q.DefaultConfig,I=f?.preference.getPreferences()??Q.DefaultPreference,N=s??I.cps,X=a??I.gameSpeed,he=c??C.autoForwardDefaultPause,ge=r??C.autoForwardDefaultPause,ye=Pe.useMemo(()=>Ka(o,e,t),[o,e,t]),Re=Pe.useMemo(()=>Va(i,r,ge),[i,r,ge]),Ne=Yr(g),[ot,R]=go(()=>n?[]:yo(ye));un(()=>{if(f)return f.preference.onPreferenceChange(()=>{T(E=>E+1)}).cancel},[f]),un(()=>{Ne.current=g},[g]),un(()=>{let E=!1,Ge=[],Yt=Math.max(.01,X),gt=Ht=>new Promise(gn=>{let yt=setTimeout(gn,Math.max(0,Ht));Ge.push(yt)}),Gt=()=>{E||Ne.current?.()};return n?ye.length===0?(R([]),()=>{E=!0}):((async()=>{do{let Ht=vo(ye);for(R([]);!E;){let{done:gn,value:yt}=Ht.next();if(gn)break;if(we.isPause(yt)){let Ys=we.from(yt);await gt((Ys.config.duration??he)/Yt)}else Jr(R,yt),yt===`
42
+ `?await gt(Xr(N,X)):await gt(Xr(yt.cps??N,X))}if(E)return;Gt(),Re.enabled&&await gt(Re.delay)}while(!E&&Re.enabled)})(),()=>{E=!0,Ge.forEach(Ht=>clearTimeout(Ht))}):(R(yo(ye)),Gt(),()=>{E=!0})},[ye,n,Re,N,X,he]);let L=e?.config,z=h??C.fontWeight,$=m??C.fontWeightBold,P=d??C.fontSize,M=v??C.fontFamily,K={fontWeight:L?.bold?$:z,fontSize:L?.fontSize??P,color:Ye(L?.color??l??C.defaultTextColor),fontFamily:L?.fontFamily??M,fontStyle:L?.italic?"italic":void 0},ee=E=>({fontWeight:E.config.bold||L?.bold?$:z,fontSize:E.config.fontSize??L?.fontSize??P,color:Ye(E.config.color??L?.color??l??C.defaultTextColor),fontFamily:E.config.fontFamily??L?.fontFamily??M,fontStyle:E.config.italic??L?.italic?"italic":void 0}),oe=(E,Ge)=>E===`
43
+ `?Pe.createElement("br",{key:Ge}):Pe.createElement("span",{key:Ge,style:ee(E),className:Pi("inline-block break-all",E.config.className)},E.config.ruby?Pe.createElement("ruby",{className:"align-bottom inline-block"},Pe.createElement("rt",{className:"block text-center"},E.config.ruby),E.text):E.text);return Pe.createElement("div",{...S,className:Pi("whitespace-pre-wrap",p),style:{...u,...K}},ot.map(oe))}function Zr(o){return Pe.createElement(So,{...o,key:o.dialog?.config.action.id})}function Wa({entry:o,gameState:e,words:t,useTypeEffect:n,isActive:i,...r}){let s=ki({entry:o,gameState:e,words:t,useTypeEffect:n,isActive:i});return Pe.createElement(So,{...r,dialog:s,key:s.config.action.id})}function za(o){let e=et();return Pe.createElement(So,{...o,dialog:e,key:e.config.action.id})}function Rt(o){return"entry"in o&&o.entry&&"gameState"in o&&o.gameState&&"words"in o&&o.words?Pe.createElement(Wa,{...o}):Pe.createElement(za,{...o})}var Ba=Rt;import Di,{useEffect as $a,useLayoutEffect as ja,useMemo as ts,useRef as qa,useState as Qa}from"react";import Ei from"react";var To=Ei.createContext(null);function _r(){let o=Ei.useContext(To);if(!o)throw new Error("useUIMenuContext must be used within a UIMenuContext");return o}var bo=Ei.createContext(null);function es(){let o=Ei.useContext(bo);if(!o)throw new Error("useUIListContext must be used within a UIListContext");return o}function Li({className:o,style:e,bindKey:t}){let n=qa(null),{register:i,unregister:r,getIndex:s}=es(),[a,c]=Qa(-1),{choose:l,evaluated:p,gameState:u}=_r(),d=a===-1?null:p[a],h=ts(()=>ue.getCtx({gameState:u}),[u]),{hidden:m,disabled:v}=ts(()=>{if(!d)return{hidden:!1,disabled:!1};let f=d.config.hidden?.evaluate(h)?.value??!1,T=!f&&(d.config.disabled?.evaluate(h)?.value??!1);return{hidden:f,disabled:T}},[d,h]);ja(()=>{if(!n.current)return;let f=n;i(f);let T=s(f);return c(T),n.current.dataset.index=T.toString(),()=>r(f)},[i,r,s]),$a(()=>{if(!t)return;let f=T=>{T.key.toLowerCase()===t.toLowerCase()&&!T.ctrlKey&&!T.metaKey&&(T.preventDefault(),T.stopPropagation(),g())};return window.addEventListener("keydown",f,!0),()=>{window.removeEventListener("keydown",f,!0)}},[t]);function g(){if(a===-1||!p[a]||m||v)return;let f=p[a];l({...f,evaluated:W.getText(f.words||[])})}let S=d&&!m;return Di.createElement(Di.Fragment,null,Di.createElement("button",{className:o,style:{...e,display:S?e?.display??void 0:"none"},onClick:g,ref:n,disabled:v},S&&Di.createElement(Zr,{dialog:new fe({useTypeEffect:!1,action:{sentence:d.prompt,words:d.words,character:null},gameState:u,evaluatedWords:d.words})})))}import Ii from"react";import{AnimatePresence as Xa}from"motion/react";function Ri({children:o,...e}){let t=Xa;return Ii.createElement(Ii.Fragment,null,Ii.createElement("div",{...e},Ii.createElement(t,null,o)))}import Nn from"react";function Nt({entry:o,character:e,...t}){let n=Nn.useContext(Bt),i=w(),r=e??o?.character??n?.config.action.character??null;return Nn.createElement(Nn.Fragment,null,Nn.createElement("div",{...t},Nn.createElement("span",{style:{color:Ye(r?.config.color||i.config.defaultNametagColor)}},r?.state.name)))}import Ya from"clsx";import Ja from"react";function ns(){let o=et(),{action:e,gameState:t}=o.config,n=e.character,i=e.sentence;if(!n||!i||!n.state.name)return ec(n||null,null);let r=t.findCurrentPortraitForCharacter(n),s=r?.image||null,a=s?U.getSrcURL(s):null,c=s&&U.isTagSrc(s)?[...s.state.currentSrc]:null,l=Lr({character:n,sentence:i,portrait:s,currentSrc:a,tags:c,gameState:t,sentenceAvatar:i.config.avatar,portraitAvatar:r?.avatar,characterAvatar:n.config.avatar}),p=_a(l.source);return{visible:!!p,src:p,character:l.character,portrait:l.portrait,alt:n.state.name?`${n.state.name} avatar`:"dialog avatar"}}function Za({className:o,style:e,alt:t,...n}){let i=ns();return!i.visible||!i.src?null:Ja.createElement("img",{...n,"data-element-type":"dialog-avatar",className:Ya("dialog-avatar",o),src:i.src,alt:t??i.alt,style:{width:96,height:96,objectFit:"cover",borderRadius:6,flex:"0 0 auto",...e}})}function _a(o){return o?A.srcToURL(o):null}function ec(o,e){return{visible:!1,src:null,character:o,portrait:e,alt:o?.state.name?`${o.state.name} avatar`:"dialog avatar"}}var Ao=Za;import{useEffect as tc}from"react";function nc(){let o=et(),[e]=Z(o.deps),t=W.getText(o.config.evaluatedWords);return tc(()=>o.events.on(fe.Events.onFlush,()=>{e()}).cancel,[o]),{done:o.isEnded(),text:t,isNarrator:o.config.action.character===null||o.config.action.character.state.name==="",metadata:o.config.action.sentence?.getMetadata()}}import{useCallback as Ni,useEffect as Co,useMemo as ic,useRef as oc,useState as is}from"react";function rc(){let o=et(),[e]=Z(o.deps),[t,n]=is(!0),[i,r]=is(!0),s=oc(null),a=o.config.gameState,c=o.config.action.sentence,l=c?.config.voiceId??null;Co(()=>o.events.on(fe.Events.onFlush,()=>{e()}).cancel,[o]);let p=ic(()=>{if(!c)return null;try{return Ze.getVoice(a,c)}catch{return null}},[a,c,l,c?.config.voice]);Co(()=>{s.current=null,r(!0)},[c]),Co(()=>{let v=!1,g=null,S=null,f=null;if(!p){n(!0);return}n(!1);let T=()=>{v||n(!0)};g=a.audioManager.getToken(p),g&&(g.isPlaying()||n(!0),S=()=>T(),f=()=>T(),g.once("ended",S),g.once("stop",f));let C=a.events.on(k.EventTypes["event:state.player.lineEnd"],()=>{T()});return()=>{v=!0,C.cancel(),g&&S&&g.off("ended",S),g&&f&&g.off("stop",f)}},[a,p]);let u=Ni(async v=>{let g=v??p;if(!g)return r(!0),null;s.current?.isPlaying()&&s.current.stop(),r(!1);let S=g instanceof URL?re.voice(g.toString()):typeof g=="string"?re.voice(g):g,f=await a.getLiveGame().playSound(S);s.current=f;let T=()=>{r(!0)};return f.once("ended",T),f.once("stop",T),f},[a,p]),d=Ni(()=>p,[p]),h=Ni(()=>l,[l]),m=Ni(()=>p?.getSrc()??null,[p]);return{done:t&&i,voice:p,playVoice:u,getVoice:d,getVoiceId:h,getVoiceSrc:m}}import xo,{createContext as yc,useContext as vc,useEffect as ss,useRef as Sc}from"react";import{useState as sc}from"react";function Mi(o){let[e]=sc(o);return e}import{AnimatePresence as ac}from"motion/react";var Gi=ac;import Un,{createContext as dc,useContext as mc,useEffect as fc,useRef as hc}from"react";import{useEffect as Mn,useLayoutEffect as cc}from"react";function lc(){let o=pt(),[e]=Z();return Mn(()=>o.onChange(e).cancel,[]),o.getPathname()}function uc(){let{router:o,path:e}=Hn(),[t]=Z();return Mn(()=>o.onChange(t).cancel,[]),o.extractParams(o.getCurrentPath(),e)}function pc(){let o=pt(),[e]=Z();return Mn(()=>o.onChange(e).cancel,[]),o.getQueryParams()}function Hi(o,e){let t=pt();cc(()=>t.onUpdate(()=>o(t)).cancel,e),Mn(()=>{o(t)},[])}function Gn(){let o=pt(),[e]=Z();return Mn(()=>o.onChange(e).cancel,[]),e}var os=dc(null);function Fn({children:o,path:e,consumedBy:t}){let i={router:pt(),path:e,consumedBy:t};return Un.createElement(os,{value:i},o)}function Hn(){let o=mc(os);if(!o)throw new Error("useLayout must be used within a LayoutRouterProvider");if(o.path===null)throw new x(`Invalid useLayout call: Trying to access layout without a parent.
44
+ This is likely caused by a nested Layout component or using Page inside a Page. `);return o}function gc({children:o,name:e,propagate:t}){let n=w(),[i]=Z(),{path:r,router:s,consumedBy:a}=Hn(),c=s.joinPath(r,e),l=Mi(()=>s.createToken(c+"@layout")),p=s.getCurrentPath(),u=hc(!1),d=m=>{u.current=m,i()},h=s.matchPath(p,c);if(Gn(),Hi(m=>{let v=m.matchPath(m.getCurrentPath(),c);if(u.current&&!v){if(!o){d(!1);return}m.registerUnmountingPath(l)}v&&m.isPathsUnmounting()&&m.unregisterUnmountingPath(l),v&&!u.current&&!m.isTransitioning()&&d(!0)},[h,o]),fc(()=>{if(!h)return;let m=s.mount(c);return()=>{m.cancel()}},[c,s,h]),a)throw new x("[PageRouter] Layout is consumed by a different layout. This is likely caused by a nested layout inside a layout.");return Un.createElement(Fn,{path:c},Un.createElement(Gi,{mode:"wait",propagate:t??n.config.animationPropagate,onExitComplete:()=>{s.unregisterUnmountingPath(l),d(!1)}},h&&u.current&&o))}function rs({children:o}){return Gn(),Un.createElement(Fn,{path:It.rootPath},Un.createElement(bi,{"data-layout-path":It.rootPath,key:It.rootPath},o))}var wo=yc(null);function Tc(){return vc(wo)}function bc({children:o,name:e}){let[t]=Z(),{path:n,router:i,consumedBy:r}=Hn(),s=Tc(),a=s?.name??e,c=a??n+"@default",l=a?i.joinPath(n,a):n,p=Mi(()=>i.createToken(l+"@page")),u=i.getCurrentPath(),d=!a,h=Sc(!1),m=f=>{h.current=f,t()},v=d&&i.exactMatch(u,n)||i.exactMatch(u,l);if(r&&r!==c)throw new x("[PageRouter] Layout Context is consumed by a different page. This is likely caused by a nested page/layout inside a page.");Gn(),Hi(f=>{let T=d&&f.exactMatch(f.getCurrentPath(),n)||f.exactMatch(f.getCurrentPath(),l);if(h.current&&!T){if(!o){m(!1);return}f.registerUnmountingPath(p)}T&&f.isPathsUnmounting()&&f.unregisterUnmountingPath(p),T&&!h.current&&!f.isTransitioning()&&m(!0)},[v,o]),ss(()=>{if(!v)return;let f=d?i.mountDefaultHandler(l):i.mount(l);return i.emitOnPageMount(),()=>{f.cancel()}},[l,v]),ss(()=>()=>{i.unregisterUnmountingPath(p),m(!1)},[]);let g=xo.createElement(Fn,{path:n,consumedBy:c},xo.createElement(Gi,{mode:"wait",onExitComplete:()=>{i.unregisterUnmountingPath(p),m(!1)}},v&&h.current&&o));return(f=>s?xo.createElement(wo,{value:{name:null}},f):f)(g)}import ko,{useCallback as Ac,useEffect as Po,useImperativeHandle as Cc,useMemo as as,useRef as Eo,useState as xc}from"react";var wc=50,kc={position:"relative",width:"100%",height:"100%",overflow:"hidden"},cs={margin:"auto",position:"absolute",top:0,bottom:0,left:0,right:0,display:"flex",alignItems:"center",justifyContent:"center"};function Pc(o){return o?Object.entries(o).reduce((e,[t,n])=>(e[`data-${t}`]=n,e),{}):{}}function ls(o,e){return e==null?o:Math.max(o,e)}function Ec(o,e,t){return o<=0||e<=0||t<=0?{width:o,height:e}:o/e>t?{width:e*t,height:e}:{width:o,height:o/t}}var us=ko.forwardRef(function({aspectRatio:e,baseWidth:t,minWidth:n,minHeight:i,debounceMs:r,className:s,style:a,id:c,dataAttributes:l,onUpdate:p,children:u},d){let h=Eo(null),[m,v]=xc({...cs,width:"0px",height:"0px"}),g=Eo(p),S=Eo(null);Po(()=>{g.current=p},[p]);let f=Ac(()=>{let I=h.current;if(!I)return;let N=I.clientWidth,X=I.clientHeight;if(N<=0||X<=0||e<=0)return;let he=Ec(N,X,e),ge=ls(he.width,n),ye=ls(he.height,i),Re=S.current;(!Re||Re.width!==ge||Re.height!==ye)&&(S.current={width:ge,height:ye},v({...cs,width:`${ge}px`,height:`${ye}px`}));let Ne=t>0?ge/t:1;g.current?.({width:ge,height:ye,scale:Ne,containerWidth:N,containerHeight:X})},[e,t,n,i]),T=as(()=>ur(f,typeof r=="number"?r:wc),[f,r]);Po(()=>{f()},[f]),Po(()=>{let I=new ResizeObserver(()=>{T()});h.current&&I.observe(h.current);let N=()=>{T()};return window.addEventListener("resize",N),()=>{I.disconnect(),window.removeEventListener("resize",N)}},[T]),Cc(d,()=>({requestUpdate:f}),[f]);let C=as(()=>Pc(l),[l]);return ko.createElement("div",{id:c,ref:h,style:kc,...C},ko.createElement("div",{className:s,style:{...m,...a}},u))}),ps=us;function Dc(){return w().getLiveGame()}import Io from"react";import Lc,{createContext as Ic,useContext as Rc,useEffect as Nc,useState as ds}from"react";var Mc={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},ms=Ic({state:Mc,dialogs:[],isActive:!1,isVisible:!1,transitionOptions:null});function mt(){return Rc(ms)}function Do(){let{dialogs:o}=mt();return o}function Gc(){let{isActive:o}=mt();return o}function Hc(){let{isVisible:o}=mt();return o}function Lo({children:o}){let t=w().getLiveGame().getGameState(),[n,i]=ds(()=>({...t.getNvlState(),dialogs:[...t.getNvlState().dialogs]})),[r,s]=ds(null);Nc(()=>{let c=m=>({...m,dialogs:[...m.dialogs]}),l=t.events.on(k.EventTypes["event:state.nvl.enter"],(m,v)=>{i(c(t.getNvlState())),s(v?.showTransition||null)}),p=t.events.on(k.EventTypes["event:state.nvl.exit"],()=>{i(c(t.getNvlState())),s(null)}),u=t.events.on(k.EventTypes["event:state.nvl.dialogAppend"],()=>{i(c(t.getNvlState()))}),d=t.events.on(k.EventTypes["event:state.nvl.visibilityChange"],(m,v)=>{i(c(t.getNvlState())),s(v||null)}),h=t.events.on(k.EventTypes["event:state.nvl.change"],m=>{i(c(m))});return()=>{l.cancel(),p.cancel(),u.cancel(),d.cancel(),h.cancel()}},[t]);let a={state:n,dialogs:n.dialogs,isActive:n.active,isVisible:n.visible,transitionOptions:r};return Lc.createElement(ms.Provider,{value:a},o)}import{AnimatePresence as Uc,motion as Fc}from"motion/react";import Kc from"clsx";function Ro({children:o,className:e,style:t}){let{isVisible:n,transitionOptions:i}=mt(),{ratio:r}=pe(),s=w(),a=i?.duration?i.duration/1e3:.3;return Io.createElement(Uc,null,n&&Io.createElement("div",{className:"absolute inset-0 p-6","data-element-type":"nvl-container-wrapper"},Io.createElement(Fc.div,{key:"nvl-container",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:a},"data-element-type":"nvl-container",className:Kc("w-full h-full overflow-auto",e),style:{transform:s.config.useAspectScale?`scale(${r.state.scale})`:void 0,transformOrigin:"top left",width:s.config.useAspectScale?s.config.width:"100%",height:s.config.useAspectScale?s.config.height:"100%",...t}},o)))}import jt from"react";function No({renderDialogItem:o,dialogs:e}){return jt.createElement(Ro,{className:"bg-black/80 text-white p-16 inset-8"},jt.createElement("div",{"data-element-type":"nvl-dialog-list",className:"flex flex-col space-y-4 p-4"},(e??[]).map((n,i)=>{let r=n.entry.character?jt.createElement(Nt,{className:"nvl-character-name font-bold mr-2",entry:n.entry}):null,s=jt.createElement(Rt,{className:"nvl-dialog-text",entry:n.entry,gameState:n.gameState,words:n.words,useTypeEffect:n.useTypeEffect,isActive:n.isActive});return jt.createElement("div",{key:`${n.entry.id}:${n.isActive?"active":"idle"}`,"data-element-type":"nvl-dialog-item","data-dialog-index":i,className:"nvl-dialog-item"},o?o({entry:n.entry,index:i,isActive:n.isActive,nametag:r,texts:s}):jt.createElement(jt.Fragment,null,r,s))})))}import Be,{useMemo as Vc}from"react";import fs from"clsx";function Oc({children:o,className:e,style:t,renderDialogItem:n}){let i=Do(),{state:r}=mt();return Be.createElement("div",{"data-element-type":"nvl-dialog-list",className:fs("flex flex-col space-y-4 p-4",e),style:t},i.map((s,a)=>Be.createElement("div",{key:`${s.id}:${r.activeDialogId===s.id?r.phase:"idle"}`},Be.createElement(Wc,{entry:s},n?n({entry:s,index:a,isActive:r.activeDialogId===s.id,nametag:s.character?Be.createElement(Nt,{className:"nvl-character-name font-bold mr-2"}):null,texts:Be.createElement(Rt,{className:"nvl-dialog-text"})}):o?Be.Children.map(o,c=>Be.isValidElement(c)?Be.cloneElement(c,{entry:s,index:a}):c):Be.createElement(hs,{entry:s,index:a})))))}function hs({entry:o,index:e,className:t,style:n,texts:i}){let r=w(),s=o.character?.state.name||null,a=Ye(o.character?.config.color||r.config.defaultTextColor),c=i??Be.createElement(Rt,{className:"nvl-dialog-text"});return Be.createElement("div",{"data-element-type":"nvl-dialog-item","data-dialog-index":e,className:fs("nvl-dialog-item",t),style:n},s&&Be.createElement("span",{className:"nvl-character-name font-bold mr-2",style:{color:a}},s,":"),c)}function Wc({entry:o,children:e}){let n=w().getLiveGame().getGameState(),i=Vc(()=>o.sentence.evaluate(ue.getCtx({gameState:n})),[o.sentence,n]),r=n.getNvlState(),s=r.activeDialogId===o.id,a=s&&r.phase==="typing",c=ki({entry:o,gameState:n,words:i,isActive:s,useTypeEffect:a});return Be.createElement(Bt,{value:c},e)}function ys({state:o}){let e=w(),t=pt(),n=Mo(null),i=Mo(null),r=Mo(!1),[s]=_e(Q.Preferences.skipDelay),[a]=_e(Q.Preferences.skipInterval),[c]=$t("skipAction");return Bc(()=>{if(!e.getLiveGame().gameState.playerCurrent){o.logger.warn("KeyEventAnnouncer","Failed to listen to playerElement events");return}if(!window){o.logger.warn("KeyEventAnnouncer","Failed to listen to window events");return}let p=()=>{i.current&&(clearTimeout(i.current),i.current=null),n.current&&(clearInterval(n.current),n.current=null),r.current=!1},u=h=>{if(e.keyMap.match("skipAction",h.key)&&e.preference.getPreference(Q.Preferences.skip)&&!r.current){o.logger.verbose("KeyEventAnnouncer","Skipping");let m=()=>{n.current=setInterval(()=>{o.events.emit(k.EventTypes["event:state.player.skip"],!1)},a)};p(),o.events.emit(k.EventTypes["event:state.player.skip"],!1),r.current=!0,s===0?m():i.current=setTimeout(m,s)}},d=h=>{e.keyMap.match("skipAction",h.key)&&p()};if(e.config.useWindowListener){let h=e.getLiveGame().onWindowEvent("keydown",u).cancel,m=e.getLiveGame().onWindowEvent("keyup",d).cancel;return()=>{p(),h(),m()}}else{let h=e.getLiveGame().onPlayerEvent("keydown",u).cancel,m=e.getLiveGame().onPlayerEvent("keyup",d).cancel;return()=>{p(),h(),m()}}},[t,s,a,c]),gs.createElement(gs.Fragment,null)}import vs,{useEffect as $c}from"react";function jc(o){let e=o;for(;e;){if(e.hasAttribute("data-layout-path"))return!0;e=e.parentElement}return!1}var Ss=['[data-element-type="nvl-container"]','[data-element-type="nvl-dialog-list"]','[data-element-type="nvl-dialog-item"]'],qc=["[data-layout-path]",'[data-element-type="menu"]','[data-element-type="notification"]'];function Qc(o,e){return!o||e&&Ss.some(t=>!!o.closest(t))?!1:[...qc,...Ss].some(t=>!!o.closest(t))}function Ts(o,e){if(!e)return!1;let t=e.getBoundingClientRect();return o.clientX>=t.left&&o.clientX<=t.right&&o.clientY>=t.top&&o.clientY<=t.bottom}function bs({state:o}){let e=w();return $c(()=>{let t=e.getLiveGame().gameState?.playerCurrent;if(!t){o.logger.warn("StageClickAnnouncer","Failed to listen to playerElement events");return}let n=i=>{let r=i.target;if(!r||!t.contains(r)||!Ts(i,t))return;let s=o.mainContentNode;s&&(!s.contains(r)||!Ts(i,s))||jc(r)||Qc(r,o.isNvlMode())||(o.events.emit(k.EventTypes["event:state.player.stageClick"]),o.recordStageClick())};if(e.config.useWindowListener){let i=e.getLiveGame().onWindowEvent("click",n);return()=>{i.cancel()}}else{let i=e.getLiveGame().onPlayerEvent("click",n);return()=>{i.cancel()}}},[e,o]),vs.createElement(vs.Fragment,null)}import{useEffect as Kn}from"react";function Go({gameState:o}){let e=o.audioManager,[t]=_e("voiceVolume"),[n]=_e("bgmVolume"),[i]=_e("soundVolume"),[r,s]=_e("globalVolume");return Kn(()=>{s(e.getGlobalVolume())},[]),Kn(()=>{e.setGroupVolume("voice",t)},[t]),Kn(()=>{e.setGroupVolume("bgm",n)},[n]),Kn(()=>{e.setGroupVolume("sound",i)},[i]),Kn(()=>{e.setGlobalVolume(r)},[r]),null}import{useEffect as Fi,useRef as Jc}from"react";import Ho,{createContext as Xc,useContext as Yc,useState as As}from"react";var qt=class qt{constructor(){this.preloaded=[];this.events=new J}add(e){let t=this.getSrc(e);return t&&this.has(t)?this:(this.preloaded.push(e),this.events.emit(qt.EventTypes["event:preloaded.add"],e),this.events.emit(qt.EventTypes["event:preloaded.change"]),this)}get(e){return this.preloaded.find(t=>this.getSrc(t)===e)}has(e){return Array.isArray(e)?e.every(t=>this.has(t)):this.preloaded.some(t=>this.getSrc(t)===e)}remove(e){if(Array.isArray(e)){let n=e.map(i=>this.getSrc(i));return this.preloaded=this.preloaded.filter(i=>!n.includes(this.getSrc(i))),this}let t=this.getSrc(e);return this.preloaded=this.preloaded.filter(n=>this.getSrc(n)!==t),this.events.emit(qt.EventTypes["event:preloaded.remove"],e),this.events.emit(qt.EventTypes["event:preloaded.change"]),this}clear(){return this.preloaded=[],this}getSrc(e){return De.getSrc(e)}};qt.EventTypes={"event:preloaded.add":"event:preloaded.add","event:preloaded.remove":"event:preloaded.remove","event:preloaded.change":"event:preloaded.change","event:preloaded.mount":"event:preloaded.mount","event:preloaded.ready":"event:preloaded.ready","event:preloaded.unmount":"event:preloaded.unmount"};var $e=qt;var Ui=class o{constructor(e){this.game=e;this.src=new Map;this.preloadTasks=new Map;this.game.addSideEffect(()=>{this.abortAll(),this.src.clear()})}static getImage(e,t,n){return dr(e,{...n,signal:t})}has(e){return this.src.has(e)}add(e,t){return this.src.set(e,t),this}remove(e){return this.src.delete(e),this}get(e){return this.src.get(e)}clear(){return this.src.clear(),this}size(){return this.src.size}isPreloading(e){return this.preloadTasks.has(e)}preload(e,t){if(this.src.has(t)||this.preloadTasks.has(t)){let u={abort:()=>{},onFinished:()=>u,onErrored:()=>u};return u}let n=t,i={};this.game.hooks.rawTrigger("preloadImage",()=>[n,(u,d)=>{n=u,i={...i,...d}}]);let r=new AbortController,s=r.signal,a=[],l={promise:o.getImage(n,s,i).then(u=>{this.preloadTasks.delete(t),u&&this.add(t,u)}).catch(u=>{e.logger.error("ImageCacheManager",`Failed to preload image: ${t}`,`Reason: ${u}`),a.forEach(d=>d(u))}),controller:r};this.preloadTasks.set(t,l);let p={abort:()=>{r.abort(),this.preloadTasks.delete(t)},onFinished:u=>(l.promise.then(u),p),onErrored:u=>(a.push(u),p)};return p}abortAll(){this.preloadTasks.forEach(e=>{e.controller.abort()}),this.preloadTasks.clear()}abort(e){let t=this.preloadTasks.get(e);t&&(t.controller.abort(),this.preloadTasks.delete(e))}preloadedSrc(){return Array.from(this.src.values())}filter(e){for(let t of this.src.keys())e.includes(t)||this.src.delete(t);return this}};var Uo=Xc(null);function Cs({children:o}){let e=w(),[t]=As(()=>new $e),[n]=As(()=>new Ui(e));return Ho.createElement(Ho.Fragment,null,Ho.createElement(Uo,{value:{preloaded:t,cacheManager:n}},o))}function pn(){if(!Uo)throw new Error("usePreloaded must be used within a PreloadedProvider");return Yc(Uo)}function xs({state:o}){let{preloaded:e,cacheManager:t}=pn(),n=w(),i=Jc(new Set),[r]=Z(),s="Preload",a=o.getLastScene()||o.getPreloadingScene(),c=n.getLiveGame().stackModel?.getTopSync()?.node?.action||null,l=n.getLiveGame().story;function p(){o.logger.debug(s,"Preload unmounted"),e.events.emit($e.EventTypes["event:preloaded.unmount"])}return Fi(()=>o.events.on(k.EventTypes["event:state:flushPreloadedScenes"],()=>{r()}).cancel,[]),Fi(()=>{if(typeof fetch>"u")return e.events.emit($e.EventTypes["event:preloaded.ready"]),o.logger.warn(s,"Fetch is not supported in this environment, skipping preload"),p;if(!n.config.preloadAllImages)return e.events.emit($e.EventTypes["event:preloaded.ready"]),o.logger.debug(s,"Preload all images is disabled, skipping preload"),p;if(n.config.forceClearCache&&(t.clear(),o.logger.weakWarn(s,"Cache cleared")),!l||!a)return l?o.logger.debug(s,"Scene not ready yet, waiting for scene before preload"):o.logger.weakWarn(s,"Story not found, skipping preload"),p;let u=performance.now(),d=De.catSrc([...a.srcManager?.src||[],...a.srcManager?.getFutureSrc()||[]]),h=new Sn(n.config.preloadConcurrency,n.config.preloadDelay),m=[],v=o.logger.group(s,!0),g=[];o.logger.debug(s,"preloading:",d,a);for(let S of d.image){let f=De.getSrc(S);if(f){if(m.push(f),t.has(f)||t.isPreloading(f)||g.includes(f)){o.logger.debug(s,`Image already loaded (${d.image.indexOf(S)+1}/${d.image.length})`,f),g.push(f);continue}g.push(f),h.addTask(()=>new Promise(T=>{t.preload(o,f).onFinished(()=>{o.logger.debug(s,`Image loaded (${d.image.indexOf(S)+1}/${d.image.length})`,f),T()}).onErrored(()=>{o.logger.weakError(s,`Failed to preload image (${d.image.indexOf(S)+1}/${d.image.length})`,f),T()})}))}}return v.end(),h.start().then(()=>{o.logger.info(s,"Image preload",`loaded ${t.size()} images in ${performance.now()-u}ms`),n.config.waitForPreload&&e.events.emit($e.EventTypes["event:preloaded.ready"]),t.filter(m)}),n.config.waitForPreload||e.events.emit($e.EventTypes["event:preloaded.ready"]),e.events.emit($e.EventTypes["event:preloaded.mount"]),p},[a,l]),Fi(()=>{i.current.clear()},[a]),Fi(()=>{if(typeof fetch>"u"||n.config.preloadAllImages)return;if(!l){o.logger.weakWarn(s,"Story not found, skipping preload");return}let u=performance.now(),d=n.getLiveGame().getAllPredictableActions(l,c,n.config.maxPreloadActions).map(f=>De.getPreloadableSrc(l,f)).filter(function(f){return f!==null});d.filter(function(f){return f?.activeType==="scene"}).forEach(f=>{i.current.has(f)||i.current.add(f)});let m=De.catSrc([...i.current,...d]),v=new Sn(n.config.preloadConcurrency,n.config.preloadDelay),g=[],S=o.logger.group(s);o.logger.debug(s,"preloading:",m);for(let f of m.image){let T=De.getSrc(f);if(T){if(g.push(T),t.has(T)||t.isPreloading(T)){o.logger.debug(s,`Image already loaded (${m.image.indexOf(f)+1}/${m.image.length})`,T);continue}v.addTask(()=>new Promise(C=>{t.preload(o,T).onFinished(()=>{o.logger.debug(s,`Image loaded (${m.image.indexOf(f)+1}/${m.image.length})`,T),C()}).onErrored(()=>{o.logger.weakError(s,`Failed to preload image (${m.image.indexOf(f)+1}/${m.image.length})`,T),C()})}))}}S.end(),v.start().then(()=>{o.logger.info(s,"Image preload (quick reload)",`loaded ${t.size()} images in ${performance.now()-u}ms`),t.filter(g)})},[c,l]),null}import Zc from"clsx";import ft,{useCallback as Fo,useMemo as _c,useRef as el}from"react";function Ko({prompt:o,choices:e,afterChoose:t,state:n,words:i,renderPrompt:r=!0}){let s=w(),a=el([]),c=Fo(m=>(a.current.push(m),a.current.indexOf(m)),[]),l=Fo(m=>{let v=a.current.indexOf(m);v!==-1&&a.current.splice(v,1)},[]),p=Fo(m=>a.current.indexOf(m),[]),u=s.config.menu,d=_c(()=>e.map(m=>({...m,words:m.prompt.evaluate(ue.getCtx({gameState:n}))})),[]);function h(m){t(m)}return ft.createElement(ft.Fragment,null,ft.createElement(To,{value:{evaluated:d,choose:h,gameState:n}},ft.createElement(bo,{value:{register:c,unregister:l,getIndex:p}},ft.createElement(dt,{className:"absolute"},r&&o&&ft.createElement(Rn,{gameState:n,action:{sentence:o,words:i,character:null},useTypeEffect:!1})),ft.createElement(zt.Div,{color:"green",border:"dashed",className:Zc("absolute"),style:{width:`${s.config.width}px`,height:`${s.config.height}px`}},ft.createElement(u,{items:d.map((m,v)=>v)})))))}function ws({items:o}){return ft.createElement(Ai,{className:"absolute flex flex-col items-center justify-center min-w-full w-full h-full"},o.map(e=>ft.createElement(Li,{key:e,className:"bg-white text-black p-2 mt-2 w-1/2"})))}import zi from"react";import Ki from"react";import Vo,{useEffect as ks,useLayoutEffect as Ps,useRef as Es,useState as Oo}from"react";function dn({element:o,state:e,skipTransform:t,skipTransition:n,overwriteDefinition:i,onTransform:r,onTransition:s,transitionsProps:a=[],propOverwrite:c}){let[l,p]=Oo(null),[u,d]=Oo(null),h=Vo.useRef(null),[m]=Oo(()=>new Qn("displayable.refGroup")),v=Es(m.next()),g=Es(Ne()),f=w().getLiveGame().getGameState(),T=typeof a=="function"?a(l):a,[C]=Z([u,l,g]);ks(()=>f.events.depends([f.events.on(k.EventTypes["event:state.player.skip"],Re)]).cancel,[u,l,g]),Ps(()=>{if(I(),!l)return;if(g.current.some(([$])=>!$.current))throw new x("Displayable: Trying to access transition groups before they are mounted");let{controller:R,task:L}=l;return R.onUpdate($=>{g.current.forEach(([P],M)=>{let K=L.resolve[M],ee=typeof K=="function"?K:K.resolver;if(!ee)throw new x(`Displayable: Trying to resolve element props but found no resolver. (reading: transitionTask.task.resolve[${M}])`);let oe=ee(...$),E=H(T[M]||T[T.length-1]||{},oe);X(P,c?c(E):E)})}).cancel},[l]),ks(()=>{if(!h.current)throw new Error(`Scope not ready. Using element: ${o.constructor.name}`)},[]),Ps(()=>{let R=e.toStyle(f,i);Object.assign(h.current.style,R),f.logger.debug("Displayable","Initial style applied",h.current,R)},[]);function I(){let R=typeof a=="function"?a(l):a;if(!g.current||!g.current.length)throw new x("Displayable: Transition group refs are not initialized correctly");if(g.current.some(([L])=>!L.current))throw new x("Displayable: Trying to access transition groups before they are mounted");g.current.forEach(([L],z)=>{if(!L.current)throw new x("Displayable: Trying to assign properties to unmounted element");X(L,R[z]||R[R.length-1]||{})})}function N(R){f.logger.debug("Displayable","Transform applied",e.toStyle(f,i),h.current),C(),r?.(R)}function X(R,L){if(!R.current)throw new x("Displayable: Trying to assign properties to unmounted element");let z=R.current,$={},P={};Object.keys(L).forEach(K=>{let ee=K;ee==="style"&&L.style?Object.assign($,L.style):L[ee]!==void 0&&ee!=="key"&&(P[ee]=L[ee])}),Object.keys($).length>0&&Object.assign(z.style,$);let M=c?c(P):P;for(let[K,ee]of Object.entries(M))z.getAttribute(K)!==ee&&z.setAttribute(K,ee)}function he(R,L){u&&(u.abort(),d(null));let z=R.animate(e,{gameState:f,ref:h,overwrites:i}),$=new Te(z);return f.timelines.attachTimeline($),z.onSkipControllerRegister(P=>{P.onAbort(()=>{$.abort(),d(null)})}),d(z),z.then(()=>{d(null),N(R),L()}),$}function ge(R,L){l&&l.controller.complete();let z=R.createTask(f),$=R.requestAnimations(z.animations),P=new y().registerSkipController(new G($.cancel)),M=new Te(P);P.skipController.onAbort(()=>{$.cancel()}),$.onCanceled(()=>{M.abort(),p(null),f.logger.debug("Displayable","Transition cancelled",R)}),f.timelines.attachTimeline(M),p({task:z,controller:$,transition:R,resolve:L});let K;if(g.current=z.resolve.map(oe=>{let E=Vo.createRef(),Ge=typeof oe=="function"?void 0:oe.key;if(!Ge)return[E,m.next()];if(Ge==="target")return K=m.next(),[E,K];if(Ge==="current")return[E,v.current];throw new x("Displayable: Invalid key type")}),!K)throw new x("Displayable: No target key found");v.current=K;let ee=g.current.map(([oe])=>{let E=oe.current;return E?.waitForLoad?E.waitForLoad():Promise.resolve()});return Promise.all(ee).then(()=>{$.start(),$.onComplete(()=>{ot(),p(null),s?.(R),L(),P.resolve()})}),M}function ye(R){return f.logger.debug("initDisplayable",o),he(q.immediate(e.get()),R)}function Re(){t&&u&&(u.abort(),d(null),f.logger.debug("transform skipped")),n&&l&&(l.controller.complete(),f.logger.debug("transition skipped"))}function Ne(){return[[Vo.createRef(),v.current]]}function ot(){g.current.forEach(([R])=>{R.current=null}),g.current=Ne()}return{transformRef:h,transitionRefs:g.current,isTransforming:!!u,transitionTask:l,initDisplayable:ye,applyTransform:he,applyTransition:ge,updateStyleSync:I,deps:[u,l,g]}}import{useEffect as tl}from"react";function Mt(o,e,t=[]){let i=w().getLiveGame().getGameState();return tl(()=>{let r=typeof e=="function"?e():e;return i.mountState(o,r).unMount},[...t]),[]}function Wo({state:o,text:e}){let{ratio:t}=pe(),[n]=Z(),{transformRef:i,transitionRefs:r,initDisplayable:s,applyTransform:a,applyTransition:c,updateStyleSync:l,deps:p,isTransforming:u}=dn({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipTextTransform,skipTransition:o.game.config.allowSkipTextTransition,overwriteDefinition:{overwrite:d=>({width:"fit-content",transform:q.propToCSSTransform(o,d,{translate:[e.config.alignX==="left"?"0%":e.config.alignX==="right"?"-100%":void 0,e.config.alignY==="top"?"100%":e.config.alignY==="bottom"?"0%":void 0]})})},transitionsProps:[{style:{width:"fit-content",whiteSpace:"nowrap",transform:`scale(${t.state.scale})`,transformOrigin:`${e.config.alignX} ${e.config.alignY}`,fontSize:`${e.state.fontSize}px`}}]});return Mt(e,{initDisplayable:s,applyTransform:a,applyTransition:c,flush:n,updateStyleSync:l},[...p]),Ki.createElement(zt.Div,{"data-element-type":"text"},Ki.createElement(zt.mDiv,{tag:"text.container",color:"green",border:"dashed",layout:u,ref:i,className:"absolute"},r.map(([d,h])=>Ki.createElement("span",{key:h,ref:d,className:e.config.className},Ki.createElement("span",null,e.state.text)))))}import mn,{useRef as Is,useState as Rs}from"react";import Vi,{useEffect as zo,useRef as Oi,forwardRef as nl}from"react";var Ds=nl(({onSizeChanged:o,onLoad:e,autoFit:t=!1},n)=>{let i=Oi(null),{ratio:r}=pe(),[s,a]=Vi.useState(()=>r.state.width),[c,l]=Vi.useState(()=>r.state.height),p=w(),u=Oi(!1),d=Oi(null),h=Oi(null);Vi.useImperativeHandle(n,()=>i.current,[]),zo(()=>{i.current&&Object.defineProperties(i.current,{isLoaded:{value:()=>u.current,configurable:!0},waitForLoad:{value:()=>u.current?Promise.resolve():(d.current||(d.current=new Promise(g=>{h.current=g})),d.current),configurable:!0}})},[]),zo(()=>(m(),r.onUpdate(m)),[o]),zo(()=>{let g=new MutationObserver(S=>{S.forEach(f=>{f.type==="attributes"&&f.attributeName==="src"&&i.current&&m()})});return i.current&&g.observe(i.current,{attributes:!0}),()=>{g.disconnect()}},[o]);function m(){if(i.current&&i.current.naturalWidth)if(i.current.naturalWidth*i.current.naturalHeight===1){let g=r.state.width,S=r.state.height,f=`${g} / ${S}`;a(g),l(S),i.current.style.aspectRatio=f,o&&o(g,S)}else{let g=t?p.config.width/i.current.naturalWidth:1,S=i.current.naturalWidth*r.state.scale*g,f=i.current.naturalHeight*r.state.scale*g;a(S),l(f),i.current.style.aspectRatio="auto",o&&o(S,f)}}function v(){m(),u.current=!0,h.current&&(h.current(),h.current=null,d.current=null),e&&e()}return Vi.createElement("img",{ref:i,onLoad:v,width:s,height:c,alt:""})});Ds.displayName="AspectScaleImage";var Ls=Ds;import Ns from"clsx";import{motion as il}from"motion/react";function Wi({image:o,state:e}){let[t]=Rs(()=>new J),[n,i]=Rs([]),{cacheManager:r}=pn(),s=Is([]),a=Is(null),{transformRef:c,transitionRefs:l,isTransforming:p,initDisplayable:u,applyTransition:d,applyTransform:h,updateStyleSync:m,deps:v}=dn({element:o,state:o.transformState,skipTransform:e.game.config.allowSkipImageTransform,skipTransition:e.game.config.allowSkipImageTransition,transitionsProps:f=>{let T=f?f.transition._getCurrentSrc():o.state.currentSrc;return[{style:{willChange:"filter",position:"absolute",transformOrigin:"center",backgroundColor:A.isColor(T)?A.colorToString(T):void 0,transform:"none",top:"auto",left:"auto",right:"auto",bottom:"auto",filter:`brightness(${1-o.state.darkness})`},src:A.isImageSrc(T)?A.srcToURL(T):U.DefaultImagePlaceholder},{style:{willChange:"filter",position:"absolute",transformOrigin:"center",transform:"translate(-50%, -50%)",top:"50%",left:"50%",right:"auto",bottom:"auto",maxWidth:"none",maxHeight:"none",filter:"brightness(1)"}}]},propOverwrite:f=>f.src?(!A.isDataURI(f.src)&&!r.has(f.src)&&!r.isPreloading(f.src)&&!s.current.includes(f.src)&&(e.game.getLiveGame().getGameState()?.logger.warn("Image",`Image not preloaded: "${f.src}".
43
45
  This may be caused by complicated image action behavior that cannot be predicted.
44
- To fix this issue, you can manually register the image using scene.preloadImage(YourImageSrc). `),s.current.push(f.src)),{...f,src:r.get(f.src)||f.src}):f});Lt(o,{createWearable:f=>{i(S=>[...S,f])},disposeWearable:f=>{i(S=>S.filter(N=>N.getId()!==f.getId()))},initDisplayable:m,applyTransform:h,applyTransition:p,events:t,updateStyleSync:d},[...T]);function y(f,S){a.current&&(t.emit("event:image.onLoad"),Object.assign(a.current.style,{width:`${f}px`,height:`${S}px`}))}function x(){t.emit("event:image.onLoad")}return rn.createElement(Gc.div,{layout:u,ref:c,className:"absolute w-max h-max","data-element-type":"image"},rn.createElement("div",{className:"relative h-full w-full",ref:a,"data-image-id":o.getId()},l.map(([f,S],N)=>rn.createElement(us,{key:S,ref:f,autoFit:o.config.autoFit,onSizeChanged:N===0?y:void 0,onLoad:N===0?x:void 0})),rn.createElement("div",{className:ms("w-full h-full top-0 left-0 absolute")},n.map(f=>rn.createElement("div",{className:ms("w-full h-full relative"),key:"wearable-"+f.getId()},rn.createElement(Hi,{image:f,state:e}))))))}function No({state:o,displayable:e}){return Ui.createElement(Ui.Fragment,null,e.map(t=>{if(t instanceof Gt)return Ui.createElement(Io,{state:o,text:t,key:"text-"+t.getId()});if(t instanceof G)return Ui.createElement(Hi,{state:o,image:t,key:"image-"+t.getId()});throw new Error("Unsupported displayable type: "+(t?.constructor?.name||t))}))}import Fi,{useEffect as Hc}from"react";import{motion as Uc}from"motion/react";function fs({state:o,layer:e,children:t}){let{transformRef:n,transitionRefs:i,initDisplayable:r,applyTransition:s,applyTransform:a,updateStyleSync:c,deps:l}=on({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipLayersTransform,skipTransition:!1,transitionsProps:[{style:{width:"100%",height:"100%",transformOrigin:"center"}}]});return Lt(e,{initDisplayable:r,applyTransition:s,applyTransform:a,updateStyleSync:c},[...l]),Hc(()=>(o.logger.debug("Layer","Layer mounted",e.getId()),()=>{o.logger.debug("Layer","Layer unmounted",e.getId())}),[]),Fi.createElement(Fi.Fragment,null,Fi.createElement(Uc.div,{layout:!0,className:"absolute w-full h-full",ref:n,"data-element-type":"layer","data-layer-id":e.getId(),key:`layer-${e.getId()}`},i.map(([u,m])=>Fi.createElement("div",{className:"relative w-full h-full",ref:u,key:m},t))))}import Fc from"clsx";import{useEffect as hs,useRef as Kc}from"react";import sn from"react";function Mo({state:o,className:e,elements:t}){let{scene:n,layers:i,texts:r,menus:s}=t,a=Kc(!1);return hs(()=>n.events.depends([n.events.on(Ue.EventTypes["event:scene.preUnmount"],()=>{if(n.state.backgroundMusic)return o.audioManager.stop(n.state.backgroundMusic,n.config.backgroundMusicFade)})]).cancel,[]),hs(()=>(n.events.emit(Ue.EventTypes["event:scene.mount"]),o.logger.debug("Scene","Scene mounted",n.getId()),()=>{n.events.emit(Ue.EventTypes["event:scene.unmount"]),o.logger.debug("Scene","Scene unmounted",n.getId())}),[]),Lt(n,{setBackgroundMusic(c,l){return new Promise(u=>{(async function(){n.state.backgroundMusic&&o.audioManager.isManaged(n.state.backgroundMusic)&&await o.audioManager.stop(n.state.backgroundMusic,l),c?(await o.audioManager.play(c,{end:c.state.volume,duration:l}),n.state.backgroundMusic=c):n.state.backgroundMusic=null,u()})()})}}),sn.createElement("div",{className:Fc(e,"w-full h-full absolute")},[...i.entries()].sort(([c],[l])=>c.state.zIndex-l.state.zIndex).map(([c,l])=>sn.createElement(fs,{state:o,layer:c,key:c.getId()},sn.createElement(No,{state:o,displayable:l}))),r.map(({action:c,onClick:l})=>sn.createElement(An,{gameState:o,key:"say-"+c.id,action:c,onFinished:u=>{u!==void 0&&(a.current=u),l(),o.events.emit(w.EventTypes["event:state.player.lineEnd"]),o.stage.next()},useTypeEffect:!a.current})),s.map(({action:c,onClick:l},u)=>sn.createElement("div",{key:"menu-"+u,"data-element-type":"menu"},sn.createElement(Po,{state:o,prompt:c.prompt,choices:c.choices,afterChoose:m=>{a.current=!1,l(m),o.stage.next()},words:c.words}))))}import Vc from"react";import{useEffect as Go,useRef as Oc}from"react";import{useCallback as gs}from"react";function ys(o){let e=gs(()=>{if(!o.current)return;let n=o.current;n.style.opacity="1",n.style.pointerEvents="auto",n.style.visibility="visible"},[o]),t=gs(()=>{if(!o.current)return;let n=o.current;n.style.opacity="0",n.style.pointerEvents="none",n.style.visibility="hidden"},[o]);return{show:e,hide:t}}function Ho({gameState:o,video:e}){let t=Oc(null),{show:n,hide:i}=ys(t);Go(()=>o.events.depends([o.events.on(w.EventTypes["event:state.player.skip"],()=>{o.game.config.allowSkipVideo&&(r(),o.logger.log("NarraLeaf-React: Video","Skipped"))})]).cancel,[]),Go(()=>{i(),e.state.display&&n()},[]),Go(()=>{if(!t.current)return;let s=t.current,a=!1,c=()=>new b(`Failed to add event listener, ref is not available
45
- at Video.tsx: useEffect`),l=()=>{a||!s||(a=!0,o.mountState(e,{show:()=>{if(!t.current)throw c();n()},hide:()=>{if(!t.current)throw c();i()},play:()=>{if(!t.current)throw c();let m=t.current;return m.currentTime=0,new Promise(p=>{o.schedule(({retry:h})=>{if(m.readyState<3){let x=()=>{m.removeEventListener("loadeddata",x),h()};m.addEventListener("loadeddata",x);return}let d=()=>{y(),p()},T=()=>{y(),p()},y=()=>{m.removeEventListener("ended",d),m.removeEventListener("stopped",T)};m.addEventListener("ended",d),m.addEventListener("stopped",T),u.push(y),m.play().catch(x=>{o.logger.error("Failed to play video: "+x),y(),p()})},10)})},pause:()=>{if(!t.current)throw c();t.current.pause()},resume:()=>{if(!t.current)throw c();return t.current.play()},stop:()=>{if(!t.current)throw c();t.current.pause(),t.current.dispatchEvent(new Event("stopped"))},seek:m=>{if(!t.current)throw c();t.current.currentTime=m}}))},u=[];return s.addEventListener("canplay",l),()=>{a=!1,s.removeEventListener("canplay",l),u.forEach(m=>m()),s.currentTime>0&&s.pause(),o.isStateMounted(e)&&o.unMountState(e)}},[o,e]);function r(){t.current&&(t.current.pause(),t.current.currentTime=0,t.current.dispatchEvent(new Event("stopped")))}return Vc.createElement("video",{ref:t,src:e.config.src,preload:"auto",muted:e.config.muted,playsInline:!0,width:"100%",height:"100%",onContextMenu:s=>s.preventDefault()})}import Wc from"clsx";import zc,{useCallback as Bc,useEffect as Ki,useRef as $c}from"react";function Uo({children:o,className:e,gameState:t}){let{ratio:n}=se(),i=C(),[r]=$(),s=$c(null),a=i.config.minWidth,c=i.config.minHeight,l=Bc(u=>{if(n.isLocked()){t.logger.weakWarn("AspectRatio","ratio is locked, skipping update");return}n.update(u.width,u.height,u.scale),n.updateMin(a,c),r()},[r,t.logger,c,a,n]);return Ki(()=>{n.setUpdate(()=>{s.current?.requestUpdate()})},[n]),Ki(()=>n.onRequestedUpdate(()=>{s.current?.requestUpdate()}),[n]),Ki(()=>{let u=requestAnimationFrame(()=>{s.current?.requestUpdate()});return()=>{cancelAnimationFrame(u)}},[i.config.aspectRatio,i.config.height,i.config.width,c,a]),Ki(()=>t.events.on(w.EventTypes["event:state.player.requestFlush"],r).cancel,[t,r]),zc.createElement($r,{ref:s,id:i.config.contentContainerId,aspectRatio:i.config.aspectRatio,baseWidth:i.config.width,minWidth:a,minHeight:c,debounceMs:i.config.ratioUpdateInterval,className:Wc(e),onUpdate:l},o)}import Ss,{useEffect as jc,useRef as qc,useState as vs}from"react";function Fo({src:o,width:e,height:t}){let[n,i]=vs({x:0,y:0}),[r,s]=vs(!1),a=qc(null),{ratio:c}=se();return jc(()=>{let l=u=>{if(a.current){let m=a.current.getBoundingClientRect(),p=u.clientX-m.left,h=u.clientY-m.top;i({x:p,y:h}),r||s(!0)}};return window.addEventListener("mousemove",l),()=>{window.removeEventListener("mousemove",l)}},[r]),Ss.createElement(ct,{ref:a,className:"overflow-hidden absolute"},Ss.createElement("img",{src:o,style:{position:"absolute",left:n.x,top:n.y,width:e,height:t,pointerEvents:"none",zIndex:1001,display:r?"block":"none",cursor:"none",transform:`scale(${c.state.scale})`},alt:""}))}import Ts from"react";import St from"react";function Ko({error:o,errorInfo:e}){return C().config.app.debug?St.createElement("div",{className:"text-left"},St.createElement("h1",null,"NarraLeaf-React cannot initialize the player correctly. (development mode)"),St.createElement("p",{className:"text-red-700"},"Message: ",o.message),St.createElement("pre",null,"Error Stack: ",o?.stack),St.createElement("pre",null,"Component Stack: ",e?.componentStack),St.createElement("pre",null,"Digest: ",e?.digest)):St.createElement("div",{className:"bg-white w-full h-full"},St.createElement("h1",null,"NarraLeaf-React crashed due to an unknown error."),St.createElement("p",null,"Please contact the game developer for further assistance."))}var Vi=class extends Ts.Component{constructor(){super(...arguments);this.state={hasError:!1,error:null,errorInfo:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t,errorInfo:null}}componentDidCatch(t,n){this.setState({error:t,errorInfo:n}),this.props.onError?.(t,n),console.error(t,n)}render(){return this.state.hasError?Ts.createElement(Ko,{error:this.state.error,errorInfo:this.state.errorInfo}):this.props.children}};import As from"clsx";import V,{useEffect as an,useReducer as Jc,useState as Rn}from"react";import{flushSync as xs}from"react-dom";import{useRef as Qc}from"react";import{useEffect as Xc}from"react";function bs({gameState:o}){let e=Qc(null);return Xc(()=>(e.current=requestAnimationFrame(()=>{setTimeout(()=>{o.events.emit(w.EventTypes["event:state.onRender"])},0)}),()=>{e.current!==null&&cancelAnimationFrame(e.current)}),[o.deps]),null}import In,{useEffect as Yc}from"react";function Vo({gameState:o}){let[e]=$(),{ratio:t}=se(),n=o.notificationMgr;Yc(()=>n.onFlush(()=>{e()}).cancel,[]);let i=o.game.config.notification;return In.createElement("div",{style:{transform:`scale(${t.state.scale})`,transformOrigin:"left top"},className:"absolute top-0 left-0 w-full h-full pointer-events-none","data-element-type":"notification"},In.createElement(i,{notifications:n.toArray()}))}function Cs({notifications:o}){return In.createElement(ki,{className:"absolute top-0 left-0 w-full h-full"},o.map(({id:e,message:t})=>In.createElement("div",{key:e,className:"absolute top-0 left-0 w-[100px] h-[80px]"},In.createElement("span",{className:"text-white text-2xl font-bold"},t))))}function ws({story:o=vn.empty(),width:e,height:t,className:n,onReady:i,onEnd:r,onError:s,children:a,active:c=!0}){let[l,u]=Jc(ue=>ue+1,0),[m,p]=Rn(0),h=C(),[d]=Rn(()=>new w(h,{update:u,forceUpdate:()=>{d.logger.weakWarn("Player","force update"),xs(()=>{u()})},forceRemount:()=>{d.logger.weakWarn("Player","force remount"),xs(()=>{p(ue=>ue+1),u()})},next:be})),T=V.createRef(),y=V.createRef(),[x,f]=Rn(!1),S=V.useRef(!1),N=V.useRef(null),q=V.useRef(null),{preloaded:ae}=nn(),[Ve,Te]=Rn(!1),[ke]=Rn(new Map);function be(){let ue=()=>{ke.forEach(E=>E.cancel())};if(d.rollLock.isLocked())return;ue();let P=!1,Q=0;for(;!P;){if(Q++>h.config.maxStackModelLoop)throw new b("Max stack model loop reached");let E=h.getLiveGame().next();if(!E){if(h.getLiveGame().stackModel&&!h.getLiveGame().stackModel.isEmpty())continue;break}if(g.isAwaitable(E)){if(N.current===E)break;N.current=E,E.onSettled(()=>{N.current===E&&(N.current=null),be()}),P=!0;break}if(E instanceof jt){if(q.current===E)break;q.current=E,E.nextUnlock().then(()=>{q.current===E&&(q.current=null),be()}),P=!0;break}if(we.isCalledActionResult(E)&&E.wait&&we.isStackModelsAwaiting(E.wait.type,E.wait.stackModels)){if(N.current===E)break;N.current=E,E.wait&&we.executeStackModelGroup(E.wait.type,E.wait.stackModels).then(()=>{N.current===E&&(N.current=null),be()}),P=!0;break}d.handle(E)}d.stage.update()}an(()=>{d.audioManager.initialize()},[]),an(()=>(h.getLiveGame().setGameState(d),o&&!h.getLiveGame().isPlaying()&&h.getLiveGame().loadStory(o),d.playerCurrent=T.current,d.mainContentNode=y.current,()=>{h.getLiveGame().setGameState(void 0),d.playerCurrent=null}),[h,o]),an(()=>ze(()=>{f(!0);let ue=d.getLastScene(),P=[];ue?P.push(ue.events.once("event:scene.mount",()=>{d.stage.next()}).cancel):d.stage.next();let Q=d.events.on(w.EventTypes["event:state.end"],()=>{r&&r({game:h,gameState:d,liveGame:h.getLiveGame(),storable:h.getLiveGame().getStorable()})});return d.stage.update(),()=>{ue&&P.forEach(E=>E()),Q.cancel()}}),[]),an(()=>ze(()=>{x&&i&&!S.current&&(S.current=!0,d.stage.forceUpdate(),h.hooks.trigger("init",[]),i({game:h,gameState:d,liveGame:h.getLiveGame(),storable:h.getLiveGame().getStorable()}))}),[x]),an(()=>ae.events.depends([ae.events.on(Ke.EventTypes["event:preloaded.ready"],()=>{Te(!0),d.stage.update(),o&&be()})]).cancel,[]),an(()=>{d.flushDep=l},[l]);let Oe=e||h.config.width,Qe=t||h.config.height;return V.createElement(Vi,{onError:s},V.createElement("div",{style:{width:typeof Oe=="number"?`${Oe}px`:Oe,height:typeof Qe=="number"?`${Qe}px`:Qe},className:As(n,"__narraleaf_content-player"),ref:T,tabIndex:0},V.createElement(Uo,{className:As("flex-grow overflow-auto"),gameState:d},V.createElement(xo,{gameState:d}),V.createElement(bs,{gameState:d}),V.createElement(ct,{className:"absolute",ref:y,style:{cursor:d.game.config.cursor?"none":"auto",overflow:d.game.config.showOverflow?"visible":"hidden"}},h.config.cursor&&V.createElement(Fo,{src:h.config.cursor,width:h.config.cursorWidth,height:h.config.cursorHeight}),V.createElement(Zc,{show:Ve&&c,key:m},V.createElement(vo,null,V.createElement(Jr,{state:d}),V.createElement(ts,{state:d}),d.getSceneElements().map(ue=>V.createElement(Mo,{key:"scene-"+ue.scene.getId(),state:d,elements:ue})),d.getVideos().map((ue,P)=>V.createElement("div",{className:"w-full h-full absolute",key:"video-"+P,"data-element-type":"video"},V.createElement(Ho,{gameState:d,video:ue}))),V.createElement(_c,{NvlComponent:h.config.nvlDialog}))),V.createElement(os,{state:d}),V.createElement(Kr,null,a),V.createElement(Vo,{gameState:d})))))}function Zc({children:o,show:e}){return V.createElement(V.Fragment,null,e?o:null)}function _c({NvlComponent:o}){let{dialogs:e,state:t}=ut(),i=C().getLiveGame().getGameState(),r=V.useMemo(()=>e.map((s,a)=>{let c=s.sentence.evaluate(re.getCtx({gameState:i})),l=t.activeDialogId===s.id,u=l&&t.phase==="typing";return{entry:s,index:a,isActive:l,gameState:i,words:c,useTypeEffect:u}}),[e,i,t.activeDialogId,t.phase]);return V.createElement(o,{dialogs:r})}import"client-only";import cn from"react";function ks({children:o,game:e}){return cn.createElement(cn.Fragment,null,cn.createElement(Ar,null,cn.createElement(vr,{game:e},cn.createElement(is,null,cn.createElement(Cr,null,o)))))}var el=(r=>(r.image="narraleaf:image",r.text="narraleaf:text",r.layer="narraleaf:layer",r.scene="narraleaf:scene",r.video="narraleaf:video",r))(el||{});import tl from"clsx";import zt,{useEffect as Es,useRef as nl}from"react";function il({children:o,...e}){let t=C(),n=yt(),{ratio:i}=se(),[r]=Je(B.Preferences.showDialog),s=nl(null),[a]=Vt("nextAction");function c(){n.requestComplete()}return Es(()=>{if(!window){console.warn(`Failed to add event listener, window is not available
46
- at Say.tsx: onElementClick`);return}let l=m=>{t.keyMap.match("nextAction",m.key)&&n.requestComplete()};window.addEventListener("keyup",l);let u=n.events.on(le.Events.simulateClick,()=>{s.current&&s.current.click()});return()=>{window.removeEventListener("keyup",l),u.cancel()}},[n,a]),Es(()=>{let l=t.preference.onPreferenceChange(B.Preferences.autoForward,u=>{u&&n.isEnded()?n.tryScheduleAutoForward():n.cancelAutoForward()});return()=>{l.cancel()}},[n]),zt.createElement("div",{"data-element-type":"dialog",className:"w-full h-full"},zt.createElement("div",{className:tl("absolute bottom-0 w-full h-full",!r&&"invisible pointer-events-auto"),onClick:c,style:{...Xn(t.config.useAspectScale,{maxWidth:t.config.dialogWidth,maxHeight:t.config.dialogHeight,transform:`scale(${i.state.scale})`,transformOrigin:"bottom left",width:t.config.width,height:t.config.height})},ref:s},zt.createElement("div",{...e},o)))}function Ps({children:o,...e}){let t=yt();return!t.config.action.sentence||!t.config.action.words?null:zt.createElement(il,{...e},o)}var bc=Ps;function Ds(){return zt.createElement(Ps,null,zt.createElement(Dt,null),zt.createElement(Pt,null))}var Nn={say:Ds,menu:rs,notification:Cs,nvlDialog:Co};var Oi=class{constructor(e){this.game=e;this.plugins=[];this.registerAll()}use(e){return this.plugins.push(e),this}register(e){e.register(this.game)}registerAll(){this.plugins.forEach(e=>e.register(this.game))}unregisterAll(){this.plugins.forEach(e=>e.unregister(this.game))}has(e){return this.plugins.some(t=>t.name===e.name)}};var Mn=class{constructor(e={}){this.keyMap=e;this.events=new W}setKeyBinding(e,t){this.keyMap[e]=t,this.events.emit("event:keyMap.change",e,t)}getKeyBinding(e){return this.keyMap[e]??null}addKeyBinding(e,t){if(t===null)return;let n=this.getKeyBinding(e)??[],i=r=>Array.isArray(r)?r:[r];Array.isArray(n)?this.setKeyBinding(e,[...n,...i(t)]):this.setKeyBinding(e,[n,...i(t)])}getKeyBindings(){return this.keyMap}onKeyBindingChange(e,t){return this.events.on("event:keyMap.change",(n,i)=>{n===e&&t(i)})}importKeyBindings(e){for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&this.setKeyBinding(t,e[t])}exportKeyBindings(){return this.keyMap}match(e,t){let n=this.getKeyBinding(e);return n===null?!1:Array.isArray(n)?n.includes(t)||n.some(i=>i.toLowerCase()===t.toLowerCase()):n===t||n.toLowerCase()===t.toLowerCase()}};var Ls=(e=>(e.game="game",e))(Ls||{}),vt=class vt{constructor(e){this.hooks=new $n;this.liveGame=null;this.sideEffect=[];this.freezeFields=[];this.preference=new Cn(vt.DefaultPreference);this.keyMap=new Mn({skipAction:["Control"],nextAction:[" "]});this.config=I(vt.DefaultConfig,e),this.plugins=new Oi(this),this.router=new Et(this)}configure(e){let[t,n]=rr(e,this.freezeFields);return n.length>0&&console.warn(`NarraLeaf-React [Game] The following fields are not allowed to be configured: ${n.join(", ")}`),this.config=I(this.config,t),this.getLiveGame().getGameState()?.events.emit(w.EventTypes["event:state.player.requestFlush"]),this}configureAndFreeze(e){return this.configure(e),this.freeze(Object.keys(e)),this}freeze(e){return this.freezeFields.push(...e),this}use(e){return this.plugins.has(e)||this.plugins.use(e).register(e),this}getLiveGame(){if(!this.liveGame){let e=this.createLiveGame();return this.liveGame=e,e}return this.liveGame}dispose(){this.plugins.unregisterAll(),this.liveGame?.dispose(),this.sideEffect.forEach(e=>e())}addSideEffect(e){this.sideEffect.push(e)}createLiveGame(){return new rt(this)}};vt.defaultSettings={volume:1},vt.DefaultPreference={autoForward:!1,skip:!0,showDialog:!0,gameSpeed:1,cps:10,voiceVolume:1,voiceFadeDuration:0,voiceEndMode:"stop",bgmVolume:1,soundVolume:1,globalVolume:1,skipDelay:500,skipInterval:100},vt.Preferences={autoForward:"autoForward",skip:"skip",showDialog:"showDialog",gameSpeed:"gameSpeed",cps:"cps",voiceVolume:"voiceVolume",voiceFadeDuration:"voiceFadeDuration",voiceEndMode:"voiceEndMode",bgmVolume:"bgmVolume",soundVolume:"soundVolume",globalVolume:"globalVolume",skipDelay:"skipDelay",skipInterval:"skipInterval"},vt.DefaultConfig={app:{debug:!1,logger:{log:!1,info:!1,warn:!0,error:!0,debug:!1,trace:!1,verbose:!1},inspector:!1,guard:{invalidExposedStateUnmounting:!0,unexpectedTimelineStatusChange:!0}},contentContainerId:"__narraleaf_content",aspectRatio:16/9,minWidth:800,minHeight:450,width:1920,height:1080,useWindowListener:!0,ratioUpdateInterval:50,preloadDelay:100,preloadConcurrency:5,waitForPreload:!0,preloadAllImages:!0,forceClearCache:!1,maxPreloadActions:10,cursor:null,cursorHeight:30,cursorWidth:30,showOverflow:!1,maxRouterHistory:10,screenshotQuality:1,useAspectScale:!0,autoForwardDelay:3*1e3,autoForwardDefaultPause:1e3,allowSkipImageTransform:!0,allowSkipImageTransition:!0,allowSkipBackgroundTransform:!0,allowSkipBackgroundTransition:!1,allowSkipTextTransform:!0,allowSkipTextTransition:!0,allowSkipLayersTransform:!0,allowSkipVideo:!1,animationPropagate:!1,dialogWidth:1920,dialogHeight:1080*.2,defaultTextColor:"#000",defaultNametagColor:"#000",notification:Nn.notification,menu:Nn.menu,dialog:Nn.say,nvlDialog:Nn.nvlDialog,onError:e=>{console.error(e)},fontSize:16,fontWeight:400,fontWeightBold:700,fontFamily:"sans-serif",stage:null,defaultMenuChoiceColor:"#000",maxStackModelLoop:1e3,maxActionHistory:100},vt.GameSettingsNamespace=Ls;var B=vt;var Wi=class Wi extends U{static executeActionsAsync(e,t){return e.game.getLiveGame().requestAsyncStackModel([{type:t.type,node:t.contentNode}]).execute()}checkActionChain(e){if(e.some(t=>!!t.contentNode.getChild()))throw new Error("Invalid action chain. Actions are chained unexpectedly.");return e}executeAction(e,t){let n=this.contentNode,[i]=n.getContent();if(this.type===pe.do)return[{type:this.type,node:this.contentNode.getChild()},{type:this.type,node:i[0].contentNode}];if(this.type===pe.doAsync){let r=Wi.executeActionsAsync(e,i[0]);return e.timelines.attachTimeline(r),super.executeAction(e,t)}else if(this.type===pe.any){if(i.length===0)return{type:this.type,node:this.contentNode.getChild()};let r=this.checkActionChain(i).map(s=>e.game.getLiveGame().requestAsyncStackModel([{type:s.type,node:s.contentNode}]));return{type:this.type,node:this.contentNode.getChild(),wait:{type:"any",stackModels:r}}}else if(this.type===pe.all){if(i.length===0)return{type:this.type,node:this.contentNode.getChild()};let r=this.checkActionChain(i).map(s=>e.game.getLiveGame().requestAsyncStackModel([{type:s.type,node:s.contentNode}]));return{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:r}}}else if(this.type===pe.allAsync){if(i.length===0)return{type:this.type,node:this.contentNode.getChild()};let r=this.checkActionChain(i).map(s=>e.game.getLiveGame().requestAsyncStackModel([{type:s.type,node:s.contentNode}]));return e.timelines.attachTimeline(g.all(...r.map(s=>s.execute()))),super.executeAction(e,t)}else if(this.type===pe.repeat){let[r,s]=this.contentNode.getContent();if(s<=0||r.length===0)return super.executeAction(e,t);let a=we.createCountLoop(e.game.getLiveGame(),s,this.checkActionChain(r));return e.logger.debug("ControlAction","repeat",r,s),{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[a]}}}else if(this.type===pe.while){let[r,s]=this.contentNode.getContent();if(r.length===0)return super.executeAction(e,t);if(!s.evaluate({gameState:e}).value)return super.executeAction(e,t);let a=we.createConditionLoop(e.game.getLiveGame(),s,this.getId(),this.checkActionChain(r));return e.logger.debug("ControlAction","while",r),{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[a]}}}else if(this.type===pe.break){if(!t.stackModel.isLoop())throw new Error("Control.breakLoop() can only be used inside a loop (repeat/while)");return t.stackModel.breakLoop(),{type:this.type,node:null}}else if(this.type===pe.sleep){let[,r]=this.contentNode.getContent(),s;typeof r=="number"?s=g.delay(r):g.isAwaitable(r)?s=r:s=g.fromPromise(r);let a=new g,c=new fe(s);return e.timelines.attachTimeline(c),s.then(()=>{a.resolve({type:this.type,node:this.contentNode.getChild()})}),a.onSkipControllerRegister(l=>{l.onAbort(()=>{c.abort()})}),a}else if(this.type===pe.waitForClick){if(e.consumeStageClick())return{type:this.type,node:this.contentNode.getChild()};let r=new g,s=new g,a=new fe(s);e.timelines.attachTimeline(a);let c=e.game.preference,l=c.getPreference(B.Preferences.autoForward),u=c.getPreference(B.Preferences.gameSpeed),m=l?e.game.config.autoForwardDelay/u:null,p=!1,h=null,d=null,T=null,y=()=>{d?.cancel(),T?.cancel(),h&&(clearTimeout(h),h=null)},x=()=>{p||(p=!0,y(),s.resolve())};return d=e.events.on(w.EventTypes["event:state.player.stageClick"],x),T=e.events.on(w.EventTypes["event:state.player.skip"],x),m!==null&&(h=setTimeout(x,m)),s.then(()=>{r.resolve({type:this.type,node:this.contentNode.getChild()})}),r.onSkipControllerRegister(f=>{f.onAbort(()=>{p||(p=!0,y(),a.abort())})}),r}throw new Error("Unknown control action type: "+this.type)}getFutureActions(e,t){if(this.callee.config.allowFutureScene===!1&&t.allowFutureScene===!1)return[...super.getFutureActions(e,t)];if(this.type===pe.break||this.type===pe.waitForClick)return super.getFutureActions(e,t);let n=this.contentNode.getContent()[0],i=super.getFutureActions(e,t);return[...n??[],...i]}stringify(e,t,n){if(this.type===pe.break)return super.stringifyWithContent("Control","break");if(this.type===pe.waitForClick)return super.stringifyWithContent("Control","waitForClick");let i=this.contentNode,[r]=i.getContent();return super.stringifyWithContent("Control",r.map(s=>s.stringify(e,t,n)).join(";"))}};Wi.ActionTypes=pe;var _=Wi;var He=class o extends X{constructor(t={}){super();this.config=t}static do(t){return new o().do(t)}static doAsync(t){return new o().doAsync(t)}static any(t){return new o().any(t)}static all(t){return new o().all(t)}static allAsync(t){return new o().allAsync(t)}static repeat(t,n){return new o().repeat(t,n)}static whileLoop(t,n){return new o().whileLoop(t,n)}static breakLoop(){return new o().breakLoop()}static sleep(t){return new o().sleep(t)}static waitForClick(){return new o().waitForClick()}do(t){return this.push(_.ActionTypes.do,t)}doAsync(t){return this.push(_.ActionTypes.doAsync,t)}any(t){return this.pushUnchained(_.ActionTypes.any,t)}all(t){return this.pushUnchained(_.ActionTypes.all,t)}allAsync(t){return this.pushUnchained(_.ActionTypes.allAsync,t)}repeat(t,n){return this.push(_.ActionTypes.repeat,n,t)}whileLoop(t,n){let i=R.from(t);return this.pushWithLambda(_.ActionTypes.while,n,i)}breakLoop(){let t=new _(this.chain(),_.ActionTypes.break,new v().setContent([]));return this.chain(t)}sleep(t){return this.push(_.ActionTypes.sleep,[],t)}waitForClick(){let t=new _(this.chain(),_.ActionTypes.waitForClick,new v().setContent([]));return this.chain(t)}push(t,n,...i){let r=this.narrativeToActions(n),s=new _(this.chain(),t,new v().setContent([this.construct(r),...i]));return this.chain(s)}pushUnchained(t,n,...i){let r=this.narrativeToActions(n),s=new _(this.chain(),t,new v().setContent([r,...i]));return this.chain(s)}pushWithLambda(t,n,i){let r=this.narrativeToActions(n),s=new _(this.chain(),t,new v().setContent([this.construct(r),i]));return this.chain(s)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?wt.say(n).getActions():ge.toActions([n]))}};var j=class j extends it{static getInitialSrc(e){if(this.isTagDefinition(e.src))return[...e.src.defaults];let t=e.src;return A.isStaticImageData(t)?A.srcToURL(t):A.isColor(t)?t:A.isImageSrc(t)?A.srcToURL(t):j.DefaultImagePlaceholder}static isTagSrc(e){return!!e.config.src}static isTagDefinition(e){return typeof e=="object"&&e!==null&&!A.isImageSrc(e)&&!A.isColor(e)&&"defaults"in e}static isStaticSrc(e){let t=e.userConfig.get().src;return!this.isTagSrc(e)&&(A.isImageSrc(t)||A.isColor(t))}static getSrcURL(e){return typeof e=="string"?e:j.isTagSrc(e)?j.getSrcFromTags(e.state.currentSrc,e.config.src.resolve):j.isStaticSrc(e)?A.isStaticImageData(e.state.currentSrc)?A.srcToURL(e.state.currentSrc):A.isColor(e.state.currentSrc)?null:e.state.currentSrc:null}static getSrcFromTags(e,t){return t(...e)}static fromSrc(e){return new j({src:e})}constructor(e={}){super();let t=j.DefaultUserConfig.create(e),n=this.createImageConfig(t);this.userConfig=t,this.config=n.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(t),this.checkConfig().registerSrc()}char(e,t){return this.combineActions(new He,n=>{if(A.isImageSrc(e)||A.isColor(e)){if(A.isColor(e)&&!this.config.isBackground)throw new Error("Color src is not allowed for non-background image");return n.chain(this._setSrc(n,e,t))}else{let i=new Y(n,Y.ActionTypes.setAppearance,new v().setContent([e,t?.copy()]));return n.chain(i).chain(this._flush())}})}darken(e,t,n){return this.combineActions(new He,i=>i.chain(this._setDarkness(i,e,t,n)))}addWearable(e){let t=Array.isArray(e)?e:[e];for(let n of t){if(n===this)throw new te("Cannot add self as a wearable");this.config.wearables.push(n),Object.assign(n.config,{isWearable:!0})}return this}wear(e){return this.addWearable(e)}bindWearable(e){return e.addWearable([this])}asWearableOf(e){return this.bindWearable(e)}useLayer(e){return this.userConfig.get().layer=e||void 0,Object.assign(this.config,{layer:e||void 0}),this}toData(){return{state:j.StateSerializer.serialize(this.state),transformState:me.TransformStateSerializer.serialize(this.transformState.get())}}fromData(e){return this.state=j.StateSerializer.deserialize(e.state),this.transformState=me.deserialize(e.transformState),this}_applyTransition(e,t){return new Se(this.chain(),he.applyTransition,new v().setContent([e,t]))}_init(e,t){return new Se(this.chain(),he.init,new v().setContent([e,t||this.config.layer||null]))}_initWearable(e){return new Y(this.chain(),Y.ActionTypes.initWearable,new v().setContent([e]))}_flush(){return new Y(this.chain(),Y.ActionTypes.flush,new v)}reset(){return this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(this.userConfig),this}resolveTags(e,t){if(!j.isTagSrc(this))throw new Error(`Tag not defined
47
- Tag must be defined in the image config`);let n=this.constructTagMap(this.config.src.groups),i=new Map,r=[];this.config.src.groups.forEach(a=>{i.set(a,null)});let s=a=>{a.forEach(c=>{let l=n.get(c);l&&i.set(l,c)})};return s(e),s(t),this.config.src.groups.forEach(a=>{let c=i.get(a);if(!c)throw new Error(`Invalid Tag Group. Tag group "${a.join(", ")}" is not resolved`);r.push(c)}),r}_mixedSrcError(){throw new te(`Trying to mix src and tags
46
+ To fix this issue, you can manually register the image using scene.preloadImage(YourImageSrc). `),s.current.push(f.src)),{...f,src:r.get(f.src)||f.src}):f});Mt(o,{createWearable:f=>{i(T=>[...T,f])},disposeWearable:f=>{i(T=>T.filter(C=>C.getId()!==f.getId()))},initDisplayable:u,applyTransform:h,applyTransition:d,events:t,updateStyleSync:m},[...v]);function g(f,T){a.current&&(t.emit("event:image.onLoad"),Object.assign(a.current.style,{width:`${f}px`,height:`${T}px`}))}function S(){t.emit("event:image.onLoad")}return mn.createElement(il.div,{layout:p,ref:c,className:"absolute w-max h-max","data-element-type":"image"},mn.createElement("div",{className:"relative h-full w-full",ref:a,"data-image-id":o.getId()},l.map(([f,T],C)=>mn.createElement(Ls,{key:T,ref:f,autoFit:o.config.autoFit,onSizeChanged:C===0?g:void 0,onLoad:C===0?S:void 0})),mn.createElement("div",{className:Ns("w-full h-full top-0 left-0 absolute")},n.map(f=>mn.createElement("div",{className:Ns("w-full h-full relative"),key:"wearable-"+f.getId()},mn.createElement(Wi,{image:f,state:e}))))))}function Bo({state:o,displayable:e}){return zi.createElement(zi.Fragment,null,e.map(t=>{if(t instanceof Vt)return zi.createElement(Wo,{state:o,text:t,key:"text-"+t.getId()});if(t instanceof U)return zi.createElement(Wi,{state:o,image:t,key:"image-"+t.getId()});throw new Error("Unsupported displayable type: "+(t?.constructor?.name||t))}))}import Bi,{useEffect as ol}from"react";import{motion as rl}from"motion/react";function Ms({state:o,layer:e,children:t}){let{transformRef:n,transitionRefs:i,initDisplayable:r,applyTransition:s,applyTransform:a,updateStyleSync:c,deps:l}=dn({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipLayersTransform,skipTransition:!1,transitionsProps:[{style:{width:"100%",height:"100%",transformOrigin:"center"}}]});return Mt(e,{initDisplayable:r,applyTransition:s,applyTransform:a,updateStyleSync:c},[...l]),ol(()=>(o.logger.debug("Layer","Layer mounted",e.getId()),()=>{o.logger.debug("Layer","Layer unmounted",e.getId())}),[]),Bi.createElement(Bi.Fragment,null,Bi.createElement(rl.div,{layout:!0,className:"absolute w-full h-full",ref:n,"data-element-type":"layer","data-layer-id":e.getId(),key:`layer-${e.getId()}`},i.map(([p,u])=>Bi.createElement("div",{className:"relative w-full h-full",ref:p,key:u},t))))}import sl from"clsx";import{AnimatePresence as al}from"motion/react";import{useEffect as $o,useReducer as cl,useRef as Vn}from"react";import Qt from"react";var ll=120;function jo({state:o,className:e,elements:t}){let{scene:n,layers:i,texts:r,menus:s}=t,a=Vn(!1),c=Vn({slotKeys:new Map,exitingKeys:new Set,menuPromptIds:new WeakMap,nextKey:0}),l=Vn([]),p=Vn(null),u=Vn(null),[,d]=cl(g=>g+1,0),h=()=>{u.current&&(clearTimeout(u.current),u.current=null)},m=()=>{let g=p.current;if(!g)return;let S=c.current;g.forEach(({slot:f,presenceKey:T})=>{S.slotKeys.get(f)===T&&S.slotKeys.delete(f),S.exitingKeys.add(T)}),p.current=null,u.current=null,l.current=[],d()};$o(()=>n.events.depends([n.events.on(ze.EventTypes["event:scene.preUnmount"],()=>{if(n.state.backgroundMusic)return o.audioManager.stop(n.state.backgroundMusic,n.config.backgroundMusicFade)})]).cancel,[]),$o(()=>(n.events.emit(ze.EventTypes["event:scene.mount"]),o.logger.debug("Scene","Scene mounted",n.getId()),()=>{n.events.emit(ze.EventTypes["event:scene.unmount"]),o.logger.debug("Scene","Scene unmounted",n.getId())}),[]),$o(()=>()=>{h()},[]),Mt(n,{setBackgroundMusic(g,S){return new Promise(f=>{(async function(){n.state.backgroundMusic&&o.audioManager.isManaged(n.state.backgroundMusic)&&await o.audioManager.stop(n.state.backgroundMusic,S),g?(await o.audioManager.play(g,{end:g.state.volume,duration:S}),n.state.backgroundMusic=g):n.state.backgroundMusic=null,f()})()})}});let v=(()=>{let g=c.current,S=r.length>0?r.map(({action:C,onClick:I},N)=>({action:C,slot:N,useTypeEffect:!a.current,onFinished:X=>{X!==void 0&&(a.current=X),I(),o.events.emit(k.EventTypes["event:state.player.lineEnd"]),o.stage.next()}})):s.flatMap((C,I)=>{if(!C.action.prompt||!C.action.words)return[];let N=g.menuPromptIds.get(C);return N||(N=`menu-prompt-${n.getId()}-${g.nextKey++}`,g.menuPromptIds.set(C,N)),[{action:{sentence:C.action.prompt,words:C.action.words,character:null,id:N},slot:I,useTypeEffect:!1}]});if(S.length===0)return!p.current&&l.current.length>0&&(p.current=l.current.map(C=>({...C,active:!1}))),p.current&&!u.current&&(u.current=setTimeout(m,ll)),p.current??[];h(),p.current=null;let f=new Set(S.map(({slot:C})=>C));for(let[C,I]of Array.from(g.slotKeys))f.has(C)||(g.exitingKeys.add(I),g.slotKeys.delete(C));let T=S.map(({slot:C,...I})=>{let N=g.slotKeys.get(C);return(!N||g.exitingKeys.has(N))&&(N=`say-${n.getId()}-${g.nextKey++}`,g.slotKeys.set(C,N)),{...I,presenceKey:N,slot:C,active:!0}});return l.current=T,T})();return Qt.createElement("div",{className:sl(e,"w-full h-full absolute")},[...i.entries()].sort(([g],[S])=>g.state.zIndex-S.state.zIndex).map(([g,S])=>Qt.createElement(Ms,{state:o,layer:g,key:g.getId()},Qt.createElement(Bo,{state:o,displayable:S}))),Qt.createElement(al,{propagate:o.game.config.animationPropagate,onExitComplete:()=>{c.current.exitingKeys.clear()}},v.map(({action:g,onFinished:S,presenceKey:f,active:T,useTypeEffect:C})=>Qt.createElement(Rn,{gameState:o,key:f,action:g,active:T,onFinished:S,useTypeEffect:C}))),s.map(({action:g,onClick:S},f)=>Qt.createElement("div",{key:"menu-"+f,"data-element-type":"menu"},Qt.createElement(Ko,{state:o,prompt:g.prompt,choices:g.choices,renderPrompt:!g.prompt,afterChoose:T=>{a.current=!1,S(T),o.stage.next()},words:g.words}))))}import ul from"react";import{useEffect as qo,useRef as pl}from"react";import{useCallback as Gs}from"react";function Hs(o){let e=Gs(()=>{if(!o.current)return;let n=o.current;n.style.opacity="1",n.style.pointerEvents="auto",n.style.visibility="visible"},[o]),t=Gs(()=>{if(!o.current)return;let n=o.current;n.style.opacity="0",n.style.pointerEvents="none",n.style.visibility="hidden"},[o]);return{show:e,hide:t}}function Qo({gameState:o,video:e}){let t=pl(null),{show:n,hide:i}=Hs(t);qo(()=>o.events.depends([o.events.on(k.EventTypes["event:state.player.skip"],()=>{o.game.config.allowSkipVideo&&(r(),o.logger.log("NarraLeaf-React: Video","Skipped"))})]).cancel,[]),qo(()=>{i(),e.state.display&&n()},[]),qo(()=>{if(!t.current)return;let s=t.current,a=!1,c=()=>new x(`Failed to add event listener, ref is not available
47
+ at Video.tsx: useEffect`),l=()=>{a||!s||(a=!0,o.mountState(e,{show:()=>{if(!t.current)throw c();n()},hide:()=>{if(!t.current)throw c();i()},play:()=>{if(!t.current)throw c();let u=t.current;return u.currentTime=0,new Promise(d=>{o.schedule(({retry:h})=>{if(u.readyState<3){let S=()=>{u.removeEventListener("loadeddata",S),h()};u.addEventListener("loadeddata",S);return}let m=()=>{g(),d()},v=()=>{g(),d()},g=()=>{u.removeEventListener("ended",m),u.removeEventListener("stopped",v)};u.addEventListener("ended",m),u.addEventListener("stopped",v),p.push(g),u.play().catch(S=>{o.logger.error("Failed to play video: "+S),g(),d()})},10)})},pause:()=>{if(!t.current)throw c();t.current.pause()},resume:()=>{if(!t.current)throw c();return t.current.play()},stop:()=>{if(!t.current)throw c();t.current.pause(),t.current.dispatchEvent(new Event("stopped"))},seek:u=>{if(!t.current)throw c();t.current.currentTime=u}}))},p=[];return s.addEventListener("canplay",l),()=>{a=!1,s.removeEventListener("canplay",l),p.forEach(u=>u()),s.currentTime>0&&s.pause(),o.isStateMounted(e)&&o.unMountState(e)}},[o,e]);function r(){t.current&&(t.current.pause(),t.current.currentTime=0,t.current.dispatchEvent(new Event("stopped")))}return ul.createElement("video",{ref:t,src:e.config.src,preload:"auto",muted:e.config.muted,playsInline:!0,width:"100%",height:"100%",onContextMenu:s=>s.preventDefault()})}import dl from"clsx";import ml,{useCallback as fl,useEffect as $i,useRef as hl}from"react";function Xo({children:o,className:e,gameState:t}){let{ratio:n}=pe(),i=w(),[r]=Z(),s=hl(null),a=i.config.minWidth,c=i.config.minHeight,l=fl(p=>{if(n.isLocked()){t.logger.weakWarn("AspectRatio","ratio is locked, skipping update");return}n.update(p.width,p.height,p.scale),n.updateMin(a,c),r()},[r,t.logger,c,a,n]);return $i(()=>{n.setUpdate(()=>{s.current?.requestUpdate()})},[n]),$i(()=>n.onRequestedUpdate(()=>{s.current?.requestUpdate()}),[n]),$i(()=>{let p=requestAnimationFrame(()=>{s.current?.requestUpdate()});return()=>{cancelAnimationFrame(p)}},[i.config.aspectRatio,i.config.height,i.config.width,c,a]),$i(()=>t.events.on(k.EventTypes["event:state.player.requestFlush"],r).cancel,[t,r]),ml.createElement(ps,{ref:s,id:i.config.contentContainerId,aspectRatio:i.config.aspectRatio,baseWidth:i.config.width,minWidth:a,minHeight:c,debounceMs:i.config.ratioUpdateInterval,className:dl(e),onUpdate:l},o)}import Us,{useEffect as gl,useRef as yl,useState as Fs}from"react";function Yo({src:o,width:e,height:t}){let[n,i]=Fs({x:0,y:0}),[r,s]=Fs(!1),a=yl(null),{ratio:c}=pe();return gl(()=>{let l=p=>{if(a.current){let u=a.current.getBoundingClientRect(),d=p.clientX-u.left,h=p.clientY-u.top;i({x:d,y:h}),r||s(!0)}};return window.addEventListener("mousemove",l),()=>{window.removeEventListener("mousemove",l)}},[r]),Us.createElement(dt,{ref:a,className:"overflow-hidden absolute"},Us.createElement("img",{src:o,style:{position:"absolute",left:n.x,top:n.y,width:e,height:t,pointerEvents:"none",zIndex:1001,display:r?"block":"none",cursor:"none",transform:`scale(${c.state.scale})`},alt:""}))}import Ks from"react";import Ct from"react";function Jo({error:o,errorInfo:e}){return w().config.app.debug?Ct.createElement("div",{className:"text-left"},Ct.createElement("h1",null,"NarraLeaf-React cannot initialize the player correctly. (development mode)"),Ct.createElement("p",{className:"text-red-700"},"Message: ",o.message),Ct.createElement("pre",null,"Error Stack: ",o?.stack),Ct.createElement("pre",null,"Component Stack: ",e?.componentStack),Ct.createElement("pre",null,"Digest: ","digest"in e?String(e.digest):"")):Ct.createElement("div",{className:"bg-white w-full h-full"},Ct.createElement("h1",null,"NarraLeaf-React crashed due to an unknown error."),Ct.createElement("p",null,"Please contact the game developer for further assistance."))}var ji=class extends Ks.Component{constructor(){super(...arguments);this.state={hasError:!1,error:null,errorInfo:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t,errorInfo:null}}componentDidCatch(t,n){this.setState({error:t,errorInfo:n}),this.props.onError?.(t,n),console.error(t,n)}render(){return this.state.hasError?Ks.createElement(Jo,{error:this.state.error,errorInfo:this.state.errorInfo}):this.props.children}};import Ws from"clsx";import B,{useEffect as Xt,useReducer as bl,useState as Wn}from"react";import{flushSync as zs}from"react-dom";import{useRef as vl}from"react";import{useEffect as Sl}from"react";function Vs({gameState:o}){let e=vl(null);return Sl(()=>(e.current=requestAnimationFrame(()=>{setTimeout(()=>{o.events.emit(k.EventTypes["event:state.onRender"])},0)}),()=>{e.current!==null&&cancelAnimationFrame(e.current)}),[o.deps]),null}import On,{useEffect as Tl}from"react";function Zo({gameState:o}){let[e]=Z(),{ratio:t}=pe(),n=o.notificationMgr;Tl(()=>n.onFlush(()=>{e()}).cancel,[]);let i=o.game.config.notification;return On.createElement("div",{style:{transform:`scale(${t.state.scale})`,transformOrigin:"left top"},className:"absolute top-0 left-0 w-full h-full pointer-events-none","data-element-type":"notification"},On.createElement(i,{notifications:n.toArray()}))}function Os({notifications:o}){return On.createElement(Ri,{className:"absolute top-0 left-0 w-full h-full"},o.map(({id:e,message:t})=>On.createElement("div",{key:e,className:"absolute top-0 left-0 w-[100px] h-[80px]"},On.createElement("span",{className:"text-white text-2xl font-bold"},t))))}function Bs({story:o=Pn.empty(),width:e,height:t,className:n,onReady:i,onPreloadedReady:r,onEnd:s,onError:a,children:c,active:l=!0}){let[p,u]=bl(L=>L+1,0),[d,h]=Wn(0),m=w(),[v]=Wn(()=>new k(m,{update:u,forceUpdate:()=>{v.logger.weakWarn("Player","force update"),zs(()=>{u()})},forceRemount:()=>{v.logger.weakWarn("Player","force remount"),zs(()=>{h(L=>L+1),u()})},next:Ne})),g=B.createRef(),S=B.createRef(),[f,T]=Wn(!1),C=B.useRef(!1),I=B.useRef(null),N=B.useRef(null),{preloaded:X}=pn(),[he,ge]=Wn(!1),ye=B.useRef(!1),[Re]=Wn(new Map);function Ne(){let L=()=>{Re.forEach(P=>P.cancel())};if(v.rollLock.isLocked())return;L();let z=!1,$=0;for(;!z;){if($++>m.config.maxStackModelLoop)throw new x("Max stack model loop reached");let P=m.getLiveGame().next();if(!P){if(m.getLiveGame().stackModel&&!m.getLiveGame().stackModel.isEmpty())continue;break}if(y.isAwaitable(P)){if(I.current===P)break;I.current=P,P.onSettled(()=>{P.isFailed()||(I.current===P&&(I.current=null),Ne())}),P.onFailed(M=>{I.current===P&&(I.current=null),v.logger.error("Player",M)}),z=!0;break}if(P instanceof _t){if(N.current===P)break;N.current=P,P.nextUnlock().then(()=>{N.current===P&&(N.current=null),Ne()}),z=!0;break}if(Ie.isCalledActionResult(P)&&P.wait&&Ie.isStackModelsAwaiting(P.wait.type,P.wait.stackModels)){if(I.current===P)break;if(I.current=P,P.wait){let M=Ie.executeStackModelGroup(P.wait.type,P.wait.stackModels);M.then(()=>{I.current===P&&(I.current=null),Ne()}),M.onFailed(K=>{I.current===P&&(I.current=null),v.logger.error("Player",K)})}z=!0;break}v.handle(P)}v.stage.update()}Xt(()=>{v.audioManager.initialize()},[]),Xt(()=>(m.getLiveGame().setGameState(v),o&&!m.getLiveGame().isPlaying()&&m.getLiveGame().loadStory(o),v.playerCurrent=g.current,v.mainContentNode=S.current,()=>{m.getLiveGame().setGameState(void 0),v.playerCurrent=null}),[m,o]),Xt(()=>We(()=>{T(!0);let L=v.getLastScene(),z=[];L?z.push(L.events.once("event:scene.mount",()=>{v.stage.next()}).cancel):v.stage.next();let $=v.events.on(k.EventTypes["event:state.end"],()=>{s&&s({game:m,gameState:v,liveGame:m.getLiveGame(),storable:m.getLiveGame().getStorable()})});return v.stage.update(),()=>{L&&z.forEach(P=>P()),$.cancel()}}),[]),Xt(()=>We(()=>{f&&i&&!C.current&&(C.current=!0,v.stage.forceUpdate(),m.hooks.trigger("init",[]),i({game:m,gameState:v,liveGame:m.getLiveGame(),storable:m.getLiveGame().getStorable()}))}),[f]),Xt(()=>We(()=>{he&&r&&!ye.current&&(ye.current=!0,r({game:m,gameState:v,liveGame:m.getLiveGame(),storable:m.getLiveGame().getStorable()}))}),[he]),Xt(()=>X.events.depends([X.events.on($e.EventTypes["event:preloaded.ready"],()=>{ge(!0),v.stage.update(),o&&m.getLiveGame().isPlaying()&&Ne()})]).cancel,[]),Xt(()=>{v.flushDep=p},[p]);let ot=e||m.config.width,R=t||m.config.height;return B.createElement(ji,{onError:a},B.createElement("div",{style:{width:typeof ot=="number"?`${ot}px`:ot,height:typeof R=="number"?`${R}px`:R},className:Ws(n,"__narraleaf_content-player"),ref:g,tabIndex:0},B.createElement(Xo,{className:Ws("flex-grow overflow-auto"),gameState:v},B.createElement(Go,{gameState:v}),B.createElement(Vs,{gameState:v}),B.createElement(dt,{className:"absolute",ref:S,style:{cursor:v.game.config.cursor?"none":"auto",overflow:v.game.config.showOverflow?"visible":"hidden"}},m.config.cursor&&B.createElement(Yo,{src:m.config.cursor,width:m.config.cursorWidth,height:m.config.cursorHeight}),B.createElement(Al,{show:he&&l,key:d},B.createElement(Lo,null,B.createElement(ys,{state:v}),B.createElement(bs,{state:v}),v.getSceneElements().map(L=>B.createElement(jo,{key:"scene-"+L.scene.getId(),state:v,elements:L})),v.getVideos().map((L,z)=>B.createElement("div",{className:"w-full h-full absolute",key:"video-"+z,"data-element-type":"video"},B.createElement(Qo,{gameState:v,video:L}))),B.createElement(Cl,{NvlComponent:m.config.nvlDialog}))),B.createElement(xs,{state:v}),B.createElement(rs,null,c),B.createElement(Zo,{gameState:v})))))}function Al({children:o,show:e}){return B.createElement(B.Fragment,null,e?o:null)}function Cl({NvlComponent:o}){let{dialogs:e,state:t}=mt(),i=w().getLiveGame().getGameState(),r=B.useMemo(()=>e.map((s,a)=>{let c=s.sentence.evaluate(ue.getCtx({gameState:i})),l=t.activeDialogId===s.id,p=l&&t.phase==="typing";return{entry:s,index:a,isActive:l,gameState:i,words:c,useTypeEffect:p}}),[e,i,t.activeDialogId,t.phase]);return B.createElement(o,{dialogs:r})}import"client-only";import fn from"react";function $s({children:o,game:e}){return fn.createElement(fn.Fragment,null,fn.createElement(Vr,null,fn.createElement(Gr,{game:e},fn.createElement(Cs,null,fn.createElement(Kr,null,o)))))}var xl=(r=>(r.image="narraleaf:image",r.text="narraleaf:text",r.layer="narraleaf:layer",r.scene="narraleaf:scene",r.video="narraleaf:video",r))(xl||{});import wl from"clsx";import ht,{useEffect as js,useRef as kl}from"react";import{motion as Pl,useIsPresent as El}from"motion/react";function Dl({children:o,initial:e,transition:t,...n}){let i=w(),r=et(),{ratio:s}=pe(),[a]=_e(Q.Preferences.showDialog),c=kl(null),[l]=$t("nextAction"),p=El();function u(){r.requestComplete()}return js(()=>{if(!window){console.warn(`Failed to add event listener, window is not available
48
+ at Say.tsx: onElementClick`);return}let d=m=>{i.keyMap.match("nextAction",m.key)&&r.requestComplete()};window.addEventListener("keyup",d);let h=r.events.on(fe.Events.simulateClick,()=>{c.current&&c.current.click()});return()=>{window.removeEventListener("keyup",d),h.cancel()}},[r,l]),js(()=>{let d=i.preference.onPreferenceChange(Q.Preferences.autoForward,h=>{h&&r.isEnded()?r.tryScheduleAutoForward():r.cancelAutoForward()});return()=>{d.cancel()}},[r]),ht.createElement("div",{"data-element-type":"dialog",className:"absolute w-full h-full"},ht.createElement("div",{className:wl("absolute bottom-0 w-full h-full",!a&&"invisible pointer-events-auto"),onClick:u,style:{...ei(i.config.useAspectScale,{maxWidth:i.config.dialogWidth,maxHeight:i.config.dialogHeight,transform:`scale(${s.state.scale})`,transformOrigin:"bottom left",width:i.config.width,height:i.config.height})},ref:c},ht.createElement(Pl.div,{...n,initial:r.config.suppressInitialAnimation?!1:e,transition:r.config.suppressInitialAnimation&&p?{duration:0}:t},o)))}function qs({children:o,...e}){let t=et();return!t.config.action.sentence||!t.config.action.words?null:ht.createElement(Dl,{...e},o)}var zc=qs;function Qs(){return ht.createElement(qs,null,ht.createElement("div",{className:"dialog-content",style:{display:"flex",alignItems:"flex-start",gap:16,width:"100%",height:"100%"}},ht.createElement(Ao,null),ht.createElement("div",{className:"dialog-text-content",style:{minWidth:0,flex:"1 1 auto"}},ht.createElement(Nt,null),ht.createElement(Rt,null))))}var zn={say:Qs,menu:ws,notification:Os,nvlDialog:No};var qi=class{constructor(e){this.game=e;this.plugins=[];this.registerAll()}use(e){return this.plugins.push(e),this}register(e){e.register(this.game)}registerAll(){this.plugins.forEach(e=>e.register(this.game))}unregisterAll(){this.plugins.forEach(e=>e.unregister(this.game))}has(e){return this.plugins.some(t=>t.name===e.name)}};var Bn=class{constructor(e={}){this.keyMap=e;this.events=new J}setKeyBinding(e,t){this.keyMap[e]=t,this.events.emit("event:keyMap.change",e,t)}getKeyBinding(e){return this.keyMap[e]??null}addKeyBinding(e,t){if(t===null)return;let n=this.getKeyBinding(e)??[],i=r=>Array.isArray(r)?r:[r];Array.isArray(n)?this.setKeyBinding(e,[...n,...i(t)]):this.setKeyBinding(e,[n,...i(t)])}getKeyBindings(){return this.keyMap}onKeyBindingChange(e,t){return this.events.on("event:keyMap.change",(n,i)=>{n===e&&t(i)})}importKeyBindings(e){for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&this.setKeyBinding(t,e[t])}exportKeyBindings(){return this.keyMap}match(e,t){let n=this.getKeyBinding(e);return n===null?!1:Array.isArray(n)?n.includes(t)||n.some(i=>i.toLowerCase()===t.toLowerCase()):n===t||n.toLowerCase()===t.toLowerCase()}};var Xs=(e=>(e.game="game",e))(Xs||{}),xt=class xt{constructor(e){this.hooks=new Yn;this.liveGame=null;this.sideEffect=[];this.freezeFields=[];this.preference=new Ln(xt.DefaultPreference);this.keyMap=new Bn({skipAction:["Control"],nextAction:[" "]});this.config=H(xt.DefaultConfig,e),this.plugins=new qi(this),this.router=new It(this)}configure(e){let[t,n]=vr(e,this.freezeFields);return n.length>0&&console.warn(`NarraLeaf-React [Game] The following fields are not allowed to be configured: ${n.join(", ")}`),this.config=H(this.config,t),this.getLiveGame().getGameState()?.events.emit(k.EventTypes["event:state.player.requestFlush"]),this}configureAndFreeze(e){return this.configure(e),this.freeze(Object.keys(e)),this}freeze(e){return this.freezeFields.push(...e),this}use(e){return this.plugins.has(e)||this.plugins.use(e).register(e),this}getLiveGame(){if(!this.liveGame){let e=this.createLiveGame();return this.liveGame=e,e}return this.liveGame}dispose(){this.plugins.unregisterAll(),this.liveGame?.dispose(),this.sideEffect.forEach(e=>e())}addSideEffect(e){this.sideEffect.push(e)}createLiveGame(){return new lt(this)}};xt.defaultSettings={volume:1},xt.DefaultPreference={autoForward:!1,skip:!0,showDialog:!0,gameSpeed:1,cps:10,voiceVolume:1,voiceFadeDuration:0,voiceEndMode:"stop",bgmVolume:1,soundVolume:1,globalVolume:1,skipDelay:500,skipInterval:100},xt.Preferences={autoForward:"autoForward",skip:"skip",showDialog:"showDialog",gameSpeed:"gameSpeed",cps:"cps",voiceVolume:"voiceVolume",voiceFadeDuration:"voiceFadeDuration",voiceEndMode:"voiceEndMode",bgmVolume:"bgmVolume",soundVolume:"soundVolume",globalVolume:"globalVolume",skipDelay:"skipDelay",skipInterval:"skipInterval"},xt.DefaultConfig={app:{debug:!1,logger:{log:!1,info:!1,warn:!0,error:!0,debug:!1,trace:!1,verbose:!1},inspector:!1,guard:{invalidExposedStateUnmounting:!0,unexpectedTimelineStatusChange:!0}},contentContainerId:"__narraleaf_content",aspectRatio:16/9,minWidth:800,minHeight:450,width:1920,height:1080,useWindowListener:!0,ratioUpdateInterval:50,preloadDelay:100,preloadConcurrency:5,waitForPreload:!0,preloadAllImages:!0,forceClearCache:!1,maxPreloadActions:10,cursor:null,cursorHeight:30,cursorWidth:30,showOverflow:!1,maxRouterHistory:10,screenshotQuality:1,useAspectScale:!0,autoForwardDelay:3*1e3,autoForwardDefaultPause:1e3,allowSkipImageTransform:!0,allowSkipImageTransition:!0,allowSkipBackgroundTransform:!0,allowSkipBackgroundTransition:!1,allowSkipTextTransform:!0,allowSkipTextTransition:!0,allowSkipLayersTransform:!0,allowSkipVideo:!1,animationPropagate:!1,dialogWidth:1920,dialogHeight:1080*.2,defaultTextColor:"#000",defaultNametagColor:"#000",notification:zn.notification,menu:zn.menu,dialog:zn.say,nvlDialog:zn.nvlDialog,onError:e=>{console.error(e)},fontSize:16,fontWeight:400,fontWeightBold:700,fontFamily:"sans-serif",stage:null,defaultMenuChoiceColor:"#000",maxStackModelLoop:1e3,maxActionHistory:100},xt.GameSettingsNamespace=Xs;var Q=xt;var Qi=class Qi extends O{static executeActionsAsync(e,t){let n=e.game.getLiveGame().requestAsyncStackModel([{type:t.type,node:t.contentNode}]);return e.game.getLiveGame().executeAsyncStackModel(n)}checkActionChain(e){if(e.some(t=>!!t.contentNode.getChild()))throw new Error("Invalid action chain. Actions are chained unexpectedly.");return e}executeAction(e,t){let n=this.contentNode,[i]=n.getContent();if(this.type===ve.do)return[{type:this.type,node:this.contentNode.getChild()},{type:this.type,node:i[0].contentNode}];if(this.type===ve.doAsync){let r=Qi.executeActionsAsync(e,i[0]);return e.timelines.attachTimeline(r),super.executeAction(e,t)}else if(this.type===ve.any){if(i.length===0)return{type:this.type,node:this.contentNode.getChild()};let r=this.checkActionChain(i).map(s=>e.game.getLiveGame().createStackModel([{type:s.type,node:s.contentNode}]));return{type:this.type,node:this.contentNode.getChild(),wait:{type:"any",stackModels:r}}}else if(this.type===ve.all){if(i.length===0)return{type:this.type,node:this.contentNode.getChild()};let r=this.checkActionChain(i).map(s=>e.game.getLiveGame().createStackModel([{type:s.type,node:s.contentNode}]));return{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:r}}}else if(this.type===ve.allAsync){if(i.length===0)return{type:this.type,node:this.contentNode.getChild()};let r=this.checkActionChain(i).map(s=>e.game.getLiveGame().requestAsyncStackModel([{type:s.type,node:s.contentNode}]));return e.timelines.attachTimeline(y.all(...r.map(s=>e.game.getLiveGame().executeAsyncStackModel(s)))),super.executeAction(e,t)}else if(this.type===ve.repeat){let[r,s]=this.contentNode.getContent();if(s<=0||r.length===0)return super.executeAction(e,t);let a=Ie.createCountLoop(e.game.getLiveGame(),s,this.checkActionChain(r));return e.logger.debug("ControlAction","repeat",r,s),{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[a]}}}else if(this.type===ve.while){let[r,s]=this.contentNode.getContent();if(r.length===0)return super.executeAction(e,t);if(!s.evaluate({gameState:e}).value)return super.executeAction(e,t);let a=Ie.createConditionLoop(e.game.getLiveGame(),s,this.getId(),this.checkActionChain(r));return e.logger.debug("ControlAction","while",r),{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[a]}}}else if(this.type===ve.break){if(!t.stackModel.isLoop())throw new Error("Control.breakLoop() can only be used inside a loop (repeat/while)");return t.stackModel.breakLoop(),{type:this.type,node:null}}else if(this.type===ve.sleep){let[,r]=this.contentNode.getContent(),s;typeof r=="number"?s=y.delay(r):y.isAwaitable(r)?s=r:s=y.fromPromise(r);let a=new y,c=new Te(s);return e.timelines.attachTimeline(c),s.then(()=>{a.resolve({type:this.type,node:this.contentNode.getChild()})}),a.onSkipControllerRegister(l=>{l.onAbort(()=>{c.abort()})}),a}else if(this.type===ve.waitForClick){if(e.consumeStageClick())return{type:this.type,node:this.contentNode.getChild()};let r=new y,s=new y,a=new Te(s);e.timelines.attachTimeline(a);let c=e.game.preference,l=c.getPreference(Q.Preferences.autoForward),p=c.getPreference(Q.Preferences.gameSpeed),u=l?e.game.config.autoForwardDelay/p:null,d=!1,h=null,m=null,v=null,g=()=>{m?.cancel(),v?.cancel(),h&&(clearTimeout(h),h=null)},S=()=>{d||(d=!0,g(),s.resolve())};return m=e.events.on(k.EventTypes["event:state.player.stageClick"],S),v=e.events.on(k.EventTypes["event:state.player.skip"],S),u!==null&&(h=setTimeout(S,u)),s.then(()=>{r.resolve({type:this.type,node:this.contentNode.getChild()})}),r.onSkipControllerRegister(f=>{f.onAbort(()=>{d||(d=!0,g(),a.abort())})}),r}throw new Error("Unknown control action type: "+this.type)}getFutureActions(e,t){if(this.callee.config.allowFutureScene===!1&&t.allowFutureScene===!1)return[...super.getFutureActions(e,t)];if(this.type===ve.break||this.type===ve.waitForClick)return super.getFutureActions(e,t);let n=this.contentNode.getContent()[0],i=super.getFutureActions(e,t);return[...n??[],...i]}stringify(e,t,n){if(this.type===ve.break)return super.stringifyWithContent("Control","break");if(this.type===ve.waitForClick)return super.stringifyWithContent("Control","waitForClick");let i=this.contentNode,[r]=i.getContent();return super.stringifyWithContent("Control",r.map(s=>s.stringify(e,t,n)).join(";"))}};Qi.ActionTypes=ve;var se=Qi;var xe=class o extends te{constructor(t={}){super();this.config=t}static do(t){return new o().do(t)}static doAsync(t){return new o().doAsync(t)}static any(t){return new o().any(t)}static all(t){return new o().all(t)}static allAsync(t){return new o().allAsync(t)}static repeat(t,n){return new o().repeat(t,n)}static whileLoop(t,n){return new o().whileLoop(t,n)}static breakLoop(){return new o().breakLoop()}static sleep(t){return new o().sleep(t)}static waitForClick(){return new o().waitForClick()}do(t){return this.push(se.ActionTypes.do,t)}doAsync(t){return this.push(se.ActionTypes.doAsync,t)}any(t){return this.pushUnchained(se.ActionTypes.any,t)}all(t){return this.pushUnchained(se.ActionTypes.all,t)}allAsync(t){return this.pushUnchained(se.ActionTypes.allAsync,t)}repeat(t,n){return this.push(se.ActionTypes.repeat,n,t)}whileLoop(t,n){let i=F.from(t);return this.pushWithLambda(se.ActionTypes.while,n,i)}breakLoop(){let t=new se(this.chain(),se.ActionTypes.break,new b().setContent([]));return this.chain(t)}sleep(t){return this.push(se.ActionTypes.sleep,[],t)}waitForClick(){let t=new se(this.chain(),se.ActionTypes.waitForClick,new b().setContent([]));return this.chain(t)}push(t,n,...i){let r=this.narrativeToActions(n),s=new se(this.chain(),t,new b().setContent([this.construct(r),...i]));return this.chain(s)}pushUnchained(t,n,...i){let r=this.narrativeToActions(n),s=new se(this.chain(),t,new b().setContent([r,...i]));return this.chain(s)}pushWithLambda(t,n,i){let r=this.narrativeToActions(n),s=new se(this.chain(),t,new b().setContent([this.construct(r),i]));return this.chain(s)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?St.say(n).getActions():Ae.toActions([n]))}};var _=class _ extends at{static getInitialSrc(e){if(this.isTagDefinition(e.src))return[...e.src.defaults];let t=e.src;return A.isStaticImageData(t)?A.srcToURL(t):A.isColor(t)?t:A.isImageSrc(t)?A.srcToURL(t):_.DefaultImagePlaceholder}static isTagSrc(e){return!!e.config.src}static isTagDefinition(e){return typeof e=="object"&&e!==null&&!A.isImageSrc(e)&&!A.isColor(e)&&"defaults"in e}static isStaticSrc(e){let t=e.userConfig.get().src;return!this.isTagSrc(e)&&(A.isImageSrc(t)||A.isColor(t))}static getSrcURL(e){return typeof e=="string"?e:_.isTagSrc(e)?_.getSrcFromTags(e.state.currentSrc,e.config.src.resolve):_.isStaticSrc(e)?A.isStaticImageData(e.state.currentSrc)?A.srcToURL(e.state.currentSrc):A.isColor(e.state.currentSrc)?null:e.state.currentSrc:null}static getSrcFromTags(e,t){return t(...e)}static fromSrc(e){return new _({src:e})}constructor(e={}){super();let t=_.DefaultUserConfig.create(e),n=this.createImageConfig(t);this.userConfig=t,this.config=n.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(t),this.checkConfig().registerSrc()}char(e,t){return this.combineActions(new xe,n=>{if(A.isImageSrc(e)||A.isColor(e)){if(A.isColor(e)&&!this.config.isBackground)throw new Error("Color src is not allowed for non-background image");return n.chain(this._setSrc(n,e,t))}else{let i=new ne(n,ne.ActionTypes.setAppearance,new b().setContent([e,t?.copy()]));return n.chain(i).chain(this._flush())}})}darken(e,t,n){return this.combineActions(new xe,i=>i.chain(this._setDarkness(i,e,t,n)))}addWearable(e){let t=Array.isArray(e)?e:[e];for(let n of t){if(n===this)throw new ce("Cannot add self as a wearable");this.config.wearables.push(n),Object.assign(n.config,{isWearable:!0})}return this}wear(e){return this.addWearable(e)}bindWearable(e){return e.addWearable([this])}asWearableOf(e){return this.bindWearable(e)}useLayer(e){return this.userConfig.get().layer=e||void 0,Object.assign(this.config,{layer:e||void 0}),this}toData(){return{state:_.StateSerializer.serialize(this.state),transformState:me.TransformStateSerializer.serialize(this.transformState.get())}}fromData(e){return this.state=_.StateSerializer.deserialize(e.state),this.transformState=me.deserialize(e.transformState),this}_applyTransition(e,t){return new Ce(this.chain(),be.applyTransition,new b().setContent([e,t]))}_init(e,t){return new Ce(this.chain(),be.init,new b().setContent([e,t||this.config.layer||null]))}_initWearable(e){return new ne(this.chain(),ne.ActionTypes.initWearable,new b().setContent([e]))}_flush(){return new ne(this.chain(),ne.ActionTypes.flush,new b)}reset(){return this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(this.userConfig),this}resolveTags(e,t){if(!_.isTagSrc(this))throw new Error(`Tag not defined
49
+ Tag must be defined in the image config`);let n=this.constructTagMap(this.config.src.groups),i=new Map,r=[];this.config.src.groups.forEach(a=>{i.set(a,null)});let s=a=>{a.forEach(c=>{let l=n.get(c);l&&i.set(l,c)})};return s(e),s(t),this.config.src.groups.forEach(a=>{let c=i.get(a);if(!c)throw new Error(`Invalid Tag Group. Tag group "${a.join(", ")}" is not resolved`);r.push(c)}),r}_mixedSrcError(){throw new ce(`Trying to mix src and tags
48
50
  To better understand the behavior of the image, you cannot mix static src and tags in the same image. `)}_invalidSrcHandlerError(){throw new Error("Invalid src handler, If you are using tags, config.src must be a function that resolves the src from the tags. If you are using src, config.src must be a string or StaticImageData")}_invalidWearableError(e){throw new Error(`Invalid wearable
49
51
  Wearable must be an Image with isWearable set to true
50
52
  It seems like you are trying to add a non-wearable image to wearables
51
53
  Image below violates the rule:
52
- `+e)}_invalidTagGroupDefinitionError(){throw new Error("Invalid tag group definition. Tags in groups must be unique and not conflicting with each other.")}_setSrc(e,t,n){return n&&e.chain(this._applyTransition(n.copy(),i=>i._setPrevSrc(Y.resolveCurrentSrc(this))._setTargetSrc(t))),new Y(e,Y.ActionTypes.setSrc,new v().setContent([t]))}_setIsBackground(e){return Object.assign(this.config,{isBackground:e}),this}registerSrc(){return j.isTagSrc(this)?this.srcManager.registerRawSrc(j.getSrcFromTags(this.config.src.defaults,this.config.src.resolve)):A.isImageSrc(this.state.currentSrc)&&this.srcManager.registerRawSrc(A.srcToURL(this.state.currentSrc)),this}createImageConfig(e){let t=e.get();return j.DefaultImageConfig.create({...t,src:j.isTagDefinition(t.src)?t.src:null})}getInitialState(){return j.DefaultImageState.create().assign({currentSrc:j.getInitialSrc(this.userConfig.get())}).get()}getInitialTransformState(e){let[t]=e.extract(me.DefaultTransformState.keys());return new me(me.DefaultTransformState.create(t.get()).get())}checkConfig(){for(let e of this.config.wearables)if(!e.config.isWearable)throw this._invalidWearableError(JSON.stringify(e.config));if(j.isTagSrc(this)){let e=this.config.src,t=new Set;for(let r of e.groups)for(let s of r){if(t.has(s))throw this._invalidTagGroupDefinitionError();t.add(s)}let n=this.constructTagMap(e.groups),i=new Set;for(let r of e.defaults){if(i.has(r))throw new Error(`Tag conflict
54
+ `+e)}_invalidTagGroupDefinitionError(){throw new Error("Invalid tag group definition. Tags in groups must be unique and not conflicting with each other.")}_setSrc(e,t,n){return n&&e.chain(this._applyTransition(n.copy(),i=>i._setPrevSrc(ne.resolveCurrentSrc(this))._setTargetSrc(t))),new ne(e,ne.ActionTypes.setSrc,new b().setContent([t]))}_setIsBackground(e){return Object.assign(this.config,{isBackground:e}),this}registerSrc(){return _.isTagSrc(this)?this.srcManager.registerRawSrc(_.getSrcFromTags(this.config.src.defaults,this.config.src.resolve)):A.isImageSrc(this.state.currentSrc)&&this.srcManager.registerRawSrc(A.srcToURL(this.state.currentSrc)),this}createImageConfig(e){let t=e.get();return _.DefaultImageConfig.create({...t,src:_.isTagDefinition(t.src)?t.src:null})}getInitialState(){return _.DefaultImageState.create().assign({currentSrc:_.getInitialSrc(this.userConfig.get())}).get()}getInitialTransformState(e){let[t]=e.extract(me.DefaultTransformState.keys());return new me(me.DefaultTransformState.create(t.get()).get())}checkConfig(){for(let e of this.config.wearables)if(!e.config.isWearable)throw this._invalidWearableError(JSON.stringify(e.config));if(_.isTagSrc(this)){let e=this.config.src,t=new Set;for(let r of e.groups)for(let s of r){if(t.has(s))throw this._invalidTagGroupDefinitionError();t.add(s)}let n=this.constructTagMap(e.groups),i=new Set;for(let r of e.defaults){if(i.has(r))throw new Error(`Tag conflict
53
55
  Tag "${r}" is conflicting with another tag
54
56
  Error found in config.tag.defaults`);if(!n.has(r))throw new Error(`Tag not found
55
57
  Tag "${r}" is not defined in tagDefinitions
56
- Error found in config.tag.defaults`);n.get(r)?.forEach(s=>i.add(s))}}return this}constructTagMap(e){let t=new Map;for(let n of e)for(let i of n)t.set(i,n);return t}_setDarkness(e,t,n,i){return new Y(e,Y.ActionTypes.setDarkness,new v().setContent([t,n,i]))}};j.DefaultImagePlaceholder="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='1' height='1'></svg>",j.StateSerializer=new Le,j.DefaultUserConfig=new K({name:"(anonymous)",autoInit:!0,src:j.DefaultImagePlaceholder,autoFit:!1,layer:void 0,...me.DefaultTransformState.getDefaultConfig()},{position:e=>k.tryParsePosition(e)}),j.DefaultImageConfig=new K({wearables:[],isWearable:!1,name:"(anonymous)",autoInit:!0,src:null,autoFit:!1,layer:void 0,isBackground:!1}),j.DefaultImageState=new K({currentSrc:j.DefaultImagePlaceholder,darkness:0});var G=j;var Tt=class extends ot{_setPrevSrc(e){return this._prevSrc=e,this}_setTargetSrc(e){return this._targetSrc=e,this}_setCurrentSrc(e){return this._currentSrc=e,this}_getPrevSrc(){return this._prevSrc}_getTargetSrc(){return this._targetSrc}_getCurrentSrc(){return this._currentSrc}requestAnimations(e){let t=super.requestAnimations(e);return t.onComplete(()=>{this._setCurrentSrc(this._getTargetSrc())}),t}asPrev(e){return super.asPrev((...t)=>I(e(...t),this._srcToProps(this._prevSrc)))}asTarget(e){return super.asTarget((...t)=>I(e(...t),this._srcToProps(this._targetSrc)))}_srcToProps(e){if(A.isColor(e))return{src:G.DefaultImagePlaceholder,style:{backgroundColor:A.isRGBAColor(e)?A.RGBAColorToHex(e):e}};if(A.isImageSrc(e))return{src:A.srcToURL(e)};throw new te("Image transition src cannot be identified, using: "+e)}};var zi=class o extends Tt{constructor(t,n,i,r){super();this.prevDarkness=t;this.targetDarkness=n;this.duration=i;this.easing=r}createTask(){return{animations:[{type:0,start:this.prevDarkness,end:this.targetDarkness,duration:this.duration,ease:this.easing}],resolve:[this.asTarget(t=>({style:{filter:`brightness(${1-t})`}})),this.asPrev(()=>({style:{opacity:0},height:0,width:0}))]}}copy(){return new o(this.prevDarkness,this.targetDarkness,this.duration,this.easing)}};var Gn=class Gn extends U{static resolveTagSrc(e,t){if(!G.isTagSrc(e))throw e._mixedSrcError();let n=e.state.currentSrc,i=e.resolveTags(n,t);return G.getSrcFromTags(i,e.config.src.resolve)}static resolveCurrentSrc(e){if(G.isStaticSrc(e))return A.isImageSrc(e.state.currentSrc)?A.srcToURL(e.state.currentSrc):e.state.currentSrc;if(G.isTagSrc(e))return G.getSrcFromTags(e.state.currentSrc,e.config.src.resolve);throw e._mixedSrcError()}executeAction(e,t){if(this.type===Ge.initWearable){let[n]=this.contentNode.getContent(),i=e.getExposedStateForce(this.callee),r=new g(s=>s);return i.createWearable(n),e.getExposedStateAsync(n,s=>{s.initDisplayable(()=>{r.resolve(super.executeAction(e,t))})}),e.actionHistory.push({action:this,stackModel:t.stackModel},s=>{i.disposeWearable(s)},[n]),r}else if(this.type===Ge.setSrc){let n=this.contentNode.getContent()[0];if(A.isColor(n)&&!this.callee.config.isBackground)throw new te("Color src is not allowed for non-background image");let i=this.callee.state.currentSrc;return this.callee.state.currentSrc=n,e.logger.debug("Image Set Src",n),e.actionHistory.push({action:this,stackModel:t.stackModel},r=>{this.callee.state.currentSrc=r},[i]),e.stage.update(),super.executeAction(e,t)}else{if(this.type===Ge.flush)return super.executeAction(e,t);if(this.type===Ge.setAppearance){let[n,i]=this.contentNode.getContent();if(!G.isTagSrc(this.callee))throw this.callee._mixedSrcError();let r=this.callee.state.currentSrc,s=this.callee.resolveTags(r,n),a=[...r],c=G.getSrcFromTags(s,this.callee.config.src.resolve),l=()=>{this.callee.state.currentSrc=a};if(e.logger.debug("Image - Set Appearance",s,c),i){let u=new g(d=>d).registerSkipController(new M(()=>super.executeAction(e,t)));i._setPrevSrc(Gn.resolveCurrentSrc(this.callee))._setTargetSrc(c);let p=e.getExposedStateForce(this.callee).applyTransition(i,()=>{this.callee.state.currentSrc=s,u.resolve(super.executeAction(e,t))}),h=e.timelines.attachTimeline(u).attachChild(p);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:h},l,[]),u}return this.callee.state.currentSrc=s,e.actionHistory.push({action:this,stackModel:t.stackModel},l),super.executeAction(e,t)}else if(this.type===Ge.setDarkness){let[n,i,r]=this.contentNode.getContent(),s=this.callee.state.darkness,a=()=>{this.callee.state.darkness=s},c=e.getExposedStateForce(this.callee);if(i&&r){let l=Gn.resolveCurrentSrc(this.callee),u=new g(d=>d),m=new zi(s,n,i,r)._setPrevSrc(l)._setTargetSrc(l),p=c.applyTransition(m,()=>{this.callee.state.darkness=n,u.resolve(super.executeAction(e,t))}),h=e.timelines.attachTimeline(u).attachChild(p);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:h},()=>{u.isSettled()||u.abort(),p.abort(),a()}),u}return this.callee.state.darkness=n,e.actionHistory.push({action:this,stackModel:t.stackModel},a),c.updateStyleSync(),super.executeAction(e,t)}}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("ImageAction")}};Gn.ActionTypes=Ge;var Y=Gn;var bt=class bt extends U{static handleSceneInit(e,t,n,i){return n.isSceneActive(e)?t:(n.registerSrcManager(e.srcManager).addScene(e).flush(),e.local.init(n.getStorable()),n.getExposedStateAsync(e,async r=>{await bt.initBackgroundMusic(e,r),i.resolve(t),n.logger.debug("Scene Action","Scene init")}),i)}static async initBackgroundMusic(e,t){e.state.backgroundMusic&&await t.setBackgroundMusic(e.state.backgroundMusic,e.config.backgroundMusicFade)}static createSceneSnapshot(e,t){let n=t.findElementByScene(e);if(!n)throw new te("Scene not found when creating snapshot (scene: "+e.getId()+")");return{state:e.toData(),local:e.local.getNamespace(t.getStorable()).toData(),element:t.createElementSnapshot(n),background:e.background.toData()}}static restoreSceneSnapshot(e,t){let n=e.element.scene,i=t.findElementByScene(n);i&&t.removeElement(i);let r=t.fromElementSnapshot(e.element);t.addElement(r),n.local.getNamespace(t.getStorable()).load(e.local),e.state&&n.fromData(e.state),e.background&&n.background.fromData(e.background)}applyTransition(e,t,n){let i=new g().registerSkipController(new M(()=>(e.logger.info("Background Transition","Skipped"),super.executeAction(e,n))));return e.getExposedStateForce(this.callee.background).applyTransition(t,()=>{i.resolve(super.executeAction(e,n))}),e.timelines.attachTimeline(i),i}exit(e){e.offSrcManager(this.callee.srcManager).removeScene(this.callee),this.callee.state.backgroundImage.reset()}applyNvlVisibility(e,t,n,i){e.setNvlVisibility(t,n);let r=Math.max(0,n?.duration||0);if(r===0)return super.executeAction(e,i);let s=super.executeAction(e,i),a=new g(l=>l),c=null;return a.registerSkipController(new M(()=>(c&&(clearTimeout(c),c=null),s))),c=e.setTimeout(()=>{c=null,a.resolve(s)},r),a}executeAction(e,t){if(this.type===H.action)return super.executeAction(e,t);if(this.is(bt,"scene:init")){let n=new g(s=>s),i=e.timelines.attachTimeline(n);e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:i},()=>{this.exit(e)},[]);let r={type:this.type,node:this.contentNode.getChild()};return bt.handleSceneInit(this.callee,r,e,g.forward(n,r))}else if(this.type===H.exit){let n=bt.createSceneSnapshot(this.callee,e);return e.actionHistory.push({action:this,stackModel:t.stackModel},i=>{let r=new g(s=>s);e.timelines.attachTimeline(r),bt.handleSceneInit(this.callee,{type:this.type,node:this.contentNode.getChild()},e,r),bt.restoreSceneSnapshot(i,e)},[n]),e.getStorable().removeNamespace(this.callee.local.getNamespaceName()),this.exit(e),super.executeAction(e,t)}else if(this.type===H.jumpTo){let n=this.contentNode.getContent()[0],i=e.getStory().getScene(n);if(!i)throw this._sceneNotFoundError(this.getSceneName(n));let r=e.getLiveGame().getStackModelForce().serialize();e.actionHistory.push({action:this,stackModel:t.stackModel},a=>{let[c]=e.getLiveGame().constructMaps();e.getLiveGame().getStackModelForce().deserialize(a,c)},[r]);let s=i.getSceneRoot().contentNode;return e.getLiveGame().clearMainStack().getStackModelForce().push({type:this.type,node:s}),null}else if(this.type===H.setBackgroundMusic){let[n,i]=this.contentNode.getContent(),r=this.callee,s=e.getExposedStateForce(r),a=r.state.backgroundMusic;return e.actionHistory.push({action:this,stackModel:t.stackModel},c=>{c&&s.setBackgroundMusic(c,0)},[a]),s.setBackgroundMusic(n,i||0),this.callee.state.backgroundMusic=n,super.executeAction(e,t)}else{if(this.type===H.preUnmount)return this.callee.events.emit("event:scene.preUnmount"),super.executeAction(e,t);if(this.type===H.transitionToScene){let[n,i,r]=this.contentNode.getContent();return n._setPrevSrc(Y.resolveCurrentSrc(this.callee.background)),i?n._setTargetSrc(Y.resolveCurrentSrc(i.background)):r&&n._setTargetSrc(r),this.applyTransition(e,n,t)}else if(this.type===H.nvlBlock){let[n,i]=this.contentNode.getContent(),r=e.createNvlSnapshot();return e.enterNvlMode(i),e.actionHistory.push({action:this,stackModel:t.stackModel},s=>{e.restoreNvlSnapshot(s)},[r]),n.length===0?{type:this.type,node:this.contentNode.getChild()}:[{type:this.type,node:this.contentNode.getChild()},{type:this.type,node:n[0].contentNode}]}else if(this.type===H.nvlShow){let[n]=this.contentNode.getContent(),i=e.getNvlState().visible,r=this.applyNvlVisibility(e,!0,n,t),s=g.isAwaitable(r)?e.timelines.attachTimeline(r):void 0;return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:s},a=>{e.setNvlVisibility(a)},[i]),r}else if(this.type===H.nvlHide){let[n]=this.contentNode.getContent(),i=e.getNvlState().visible,r=this.applyNvlVisibility(e,!1,n,t),s=g.isAwaitable(r)?e.timelines.attachTimeline(r):void 0;return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:s},a=>{e.setNvlVisibility(a)},[i]),r}else if(this.type===H.nvlEnd){let[n]=this.contentNode.getContent(),i=e.createNvlSnapshot();return e.actionHistory.push({action:this,stackModel:t.stackModel},r=>{e.restoreNvlSnapshot(r)},[i]),e.exitNvlMode(n||null),{type:this.type,node:null}}}throw new Error("Unknown scene action type: "+this.type)}getFutureActions(e,t={}){if(this.type===H.jumpTo&&t.allowFutureScene!==!1){let i=this.contentNode.getContent()[0],r=e.getScene(i,!0);r.isSceneRootConstructed()||r.constructSceneRoot(e);let s=e.getScene(i,!0).getSceneRoot()?.contentNode;return s?.action?[s.action]:[]}if(this.type===H.nvlBlock){let[i]=this.contentNode.getContent(),r=super.getFutureActions(e,t);return[...i??[],...r]}let n=this.contentNode.getChild()?.action;return n?[n]:[]}_sceneNotFoundError(e){return new te(`Scene with name ${e} not found
58
+ Error found in config.tag.defaults`);n.get(r)?.forEach(s=>i.add(s))}}return this}constructTagMap(e){let t=new Map;for(let n of e)for(let i of n)t.set(i,n);return t}_setDarkness(e,t,n,i){return new ne(e,ne.ActionTypes.setDarkness,new b().setContent([t,n,i]))}};_.DefaultImagePlaceholder="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='1' height='1'></svg>",_.StateSerializer=new He,_.DefaultUserConfig=new j({name:"(anonymous)",autoInit:!0,src:_.DefaultImagePlaceholder,autoFit:!1,layer:void 0,...me.DefaultTransformState.getDefaultConfig()},{position:e=>D.tryParsePosition(e)}),_.DefaultImageConfig=new j({wearables:[],isWearable:!1,name:"(anonymous)",autoInit:!0,src:null,autoFit:!1,layer:void 0,isBackground:!1}),_.DefaultImageState=new j({currentSrc:_.DefaultImagePlaceholder,darkness:0});var U=_;var nt=class extends ct{_setPrevSrc(e){return this._prevSrc=e,this}_setTargetSrc(e){return this._targetSrc=e,this}_setCurrentSrc(e){return this._currentSrc=e,this}_getPrevSrc(){return this._prevSrc}_getTargetSrc(){return this._targetSrc}_getCurrentSrc(){return this._currentSrc}requestAnimations(e){let t=super.requestAnimations(e);return t.onComplete(()=>{this._setCurrentSrc(this._getTargetSrc())}),t}asPrev(e){return super.asPrev((...t)=>H(e(...t),this._srcToProps(this._prevSrc)))}asTarget(e){return super.asTarget((...t)=>H(e(...t),this._srcToProps(this._targetSrc)))}_srcToProps(e){if(A.isColor(e))return{src:U.DefaultImagePlaceholder,style:{backgroundColor:A.isRGBAColor(e)?A.RGBAColorToHex(e):e}};if(A.isImageSrc(e))return{src:A.srcToURL(e)};throw new ce("Image transition src cannot be identified, using: "+e)}};var Xi=class o extends nt{constructor(t,n,i,r){super();this.prevDarkness=t;this.targetDarkness=n;this.duration=i;this.easing=r}createTask(){return{animations:[{type:0,start:this.prevDarkness,end:this.targetDarkness,duration:this.duration,ease:this.easing}],resolve:[this.asTarget(t=>({style:{filter:`brightness(${1-t})`}})),this.asPrev(()=>({style:{opacity:0},height:0,width:0}))]}}copy(){return new o(this.prevDarkness,this.targetDarkness,this.duration,this.easing)}};var $n=class $n extends O{static resolveTagSrc(e,t){if(!U.isTagSrc(e))throw e._mixedSrcError();let n=e.state.currentSrc,i=e.resolveTags(n,t);return U.getSrcFromTags(i,e.config.src.resolve)}static resolveCurrentSrc(e){if(U.isStaticSrc(e))return A.isImageSrc(e.state.currentSrc)?A.srcToURL(e.state.currentSrc):e.state.currentSrc;if(U.isTagSrc(e))return U.getSrcFromTags(e.state.currentSrc,e.config.src.resolve);throw e._mixedSrcError()}executeAction(e,t){if(this.type===Oe.initWearable){let[n]=this.contentNode.getContent(),i=e.getExposedStateForce(this.callee),r=new y(s=>s);return i.createWearable(n),e.getExposedStateAsync(n,s=>{s.initDisplayable(()=>{r.resolve(super.executeAction(e,t))})}),e.actionHistory.push({action:this,stackModel:t.stackModel},s=>{i.disposeWearable(s)},[n]),r}else if(this.type===Oe.setSrc){let n=this.contentNode.getContent()[0];if(A.isColor(n)&&!this.callee.config.isBackground)throw new ce("Color src is not allowed for non-background image");let i=this.callee.state.currentSrc;return this.callee.state.currentSrc=n,e.logger.debug("Image Set Src",n),e.actionHistory.push({action:this,stackModel:t.stackModel},r=>{this.callee.state.currentSrc=r},[i]),e.stage.update(),super.executeAction(e,t)}else{if(this.type===Oe.flush)return super.executeAction(e,t);if(this.type===Oe.setAppearance){let[n,i]=this.contentNode.getContent();if(!U.isTagSrc(this.callee))throw this.callee._mixedSrcError();let r=this.callee.state.currentSrc,s=this.callee.resolveTags(r,n),a=[...r],c=U.getSrcFromTags(s,this.callee.config.src.resolve),l=()=>{this.callee.state.currentSrc=a};if(e.logger.debug("Image - Set Appearance",s,c),i){let p=new y(m=>m).registerSkipController(new G(()=>super.executeAction(e,t)));i._setPrevSrc($n.resolveCurrentSrc(this.callee))._setTargetSrc(c);let d=e.getExposedStateForce(this.callee).applyTransition(i,()=>{this.callee.state.currentSrc=s,p.resolve(super.executeAction(e,t))}),h=e.timelines.attachTimeline(p).attachChild(d);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:h},l,[]),p}return this.callee.state.currentSrc=s,e.actionHistory.push({action:this,stackModel:t.stackModel},l),super.executeAction(e,t)}else if(this.type===Oe.setDarkness){let[n,i,r]=this.contentNode.getContent(),s=this.callee.state.darkness,a=()=>{this.callee.state.darkness=s},c=e.getExposedStateForce(this.callee);if(i&&r){let l=$n.resolveCurrentSrc(this.callee),p=new y(m=>m),u=new Xi(s,n,i,r)._setPrevSrc(l)._setTargetSrc(l),d=c.applyTransition(u,()=>{this.callee.state.darkness=n,p.resolve(super.executeAction(e,t))}),h=e.timelines.attachTimeline(p).attachChild(d);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:h},()=>{p.isSettled()||p.abort(),d.abort(),a()}),p}return this.callee.state.darkness=n,e.actionHistory.push({action:this,stackModel:t.stackModel},a),c.updateStyleSync(),super.executeAction(e,t)}}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("ImageAction")}};$n.ActionTypes=Oe;var ne=$n;var wt=class wt extends O{static handleSceneInit(e,t,n,i){return n.isSceneActive(e)?t:(n.registerSrcManager(e.srcManager).addScene(e).flush(),e.local.init(n.getStorable()),n.getExposedStateAsync(e,async r=>{await wt.initBackgroundMusic(e,r),i.resolve(t),n.logger.debug("Scene Action","Scene init")}),i)}static async initBackgroundMusic(e,t){e.state.backgroundMusic&&await t.setBackgroundMusic(e.state.backgroundMusic,e.config.backgroundMusicFade)}static createSceneSnapshot(e,t){let n=t.findElementByScene(e);if(!n)throw new ce("Scene not found when creating snapshot (scene: "+e.getId()+")");return{state:e.toData(),local:e.local.getNamespace(t.getStorable()).toData(),element:t.createElementSnapshot(n),background:e.background.toData()}}static restoreSceneSnapshot(e,t){let n=e.element.scene,i=t.findElementByScene(n);i&&t.removeElement(i);let r=t.fromElementSnapshot(e.element);t.addElement(r),n.local.getNamespace(t.getStorable()).load(e.local),e.state&&n.fromData(e.state),e.background&&n.background.fromData(e.background)}applyTransition(e,t,n){let i=new y().registerSkipController(new G(()=>(e.logger.info("Background Transition","Skipped"),super.executeAction(e,n))));return e.getExposedStateForce(this.callee.background).applyTransition(t,()=>{i.resolve(super.executeAction(e,n))}),e.timelines.attachTimeline(i),i}exit(e){e.offSrcManager(this.callee.srcManager).removeScene(this.callee),this.callee.state.backgroundImage.reset()}applyNvlVisibility(e,t,n,i){e.setNvlVisibility(t,n);let r=Math.max(0,n?.duration||0);if(r===0)return super.executeAction(e,i);let s=super.executeAction(e,i),a=new y(l=>l),c=null;return a.registerSkipController(new G(()=>(c&&(clearTimeout(c),c=null),s))),c=e.setTimeout(()=>{c=null,a.resolve(s)},r),a}executeAction(e,t){if(this.type===V.action)return super.executeAction(e,t);if(this.is(wt,"scene:init")){let n=new y(s=>s),i=e.timelines.attachTimeline(n);e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:i},()=>{this.exit(e)},[]);let r={type:this.type,node:this.contentNode.getChild()};return wt.handleSceneInit(this.callee,r,e,y.forward(n,r))}else if(this.type===V.exit){let n=wt.createSceneSnapshot(this.callee,e);return e.actionHistory.push({action:this,stackModel:t.stackModel},i=>{let r=new y(s=>s);e.timelines.attachTimeline(r),wt.handleSceneInit(this.callee,{type:this.type,node:this.contentNode.getChild()},e,r),wt.restoreSceneSnapshot(i,e)},[n]),e.getStorable().removeNamespace(this.callee.local.getNamespaceName()),this.exit(e),super.executeAction(e,t)}else if(this.type===V.jumpTo){let n=this.contentNode.getContent()[0],i=e.getStory().getScene(n);if(!i)throw this._sceneNotFoundError(this.getSceneName(n));let r=e.getLiveGame().getStackModelForce().serialize();e.actionHistory.push({action:this,stackModel:t.stackModel},a=>{let[c]=e.getLiveGame().constructMaps();e.getLiveGame().getStackModelForce().deserialize(a,c)},[r]);let s=i.getSceneRoot().contentNode;return e.getLiveGame().clearMainStack().getStackModelForce().push({type:this.type,node:s}),null}else if(this.type===V.setBackgroundMusic){let[n,i]=this.contentNode.getContent(),r=this.callee,s=e.getExposedStateForce(r),a=r.state.backgroundMusic;return e.actionHistory.push({action:this,stackModel:t.stackModel},c=>{s.setBackgroundMusic(c,0)},[a]),s.setBackgroundMusic(n,i||0),super.executeAction(e,t)}else{if(this.type===V.preUnmount)return this.callee.events.emit("event:scene.preUnmount"),super.executeAction(e,t);if(this.type===V.transitionToScene){let[n,i,r]=this.contentNode.getContent();return n._setPrevSrc(ne.resolveCurrentSrc(this.callee.background)),i?n._setTargetSrc(ne.resolveCurrentSrc(i.background)):r&&n._setTargetSrc(r),this.applyTransition(e,n,t)}else if(this.type===V.nvlBlock){let[n,i]=this.contentNode.getContent(),r=e.createNvlSnapshot();return e.enterNvlMode(i),e.actionHistory.push({action:this,stackModel:t.stackModel},s=>{e.restoreNvlSnapshot(s)},[r]),n.length===0?{type:this.type,node:this.contentNode.getChild()}:[{type:this.type,node:this.contentNode.getChild()},{type:this.type,node:n[0].contentNode}]}else if(this.type===V.nvlShow){let[n]=this.contentNode.getContent(),i=e.getNvlState().visible,r=this.applyNvlVisibility(e,!0,n,t),s=y.isAwaitable(r)?e.timelines.attachTimeline(r):void 0;return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:s},a=>{e.setNvlVisibility(a)},[i]),r}else if(this.type===V.nvlHide){let[n]=this.contentNode.getContent(),i=e.getNvlState().visible,r=this.applyNvlVisibility(e,!1,n,t),s=y.isAwaitable(r)?e.timelines.attachTimeline(r):void 0;return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:s},a=>{e.setNvlVisibility(a)},[i]),r}else if(this.type===V.nvlEnd){let[n]=this.contentNode.getContent(),i=e.createNvlSnapshot();return e.actionHistory.push({action:this,stackModel:t.stackModel},r=>{e.restoreNvlSnapshot(r)},[i]),e.exitNvlMode(n||null),{type:this.type,node:null}}}throw new Error("Unknown scene action type: "+this.type)}getFutureActions(e,t={}){if(this.type===V.jumpTo&&t.allowFutureScene!==!1){let i=this.contentNode.getContent()[0],r=e.getScene(i,!0);r.isSceneRootConstructed()||r.constructSceneRoot(e);let s=e.getScene(i,!0).getSceneRoot()?.contentNode;return s?.action?[s.action]:[]}if(this.type===V.nvlBlock){let[i]=this.contentNode.getContent(),r=super.getFutureActions(e,t);return[...i??[],...r]}let n=this.contentNode.getChild()?.action;return n?[n]:[]}_sceneNotFoundError(e){return new ce(`Scene with name ${e} not found
57
59
  Make sure you have registered the scene using story.register
58
60
  Action: (id: ${this.getId()}) ${this.type}
59
- At: ${this.__stack}`)}getSceneName(e){return typeof e=="string"?e:e.config.name}stringify(e,t,n){if(this.type===H.jumpTo){if(t.has(this))return super.stringifyWithContent("Scene","[[recursive]]");t.add(this);let[i]=this.contentNode.getContent();return super.stringifyWithContent("Scene",`jumpTo {${i.stringify(e,t,n)}}`)}return super.stringifyWithName("SceneAction")}};bt.ActionTypes=H;var O=bt;var Oo=class o{static isHexString(e){return typeof e!="string"?!1:/^#[0-9A-F]{6}$/i.test(e)}static fromHex(e){let t=e.slice(1),n=parseInt(t.slice(0,2),16),i=parseInt(t.slice(2,4),16),r=parseInt(t.slice(4,6),16),s=t.length===8?parseInt(t.slice(6,8),16)/255:1;return new o(n,i,r,s)}constructor(e,t,n,i=1){this.r=e,this.g=t,this.b=n,this.a=i}toString(){return`rgba(${this.r}, ${this.g}, ${this.b}, ${this.a})`}toHex(){return"#"+this.r.toString(16)+this.g.toString(16)+this.b.toString(16)}},_e=class _e{static srcToURL(e){return typeof e=="string"?e:e.src}static staticImageDataToSrc(e){return typeof e=="string"?e:e.src}static isStaticImageData(e){return e?.src!==void 0&&typeof e.src=="string"}static isExternalSrc(e){return e.startsWith("http://")||e.startsWith("https://")}static isImageSrc(e){return typeof e=="string"&&!this.isColor(e)||_e.isStaticImageData(e)}static isImageURL(e){return typeof e=="string"&&!this.isColor(e)}static isColor(e){return _e.isHexString(e)||_e.isNamedColor(e)||_e.isRGBAColor(e)}static isNamedColor(e){return tr(e)}static isRGBAColor(e){return e&&typeof e=="object"&&"r"in e&&"g"in e&&"b"in e}static RGBAColorToHex(e){let t=e.r.toString(16).padStart(2,"0"),n=e.g.toString(16).padStart(2,"0"),i=e.b.toString(16).padStart(2,"0"),r=e.a?Math.round(e.a*255).toString(16).padStart(2,"0"):"";return`#${t}${n}${i}${r}`}static colorToString(e){if(_e.isHexString(e))return e;if(_e.isNamedColor(e))return e;if(_e.isRGBAColor(e))return _e.RGBAColorToHex(e);throw new Error("Unknown color type")}static isHexString(e){return typeof e!="string"?!1:/^#([0-9A-F]{3}|[0-9A-F]{6}|[0-9A-F]{4}|[0-9A-F]{8})$/i.test(e)}static toBackgroundSrc(e){return typeof e=="string"?e:e.src}static isDataURI(e){return e.startsWith("data:")}static offset(e,t,n={invertX:!1,invertY:!1}){let[i,r]=e,[s,a]=t,c=this.calc(i,s),l=this.calc(r,a),u=n.invertX?{right:c}:{left:c},m=n.invertY?{bottom:l}:{top:l};return{left:"auto",right:"auto",top:"auto",bottom:"auto",...u,...m}}static calc(e,t){let n=typeof e=="string"?e:`${e}px`;if(t===void 0)return`calc(${n} + 0px)`;let i=typeof t=="string"?"+":t<0?"-":"+",r=typeof t=="string"?t:`${Math.abs(t)}px`;return`calc(${n} ${i} ${r})`}static formatLength(e){return typeof e=="number"?`${e}px`:e}static toPixel(e){return typeof e=="number"?e:parseFloat(e)}};_e.RGBColor=Oo;var A=_e,Wo=class o extends Error{static isUseError(e){return e instanceof o}constructor(e,t,n="UseError"){super(e),this.props=t,this.name=n}},ye=class o extends Wo{static isWarning(e){return e instanceof o}constructor(e,t){super(e,{info:t},"StaticScriptWarning")}},pi=class{constructor(e){this.scene=e}run(e){let t=new Map,n=new Map,i=[],r=new Set,s=this.scene.getAllChildren(e,this.scene.getSceneRoot());if(!s.length)return null;for(i.push(s[0]);i.length;){let a=i.shift();this.checkAction(e,a,{imageStates:t,scenes:n},r);let c=a.contentNode.getChild();c&&c.action&&i.push(c.action)}return t}checkAction(e,t,{imageStates:n,scenes:i},r){if(t instanceof Y)n.has(t.callee)||n.set(t.callee,{isDisposed:!1,usedExternalSrc:!1}),this.checkImage(n.get(t.callee),t);else if(t instanceof O){let s=t.callee;if(i.has(s.config.name)){if(i.get(s.config.name)!==s){let a=`Scene with name: ${s.config.name} is duplicated
61
+ At: ${this.__stack}`)}getSceneName(e){return typeof e=="string"?e:e.config.name}stringify(e,t,n){if(this.type===V.jumpTo){if(t.has(this))return super.stringifyWithContent("Scene","[[recursive]]");t.add(this);let[i]=this.contentNode.getContent();return super.stringifyWithContent("Scene",`jumpTo {${i.stringify(e,t,n)}}`)}return super.stringifyWithName("SceneAction")}};wt.ActionTypes=V;var Y=wt;var _o=class o{static isHexString(e){return typeof e!="string"?!1:/^#[0-9A-F]{6}$/i.test(e)}static fromHex(e){let t=e.slice(1),n=parseInt(t.slice(0,2),16),i=parseInt(t.slice(2,4),16),r=parseInt(t.slice(4,6),16),s=t.length===8?parseInt(t.slice(6,8),16)/255:1;return new o(n,i,r,s)}constructor(e,t,n,i=1){this.r=e,this.g=t,this.b=n,this.a=i}toString(){return`rgba(${this.r}, ${this.g}, ${this.b}, ${this.a})`}toHex(){return"#"+this.r.toString(16)+this.g.toString(16)+this.b.toString(16)}},it=class it{static srcToURL(e){return typeof e=="string"?e:e.src}static staticImageDataToSrc(e){return typeof e=="string"?e:e.src}static isStaticImageData(e){return e?.src!==void 0&&typeof e.src=="string"}static isExternalSrc(e){return e.startsWith("http://")||e.startsWith("https://")}static isImageSrc(e){return typeof e=="string"&&!this.isColor(e)||it.isStaticImageData(e)}static isImageURL(e){return typeof e=="string"&&!this.isColor(e)}static isColor(e){return it.isHexString(e)||it.isNamedColor(e)||it.isRGBAColor(e)}static isNamedColor(e){return fr(e)}static isRGBAColor(e){return e&&typeof e=="object"&&"r"in e&&"g"in e&&"b"in e}static RGBAColorToHex(e){let t=e.r.toString(16).padStart(2,"0"),n=e.g.toString(16).padStart(2,"0"),i=e.b.toString(16).padStart(2,"0"),r=e.a?Math.round(e.a*255).toString(16).padStart(2,"0"):"";return`#${t}${n}${i}${r}`}static colorToString(e){if(it.isHexString(e))return e;if(it.isNamedColor(e))return e;if(it.isRGBAColor(e))return it.RGBAColorToHex(e);throw new Error("Unknown color type")}static isHexString(e){return typeof e!="string"?!1:/^#([0-9A-F]{3}|[0-9A-F]{6}|[0-9A-F]{4}|[0-9A-F]{8})$/i.test(e)}static toBackgroundSrc(e){return typeof e=="string"?e:e.src}static isDataURI(e){return e.startsWith("data:")}static offset(e,t,n={invertX:!1,invertY:!1}){let[i,r]=e,[s,a]=t,c=this.calc(i,s),l=this.calc(r,a),p=n.invertX?{right:c}:{left:c},u=n.invertY?{bottom:l}:{top:l};return{left:"auto",right:"auto",top:"auto",bottom:"auto",...p,...u}}static calc(e,t){let n=typeof e=="string"?e:`${e}px`;if(t===void 0)return`calc(${n} + 0px)`;let i=typeof t=="string"?"+":t<0?"-":"+",r=typeof t=="string"?t:`${Math.abs(t)}px`;return`calc(${n} ${i} ${r})`}static formatLength(e){return typeof e=="number"?`${e}px`:e}static toPixel(e){return typeof e=="number"?e:parseFloat(e)}};it.RGBColor=_o;var A=it,er=class o extends Error{static isUseError(e){return e instanceof o}constructor(e,t,n="UseError"){super(e),this.props=t,this.name=n}},Se=class o extends er{static isWarning(e){return e instanceof o}constructor(e,t){super(e,{info:t},"StaticScriptWarning")}},gi=class{constructor(e){this.scene=e}run(e){let t=new Map,n=new Map,i=[],r=new Set,s=this.scene.getAllChildren(e,this.scene.getSceneRoot());if(!s.length)return null;for(i.push(s[0]);i.length;){let a=i.shift();this.checkAction(e,a,{imageStates:t,scenes:n},r);let c=a.contentNode.getChild();c&&c.action&&i.push(c.action)}return t}checkAction(e,t,{imageStates:n,scenes:i},r){if(t instanceof ne)n.has(t.callee)||n.set(t.callee,{isDisposed:!1,usedExternalSrc:!1}),this.checkImage(n.get(t.callee),t);else if(t instanceof Y){let s=t.callee;if(i.has(s.config.name)){if(i.get(s.config.name)!==s){let a=`Scene with name: ${s.config.name} is duplicated
60
62
  Scene: ${s.config.name}
61
63
 
62
- At: ${t.__stack}`;throw new ye(a)}}else i.set(s.config.name,s);if(t.type===H.jumpTo){let a=t.contentNode.getContent()[0],c=e.getScene(a,!0);if(r.has(c))return;r.add(c)}}}checkImage(e,t){if(t.type===Ge.setSrc){let i=t.contentNode.getContent()[0];A.isImageURL(i)&&A.isExternalSrc(i)&&(e.usedExternalSrc=!0)}}},te=class o extends Error{static toMessage(e,t){let n=[];return n.push(...Array.isArray(e)?e:[e]),t&&n.push(...Array.isArray(t)?t.map(o.getActionTrace):[o.getActionTrace(t)]),n.join("")}static getActionTrace(e){return`
64
+ At: ${t.__stack}`;throw new Se(a)}}else i.set(s.config.name,s);if(t.type===V.jumpTo){let a=t.contentNode.getContent()[0],c=e.getScene(a,!0);if(r.has(c))return;r.add(c)}}}checkImage(e,t){if(t.type===Oe.setSrc){let i=t.contentNode.getContent()[0];A.isImageURL(i)&&A.isExternalSrc(i)&&(e.usedExternalSrc=!0)}}},ce=class o extends Error{static toMessage(e,t){let n=[];return n.push(...Array.isArray(e)?e:[e]),t&&n.push(...Array.isArray(t)?t.map(o.getActionTrace):[o.getActionTrace(t)]),n.join("")}static getActionTrace(e){return`
63
65
  Using action (id: ${e.getId()})
64
- at: ${e.__stack}`}constructor(e,t){super(o.toMessage(e,t)),this.name="RuntimeScriptError"}},b=class extends Error{constructor(e){super(e),this.name="RuntimeGameError"}},xe=class extends Error{constructor(e){super(e),this.name="RuntimeInternalError"}};function ol(o,e){return F.color(o,e)}function rl(o){return F.bold(o)}function sl(o){return F.italic(o)}var zo=class o extends Tt{constructor(t,n){super();this.duration=t;this.easing=n}createTask(){return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(t=>({style:{opacity:1-t}})),this.asTarget(t=>({style:{opacity:t}}))]}}copy(){return new o(this.duration,this.easing)}};var Bo=class o extends Tt{constructor(t,n=[0,0],i){super();this.duration=t;this.startPos=n;this.easing=i}createTask(t){return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing},{type:0,start:this.startPos[0],end:0,duration:this.duration,ease:this.easing},{type:0,start:this.startPos[1],end:0,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(()=>({})),this.asTarget((n,i,r)=>({style:{opacity:n,...A.offset(["50%","50%"],[i,r],t.getStory().getInversionConfig()),transform:"translate(-50%, 50%)"}}))]}}copy(){return new o(this.duration,this.startPos,this.easing)}};var $o=class extends Tn{constructor(){super();this.unlocked={};this.setupActions()}serialize(){return{unlocked:this.unlocked}}deserialize(t){this.unlocked=t.unlocked}add(t,n){return this.trigger("add",t,n)}has(t){return new R(()=>this.unlocked[t]!==void 0)}remove(t){return this.trigger("remove",t)}clear(){return this.trigger("clear")}$remove(t){delete this.unlocked[t]}$clear(){this.unlocked={}}$get(t){return this.unlocked[t]}$set(t,n){this.unlocked[t]=n}$getAll(){return this.unlocked}$has(t){return this.unlocked[t]!==void 0}setupActions(){this.on("add",(t,n,i)=>{let r={gameState:t.gameState,game:t.game,liveGame:t.liveGame,storable:t.storable,$:t.$},s=typeof i=="function"?i(r):i;this.unlocked[n]=s}),this.on("remove",(t,n)=>{delete this.unlocked[n]}),this.on("clear",t=>{this.$clear()})}};var Bi=class{static getActionId(e){return e.getId()}static setActionId(e,t){return e.setId(t),e}static chainToActions(e){return e.getActions()}static wrapAction(e){let t=ge.isChained(e)?e.getActions():e;return He.do(t)}static getNamespaceName(e){return e.getNamespaceName()}static getCurrentScene(e){return e.getCurrentScene()}};Bi.DynamicPersistent=Jt;if(typeof document<"u"){let o=document.createElement("style");o.textContent=`/*! tailwindcss v4.1.8 | MIT License | https://tailwindcss.com */
65
- @layer properties{@supports ((-webkit-hyphens:none) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial}}}.invisible{visibility:hidden}.visible{visibility:visible}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.z-20{z-index:20}.container{width:100%}.\\!hidden{display:none!important}.block{display:block}.contents{display:contents}.flex{display:flex}.hidden{display:none}.inline-block{display:inline-block}.h-\\[80px\\]{height:80px}.h-full{height:100%}.h-max{height:-moz-max-content;height:max-content}.w-1\\/2{width:50%}.w-\\[100px\\]{width:100px}.w-full{width:100%}.w-max{width:-moz-max-content;width:max-content}.min-w-full{min-width:100%}.flex-grow{flex-grow:1}.transform{transform:var(--tw-rotate-x,)var(--tw-rotate-y,)var(--tw-rotate-z,)var(--tw-skew-x,)var(--tw-skew-y,)}.resize{resize:both}.flex-col{flex-direction:column}.items-center{align-items:center}.justify-center{justify-content:center}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.border{border-style:var(--tw-border-style);border-width:1px}.border-2{border-style:var(--tw-border-style);border-width:2px}.text-center{text-align:center}.text-left{text-align:left}.align-bottom{vertical-align:bottom}.break-all{word-break:break-all}.whitespace-pre-wrap{white-space:pre-wrap}.italic{font-style:italic}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.invert{--tw-invert:invert(100%);filter:var(--tw-blur,)var(--tw-brightness,)var(--tw-contrast,)var(--tw-grayscale,)var(--tw-hue-rotate,)var(--tw-invert,)var(--tw-saturate,)var(--tw-sepia,)var(--tw-drop-shadow,)}.filter{filter:var(--tw-blur,)var(--tw-brightness,)var(--tw-contrast,)var(--tw-grayscale,)var(--tw-hue-rotate,)var(--tw-invert,)var(--tw-saturate,)var(--tw-sepia,)var(--tw-drop-shadow,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,visibility,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,ease);transition-duration:var(--tw-duration,0s)}.__narraleaf_content-player *{-webkit-user-select:none;-moz-user-select:none;user-select:none}.__narraleaf_content-player img{pointer-events:none;-webkit-user-drag:none;-webkit-user-select:none}.__narraleaf_content-player .pointer-disabled{pointer-events:none}.__narraleaf_content-player .pointer-disabled>:not(.pointer-disabled){pointer-events:auto}.__narraleaf_content-player img:before,.__narraleaf_content-player img:after{content:none!important;border:none!important}.pointer-events-auto{pointer-events:auto}.pointer-events-none{pointer-events:none}.bottom-0{bottom:0}.left-0{left:0}.right-0{right:0}.top-0{top:0}.bg-cover{background-size:cover}.bg-center{background-position:50%}.pointer-events-auto-rest *{pointer-events:auto}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}\r
66
- `,document.head.appendChild(o)}export{Rt as Align,ii as Character,$e as CommonPosition,mn as CommonPositionType,Zi as Condition,He as Control,Ie as Coord2D,Co as DefaultNvlContainer,Xr as DefaultNvlDialogItem,Bi as DevTools,bc as Dialog,zo as Dissolve,el as ExposedStateType,Bo as FadeIn,Br as FixedAspectRatioContainer,$o as Gallery,B as Game,yi as GameMenu,ks as GameProviders,w as GameState,G as Image,Tt as ImageTransition,ct as Isolated,xi as Item,tn as KeyBindingType,Mn as KeyMap,R as Lambda,_t as Layer,Qa as Layout,Dn as LayoutRouterProvider,rt as LiveGame,_i as Menu,Sn as NVLToken,nt as Namespace,Dt as Nametag,ki as Notifications,bo as NvlContainer,vc as NvlDialogList,vo as NvlProvider,_a as Page,fo as PageInjectContext,Pe as Pause,Yt as Persistent,ws as Player,Cn as Preference,br as RootPath,Ue as Scene,re as Script,ne as Sentence,Tn as Service,Z as Sound,Ct as SoundType,aa as Stage,fn as Storable,vn as Story,Gt as Text,hn as TextTransition,Ea as Texts,z as Transform,ot as Transition,no as Video,F as Word,rl as b,ol as c,sl as i,Ma as useDialog,C as useGame,mc as useIsNvlMode,fc as useIsNvlVisible,Vt as useKeyBinding,ac as useLiveGame,ut as useNvl,So as useNvlDialogs,Wa as useParams,Oa as usePathname,Je as usePreference,za as useQueryParams,at as useRouter,Ua as useVoiceState};
66
+ at: ${e.__stack}`}constructor(e,t){super(o.toMessage(e,t)),this.name="RuntimeScriptError"}},x=class extends Error{constructor(e){super(e),this.name="RuntimeGameError"}},Le=class extends Error{constructor(e){super(e),this.name="RuntimeInternalError"}};function Ll(o,e){return W.color(o,e)}function Il(o){return W.bold(o)}function Rl(o){return W.italic(o)}var tr=class o extends nt{constructor(t,n){super();this.duration=t;this.easing=n}createTask(){return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(t=>({style:{opacity:1-t}})),this.asTarget(t=>({style:{opacity:t}}))]}}copy(){return new o(this.duration,this.easing)}};var nr=class o extends nt{constructor(t,n=[0,0],i){super();this.duration=t;this.startPos=n;this.easing=i}createTask(t){return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing},{type:0,start:this.startPos[0],end:0,duration:this.duration,ease:this.easing},{type:0,start:this.startPos[1],end:0,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(()=>({})),this.asTarget((n,i,r)=>({style:{opacity:n,...A.offset(["50%","50%"],[i,r],t.getStory().getInversionConfig()),transform:"translate(-50%, 50%)"}}))]}}copy(){return new o(this.duration,this.startPos,this.easing)}};var ir=class o extends nt{constructor(t,n,i){super();this.duration=t;this.easing=n;this.clipPathResolver=i}static circle(t){let{duration:n,easing:i,center:r="50% 50%",from:s=0,to:a=150}=t;return new o(n,i,c=>o.circleClipPath(o.lerp(s,a,c),r))}static wipe(t){let{duration:n,easing:i,direction:r="left",reverse:s=!1}=t,a=s?0:100,c=s?100:0;return new o(n,i,l=>o.wipeClipPath(r,o.lerp(a,c,l)))}createTask(){return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(()=>({style:{opacity:1,clipPath:"none"}})),this.asTarget(t=>({style:{opacity:1,clipPath:this.clipPathResolver(t)}}))]}}copy(){return new o(this.duration,this.easing,this.clipPathResolver)}static lerp(t,n,i){return t+(n-t)*i}static circleClipPath(t,n){return`circle(${o.formatNumber(t)}% at ${n})`}static wipeClipPath(t,n){let i=o.formatNumber(n);switch(t){case"right":return`inset(0 0 0 ${i}%)`;case"top":return`inset(0 0 ${i}% 0)`;case"bottom":return`inset(${i}% 0 0 0)`;case"left":default:return`inset(0 ${i}% 0 0)`}}static formatNumber(t){return Number.isInteger(t)?String(t):t.toFixed(3).replace(/0+$/,"").replace(/\.$/,"")}};var or=class extends En{constructor(){super();this.unlocked={};this.setupActions()}serialize(){return{unlocked:this.unlocked}}deserialize(t){this.unlocked=t.unlocked}add(t,n){return this.trigger("add",t,n)}has(t){return new F(()=>this.unlocked[t]!==void 0)}remove(t){return this.trigger("remove",t)}clear(){return this.trigger("clear")}$remove(t){delete this.unlocked[t]}$clear(){this.unlocked={}}$get(t){return this.unlocked[t]}$set(t,n){this.unlocked[t]=n}$getAll(){return this.unlocked}$has(t){return this.unlocked[t]!==void 0}setupActions(){this.on("add",(t,n,i)=>{let r={gameState:t.gameState,game:t.game,liveGame:t.liveGame,storable:t.storable,$:t.$},s=typeof i=="function"?i(r):i;this.unlocked[n]=s}),this.on("remove",(t,n)=>{delete this.unlocked[n]}),this.on("clear",t=>{this.$clear()})}};var Yi=class{static getActionId(e){return e.getId()}static setActionId(e,t){return e.setId(t),e}static getStaticId(e){return e.getStaticId()}static setStaticId(e,t){return e.setStaticId(t),e}static chainToActions(e){return e.getActions()}static wrapAction(e){let t=Ae.isChained(e)?e.getActions():e;return xe.do(t)}static getNamespaceName(e){return e.getNamespaceName()}static getCurrentScene(e){return e.getCurrentScene()}};Yi.DynamicPersistent=rn;if(typeof document<"u"){let o=document.createElement("style");o.textContent=`/*! tailwindcss v4.3.1 | MIT License | https://tailwindcss.com */
67
+ @layer properties{@supports ((-webkit-hyphens:none) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial}}}.invisible{visibility:hidden}.visible{visibility:visible}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.z-20{z-index:20}.container{width:100%}.\\!hidden{display:none!important}.block{display:block}.contents{display:contents}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline-block{display:inline-block}.h-\\[80px\\]{height:80px}.h-full{height:100%}.h-max{height:-moz-max-content;height:max-content}.w-1\\/2{width:50%}.w-\\[100px\\]{width:100px}.w-full{width:100%}.w-max{width:-moz-max-content;width:max-content}.min-w-full{min-width:100%}.flex-grow{flex-grow:1}.transform{transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)}.resize{resize:both}.flex-col{flex-direction:column}.items-center{align-items:center}.justify-center{justify-content:center}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.border{border-style:var(--tw-border-style);border-width:1px}.border-2{border-style:var(--tw-border-style);border-width:2px}.text-center{text-align:center}.text-left{text-align:left}.align-bottom{vertical-align:bottom}.break-all{word-break:break-all}.whitespace-pre-wrap{white-space:pre-wrap}.italic{font-style:italic}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.invert{--tw-invert:invert(100%);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.filter{filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.backdrop-filter{backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,ease);transition-duration:var(--tw-duration,0s)}.__narraleaf_content-player *{-webkit-user-select:none;-moz-user-select:none;user-select:none}.__narraleaf_content-player img{pointer-events:none;-webkit-user-drag:none;-webkit-user-select:none}.__narraleaf_content-player .pointer-disabled{pointer-events:none}.__narraleaf_content-player .pointer-disabled>:not(.pointer-disabled){pointer-events:auto}.__narraleaf_content-player img:before,.__narraleaf_content-player img:after{content:none!important;border:none!important}.pointer-events-auto{pointer-events:auto}.pointer-events-none{pointer-events:none}.bottom-0{bottom:0}.left-0{left:0}.right-0{right:0}.top-0{top:0}.bg-cover{background-size:cover}.bg-center{background-position:50%}.pointer-events-auto-rest *{pointer-events:auto}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}
68
+ `,document.head.appendChild(o)}export{Ft as Align,Ao as Avatar,ci as Character,qe as CommonPosition,bn as CommonPositionType,oo as Condition,xe as Control,Ue as Coord2D,No as DefaultNvlContainer,hs as DefaultNvlDialogItem,Yi as DevTools,zc as Dialog,tr as Dissolve,xl as ExposedStateType,nr as FadeIn,us as FixedAspectRatioContainer,or as Gallery,Q as Game,Ai as GameMenu,$s as GameProviders,k as GameState,U as Image,nt as ImageTransition,dt as Isolated,Li as Item,ln as KeyBindingType,Bn as KeyMap,F as Lambda,an as Layer,gc as Layout,Fn as LayoutRouterProvider,lt as LiveGame,ir as MaskTransition,ro as Menu,kn as NVLToken,st as Namespace,Nt as Nametag,St as Narrator,Ri as Notifications,Ro as NvlContainer,Oc as NvlDialogList,Lo as NvlProvider,bc as Page,wo as PageInjectContext,we as Pause,on as Persistent,Bs as Player,Ln as Preference,Fr as RootPath,ze as Scene,ue as Script,ie as Sentence,En as Service,re as Sound,kt as SoundType,Ca as Stage,An as Storable,Pn as Story,Vt as Text,Cn as TextTransition,Ba as Texts,Oa as TextsPreview,q as Transform,ct as Transition,co as Video,W as Word,Il as b,Ll as c,Rl as i,ns as useAvatar,nc as useDialog,w as useGame,Gc as useIsNvlMode,Hc as useIsNvlVisible,$t as useKeyBinding,Dc as useLiveGame,mt as useNvl,Do as useNvlDialogs,uc as useParams,lc as usePathname,_e as usePreference,pc as useQueryParams,pt as useRouter,rc as useVoiceState};