narraleaf-react 0.31.1 → 0.31.2

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 (2) hide show
  1. package/dist/main.js +5 -5
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -3,7 +3,7 @@ var ye={action:"displayable:action",applyTransform:"displayable:applyTransform",
3
3
  `).trim():""}function Gi(o){return new Promise(e=>setTimeout(e,o))}var Ni=class Ni{constructor(e){this.abortHandler=e;this.events=new q;this.aborted=!1}abort(...e){this.aborted||(this.aborted=!0,this.abortHandler(...e),this.events.emit(Ni.EventTypes["event:skipController.abort"]))}isAborted(){return this.aborted}cancel(){this.aborted=!0}onAbort(e){return this.events.on("event:skipController.abort",e)}};Ni.EventTypes={"event:skipController.abort":"event:skipController.abort"};var H=Ni;var zn=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}},xn=class{constructor(){this.locks=[]}unlock(e){return e.unlock(),this.off(e),e}register(e){let t=e||new zn;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 Hi(o,e,t={}){return o?e:t}function Vs(o,e){if(e<=0)return o;let t=null;return function(...n){t&&clearTimeout(t),t=setTimeout(()=>{o(...n)},e)}}var Di=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 Os(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 Us(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 wn=class{constructor(e,t){this.concurrency=e;this.delay=t;this.tasks=[]}addTask(e){this.tasks.push(e)}get size(){return this.tasks.length}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())),this.tasks.length!==0&&(await Gi(this.delay),await e())};await e()}};function rt(o){let e,t=Promise.resolve().then(()=>{e=o()});return()=>{t.then(()=>{e&&e()})}}function Ws(o,e){let t={};for(let n in o)e.includes(n)||(t[n]=o[n]);return t}var Qe=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 Bs(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 Ks(o){return o.constructor.name==="AsyncFunction"||Object.prototype.toString.call(o)==="[object AsyncFunction]"}function Fi(o){let e={};for(let t in o)o[t]!==void 0&&(e[t]=o[t]);return e}function Xo(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"&&!Xo(n,e)||typeof n=="function"||typeof n=="symbol")return!1}return!0}var Li=class{constructor(e=""){this.prefix=e;this.counter=0}next(){return`${this.prefix?this.prefix+"-":""}${this.counter++}`}};function Vi(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 zs(o=16){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",t="";for(let n=0;n<o;n++)t+=e[Math.floor(Math.random()*e.length)];return t}var Ri=class{constructor(e=""){this.prefix=e;this.counter=0}generateId(){return`${this.prefix?this.prefix+"-":""}${this.counter++}`}},Ii=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 Mi=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 $s(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 js(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,d=s*c+(u>>>0)>>>0;e=l,t=d}return("00000000"+t.toString(16)).slice(-8)+("00000000"+e.toString(16)).slice(-8)}var $n=class{constructor(e,t,n){this.callee=e,this.type=t,this.contentNode=n,this.__stack=Qo(),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]:[]}};$n.ActionTypes={action:"action"};var $=class extends $n{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 S(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 qt=class qt extends ${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 qt.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 ie("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)}applyStageTransition(e,t,n,i){let r=new S().registerSkipController(new H(()=>(e.logger.info("Stage Transition","Skipped"),super.executeAction(e,i)))),s=()=>{r.isSettled()||r.resolve(super.executeAction(e,i))},a=e.stageTransition.apply(t,{from:this.callee,to:n},s),c=e.timelines.attachTimeline(r).attachChild(a);return a.onCancelled(s),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:c},()=>{r.isSettled()||r.abort(),a.abort()}),r}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 S(l=>l),c=null;return a.registerSkipController(new H(()=>(c&&(clearTimeout(c),c=null),s))),c=e.setTimeout(()=>{c=null,a.resolve(s)},r),a}executeAction(e,t){if(this.type===X.action)return super.executeAction(e,t);if(this.is(qt,"scene:init")){let n=new S(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 qt.handleSceneInit(this.callee,r,e,S.forward(n,r))}else if(this.type===X.exit){let n=qt.createSceneSnapshot(this.callee,e);return e.actionHistory.push({action:this,stackModel:t.stackModel},i=>{let r=new S(s=>s);e.timelines.attachTimeline(r),qt.handleSceneInit(this.callee,{type:this.type,node:this.contentNode.getChild()},e,r),qt.restoreSceneSnapshot(i,e)},[n]),e.getStorable().removeNamespace(this.callee.local.getNamespaceName()),this.exit(e),super.executeAction(e,t)}else if(this.type===X.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===X.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===X.preUnmount)return this.callee.events.emit("event:scene.preUnmount"),super.executeAction(e,t);if(this.type===X.transitionToScene){let[n,i]=this.contentNode.getContent();return this.applyStageTransition(e,n,i,t)}else if(this.type===X.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===X.nvlShow){let[n]=this.contentNode.getContent(),i=e.getNvlState().visible,r=this.applyNvlVisibility(e,!0,n,t),s=S.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===X.nvlHide){let[n]=this.contentNode.getContent(),i=e.getNvlState().visible,r=this.applyNvlVisibility(e,!1,n,t),s=S.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===X.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===X.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===X.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 ie(`Scene with name ${e} not found
4
4
  Make sure you have registered the scene using story.register
5
5
  Action: (id: ${this.getId()}) ${this.type}
6
- At: ${this.__stack}`)}getSceneName(e){return typeof e=="string"?e:e.config.name}stringify(e,t,n){if(this.type===X.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")}};qt.ActionTypes=X;var se=qt;var Jo=class{constructor(e){this.type=e,this.content=void 0}setContent(e){return this.content=e,this}getContent(){return this.content}},x=class o extends Jo{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 Oi={center:"center",left:"left",right:"right"};import{animate as tl}from"motion/react";var Pn=(n=>(n.Left="left",n.Center="center",n.Right="right",n))(Pn||{}),qs={left:"33.33%",center:"50%",right:"66.66%"},mt=class mt{static isUnknown(e){return e===mt.Unknown}static D2PositionToCSS(e,t=!1,n=!1,i){let r=this.calc(e.y,e.yoffset,i?.height),s=this.calc(e.x,e.xoffset,i?.width),a=n?{bottom:r}:{top:r},c=t?{right:s}:{left:s};return this.wrap({...a,...c})}static calc(e,t,n){if(!e||mt.isUnknown(e))return"auto";let i=!(t===void 0||mt.isUnknown(t));if(typeof n=="number"&&n>0){let s=mt.toPercent(e,n);if(s!==null){let a=i?t/n*100:0;return`${Math.round((s+a)*1e6)/1e6}%`}}return i?`calc(${typeof e=="number"?`${e}px`:e} + ${t}px)`:`calc(${e} + 0px)`}static toPercent(e,t){if(typeof e=="number")return t>0?e/t*100:null;let n=/^(-?\d+(?:\.\d+)?)%$/.exec(e.trim());return n?parseFloat(n[1]):null}static toCoord2D(e){if(st.isCommonPositionType(e))return ft.fromCommonPosition(e);if(ft.isCoord2DPosition(e))return e;if(fn.isAlignPosition(e))return ft.fromAlignPosition(e);if(typeof e=="object"&&e!==null&&["x","y","xalign","yalign","xoffset","yoffset"].some(t=>t in e))return this.rawPositionToCoord2D(e);throw new Error("Invalid position type")}static orUnknown(e){return mt.isUnknown(e)||e===void 0?mt.Unknown:e}static mergePosition(e,t){let n=this.toCoord2D(e),i=this.toCoord2D(t);return ft.merge(n,i)}static serializePosition(e){let t=this.toCoord2D(e);return{x:mt.isUnknown(t.x)?0:t.x,y:mt.isUnknown(t.y)?0:t.y,xoffset:mt.isUnknown(t.xoffset)?0:t.xoffset,yoffset:mt.isUnknown(t.yoffset)?0:t.yoffset}}static isRawCommonPositionType(e){return Object.values(Pn).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"&&e!==null&&("xalign"in e||"yalign"in e)}static isRawPosition(e){return this.isRawCommonPositionType(e)||this.isRawCoord2DPosition(e)||this.isRawAlignPosition(e)}static isPosition(e){return e instanceof st||e instanceof ft||e instanceof fn}static rawPositionToCoord2D(e){if(this.isRawCommonPositionType(e))return ft.fromCommonPosition(new st(e));if(this.isRawAlignPosition(e))return ft.fromAlignPosition(e);if(this.isRawCoord2DPosition(e))return new ft(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}}};mt.Unknown=Symbol("Unknown");var N=mt,Ui=class Ui{static isCommonPositionType(e){return e instanceof Ui}constructor(e){this.position=e}toCSS(){return{x:qs[this.position],y:"50%",xoffset:0,yoffset:0}}};Ui.Positions=Pn;var st=Ui,ft=class o{static isCoord2DPosition(e){return e instanceof o}static fromCommonPosition(e){return new o({x:qs[e.position],y:"50%"})}static fromAlignPosition(e){let t=n=>!n||N.isUnknown(n)?N.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:N.isUnknown(t.x)?e.x:t.x,y:N.isUnknown(t.y)?e.y:t.y,xoffset:N.isUnknown(t.xoffset)?e.xoffset:t.xoffset,yoffset:N.isUnknown(t.yoffset)?e.yoffset:t.yoffset})}constructor(e,t){typeof e=="object"?(this.x=N.orUnknown(e.x),this.y=N.orUnknown(e.y),this.xoffset=N.orUnknown(e.xoffset),this.yoffset=N.orUnknown(e.yoffset)):(this.x=N.orUnknown(e),this.y=N.orUnknown(t),this.xoffset=N.Unknown,this.yoffset=N.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}}},fn=class o{static isAlignPosition(e){return e instanceof o}constructor(e,t){typeof e=="object"?(this.xalign=N.orUnknown(e.xalign),this.yalign=N.orUnknown(e.yalign),this.xoffset=N.orUnknown(e.xoffset),this.yoffset=N.orUnknown(e.yoffset)):(this.xalign=N.orUnknown(e),this.yalign=N.orUnknown(t),this.xoffset=N.Unknown,this.yoffset=N.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:N.isUnknown(this.xalign)?this.xalign:`${this.xalign*100}%`,y:N.isUnknown(this.yalign)?this.yalign:`${this.yalign*100}%`,xoffset:this.xoffset,yoffset:this.yoffset}}};var B=class o{constructor(e,t){this.defaultConfig=e;this.handlers=t||{}}create(e={}){return new Zo(this.mergeWithDefaultConfig(e))}copy(){return new o(z({},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)?z({},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}},Zo=class o{constructor(e){this.config=e}get(){return this.config}copy(){return new o(z({},this.config))}join(e){let t=Ws(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 nl={[Oi.left]:"25.33%",[Oi.center]:"50%",[Oi.right]:"75.66%"},xt=class xt{constructor(e={}){this.state={};this.locked=null;this.frozen=!1;this.state=e}static deserialize(e){return new xt(xt.TransformStateSerializer.deserialize(e))}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?N.toCoord2D(N.tryParsePosition(e||t)):N.mergePosition(N.tryParsePosition(e),N.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=xt.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 Fi(Z.constructStyle(e,this.state,t))}toStyle(e,t){return Fi(Z.constructStyle(e,this.state,t))}serialize(){return xt.TransformStateSerializer.serialize(this.state)}clone(){return new xt(xt.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=xt.mergeState(this.state,t),this}forceOverwrite(e){return this.state=e,this}};xt.DefaultTransformState=new B({scaleX:1,scaleY:1,zoom:1,rotation:0,position:new st("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}),xt.TransformStateSerializer=new Qe({position:e=>N.serializePosition(N.tryParsePosition(e))},{position:e=>N.toCoord2D(e)});var J=xt,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 st.isCommonPositionType(e)||ft.isCoord2DPosition(e)||fn.isAlignPosition(e)}static immediate(e){return new De(e,{duration:0,ease:"linear"})}static left(e,t){return new De({position:st.Positions.Left},{duration:e,ease:t})}static right(e,t){return new De({position:st.Positions.Right},{duration:e,ease:t})}static center(e,t){return new De({position:st.Positions.Center},{duration:e,ease:t})}static create(e){return new De([],e)}static positionToCSS(e,t,n,i){return e?N.isRawPosition(e)?N.D2PositionToCSS(N.rawPositionToCoord2D(e),n,t,i):N.D2PositionToCSS(e.toCSS(),n,t,i):{}}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?N.toCoord2D(N.tryParsePosition(e||t)):N.mergePosition(N.tryParsePosition(e),N.tryParsePosition(t))}static mergeState(e,t){let n=this.mergePosition(e.position,t.position);return{...z(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,f){return typeof p>"u"?typeof f<"u"?h(f):"":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||{},a=e.game?.config,c=a&&a.width>0&&a.height>0?{width:a.width,height:a.height}:void 0;return{...De.positionToCSS(t.position,i,r,c),opacity:t.opacity,color:"fontColor"in t&&t.fontColor?kn(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,companionRefs:r}){if(!n.current)throw new Error("No ref found when animating.");this.commit();let{finalState:s,sequences:a,options:c}=this.constructAnimation({gameState:t,transformState:e,overwrites:i,current:n.current,companions:r?.filter(m=>!!m.ref.current).map(({ref:m,project:y})=>({el:m.current,project:y}))});a.length||t.logger.warn("Transform","No sequences to animate.");let l=!1,u=e.lock(),d=tl(a,c),p=()=>{e.overwrite(u,s.get()).unlock(u),d.complete(),l=!0},h=new S().registerSkipController(new H(p)),f=()=>{l||e.overwrite(u,s.get()).unlock(u),l=!0,t.logger.debug("Transform","Transform Completed",e.toStyle(t,i)),h.resolve()};return d.then(f,(m=>{t.logger.error("Failed to animate transform. "+(m?.toString?.()||""));try{f()}catch{h.resolve()}})),d.play(),t.logger.debug("Transform","Ready to animate transform.",{finalState:s,sequences:a,options:c},this),h}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,companions:r}){let s=t.clone(),a=s.lock(),c=this.sequences.flatMap(({props:l,options:u})=>{let d=s.assign(a,l),p=d.toFramesDefinition(e,n),h=this.getOptions(u),f=[i,p,h];if(!r||!r.length)return[f];let m=d.get();return[f,...r.map(({el:y,project:b})=>[y,Fi(b(m)),{...h,at:"<"}])]});return{finalState:s.unlock(a).freeze(),sequences:c,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}lens(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 ie("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 ie("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=nl;var Z=De;var Wi=class{constructor(){this.id="";this._staticId=null;this._dirty=!1}setId(e){this.id=e}getId(){return this.id}getStaticId(){return this._staticId}setStaticId(e){return this._staticId=e,this}resolveId(e){return this.setId(this._staticId||e),this}markDirty(){return this._dirty=!0,this}isDirty(){return this._dirty}reset(){this._dirty=!1}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 Ys=Symbol("_Chained"),Qs;Qs=Ys;var _o=class _o{constructor(e){this[Qs]=!0;this.__actions=[];this.__self=e}static isChained(e){return e&&e[Ys]}static toActions(e){return e.flat(2).map(t=>_o.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()}},ze=_o,En=class extends Wi{chain(e){let t=ze.isChained(this)?this:this.proxy(this,new ze(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 ce=class extends En{constructor(){super()}toData(){return null}fromChained(e){return e.getActions()}};var Nt=class extends ${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)}}`:""}`)}};Nt.ActionTypes=Ms;var jn=64;function Js(o){return typeof o=="object"&&o!==null&&Object.getPrototypeOf(o)===Object.prototype}function er(o){return o.length?o.map(e=>typeof e=="number"?`[${e}]`:`.${e}`).join(""):"the value itself"}function Bi(o,e=0,t=new Set){if(e>jn)return!1;if(typeof o=="number"||typeof o=="string"||typeof o=="boolean"||o==null||o instanceof Date)return!0;if(typeof o!="object"||t.has(o))return!1;t.add(o);try{return Array.isArray(o)?o.every(n=>Bi(n,e+1,t)):Js(o)?Object.values(o).every(n=>Bi(n,e+1,t)):!1}finally{t.delete(o)}}function Zs(o,e){let t=[],n=[];return{data:tr(o,[],0,new Set,t,n,e),dates:t,undefineds:n}}function tr(o,e,t,n,i,r,s){if(t>jn)throw new k(`A stored value nests deeper than ${jn} levels and cannot be saved
6
+ At: ${this.__stack}`)}getSceneName(e){return typeof e=="string"?e:e.config.name}stringify(e,t,n){if(this.type===X.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")}};qt.ActionTypes=X;var se=qt;var Jo=class{constructor(e){this.type=e,this.content=void 0}setContent(e){return this.content=e,this}getContent(){return this.content}},x=class o extends Jo{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 Oi={center:"center",left:"left",right:"right"};import{animate as tl}from"motion/react";var Pn=(n=>(n.Left="left",n.Center="center",n.Right="right",n))(Pn||{}),qs={left:"33.33%",center:"50%",right:"66.66%"},mt=class mt{static isUnknown(e){return e===mt.Unknown}static D2PositionToCSS(e,t=!1,n=!1,i){let r=this.calc(e.y,e.yoffset,i?.height),s=this.calc(e.x,e.xoffset,i?.width),a=n?{bottom:r}:{top:r},c=t?{right:s}:{left:s};return this.wrap({...a,...c})}static calc(e,t,n){if(!e||mt.isUnknown(e))return"auto";let i=!(t===void 0||mt.isUnknown(t));if(typeof n=="number"&&n>0){let s=mt.toPercent(e,n);if(s!==null){let a=i?t/n*100:0;return`${Math.round((s+a)*1e6)/1e6}%`}}return i?`calc(${typeof e=="number"?`${e}px`:e} + ${t}px)`:`calc(${e} + 0px)`}static toPercent(e,t){if(typeof e=="number")return t>0?e/t*100:null;let n=/^(-?\d+(?:\.\d+)?)%$/.exec(e.trim());return n?parseFloat(n[1]):null}static toCoord2D(e){if(st.isCommonPositionType(e))return ft.fromCommonPosition(e);if(ft.isCoord2DPosition(e))return e;if(fn.isAlignPosition(e))return ft.fromAlignPosition(e);if(typeof e=="object"&&e!==null&&["x","y","xalign","yalign","xoffset","yoffset"].some(t=>t in e))return this.rawPositionToCoord2D(e);throw new Error("Invalid position type")}static orUnknown(e){return mt.isUnknown(e)||e===void 0?mt.Unknown:e}static mergePosition(e,t){let n=this.toCoord2D(e),i=this.toCoord2D(t);return ft.merge(n,i)}static serializePosition(e){let t=this.toCoord2D(e);return{x:mt.isUnknown(t.x)?0:t.x,y:mt.isUnknown(t.y)?0:t.y,xoffset:mt.isUnknown(t.xoffset)?0:t.xoffset,yoffset:mt.isUnknown(t.yoffset)?0:t.yoffset}}static isRawCommonPositionType(e){return Object.values(Pn).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"&&e!==null&&("xalign"in e||"yalign"in e)}static isRawPosition(e){return this.isRawCommonPositionType(e)||this.isRawCoord2DPosition(e)||this.isRawAlignPosition(e)}static isPosition(e){return e instanceof st||e instanceof ft||e instanceof fn}static rawPositionToCoord2D(e){if(this.isRawCommonPositionType(e))return ft.fromCommonPosition(new st(e));if(this.isRawAlignPosition(e))return ft.fromAlignPosition(e);if(this.isRawCoord2DPosition(e))return new ft(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}}};mt.Unknown=Symbol("Unknown");var N=mt,Ui=class Ui{static isCommonPositionType(e){return e instanceof Ui}constructor(e){this.position=e}toCSS(){return{x:qs[this.position],y:"50%",xoffset:0,yoffset:0}}};Ui.Positions=Pn;var st=Ui,ft=class o{static isCoord2DPosition(e){return e instanceof o}static fromCommonPosition(e){return new o({x:qs[e.position],y:"50%"})}static fromAlignPosition(e){let t=n=>!n||N.isUnknown(n)?N.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:N.isUnknown(t.x)?e.x:t.x,y:N.isUnknown(t.y)?e.y:t.y,xoffset:N.isUnknown(t.xoffset)?e.xoffset:t.xoffset,yoffset:N.isUnknown(t.yoffset)?e.yoffset:t.yoffset})}constructor(e,t){typeof e=="object"?(this.x=N.orUnknown(e.x),this.y=N.orUnknown(e.y),this.xoffset=N.orUnknown(e.xoffset),this.yoffset=N.orUnknown(e.yoffset)):(this.x=N.orUnknown(e),this.y=N.orUnknown(t),this.xoffset=N.Unknown,this.yoffset=N.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}}},fn=class o{static isAlignPosition(e){return e instanceof o}constructor(e,t){typeof e=="object"?(this.xalign=N.orUnknown(e.xalign),this.yalign=N.orUnknown(e.yalign),this.xoffset=N.orUnknown(e.xoffset),this.yoffset=N.orUnknown(e.yoffset)):(this.xalign=N.orUnknown(e),this.yalign=N.orUnknown(t),this.xoffset=N.Unknown,this.yoffset=N.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:N.isUnknown(this.xalign)?this.xalign:`${this.xalign*100}%`,y:N.isUnknown(this.yalign)?this.yalign:`${this.yalign*100}%`,xoffset:this.xoffset,yoffset:this.yoffset}}};var B=class o{constructor(e,t){this.defaultConfig=e;this.handlers=t||{}}create(e={}){return new Zo(this.mergeWithDefaultConfig(e))}copy(){return new o(z({},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)?z({},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}},Zo=class o{constructor(e){this.config=e}get(){return this.config}copy(){return new o(z({},this.config))}join(e){let t=Ws(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 nl={[Oi.left]:"25.33%",[Oi.center]:"50%",[Oi.right]:"75.66%"},xt=class xt{constructor(e={}){this.state={};this.locked=null;this.frozen=!1;this.state=e}static deserialize(e){return new xt(xt.TransformStateSerializer.deserialize(e))}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?N.toCoord2D(N.tryParsePosition(e||t)):N.mergePosition(N.tryParsePosition(e),N.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=xt.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 Fi(Z.constructStyle(e,this.state,t))}toStyle(e,t){return Fi(Z.constructStyle(e,this.state,t))}serialize(){return xt.TransformStateSerializer.serialize(this.state)}clone(){return new xt(xt.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=xt.mergeState(this.state,t),this}forceOverwrite(e){return this.state=e,this}resetTo(e){return this.state=e,this.locked=null,this.frozen=!1,this}};xt.DefaultTransformState=new B({scaleX:1,scaleY:1,zoom:1,rotation:0,position:new st("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}),xt.TransformStateSerializer=new Qe({position:e=>N.serializePosition(N.tryParsePosition(e))},{position:e=>N.toCoord2D(e)});var J=xt,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 st.isCommonPositionType(e)||ft.isCoord2DPosition(e)||fn.isAlignPosition(e)}static immediate(e){return new De(e,{duration:0,ease:"linear"})}static left(e,t){return new De({position:st.Positions.Left},{duration:e,ease:t})}static right(e,t){return new De({position:st.Positions.Right},{duration:e,ease:t})}static center(e,t){return new De({position:st.Positions.Center},{duration:e,ease:t})}static create(e){return new De([],e)}static positionToCSS(e,t,n,i){return e?N.isRawPosition(e)?N.D2PositionToCSS(N.rawPositionToCoord2D(e),n,t,i):N.D2PositionToCSS(e.toCSS(),n,t,i):{}}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?N.toCoord2D(N.tryParsePosition(e||t)):N.mergePosition(N.tryParsePosition(e),N.tryParsePosition(t))}static mergeState(e,t){let n=this.mergePosition(e.position,t.position);return{...z(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,f){return typeof p>"u"?typeof f<"u"?h(f):"":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||{},a=e.game?.config,c=a&&a.width>0&&a.height>0?{width:a.width,height:a.height}:void 0;return{...De.positionToCSS(t.position,i,r,c),opacity:t.opacity,color:"fontColor"in t&&t.fontColor?kn(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,companionRefs:r}){if(!n.current)throw new Error("No ref found when animating.");this.commit();let{finalState:s,sequences:a,options:c}=this.constructAnimation({gameState:t,transformState:e,overwrites:i,current:n.current,companions:r?.filter(m=>!!m.ref.current).map(({ref:m,project:y})=>({el:m.current,project:y}))});a.length||t.logger.warn("Transform","No sequences to animate.");let l=!1,u=e.lock(),d=tl(a,c),p=()=>{e.overwrite(u,s.get()).unlock(u),d.complete(),l=!0},h=new S().registerSkipController(new H(p)),f=()=>{l||e.overwrite(u,s.get()).unlock(u),l=!0,t.logger.debug("Transform","Transform Completed",e.toStyle(t,i)),h.resolve()};return d.then(f,(m=>{t.logger.error("Failed to animate transform. "+(m?.toString?.()||""));try{f()}catch{h.resolve()}})),d.play(),t.logger.debug("Transform","Ready to animate transform.",{finalState:s,sequences:a,options:c},this),h}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,companions:r}){let s=t.clone(),a=s.lock(),c=this.sequences.flatMap(({props:l,options:u})=>{let d=s.assign(a,l),p=d.toFramesDefinition(e,n),h=this.getOptions(u),f=[i,p,h];if(!r||!r.length)return[f];let m=d.get();return[f,...r.map(({el:y,project:b})=>[y,Fi(b(m)),{...h,at:"<"}])]});return{finalState:s.unlock(a).freeze(),sequences:c,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}lens(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 ie("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 ie("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=nl;var Z=De;var Wi=class{constructor(){this.id="";this._staticId=null;this._dirty=!1}setId(e){this.id=e}getId(){return this.id}getStaticId(){return this._staticId}setStaticId(e){return this._staticId=e,this}resolveId(e){return this.setId(this._staticId||e),this}markDirty(){return this._dirty=!0,this}isDirty(){return this._dirty}reset(){this._dirty=!1}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 Ys=Symbol("_Chained"),Qs;Qs=Ys;var _o=class _o{constructor(e){this[Qs]=!0;this.__actions=[];this.__self=e}static isChained(e){return e&&e[Ys]}static toActions(e){return e.flat(2).map(t=>_o.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()}},ze=_o,En=class extends Wi{chain(e){let t=ze.isChained(this)?this:this.proxy(this,new ze(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 ce=class extends En{constructor(){super()}toData(){return null}fromChained(e){return e.getActions()}};var Nt=class extends ${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)}}`:""}`)}};Nt.ActionTypes=Ms;var jn=64;function Js(o){return typeof o=="object"&&o!==null&&Object.getPrototypeOf(o)===Object.prototype}function er(o){return o.length?o.map(e=>typeof e=="number"?`[${e}]`:`.${e}`).join(""):"the value itself"}function Bi(o,e=0,t=new Set){if(e>jn)return!1;if(typeof o=="number"||typeof o=="string"||typeof o=="boolean"||o==null||o instanceof Date)return!0;if(typeof o!="object"||t.has(o))return!1;t.add(o);try{return Array.isArray(o)?o.every(n=>Bi(n,e+1,t)):Js(o)?Object.values(o).every(n=>Bi(n,e+1,t)):!1}finally{t.delete(o)}}function Zs(o,e){let t=[],n=[];return{data:tr(o,[],0,new Set,t,n,e),dates:t,undefineds:n}}function tr(o,e,t,n,i,r,s){if(t>jn)throw new k(`A stored value nests deeper than ${jn} levels and cannot be saved
7
7
  at ${s}, ${er(e)}
8
8
  A saved game this deep is almost always a data-structure bug. Flatten the value,
9
9
  or keep the deep part outside the store and save an id for it.`);if(o===void 0)return r.push([...e]),null;if(o===null)return null;if(o instanceof Date)return i.push([...e]),o.toISOString();if(typeof o=="number"||typeof o=="string"||typeof o=="boolean")return o;if(typeof o=="object"){if(n.has(o))throw new k(`A stored value refers back to itself and cannot be saved
@@ -17,14 +17,14 @@ At: ${this.__stack}`)}getSceneName(e){return typeof e=="string"?e:e.config.name}
17
17
  Use \`story.registerPersistent\` to register a persistent namespace`);return this.namespaces[e]}setNamespace(e,t){return this.namespaces[e]?.detach(this),this.namespaces[e]=t,t.attach(this),this}hasNamespace(e){return!!this.namespaces[e]}removeNamespace(e){return this.namespaces[e]?.detach(this),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)}onChange(e,t,n){let i=typeof e=="string"?e:null,r=typeof t=="string"?t:null,s=typeof e=="function"?e:typeof t=="function"?t:n;if(!s)throw new k("No listener provided when subscribing to storable changes");return this.events.on(en.EventTypes["event:storable.change"],a=>{i!==null&&a.namespace!==i||r!==null&&a.key!==r||s(a)})}onRestore(e){return this.events.on(en.EventTypes["event:storable.restore"],e)}toData(){return this.entries().reduce((e,[t,n])=>(e[t]=n.toData(),e),{})}load(e){if(!e){console.warn("No data to load");return}let t=this.restoreBatch=new Set;try{Object.entries(e).forEach(([n,i])=>{this.namespaces[n]||this.addNamespace(new Gt(n,{})),this.namespaces[n].deserialize(i)})}finally{this.restoreBatch=null}this.events.emit(en.EventTypes["event:storable.restore"],{namespaces:Array.from(t)})}clear(){return this.values().forEach(e=>e.detach(this)),this.namespaces={},this}reportChange(e){this.events.emit(en.EventTypes["event:storable.change"],e)}reportRestore(e){if(this.restoreBatch){this.restoreBatch.add(e);return}this.events.emit(en.EventTypes["event:storable.restore"],{namespaces:[e]})}};en.EventTypes={"event:storable.change":"event:storable.change","event:storable.restore":"event:storable.restore"};var qn=en;var et=class extends ${executeAction(e,t){let n={action:this,stackModel:t.stackModel};if(this.type===It.play){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.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===It.stop){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.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===It.setVolume){let[i,r]=this.contentNode.getContent(),s=this.callee.toData(),a=S.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===It.setRate){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.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===It.pause){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.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===It.resume){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.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===It.seek){let[i]=this.contentNode.getContent(),r=e.audioManager.getPosition(this.callee),s=S.forward(e.audioManager.seek(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{e.audioManager.seek(this.callee,a)},[r]),s}else if(this.type===It.mute){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.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")}};et.ActionTypes=It;var tt={bgm:"bgm",sound:"sound",voice:"voice"},Ki=8,tn=class extends Error{constructor(e){super(e),this.name="AudioBusError"}};function Dn(o){return o===void 0||!Number.isFinite(o)?1:Math.min(1,Math.max(0,o))}var Qn=class o{constructor(e,t){this.nodes=e;this.index=t}static resolve(e=[]){let t=new Map,n=c=>{t.set(c.id,{id:c.id,parentId:c.parentId??null,volume:Dn(c.volume)})};Object.values(tt).forEach(c=>n({id:c}));let i=new Set;e.forEach(c=>{let l=c?.id;if(typeof l!="string"||l.trim().length===0)throw new tn(`Audio bus id must be a non-empty string, got ${JSON.stringify(l)}.`);if(i.has(l))throw new tn(`Audio bus "${l}" is declared more than once.`);i.add(l),n(c)}),o.assertResolvable(t);let r=[],s=new Map,a=c=>{let l=s.get(c);if(l)return l;let u=t.get(c),d=u.parentId===null?null:a(u.parentId),p={id:u.id,parentId:u.parentId,volume:u.volume,depth:d?d.depth+1:1};return s.set(c,p),r.push(p),p};return t.forEach(c=>a(c.id)),new o(r,s)}static isSeeded(e){return Object.values(tt).includes(e)}static assertResolvable(e){e.forEach(t=>{let n=[t.id],i=new Set([t.id]),r=t;for(;r.parentId!==null;){let s=e.get(r.parentId);if(!s)throw new tn(`Audio bus "${r.id}" names an unknown parent "${r.parentId}".`);if(i.has(s.id))throw new tn(`Audio bus tree has a cycle: ${[...n,s.id].join(" -> ")}.`);if(i.add(s.id),n.push(s.id),n.length>Ki)throw new tn(`Audio bus "${t.id}" nests deeper than ${Ki}: ${n.join(" -> ")}.`);r=s}})}getNodes(){return this.nodes}get(e){return this.index.get(e)??null}has(e){return this.index.has(e)}isUnder(e,t){let n=this.index.get(e),i=0;for(;n&&i<=Ki;){if(n.id===t)return!0;n=n.parentId===null?void 0:this.index.get(n.parentId),i++}return!1}},or=Qn.resolve();function ol(o){or=o}function rr(){return or}function zi(o,e){let t=or;return t.has(o)?e.some(n=>t.isUnder(o,n)):!0}var ta={[tt.bgm]:"bgmVolume",[tt.sound]:"soundVolume",[tt.voice]:"voiceVolume"};function na(o){let e={};return Object.entries(ta).forEach(([t,n])=>{e[t]={get:()=>Dn(o.getPreference(n)),set:i=>o.setPreference(n,i),subscribe:i=>o.onPreferenceChange(n,i)}}),e}var Yn=class Yn{constructor(e,t={}){this.declarations=e;this.events=new q;this.overrides=new Map;this.aliasTokens=[];this.tree=null;this.events.setMaxListeners(64),this.aliases=t,Object.entries(t).forEach(([n,i])=>{this.aliasTokens.push(i.subscribe(r=>{this.announce(n,Dn(r))}))})}dispose(){this.aliasTokens.forEach(e=>e.cancel()),this.aliasTokens.length=0}announce(e,t){let n=t;try{n=this.getEffectiveVolume(e)}catch{}this.events.emit(Yn.EventTypes["event:audioBus.volumeChange"],e,t,n)}getTree(){return this.tree||(this.tree=Qn.resolve(this.declarations()??[]),ol(this.tree)),this.tree}invalidate(){return this.tree=null,this}isResolved(){return this.tree!==null}setVolume(e,t){let n=Dn(t),i=this.aliases[e];return i?(i.set(n),this):(this.overrides.set(e,n),this.announce(e,n),this)}setVolumes(e){return Object.entries(e).forEach(([t,n])=>this.setVolume(t,n)),this}getVolume(e){let t=this.aliases[e];return t?Dn(t.get()):this.overrides.get(e)??1}getDeclaredVolume(e){return this.getTree().get(e)?.volume??1}getEffectiveVolume(e){return Dn(this.getDeclaredVolume(e)*this.getVolume(e))}list(){return this.getTree().getNodes().map(e=>({id:e.id,parentId:e.parentId,volume:this.getVolume(e.id),declaredVolume:e.volume,effectiveVolume:this.getEffectiveVolume(e.id)}))}getVolumes(){let e={};return this.list().forEach(t=>{e[t.id]=t.volume}),e}onVolumeChange(e){return this.events.on(Yn.EventTypes["event:audioBus.volumeChange"],e)}};Yn.EventTypes={"event:audioBus.volumeChange":"event:audioBus.volumeChange"};var Xn=Yn;var ia=(n=>(n.Voice="voice",n.Bgm="bgm",n.Sound="sound",n))(ia||{}),Ae=class Ae extends ce{static toSound(e){return e==null?null:typeof e=="string"?new Ae({src:e}):e}static isSound(e){return e instanceof Ae}static voice(e){let t=typeof e=="string"?{src:e}:e;return new Ae({type:"voice",...t})}static bgm(e){let t=typeof e=="string"?{src:e}:e;return new Ae({type:"bgm",...t})}static sound(e){let t=typeof e=="string"?{src:e}:e;return new Ae({type:"sound",...t})}constructor(e={}){super();let t=typeof e=="string"?{src:e}:e,n=Ae.DefaultUserConfig.create(t),[i]=n.extract(Ae.DefaultConfig.keys());this.config=i.get(),this.state=this.getInitialState(n),this.userConfig=n}play(e){return rr().isUnder(this.config.type,tt.bgm)&&console.warn(`NarraLeaf-React [Sound] Playing a bgm-typed sound (src: ${this.config.src}) with \`play()\`. It will play on the music bus but is not the scene's background music, so leaving the scene will not stop it and it will not cross-fade. Use \`scene.setBackgroundMusic()\` if that is what you wanted.`),this.pushAction(et.ActionTypes.play,[{end:this.state.volume,duration:e||0}])}stop(e){return this.pushAction(et.ActionTypes.stop,[{end:0,duration:e||0}])}setVolume(e,t){return this.pushAction(et.ActionTypes.setVolume,[e,t||0])}mute(e=!0){return this.pushAction(et.ActionTypes.mute,[e])}unmute(){return this.mute(!1)}setRate(e){return this.pushAction(et.ActionTypes.setRate,[e])}pause(e){return this.pushAction(et.ActionTypes.pause,[{end:0,duration:e||0}])}resume(e){return this.pushAction(et.ActionTypes.resume,[{end:this.state.volume,duration:e||0}])}seek(e){return this.pushAction(et.ActionTypes.seek,[e])}getSrc(){return this.config.src}toData(){return{state:Ae.StateSerializer.serialize(this.state)}}fromData(e){return this.state=Ae.StateSerializer.deserialize(e.state),this}copy(){return new Ae(this.userConfig.get())}reset(){return super.reset(),this.state=this.getInitialState(this.userConfig),this}getInitialState(e){return Ae.DefaultState.create({...e.get()}).get()}pushAction(e,t){return this.chain(new et(this.chain(),e,new x().setContent(t)))}};Ae.noSound="data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgA",Ae.DefaultUserConfig=new B({src:Ae.noSound,loop:!1,volume:1,streaming:!1,rate:1,seek:0,endTime:void 0,loopStart:void 0,type:"sound"}),Ae.DefaultConfig=new B({src:Ae.noSound,loop:!1,streaming:!1,seek:0,endTime:void 0,loopStart:void 0,type:"sound"}),Ae.DefaultState=new B({volume:1,rate:1,paused:!1,muted:!1}),Ae.StateSerializer=new Qe;var ve=Ae;var oa=3;var Bm={};var Ln=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 hn=class hn{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===hn.SrcTypes.image?t.add(s):r===hn.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 I?I.getSrcURL(e):e.type==="image"?I.getSrcURL(e.src):e.type==="video"?e.src:e.type==="audio"?e.src.getSrc():""}static getPreloadableSrc(e,t){if(t.is(se,X.jumpTo)){let n=t.contentNode.getContent()[0],r=e.getScene(n,!0).state.backgroundImage;if(w.isImageURL(r.config.src))return{type:"image",src:r.config.src,activeType:"once"}}else if(t instanceof Se){let n=t;if(t.is(Se,dt.setSrc)){let i=t.contentNode.getContent()[0];if(w.isImageSrc(i))return{type:"image",src:w.srcToURL(i),activeType:"scene"}}else{if(t.type===dt.initWearable)return{type:"image",src:t.contentNode.getContent()[0],activeType:"scene"};if(t.type===dt.setAppearance){let i=t.contentNode.getContent()[0];if(I.isLayeredSrc(n.callee))return null;if(!n.callee.config.src||typeof n.callee.config.src?.resolve!="function")throw n.callee._invalidSrcHandlerError();if(I.isTagSrc(n.callee)&&i.length===n.callee.config.src.groups.length)return{type:"image",src:I.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 ve){if(this.isSrcRegistered(e.getSrc()))return this;this.src.push({type:"audio",src:e})}else if(e instanceof I||w.isStaticImageData(e)){if(e instanceof I){if(!w.isImageURL(e.state.currentSrc))return this;if(this.isSrcRegistered(I.getSrcURL(e)))return this}else if(this.isSrcRegistered(w.srcToURL(e.src)))return this;this.src.push({type:"image",src:w.isStaticImageData(e)?w.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 ve?t:new ve({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 ve?e.getSrc():e;return this.src.some(n=>n.type===hn.SrcTypes.audio?t===n.src.getSrc():n.type===hn.SrcTypes.image?t===I.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)}};hn.SrcTypes={image:"image",video:"video",audio:"audio"};var Le=hn;var $e=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 at=class o{static isTextEvent(e){return e instanceof o}static expression(e,t,n={}){return new o({expression:{image:e,appearance:t},sound:n.sound})}static sound(e){return new o({sound:e})}constructor(e){this.config=e}};function ra(o,e){let{render:t,data:n,...i}=e,r=z(o,i);return"render"in e?r.render=e.render:"render"in o&&(r.render=o.render),"data"in e?r.data=e.data:"data"in o&&(r.data=o.data),r}var Re=class Re{static isWord(e){return e instanceof Re}static color(e,t){return Re.isWord(e)?e.copy().assign({color:t}):new Re(e,{color:t})}static bold(e){return Re.isWord(e)?e.copy().assign({bold:!0}):new Re(e,{bold:!0})}static italic(e){return Re.isWord(e)?e.copy().assign({italic:!0}):new Re(e,{italic:!0})}static custom(e,t,n={}){let i={...n,render:t};return Re.isWord(e)?e.copy().assign(i):new Re(e,i)}static getText(e){return e.filter(t=>!t.isPause()&&!t.isTextEvent()).map(t=>t.toString()).join("")}constructor(e,t={}){this.text=e,this.config=ra(Re.defaultConfig,t)}evaluate(e){if($e.isPause(this.text))return[this];if(at.isTextEvent(this.text))return[this];if(typeof this.text=="function"){let t=this.text(e);return Array.isArray(t)?t.map(n=>Re.isWord(n)?n.inherit(this.config).evaluate(e):new Re(n,this.config)).flat():Re.isWord(t)?t.inherit(this.config).evaluate(e):[new Re(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=ra(this.config,e),this}copy(){return new Re(this.text,this.config)}isPause(){return $e.isPause(this.text)}isTextEvent(){return at.isTextEvent(this.text)}toString(){return typeof this.text=="string"?this.text:""}};Re.defaultConfig={},Re.defaultColor="#000";var _=Re;var nn=class extends ${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")}};nn.ActionTypes=Ns;var Ce=class o extends ce{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 nn(t,nn.ActionTypes.action,new x().setContent(this));return this.chain(n)}execute({gameState:e}){return this.handler(o.getCtx({gameState:e}))}fromChained(e){return[new nn(this.chain(),nn.ActionTypes.action,new x().setContent(e))]}};var $i=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 xe=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()}),rt(()=>{this.preventAttach()})}static proxy(e){let t=new S,n=new S,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 k("Cannot create an 'any' timeline with no awaitables.");let t=new S,n=new S,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 k("Cannot create an 'all' timeline with no awaitables.");let t=new S,n=new S,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 S,s=()=>{if(i){let a;i.onSkipControllerRegister(c=>{a=c.onAbort(()=>{r.abort()})}),i.then(c=>{a?.cancel(),n=c,i=e(c),i?rt(()=>s()):r.resolve(n)})}else r.resolve(n)};return r.registerSkipController(new H(()=>(i&&i.abort(),t))),i=e(t),i?rt(()=>s()):rt(()=>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()?rt(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 k(`Attaching to this timeline violates the timeline's state.
18
18
  Timeline attaching is only allowed synchronously after the timeline is created.
19
19
  Current _ableToAttach: `+this._ableToAttach);let t=S.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())}},ji=class{constructor(e){this.guard=e;this.timelines=[]}attachTimeline(e){this.cleanupSettled();let t=e instanceof xe?e:new xe(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 wt=class wt extends ${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:ve.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)}static cutTrailingVoice(e,t){let n=wt.trailingVoice.get(e);n&&n!==t&&e.audioManager.isPlaying(n)&&e.timelines.attachTimeline(e.audioManager.stop(n,0)),t?wt.trailingVoice.set(e,t):wt.trailingVoice.delete(e)}executeAction(e,t){if(this.type===jt.say){let n=null,i="",r=null,s=new S(y=>y).registerSkipController(new H(()=>{n?.()})),a=new xe(s),c=this.contentNode.getContent(),l=e.isNvlMode(),u=e.getLiveGame(),d=e.createPresentationSnapshot(),p=u.lastDialog?{sentence:u.lastDialog.sentence,speaker:u.lastDialog.speaker}:null,h=wt.getVoice(e,c);if(h){wt.cutTrailingVoice(e,h);let y=e.audioManager.play(h);a.attachChild(y)}let f=h?e.events.on(E.EventTypes["event:state.player.lineEnd"],()=>{let y=wt.endVoiceWithPreference(e,h);y&&e.timelines.attachTimeline(y),f?.cancel()}):null;if(l){let y=this.getId(),v=(e.getActiveNvlDialogForAction(y)||e.getLatestNvlDialogForAction(y))?.id||e.allocateNvlDialogId(y),g=c.evaluate(Ce.getCtx({gameState:e}));i=_.getText(g),u.events.emit(Ht.EventTypes["event:character.prompt"],{character:c.config.character,sentence:c,text:i});let C=!1,T=()=>{C||(C=!0,e.events.emit(E.EventTypes["event:state.player.lineEnd"]),e.gameHistory.resolvePending(m),s.resolve({type:this.type,node:this.contentNode.getChild()}))},{created:A}=e.ensureNvlDialog({id:v,actionId:y,character:this.callee,sentence:c,text:i});r=v;let P=e.consumeNvlTypingSuppression(),D=A&&!P?"typing":"awaitAdvance";e.activateNvlDialog(v,D,!A);let W=e.waitForNvlAdvance(v,()=>{e.settleNvlDialog(v),T()});n=()=>{W.cancel()}}else{let y=e.idManager.generateId(),b=e.createDialog(y,c,()=>{e.settleAdvDialog(y),e.gameHistory.resolvePending(m),s.resolve({type:this.type,node:this.contentNode.getChild()})});e.beginAdvDialog(y,this.getId()),i=b.text,n=()=>{e.settleAdvDialog(y),b.cancel()}}u.setLastDialog(i,this.callee.state.name),e.timelines.attachTimeline(a);let{id:m}=e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:a},()=>{if(f?.cancel(),h&&e.audioManager.isPlaying(h)){let y=wt.endVoiceWithPreference(e,h);y&&a.attachChild(y)}n?.(),r&&(e.removeNvlDialog(r),e.settleNvlDialog(r)),e.restorePresentationSnapshot(d),p?u.setLastDialog(p.sentence,p.speaker):u.lastDialog=null});return e.gameHistory.push({token:m,action:this,element:{type:"say",text:i,voice:h?h.getSrc():null,voiceId:c.config.voiceId??null,character:this.callee.state.name},isPending:!0,snapshot:u.captureGameState()}),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")}};wt.ActionTypes=jt,wt.trailingVoice=new WeakMap;var nt=wt;function ar(o){return"image"in o?{image:o.image,avatar:o.avatar}:{image:o}}function ca(o){let{sentenceAvatar:e,portraitAvatar:t,characterAvatar:n}=o;if(!o.character||!o.character.state.name||e===!1)return aa(o);let i=sr(e,o);if(i.resolved)return{source:i.source,character:o.character,portrait:o.portrait};let r=sr(t,o);if(r.resolved)return{source:r.source,character:o.character,portrait:o.portrait};let s=sr(n,o);return s.resolved?{source:s.source,character:o.character,portrait:o.portrait}:{source:null,character:o.character,portrait:o.portrait}}function sr(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 aa(o){return{source:null,character:o.character||null,portrait:o.portrait||null}}function la(o,e){let t=[],n=i=>{i&&typeof i!="function"&&w.isImageSrc(i)&&t.push(i)};n(e?.config.avatar),n(o.config.avatar);for(let i of o.config.portraits||[])n(ar(i).avatar);return t}var on=class extends ${executeAction(e,t){let n={action:this,stackModel:t.stackModel};if(this.type===Ei.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===Ei.setFontSize){let i=this.callee.state.fontSize;this.callee.state.fontSize=this.contentNode.getContent()[0];let r=e.getExposedStateForce(this.callee);return r.flush(),r.updateStyleSync(),e.actionHistory.push(n,s=>{this.callee.state.fontSize=s},[i]),super.executeAction(e,t)}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("TextAction")}};on.ActionTypes=Ei;var Jn=class Jn extends ${executeAction(e,t){if(this.type===ye.applyTransform){let[n]=this.contentNode.getContent(),i=this.callee;return this.applyTransform(e,i,n,t)}else if(this.type===ye.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===ye.init){let[n,i,r]=this.contentNode.getContent(),s=this.callee;return this.initDisplayable(e,n,s,i||null,r,t)}else if(this.type===ye.bringToFront)return this.bringToFront(e,this.callee,t);throw this.unknownTypeError()}applyTransform(e,t,n,i,r){let s=new S().registerSkipController(new H(()=>(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(),u=c.applyTransform(n,a),d=e.timelines.attachTimeline(s).attachChild(u);return u.onCancelled(a),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:d},p=>{s.isSettled()||s.abort(),u.abort(),t.transformState.forceOverwrite(p.state)},[l]),s}applyTransition(e,t,n,i,r){let s=new S().registerSkipController(new H(()=>(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),u=e.timelines.attachTimeline(s).attachChild(l);return l.onCancelled(a),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:u},()=>{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 S().registerSkipController(new H(()=>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}bringToFront(e,t,n){let i=e.findElementByDisplayable(t),r=i&&Jn.getLayerElements(i,t);if(!r)throw new k(`Displayable not found when bringing it to front. The element may not be on stage yet. (element: ${t.getId()})`);let s=r.indexOf(t);s!==r.length-1&&(r.splice(s,1),r.push(t),e.flush()),e.actionHistory.push({action:this,stackModel:n.stackModel},c=>{let l=e.findElementByDisplayable(t),u=l&&Jn.getLayerElements(l,t);if(!u)return;let d=u.indexOf(t);d!==c&&(u.splice(d,1),u.splice(c,0,t),e.flush())},[s]);let a=new S;return a.resolve(super.executeAction(e,n)),a}static getLayerElements(e,t){for(let n of e.layers.values())if(n.includes(t))return n;return null}stringify(e,t,n){return super.stringifyWithName("DisplayableAction")}};Jn.ActionTypes=ye;var Ie=Jn;var ct=class o extends ce{constructor(){super(...arguments);this.srcManager=new Le}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}))}effect(t,n){return this.registerEffectSrc(t),this.transform(new Z(t,n))}mask(t,n={}){let i=w.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,u={duration:a,ease:c,...l},d=o.createClipPathTransform([[o.circleClipPath(i,n),{duration:0}],[o.circleClipPath(r,n),u]]);return s?this.combineActions(new je,p=>p.transform(d).clearClip({duration:0})):this.transform(d)}circleClose(t={}){let{center:n="50% 50%",from:i=150,to:r=0,clearClip:s=!1,duration:a=600,ease:c="easeInOut",...l}=t,u={duration:a,ease:c,...l},d=o.createClipPathTransform([[o.circleClipPath(i,n),{duration:0}],[o.circleClipPath(r,n),u]]);return s?this.combineActions(new je,p=>p.transform(d).clearClip({duration:0})):this.transform(d)}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},u=o.wipeClipPath(n,100),d=o.wipeClipPath(n,0),p=o.createClipPathTransform([[i?d:u,{duration:0}],[i?u:d,l]]);return r?this.combineActions(new je,h=>h.transform(p).clearClip({duration:0})):this.transform(p)}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 Ie(n,ye.applyTransform,new x().setContent([t.copy()]));return n.chain(i)}bringToFront(){let t=this.chain(),n=new Ie(t,ye.bringToFront,new x().setContent([]));return t.chain(n)}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 Z(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 Z?t.copy():new Z({opacity:1},t),r=new Ie(n,ye.applyTransform,new x().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 Ie(n,ye.applyTransform,new x().setContent([i]));return n.chain(r)}};var ht=(t=>(t[t.Number=0]="Number",t[t.HexColor=1]="HexColor",t))(ht||{});import{animate as rl}from"motion/react";var Ft=class{requestAnimations(e){let t=e.map(m=>m.start),n=[],i=0,r=!1,s=!1,a=!1,c=[],l=[],u=[],d=()=>{e.forEach((m,y)=>{t[y]=m.end}),i=e.length,c.forEach(m=>m(t)),l.forEach(m=>m())};return{onUpdate:m=>(c.push(m),{cancel:()=>{let y=c.indexOf(m);y!==-1&&c.splice(y,1)}}),onComplete:m=>(l.push(m),{cancel:()=>{let y=l.indexOf(m);y!==-1&&l.splice(y,1)}}),onCanceled:m=>(u.push(m),{cancel:()=>{let y=u.indexOf(m);y!==-1&&u.splice(y,1)}}),complete:()=>{if(!(i===e.length||s)){if(!r){a=!0;return}n.forEach(m=>m.complete())}},start:()=>{if(!(r||s||i===e.length)){if(r=!0,a){d();return}e.forEach((m,y)=>{n.push(this.requestMotion(m,{onComplete:()=>{t[y]=m.end,c.forEach(b=>b(t)),i++,i===e.length&&l.forEach(b=>b())},onUpdate:b=>{t[y]=b,c.forEach(v=>v(t))}}))})}},cancel:()=>{s=!0,n.forEach(m=>m.cancel()),u.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 rl(e.start,e.end,{duration:e.duration/1e3,onUpdate:n=>{t.onUpdate&&t.onUpdate(n)},onComplete:()=>{t.onComplete&&t.onComplete()},ease:e.ease})}};Ft.AnimationType=ht;var Zn=class extends Ft{_setElement(e){return this._element=e,this}getTextState(){if(this._element===void 0)throw new k(`Trying to access text state, but element is not set
20
- This should not happen, please report this issue to the developers`);return this._element.state}};var qi=class o extends Zn{constructor(e){super(),this.fontSize=e.fontSize,this.duration=e.duration,this.easing=e.easing}createTask(){return{animations:[{type:0,start:this.getTextState().fontSize,end:this.fontSize,duration:this.duration,ease:this.easing}],resolve:[this.asTarget(e=>({style:{fontSize:`${e}px`}}))]}}copy(){return new o({fontSize:this.fontSize,duration:this.duration,easing:this.easing})}};var we=class we extends ct{static get DefaultUserConfig(){return we._defaultUserConfig??(we._defaultUserConfig=new B({alignX:"center",alignY:"center",className:"",fontSize:16,fontColor:"#000000",text:"",...J.DefaultTransformState.getDefaultConfig()},{position:e=>N.tryParsePosition(e)}))}static get DefaultTextTransformState(){return we._defaultTextTransformState??(we._defaultTextTransformState=new B({fontColor:"#000000",...J.DefaultTransformState.getDefaultConfig()}))}constructor(e,t={}){super();let n=typeof e=="string"?{...t,text:e}:e,i=we.DefaultUserConfig.create(n),r=we.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 on(t,on.ActionTypes.setText,new x().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 je,i=>{if(t){let s=new qi({fontSize:e,duration:t,easing:n});i.chain(this._applyTransition(i,s))}let r=new on(i,on.ActionTypes.setFontSize,new x().setContent([e]));return i.chain(r)})}useLayer(e){return this.userConfig.get().layer=e,Object.assign(this.config,{layer:e}),this}toData(){return{state:we.StateSerializer.serialize(this.state),transformState:this.transformState.serialize()}}fromData(e){return this.state=we.StateSerializer.deserialize(e.state),this.transformState=J.deserialize(e.transformState),this}_init(e){return new Ie(this.chain(),ye.init,new x().setContent([e||null,this.config.layer||null]))}reset(){super.reset(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(this.userConfig)}getInitialTransformState(e){let[t]=e.extract(we.DefaultTextTransformState.keys());return new J(we.DefaultTextTransformState.create(t.get()).get())}_applyTransition(e,t){return new Ie(e,ye.applyTransition,new x().setContent([t,n=>n._setElement(this)]))}getInitialState(){return we.DefaultTextState.create({fontSize:this.userConfig.get().fontSize,text:this.userConfig.get().text}).get()}};we._defaultUserConfig=null,we.DefaultTextConfig=new B({alignX:"center",alignY:"center",className:"",layer:void 0}),we.DefaultTextState=new B({fontSize:16,display:!1,text:""}),we._defaultTextTransformState=null,we.StateSerializer=new Qe;var gn=we;var _n=class extends ${executeAction(e,t){if(this.type===_e.setMotion){let[n]=this.contentNode.getContent();return this.patchState(e,t,{motion:n})}else if(this.type===_e.setExpression){let[n]=this.contentNode.getContent();return this.patchState(e,t,{expression:n})}else if(this.type===_e.setSkin){let[n]=this.contentNode.getContent();return this.patchState(e,t,{skin:n})}else if(this.type===_e.setParam){let[n,i]=this.contentNode.getContent();return this.patchState(e,t,{params:{[n]:i}})}else if(this.type===_e.setSlot){let[n,i]=this.contentNode.getContent();return this.patchState(e,t,{slots:{[n]:i}})}else if(this.type===_e.command){let[n,i,r]=this.contentNode.getContent();return this.runCommand(e,t,n,i,r?.await===!0)}throw super.unknownTypeError()}patchState(e,t,n){let i=this.callee,r=i._patchState(n);return this.pushState(e,i),e.actionHistory.push({action:this,stackModel:t.stackModel},s=>{i.state=s,this.pushState(e,i)},[r]),super.executeAction(e,t)}pushState(e,t){t._applyState().catch(n=>{e.logger.error("Puppet",`Backend "${t.config.backend}" threw while applying state`,n)})}runCommand(e,t,n,i,r){let s=this.callee,a=()=>s._runCommand(n,i).then(u=>{u||e.logger.weakWarn("Puppet",`Command "${n}" was dropped: the puppet is not on stage. Show the element before commanding it.`)}).catch(u=>{e.logger.error("Puppet",`Backend "${s.config.backend}" threw while running "${n}"`,u)});if(!r)return a(),super.executeAction(e,t);let c=new S().registerSkipController(new H(()=>(e.logger.info("Puppet Command","Skipped"),super.executeAction(e,t))));a().then(()=>{c.isSettled()||c.resolve(super.executeAction(e,t))});let l=e.timelines.attachTimeline(c);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:l},()=>{c.isSettled()||c.abort()}),c}stringify(e,t,n){return super.stringifyWithName("PuppetAction")}};_n.ActionTypes=_e;var Ge=class Ge extends ct{constructor(t){super();this.events=new q;this.instance=null;this.status="unmounted";let n=Ge.DefaultUserConfig.create(t),i=Ge.DefaultPuppetConfig.create(n.get());if(this.userConfig=n,this.config=i.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(n),!this.config.backend)throw new ie("Puppet must have a backend name");if(!this.config.src)throw new ie("Puppet must have a src")}static get DefaultUserConfig(){return Ge._defaultUserConfig??(Ge._defaultUserConfig=new B({backend:"",src:"",options:{},size:null,className:"",layer:void 0,motion:null,expression:null,skin:null,params:{},slots:{},...J.DefaultTransformState.getDefaultConfig()},{position:t=>N.tryParsePosition(t)}))}static normalizeState(t){let n=t&&typeof t=="object"&&!Array.isArray(t)?t:{};return{...n,motion:typeof n.motion=="string"?n.motion:null,expression:typeof n.expression=="string"?n.expression:null,skin:typeof n.skin=="string"?n.skin:null,params:Ge.copyParams(n.params),slots:Ge.copySlots(n.slots)}}static mergeState(t,n){return Ge.normalizeState({...t,...n,params:{...t.params,...n.params||{}},slots:{...t.slots,...n.slots||{}}})}static copyParams(t){let n={};if(!t||typeof t!="object")return n;for(let[i,r]of Object.entries(t))typeof r=="number"&&Number.isFinite(r)&&(n[i]=r);return n}static copySlots(t){let n={};if(!t||typeof t!="object")return n;for(let[i,r]of Object.entries(t))(typeof r=="string"||r===null)&&(n[i]=r);return n}setMotion(t){return this.chain(this.createAction(_e.setMotion,[t]))}setExpression(t){return this.chain(this.createAction(_e.setExpression,[t]))}setSkin(t){return this.chain(this.createAction(_e.setSkin,[t]))}setParam(t,n){return this.chain(this.createAction(_e.setParam,[t,n]))}setSlot(t,n){return this.chain(this.createAction(_e.setSlot,[t,n]))}command(t,n,i){return this.chain(this.createAction(_e.command,[t,n,i]))}getStatus(){return this.status}onStatusChange(t){return this.events.on("event:puppet.statusChange",t)}useLayer(t){return this.userConfig.get().layer=t,Object.assign(this.config,{layer:t}),this}toData(){return{state:Ge.normalizeState(this.state),transformState:this.transformState.serialize()}}fromData(t){return this.state=Ge.normalizeState(t.state),this.transformState=J.deserialize(t.transformState),this}_init(t){return new Ie(this.chain(),ye.init,new x().setContent([t||null,this.config.layer||null]))}reset(){super.reset(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(this.userConfig)}_resolveSize(t){let n=this.config.size;return n?{width:n.width,height:n.height}:{width:t.width,height:t.height}}_getStatus(){return this.getStatus()}_setStatus(t){this.status!==t&&(this.status=t,this.events.emit("event:puppet.statusChange",t))}_onStatusChange(t){return this.onStatusChange(t)}_attachInstance(t){this.instance=t}_getInstance(){return this.instance}_patchState(t){let n=Ge.normalizeState(this.state);return this.state=Ge.mergeState(this.state,t),n}async _applyState(){let t=this.instance;t&&await t.apply(Ge.normalizeState(this.state))}async _runCommand(t,n){let i=this.instance;return i?(await i.command(t,n),!0):!1}async _describe(){let t=this.instance;return!t||typeof t.describe!="function"?null:await t.describe()}createAction(t,n){return new _n(this.chain(),t,x.create(n))}getInitialTransformState(t){let[n]=t.extract(J.DefaultTransformState.keys());return new J(J.DefaultTransformState.create(n.get()).get())}getInitialState(){let t=this.userConfig.get();return Ge.normalizeState({motion:t.motion,expression:t.expression,skin:t.skin,params:t.params,slots:t.slots})}};Ge._defaultUserConfig=null,Ge.DefaultPuppetConfig=new B({backend:"",src:"",options:{},size:null,className:"",layer:void 0});var kt=Ge;var ei=class ei extends ${executeAction(e,t){let n=this;if(n.is(ei,"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(ei,"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")}};ei.ActionTypes=Kn;var Yi=ei;var lt=class lt{static isSentence(e){return e instanceof lt}static toSentence(e){return lt.isSentence(e)?e:new lt(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 _.isWord(e)?e:new _(e)}static formatStaticWord(e,t){return Array.isArray(e)?e.map(n=>this.formatStaticWord(n,t)).flat(2):[_.isWord(e)?e:new _(e,t)]}static isSentencePrompt(e){return Array.isArray(e)?e.every(lt.isSingleWord):lt.isSingleWord(e)}static isSingleWord(e){return typeof e=="string"||_.isWord(e)||$e.isPause(e)||at.isTextEvent(e)||typeof e=="function"}getMetadata(){return this.config.metadata}constructor(e,t={}){this.text=lt.format(e),this.config=z(lt.defaultConfig,{...t,voice:typeof t.voice=="string"?ve.voice(t.voice):ve.toSound(t.voice)}),this.state=Fs(lt.defaultState)}toData(){return null}fromData(e){return this.state=z(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(...lt.formatStaticWord(i))}return t}copy(){return new lt([...this.text],this.config)}};lt.defaultConfig={pause:!0,voice:null,character:null,voiceId:null},lt.defaultState={};var de=lt;var rn=class rn extends ce{constructor(e,t={}){super(),this.config=z(rn.defaultConfig,t),this.authoredName=e||"",this.state=this.getInitialState();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=>de.isSingleWord(c))){let c=e,l=de.format([t,...n]),u=new de(Os(c,l),{character:this}),d=new nt(this.chain(),nt.ActionTypes.say,new x().setContent(u));return this.chain(d)}let i=t||{},r=e,s=Array.isArray(r)?new de(r,{...i,character:this}):(de.isSentence(r)?r:new de(r,{...i,character:this})).copy();s.setCharacter(this);let a=new nt(this.chain(),nt.ActionTypes.say,new x().setContent(s));return this.chain(a)}setName(e){let t=new nt(this.chain(),nt.ActionTypes.setName,new x().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&&de.isSingleWord(t)?this.say(e,t,...n):this.say(e):typeof e=="string"?this.say(e,t):de.isSentence(e)?this.say(e):this.say(e,t)}toData(){return{state:rn.StateSerializer.serialize(this.state)}}fromData(e){return this.state=rn.StateSerializer.deserialize(e.state),this}reset(){return super.reset(),this.state=this.getInitialState(),this}getInitialState(){return{name:this.authoredName}}};rn.defaultCharacterColor="#000",rn.defaultConfig={portraits:[]},rn.StateSerializer=new Qe;var Qi=rn,Yt=new Qi(null);var j=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()})`}},cr=class o extends ce{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 He(`ELSE condition already set
20
+ This should not happen, please report this issue to the developers`);return this._element.state}};var qi=class o extends Zn{constructor(e){super(),this.fontSize=e.fontSize,this.duration=e.duration,this.easing=e.easing}createTask(){return{animations:[{type:0,start:this.getTextState().fontSize,end:this.fontSize,duration:this.duration,ease:this.easing}],resolve:[this.asTarget(e=>({style:{fontSize:`${e}px`}}))]}}copy(){return new o({fontSize:this.fontSize,duration:this.duration,easing:this.easing})}};var we=class we extends ct{static get DefaultUserConfig(){return we._defaultUserConfig??(we._defaultUserConfig=new B({alignX:"center",alignY:"center",className:"",fontSize:16,fontColor:"#000000",text:"",...J.DefaultTransformState.getDefaultConfig()},{position:e=>N.tryParsePosition(e)}))}static get DefaultTextTransformState(){return we._defaultTextTransformState??(we._defaultTextTransformState=new B({fontColor:"#000000",...J.DefaultTransformState.getDefaultConfig()}))}constructor(e,t={}){super();let n=typeof e=="string"?{...t,text:e}:e,i=we.DefaultUserConfig.create(n),r=we.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 on(t,on.ActionTypes.setText,new x().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 je,i=>{if(t){let s=new qi({fontSize:e,duration:t,easing:n});i.chain(this._applyTransition(i,s))}let r=new on(i,on.ActionTypes.setFontSize,new x().setContent([e]));return i.chain(r)})}useLayer(e){return this.userConfig.get().layer=e,Object.assign(this.config,{layer:e}),this}toData(){return{state:we.StateSerializer.serialize(this.state),transformState:this.transformState.serialize()}}fromData(e){return this.state=we.StateSerializer.deserialize(e.state),this.transformState.resetTo(J.deserialize(e.transformState).get()),this}_init(e){return new Ie(this.chain(),ye.init,new x().setContent([e||null,this.config.layer||null]))}reset(){super.reset(),this.state=this.getInitialState(),this.transformState.resetTo(this.getInitialTransformState(this.userConfig).get())}getInitialTransformState(e){let[t]=e.extract(we.DefaultTextTransformState.keys());return new J(we.DefaultTextTransformState.create(t.get()).get())}_applyTransition(e,t){return new Ie(e,ye.applyTransition,new x().setContent([t,n=>n._setElement(this)]))}getInitialState(){return we.DefaultTextState.create({fontSize:this.userConfig.get().fontSize,text:this.userConfig.get().text}).get()}};we._defaultUserConfig=null,we.DefaultTextConfig=new B({alignX:"center",alignY:"center",className:"",layer:void 0}),we.DefaultTextState=new B({fontSize:16,display:!1,text:""}),we._defaultTextTransformState=null,we.StateSerializer=new Qe;var gn=we;var _n=class extends ${executeAction(e,t){if(this.type===_e.setMotion){let[n]=this.contentNode.getContent();return this.patchState(e,t,{motion:n})}else if(this.type===_e.setExpression){let[n]=this.contentNode.getContent();return this.patchState(e,t,{expression:n})}else if(this.type===_e.setSkin){let[n]=this.contentNode.getContent();return this.patchState(e,t,{skin:n})}else if(this.type===_e.setParam){let[n,i]=this.contentNode.getContent();return this.patchState(e,t,{params:{[n]:i}})}else if(this.type===_e.setSlot){let[n,i]=this.contentNode.getContent();return this.patchState(e,t,{slots:{[n]:i}})}else if(this.type===_e.command){let[n,i,r]=this.contentNode.getContent();return this.runCommand(e,t,n,i,r?.await===!0)}throw super.unknownTypeError()}patchState(e,t,n){let i=this.callee,r=i._patchState(n);return this.pushState(e,i),e.actionHistory.push({action:this,stackModel:t.stackModel},s=>{i.state=s,this.pushState(e,i)},[r]),super.executeAction(e,t)}pushState(e,t){t._applyState().catch(n=>{e.logger.error("Puppet",`Backend "${t.config.backend}" threw while applying state`,n)})}runCommand(e,t,n,i,r){let s=this.callee,a=()=>s._runCommand(n,i).then(u=>{u||e.logger.weakWarn("Puppet",`Command "${n}" was dropped: the puppet is not on stage. Show the element before commanding it.`)}).catch(u=>{e.logger.error("Puppet",`Backend "${s.config.backend}" threw while running "${n}"`,u)});if(!r)return a(),super.executeAction(e,t);let c=new S().registerSkipController(new H(()=>(e.logger.info("Puppet Command","Skipped"),super.executeAction(e,t))));a().then(()=>{c.isSettled()||c.resolve(super.executeAction(e,t))});let l=e.timelines.attachTimeline(c);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:l},()=>{c.isSettled()||c.abort()}),c}stringify(e,t,n){return super.stringifyWithName("PuppetAction")}};_n.ActionTypes=_e;var Ge=class Ge extends ct{constructor(t){super();this.events=new q;this.instance=null;this.status="unmounted";let n=Ge.DefaultUserConfig.create(t),i=Ge.DefaultPuppetConfig.create(n.get());if(this.userConfig=n,this.config=i.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(n),!this.config.backend)throw new ie("Puppet must have a backend name");if(!this.config.src)throw new ie("Puppet must have a src")}static get DefaultUserConfig(){return Ge._defaultUserConfig??(Ge._defaultUserConfig=new B({backend:"",src:"",options:{},size:null,className:"",layer:void 0,motion:null,expression:null,skin:null,params:{},slots:{},...J.DefaultTransformState.getDefaultConfig()},{position:t=>N.tryParsePosition(t)}))}static normalizeState(t){let n=t&&typeof t=="object"&&!Array.isArray(t)?t:{};return{...n,motion:typeof n.motion=="string"?n.motion:null,expression:typeof n.expression=="string"?n.expression:null,skin:typeof n.skin=="string"?n.skin:null,params:Ge.copyParams(n.params),slots:Ge.copySlots(n.slots)}}static mergeState(t,n){return Ge.normalizeState({...t,...n,params:{...t.params,...n.params||{}},slots:{...t.slots,...n.slots||{}}})}static copyParams(t){let n={};if(!t||typeof t!="object")return n;for(let[i,r]of Object.entries(t))typeof r=="number"&&Number.isFinite(r)&&(n[i]=r);return n}static copySlots(t){let n={};if(!t||typeof t!="object")return n;for(let[i,r]of Object.entries(t))(typeof r=="string"||r===null)&&(n[i]=r);return n}setMotion(t){return this.chain(this.createAction(_e.setMotion,[t]))}setExpression(t){return this.chain(this.createAction(_e.setExpression,[t]))}setSkin(t){return this.chain(this.createAction(_e.setSkin,[t]))}setParam(t,n){return this.chain(this.createAction(_e.setParam,[t,n]))}setSlot(t,n){return this.chain(this.createAction(_e.setSlot,[t,n]))}command(t,n,i){return this.chain(this.createAction(_e.command,[t,n,i]))}getStatus(){return this.status}onStatusChange(t){return this.events.on("event:puppet.statusChange",t)}useLayer(t){return this.userConfig.get().layer=t,Object.assign(this.config,{layer:t}),this}toData(){return{state:Ge.normalizeState(this.state),transformState:this.transformState.serialize()}}fromData(t){return this.state=Ge.normalizeState(t.state),this.transformState.resetTo(J.deserialize(t.transformState).get()),this}_init(t){return new Ie(this.chain(),ye.init,new x().setContent([t||null,this.config.layer||null]))}reset(){super.reset(),this.state=this.getInitialState(),this.transformState.resetTo(this.getInitialTransformState(this.userConfig).get())}_resolveSize(t){let n=this.config.size;return n?{width:n.width,height:n.height}:{width:t.width,height:t.height}}_getStatus(){return this.getStatus()}_setStatus(t){this.status!==t&&(this.status=t,this.events.emit("event:puppet.statusChange",t))}_onStatusChange(t){return this.onStatusChange(t)}_attachInstance(t){this.instance=t}_getInstance(){return this.instance}_patchState(t){let n=Ge.normalizeState(this.state);return this.state=Ge.mergeState(this.state,t),n}async _applyState(){let t=this.instance;t&&await t.apply(Ge.normalizeState(this.state))}async _runCommand(t,n){let i=this.instance;return i?(await i.command(t,n),!0):!1}async _describe(){let t=this.instance;return!t||typeof t.describe!="function"?null:await t.describe()}createAction(t,n){return new _n(this.chain(),t,x.create(n))}getInitialTransformState(t){let[n]=t.extract(J.DefaultTransformState.keys());return new J(J.DefaultTransformState.create(n.get()).get())}getInitialState(){let t=this.userConfig.get();return Ge.normalizeState({motion:t.motion,expression:t.expression,skin:t.skin,params:t.params,slots:t.slots})}};Ge._defaultUserConfig=null,Ge.DefaultPuppetConfig=new B({backend:"",src:"",options:{},size:null,className:"",layer:void 0});var kt=Ge;var ei=class ei extends ${executeAction(e,t){let n=this;if(n.is(ei,"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(ei,"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")}};ei.ActionTypes=Kn;var Yi=ei;var lt=class lt{static isSentence(e){return e instanceof lt}static toSentence(e){return lt.isSentence(e)?e:new lt(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 _.isWord(e)?e:new _(e)}static formatStaticWord(e,t){return Array.isArray(e)?e.map(n=>this.formatStaticWord(n,t)).flat(2):[_.isWord(e)?e:new _(e,t)]}static isSentencePrompt(e){return Array.isArray(e)?e.every(lt.isSingleWord):lt.isSingleWord(e)}static isSingleWord(e){return typeof e=="string"||_.isWord(e)||$e.isPause(e)||at.isTextEvent(e)||typeof e=="function"}getMetadata(){return this.config.metadata}constructor(e,t={}){this.text=lt.format(e),this.config=z(lt.defaultConfig,{...t,voice:typeof t.voice=="string"?ve.voice(t.voice):ve.toSound(t.voice)}),this.state=Fs(lt.defaultState)}toData(){return null}fromData(e){return this.state=z(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(...lt.formatStaticWord(i))}return t}copy(){return new lt([...this.text],this.config)}};lt.defaultConfig={pause:!0,voice:null,character:null,voiceId:null},lt.defaultState={};var de=lt;var rn=class rn extends ce{constructor(e,t={}){super(),this.config=z(rn.defaultConfig,t),this.authoredName=e||"",this.state=this.getInitialState();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=>de.isSingleWord(c))){let c=e,l=de.format([t,...n]),u=new de(Os(c,l),{character:this}),d=new nt(this.chain(),nt.ActionTypes.say,new x().setContent(u));return this.chain(d)}let i=t||{},r=e,s=Array.isArray(r)?new de(r,{...i,character:this}):(de.isSentence(r)?r:new de(r,{...i,character:this})).copy();s.setCharacter(this);let a=new nt(this.chain(),nt.ActionTypes.say,new x().setContent(s));return this.chain(a)}setName(e){let t=new nt(this.chain(),nt.ActionTypes.setName,new x().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&&de.isSingleWord(t)?this.say(e,t,...n):this.say(e):typeof e=="string"?this.say(e,t):de.isSentence(e)?this.say(e):this.say(e,t)}toData(){return{state:rn.StateSerializer.serialize(this.state)}}fromData(e){return this.state=rn.StateSerializer.deserialize(e.state),this}reset(){return super.reset(),this.state=this.getInitialState(),this}getInitialState(){return{name:this.authoredName}}};rn.defaultCharacterColor="#000",rn.defaultConfig={portraits:[]},rn.StateSerializer=new Qe;var Qi=rn,Yt=new Qi(null);var j=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()})`}},cr=class o extends ce{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 He(`ELSE condition already set
21
21
  You are trying to set an ELSE-IF condition after an ELSE condition`);return this.conditions.ElseIf.push({condition:j.from(t),action:this.construct(Array.isArray(n)?n:[n])}),this.chain()}Else(t){if(this.conditions.Else.action)throw new He(`ELSE condition already set
22
- 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(Nt,[this,Nt.ActionTypes.action,new x().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 ze.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=j.from(t),this.conditions.If.action=this.construct(n);let i=this.chain(),r=new Nt(i,Nt.ActionTypes.action,new x().setContent(this.conditions));return i.chain(r)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?Yt.say(n).getActions():ze.toActions([n]))}};var Xi=class Xi extends ce{constructor(e,t){super(),this.namespace=this.prefix(e),this.defaultContent=t}init(e){e.hasNamespace(this.namespace)||e.addNamespace(new Gt(this.namespace,this.defaultContent))}getNamespace(e){return e.getNamespace(this.namespace)}set(e,t){return this.chain(this.createAction(Kn.set,[e,t]))}assign(e){return this.chain(this.createAction(Kn.assign,[e]))}equals(e,t){return new j(n=>{let i=n.storable.getNamespace(this.namespace),r=j.isLambda(t)||j.isLambdaHandler(t)?j.from(t).evaluate(n).value:t;return i.equals(e,r)})}notEquals(e,t){return new j(n=>{let i=n.storable.getNamespace(this.namespace),r=j.isLambda(t)||j.isLambdaHandler(t)?j.from(t).evaluate(n).value:t;return!i.equals(e,r)})}isTrue(e){return new j(({storable:t})=>t.getNamespace(this.namespace).equals(e,!0))}isFalse(e){return new j(({storable:t})=>t.getNamespace(this.namespace).equals(e,!1))}isNotNull(e){return new j(({storable:t})=>{let n=t.getNamespace(this.namespace).get(e);return n!=null})}toWord(e){return new _(({storable:t})=>[String(t.getNamespace(this.namespace).get(e))])}get(e){return this.toWord(e)}conditional(e,t,n){return new _(i=>j.from(e).evaluate(i).value?t:n)}evaluate(e,t){return new j(({storable:n})=>t(n.getNamespace(this.namespace).get(e)))}getNamespaceName(){return this.namespace}prefix(e,t=Xi.NamespacePrefix){return t+":"+String(e)}createAction(e,t){return new Yi(this.chain(),e,x.create(t))}};Xi.NamespacePrefix="persistent";var Rn=Xi,Ji=class Ji extends Rn{constructor(e){super(e,{}),this.namespace=this.prefix(e,Ji.LocalNamespacePrefix)}init(e){e.removeNamespace(this.namespace).addNamespace(new Gt(this.namespace,this.defaultContent))}};Ji.LocalNamespacePrefix="local";var In=Ji;var Mn=class extends ${executeAction(e,t){if(this.type===mn.action)return super.executeAction(e,t);if(this.type===mn.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")}};Mn.ActionTypes=mn;var it=class it extends ct{static get DefaultUserConfig(){return it._defaultUserConfig??(it._defaultUserConfig=new B({zIndex:0,...J.DefaultTransformState.getDefaultConfig(),opacity:1}))}constructor(e,t={}){super();let n=it.DefaultUserConfig.create(t),i=it.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 Mn(this.chain(),mn.setZIndex,new x().setContent([e])))}bringToFront(){throw new k(`A layer cannot be brought to front. Layers are ordered by z-index, not by the order they were added in \u2014 use Layer.setZIndex to raise one. (layer: ${this.config.name})`)}reset(){return super.reset(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(),this}toData(){return{state:it.StateSerializer.serialize(this.state),transformState:this.transformState.serialize()}}fromData(e){return this.state=it.StateSerializer.deserialize(e.state),this.transformState=J.deserialize(e.transformState),this}copy(){return new it(this.config.name,this.userConfig.get())}setName(e){return this.config.name=e,this}_init(e){return[new Mn(this.chain(),mn.action,new x),new Ie(this.chain(),ye.init,new x().setContent([e,null,!1]))]}getInitialState(){return it.DefaultState.create({zIndex:this.config.zIndex}).get()}getInitialTransformState(){let[e]=this.userConfig.extract(J.DefaultTransformState.keys());return new J(J.DefaultTransformState.create(e.get()).get())}};it._defaultUserConfig=null,it.DefaultConfig=new B({name:"(anonymous)",zIndex:0}),it.StateSerializer=new Qe,it.DefaultState=new B({zIndex:0});var Nn=it;var ti=class extends ce{constructor(e){super(),this.scene=e}show(e){let t=new se(this.scene.chain(),X.nvlShow,new x().setContent([e]));return this.chain(t)}hide(e){let t=new se(this.scene.chain(),X.nvlHide,new x().setContent([e]));return this.chain(t)}end(){let e=new se(this.scene.chain(),X.nvlEnd,new x().setContent([]));return this.chain(e)}};var Fe=class Fe extends Ln{constructor(t,n){super();this.srcManager=new Le;this.events=new q;this.actions=[];this.voiceCache=new Map;this._futureActions_=[];this.labelMap=new Map;let i=Fe.DefaultSceneConfig.getDefaultConfig().defaultBackgroundLayer.copy().setName("[[Background Layer of "+t+"]]"),r=Fe.DefaultSceneConfig.getDefaultConfig().defaultDisplayableLayer.copy().setName("[[Displayable Layer of "+t+"]]"),s=Fe.DefaultUserConfig.create(n),a=Fe.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 In(t)}static get DefaultSceneConfig(){return Fe._defaultSceneConfig??(Fe._defaultSceneConfig=new B({name:"",backgroundMusicFade:0,voices:null,layers:[],defaultBackgroundLayer:new Nn("[[Background Layer]]",{zIndex:-1}),defaultDisplayableLayer:new Nn("[[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=>{ve.isSound(r)&&Fe.validateVoice(r)}),i(t))return t;throw new He(`Invalid voices config: ${t}`)}}))}static validateVoice(t){if(!zi(t.config.type,[tt.voice,tt.sound]))throw new He(`Voice must be a voice, but got ${t.config.type}.
22
+ 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(Nt,[this,Nt.ActionTypes.action,new x().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 ze.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=j.from(t),this.conditions.If.action=this.construct(n);let i=this.chain(),r=new Nt(i,Nt.ActionTypes.action,new x().setContent(this.conditions));return i.chain(r)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?Yt.say(n).getActions():ze.toActions([n]))}};var Xi=class Xi extends ce{constructor(e,t){super(),this.namespace=this.prefix(e),this.defaultContent=t}init(e){e.hasNamespace(this.namespace)||e.addNamespace(new Gt(this.namespace,this.defaultContent))}getNamespace(e){return e.getNamespace(this.namespace)}set(e,t){return this.chain(this.createAction(Kn.set,[e,t]))}assign(e){return this.chain(this.createAction(Kn.assign,[e]))}equals(e,t){return new j(n=>{let i=n.storable.getNamespace(this.namespace),r=j.isLambda(t)||j.isLambdaHandler(t)?j.from(t).evaluate(n).value:t;return i.equals(e,r)})}notEquals(e,t){return new j(n=>{let i=n.storable.getNamespace(this.namespace),r=j.isLambda(t)||j.isLambdaHandler(t)?j.from(t).evaluate(n).value:t;return!i.equals(e,r)})}isTrue(e){return new j(({storable:t})=>t.getNamespace(this.namespace).equals(e,!0))}isFalse(e){return new j(({storable:t})=>t.getNamespace(this.namespace).equals(e,!1))}isNotNull(e){return new j(({storable:t})=>{let n=t.getNamespace(this.namespace).get(e);return n!=null})}toWord(e){return new _(({storable:t})=>[String(t.getNamespace(this.namespace).get(e))])}get(e){return this.toWord(e)}conditional(e,t,n){return new _(i=>j.from(e).evaluate(i).value?t:n)}evaluate(e,t){return new j(({storable:n})=>t(n.getNamespace(this.namespace).get(e)))}getNamespaceName(){return this.namespace}prefix(e,t=Xi.NamespacePrefix){return t+":"+String(e)}createAction(e,t){return new Yi(this.chain(),e,x.create(t))}};Xi.NamespacePrefix="persistent";var Rn=Xi,Ji=class Ji extends Rn{constructor(e){super(e,{}),this.namespace=this.prefix(e,Ji.LocalNamespacePrefix)}init(e){e.removeNamespace(this.namespace).addNamespace(new Gt(this.namespace,this.defaultContent))}};Ji.LocalNamespacePrefix="local";var In=Ji;var Mn=class extends ${executeAction(e,t){if(this.type===mn.action)return super.executeAction(e,t);if(this.type===mn.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")}};Mn.ActionTypes=mn;var it=class it extends ct{static get DefaultUserConfig(){return it._defaultUserConfig??(it._defaultUserConfig=new B({zIndex:0,...J.DefaultTransformState.getDefaultConfig(),opacity:1}))}constructor(e,t={}){super();let n=it.DefaultUserConfig.create(t),i=it.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 Mn(this.chain(),mn.setZIndex,new x().setContent([e])))}bringToFront(){throw new k(`A layer cannot be brought to front. Layers are ordered by z-index, not by the order they were added in \u2014 use Layer.setZIndex to raise one. (layer: ${this.config.name})`)}reset(){return super.reset(),this.state=this.getInitialState(),this.transformState.resetTo(this.getInitialTransformState().get()),this}toData(){return{state:it.StateSerializer.serialize(this.state),transformState:this.transformState.serialize()}}fromData(e){return this.state=it.StateSerializer.deserialize(e.state),this.transformState.resetTo(J.deserialize(e.transformState).get()),this}copy(){return new it(this.config.name,this.userConfig.get())}setName(e){return this.config.name=e,this}_init(e){return[new Mn(this.chain(),mn.action,new x),new Ie(this.chain(),ye.init,new x().setContent([e,null,!1]))]}getInitialState(){return it.DefaultState.create({zIndex:this.config.zIndex}).get()}getInitialTransformState(){let[e]=this.userConfig.extract(J.DefaultTransformState.keys());return new J(J.DefaultTransformState.create(e.get()).get())}};it._defaultUserConfig=null,it.DefaultConfig=new B({name:"(anonymous)",zIndex:0}),it.StateSerializer=new Qe,it.DefaultState=new B({zIndex:0});var Nn=it;var ti=class extends ce{constructor(e){super(),this.scene=e}show(e){let t=new se(this.scene.chain(),X.nvlShow,new x().setContent([e]));return this.chain(t)}hide(e){let t=new se(this.scene.chain(),X.nvlHide,new x().setContent([e]));return this.chain(t)}end(){let e=new se(this.scene.chain(),X.nvlEnd,new x().setContent([]));return this.chain(e)}};var Fe=class Fe extends Ln{constructor(t,n){super();this.srcManager=new Le;this.events=new q;this.actions=[];this.voiceCache=new Map;this._futureActions_=[];this.labelMap=new Map;let i=Fe.DefaultSceneConfig.getDefaultConfig().defaultBackgroundLayer.copy().setName("[[Background Layer of "+t+"]]"),r=Fe.DefaultSceneConfig.getDefaultConfig().defaultDisplayableLayer.copy().setName("[[Displayable Layer of "+t+"]]"),s=Fe.DefaultUserConfig.create(n),a=Fe.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 In(t)}static get DefaultSceneConfig(){return Fe._defaultSceneConfig??(Fe._defaultSceneConfig=new B({name:"",backgroundMusicFade:0,voices:null,layers:[],defaultBackgroundLayer:new Nn("[[Background Layer]]",{zIndex:-1}),defaultDisplayableLayer:new Nn("[[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=>{ve.isSound(r)&&Fe.validateVoice(r)}),i(t))return t;throw new He(`Invalid voices config: ${t}`)}}))}static validateVoice(t){if(!zi(t.config.type,[tt.voice,tt.sound]))throw new He(`Voice must be a voice, but got ${t.config.type}.
23
23
  To prevent unintended behavior and unexpected results, the sound have to be on the voice bus (or any bus beneath it). Please use \`Sound.voice()\` to create the sound.`)}static isScene(t){return t instanceof Fe}static getScene(t,n){return typeof n=="string"?t.getScene(n):n}static getStateSerializer(t){return new Qe({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(je.do([this.background.char(t,n)]))}jumpTo(t,n={}){return this.combineActions(new je({allowFutureScene:!1}),i=>{let s=z({},n instanceof Ft?{transition:n}:n);return i.chain(new se(i,"scene:preUnmount",new x().setContent([]))).chain(this._initScene(t))._transitionToScene(s.transition,t).chain(this._exit()),i})._jumpTo(t)}setBackgroundMusic(t,n){return this.chain(new se(this.chain(),X.setBackgroundMusic,new x().setContent([t,n])))}nvl(t,n){let i,r;n!==void 0?(i=t,r=n):(i=void 0,r=t);let s=new ti(this),a=typeof r=="function"?r(s):r,c=this.narrativeToActions(a),l={showTransition:i,hideTransition:i},u=new se(this.chain(),X.nvlEnd,new x().setContent([l])),d=[...c,u];super.constructNodes(d);let p=new se(this.chain(),X.nvlBlock,new x().setContent([d,l]));return this.chain(p)}action(t){return this.actions=t,this}preloadImage(t){if(!w.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:Fe.getStateSerializer(this).serialize(this.state)}}fromData(t){return this.state=Fe.getStateSerializer(this).deserialize(t.state),this}constructSceneRoot(t){this.sceneRoot=new se(this.chain(),"scene:action",new x);let n=this.actions,r=this.narrativeToActions(typeof n=="function"?n(this):n).map(m=>ze.isChained(m)?m.fromChained(m):m).flat(2),s=[],a=[],c=[];this.getAllChildrenElements(t,r,{allowFutureScene:!1}).forEach(m=>{ze.isChained(m)||(m instanceof I?s.push(m):m instanceof gn?a.push(m):m instanceof kt&&c.push(m))});let l=[],u=[],d=new Map;s.forEach(m=>{m.config.isWearable?u.push(m):m.config.autoInit&&l.push(m);for(let y of m.config.wearables){if(d.get(y)&&d.get(y)!==m)throw new Error(`Wearable image cannot be used multiple times
24
24
  Maybe you bind the same wearable image to multiple parent images
25
25
  Parent Conflict (src: `+d.get(y)?.state.currentSrc+`)
26
26
  Current Parent (src: `+m.state.currentSrc+")");d.set(y,m)}});let p=[...this._initScene(this),...l.map(m=>m._init(this)),...u.map(m=>{if(!d.has(m))throw new Error("Wearable image must have a parent image");return d.get(m)._initWearable(m)}),...a.map(m=>m._init()),...c.map(m=>m._init()),...r],h=super.constructNodes(p),f=new x(this.sceneRoot,void 0,h||void 0).setContent(this);return h?.setParent(f),this.sceneRoot?.setContentNode(f),this._futureActions_=p,this.constructLabels(t),this}constructLabels(t){let n=this.getAllChildren(t,this.sceneRoot||[],{allowFutureScene:!1}),i=new Map;for(let r of n)if(r instanceof oe&&r.type===ne.label){let[s]=r.contentNode.getContent();if(i.has(s))throw new He(`Duplicate label "${s}" in scene "${this.config.name}". Label names must be unique within a scene.`);i.set(s,r)}this.labelMap=i;for(let r of n)if(r instanceof oe&&r.type===ne.jump){let[s]=r.contentNode.getContent(),a=i.get(s);if(!a)throw new He(`Jump target label "${s}" not found in scene "${this.config.name}". Control.jump can only jump to a Control.label declared in the same scene.`);r.setJumpTarget(a)}}getLabel(t){return this.labelMap.get(t)||null}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?Yt.say(n).getActions():ze.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 se){let l=c.callee;if(w.isImageSrc(l.state.backgroundImage.state.currentSrc)&&this.srcManager.register({type:"image",src:w.srcToURL(l.state.backgroundImage.state.currentSrc)}),c.type===X.jumpTo){let u=c,d=Fe.getScene(t,u.contentNode.getContent()[0]);if(!d)throw c._sceneNotFoundError(c.getSceneName(u.contentNode.getContent()[0]));let p=Le.getPreloadableSrc(t,c);if(p&&this.srcManager.register(p),r.has(u)||n.has(d))continue;r.add(u),a.add(d),n.add(d)}}else if(c instanceof Se){let l=Le.getPreloadableSrc(t,c);l&&this.srcManager.register(l)}else if(c instanceof et)this.srcManager.register(c.callee);else if(c instanceof nt){let l=c.type===jt.say?c.contentNode.getContent():null;for(let u of la(c.callee,l))this.srcManager.register({type:"image",src:w.srcToURL(u)})}else if(c instanceof oe){let u=c.getFutureActions(t,{allowFutureScene:!0});s.push(...u)}else c instanceof Ie&&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 He(`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.resolveId(`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"?this.voiceOfSrc(r):(Fe.validateVoice(r),r)}let i=n[t];return typeof i=="string"?this.voiceOfSrc(i):i||null}return null}voiceOfSrc(t){let n=this.voiceCache.get(t);if(n)return n;let i=ve.voice(t);return this.voiceCache.set(t,i),i}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(){super.reset(),this.state.backgroundImage.reset(),this.state.backgroundMusic?.reset(),this.state=this.getInitialState()}getInitialState(){let t=this.userConfig.get();if(t.backgroundMusic&&!zi(t.backgroundMusic.config.type,[tt.bgm]))throw new He(`[Scene: ${this.config.name}] Background music must be a bgm, but got ${t.backgroundMusic.config.type}.
27
- To prevent unintended behavior and unexpected results, the sound have to be on the music bus (or any bus beneath it). Please use \`Sound.bgm()\` to create the sound.`);let n=this.state?.backgroundImage?this.state.backgroundImage.reset():new I({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 se(this.chain(),"scene:jumpTo",new x().setContent([t])))}_exit(){return new se(this.chain(),"scene:exit",new x().setContent([]))}_transitionToScene(t,n){let i=this.chain();return t?i.chain(new se(i,X.transitionToScene,new x().setContent([t,n]))):i}_init(t){return new se(this.chain(),"scene:init",new x().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)]}};Fe.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"},Fe.DefaultUserConfig=new B({backgroundMusic:null,backgroundMusicFade:0,voices:void 0,background:"#fff",layers:[]}),Fe._defaultSceneConfig=null;var gt=Fe;import*as Ta from"howler";var Zi=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 sl={volume:1,limit:1/0},al=class pa{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={...sl,...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 pa(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}}},da=!1;function cl(o){da=o}function sn(o,e){da||(e!==void 0?console.warn(o,e):console.warn(o))}var ll=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){sn("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){sn("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){sn("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()}},ua=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}},ul=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 ll(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){sn("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){sn("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 ua(this,e);return r.finish(),r}this.volume=o,this._isMuted||(this.gainNode.gain.value=o);let n=new ua(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}},pl=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}},dl=10*1024*1024,ml=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 pl(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}}},fl={volume:1,latencyHint:"interactive",sampleRate:44100,maxChannels:128,silent:!1},ma=class{constructor(o){this.registeredChannels=new Set,this.isReady=!1,this.readyPromise=null,this.destroyed=!1,this.unlockHandler=null,this.options={...fl,...o},cl(!!this.options.silent),this.audioContext=new AudioContext({latencyHint:this.options.latencyHint,sampleRate:this.options.sampleRate}),this.audioCache=new ml(this.audioContext),this.masterChannel=new al("__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=>{sn("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 d=new ul(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?.())};d.once("ended",h),d.once("stop",h)}return d}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<dl?"full":"stream"}catch(t){return sn("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=>{sn("Failed to close AudioContext during destroy().",o)}))}isDestroyed(){return this.destroyed}};var ue=class ue{constructor(e){this.gameState=e;this.state=new Map;this.channels=new Map;this.busTree=null;this.busSubscription=null;this.unknownBuses=new Set;this.globalVolume=1;this.ready=Promise.resolve();this.isReady=!1;this.isInitializing=!1}get mixer(){return this.gameState.game.audioBuses}initialize(){if(this.isReady||this.isInitializing)return;this.mixer.getTree();let e=new ma({maxChannels:ue.MaxChannels});this.sound=e,this.isInitializing=!0,this.ready=e.onceReady().then(()=>{e.setVolume(this.globalVolume),this.realizeBusTree(e),this.isReady=!0,this.isInitializing=!1}).catch(t=>{throw this.isInitializing=!1,this.gameState.logger.error("AudioManager","Failed to initialize audio subsystem",t),t})}realizeBusTree(e){let t=this.mixer.getTree();this.busTree=t,this.channels.clear(),t.getNodes().forEach(n=>{let i=this.mixer.getEffectiveVolume(n.id),r=n.parentId===null?null:this.channels.get(n.parentId)??null,a=(r?r.getChannel(n.id):e.getChannel(n.id))??(r?r.createChannel(n.id,{volume:i}):e.createChannel(n.id,{volume:i}));this.applyBusVolume(a,i,!1),this.channels.set(n.id,a)}),this.busSubscription?.cancel(),this.busSubscription=this.mixer.onVolumeChange((n,i,r)=>{this.applyBusVolume(this.channels.get(n)??null,r,!0)})}applyBusVolume(e,t,n){if(!e)return;let i=ue.readGain(e);if(e.setVolume(t),!n||i===null)return;let r=e.getGainNode().gain,s=e.getVolume();if(typeof r.setTargetAtTime!="function"||typeof r.cancelScheduledValues!="function"||typeof this.sound?.getAudioContext!="function")return;let a=this.sound.getAudioContext().currentTime;r.cancelScheduledValues(a),r.setValueAtTime(i,a),r.setTargetAtTime(s,a,ue.BusRampTimeConstant),r.setValueAtTime(s,a+ue.BusRampSettle)}static readGain(e){if(typeof e.getGainNode!="function")return null;let t=e.getGainNode()?.gain;return typeof t?.value=="number"?t.value:null}channelFor(e){let t=this.channels.get(e.config.type);return t||(this.channels.size>0&&!this.unknownBuses.has(e.config.type)&&(this.unknownBuses.add(e.config.type),this.gameState.logger.weakWarn("AudioManager",`No audio bus "${e.config.type}" is declared; playing on "${tt.sound}" instead.`)),this.channels.get(tt.sound)??null)}static defaultFade(e){return{end:e.state.volume,duration:0}}play(e,t=ue.defaultFade(e)){let n=new S;return this.ready.then(async()=>{this.state.has(e)&&this.state.get(e).token.stop();try{let i=this.channelFor(e),r=await this.sound.load(e.config.src),s=ue.clipRegionOf(e),a=await i.play(r,{volume:0,...ue.playRegionOf(s,e.config.loop),loop:e.config.loop,rate:e.state.rate});e.config.loop&&ue.applyLoopRegion(a,s);let c=e.state.muted??!1;a.mute(c),e.state.muted=c,this.state.set(e,{token:a,cachedAudio:r,originalVolume:t.end}),t.duration>0?await a.fade(0,t.end,t.duration).finished:a.setVolume(t.end),e.state.volume=t.end,e.state.paused=!1,e.config.loop||await new Promise(l=>{a.once("ended",()=>l())}),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=ue.defaultFade(e)){await this.ready,this.state.has(e)&&this.state.get(e).token.stop();try{let n=this.channelFor(e);if(!n)throw new k(`Channel not found for audio bus: "${e.config.type}"`);let i=await this.sound.load(e.config.src),r=ue.clipRegionOf(e),s=await n.play(i,{volume:0,...ue.playRegionOf(r,e.config.loop),loop:e.config.loop,rate:e.state.rate});e.config.loop&&ue.applyLoopRegion(s,r);let a=e.state.muted??!1;return s.mute(a),e.state.muted=a,this.state.set(e,{token:s,cachedAudio:i,originalVolume:t.end}),t.duration>0?s.fade(0,t.end,t.duration):s.setVolume(t.end),e.state.volume=t.end,e.state.paused=!1,s}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 S;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 S;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 S;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 S;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 S;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}seek(e,t){if(!this.state.has(e))return S.resolve(void 0);let n=this.state.get(e),i=ue.clampToRegion(t,ue.clipRegionOf(e));return n.token.seek(i),n.pausePosition!==void 0&&(n.pausePosition=i),S.resolve(void 0)}static clipRegionOf(e){let t=e.config.seek,n=e.config.endTime;if(n===void 0||!Number.isFinite(n)||n<=t)return{startTime:t};let i=e.config.loopStart;return i===void 0||!Number.isFinite(i)?{startTime:t,endTime:n}:{startTime:t,endTime:n,loopStart:i}}static playRegionOf(e,t){return t||e.endTime===void 0?{startTime:e.startTime}:{startTime:e.startTime,endTime:e.endTime}}static applyLoopRegion(e,t){let{startTime:n,endTime:i}=t;if(i===void 0||!Number.isFinite(i)||i<=n||typeof AudioBufferSourceNode>"u")return;let r=e.sourceController;if(typeof r?.getSource!="function")return;let s=r.getSource();if(!(s instanceof AudioBufferSourceNode))return;let a=t.loopStart,c=a!==void 0&&Number.isFinite(a)?Math.min(Math.max(a,n),i):n;s.loop=!0,s.loopStart=c<i?c:n,s.loopEnd=i}static clampToRegion(e,t){let n=Math.max(0,e);return t.endTime===void 0?n:n>=t.endTime?t.startTime:n}setRate(e,t){return this.state.has(e)?(this.state.get(e).token.setRate(t),e.state.rate=t,S.resolve(void 0)):S.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.getBuses().map(e=>[e.id,e.volume])}}fromData(e,t){return e.groups?.forEach(([n,i])=>{this.setBusVolume(n,i)}),e.sounds.forEach(([n,i])=>{let r=t.get(n);if(!r){this.gameState.logger.weakWarn("AudioManager",`Skipped restoring a sound that is not in this story (id: "${n}")`);return}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.channelFor(e),i=await this.sound.load(e.config.src),r=ue.clipRegionOf(e),s=r.endTime!==void 0&&e.config.loop,a=await n.play(i,{volume:e.state.volume,...ue.playRegionOf(r,e.config.loop),startTime:s?r.startTime:t.position,loop:e.config.loop,rate:e.state.rate});e.config.loop&&ue.applyLoopRegion(a,r),s&&Math.abs(t.position-r.startTime)>.01&&a.seek(ue.clampToRegion(t.position,r)),this.state.set(e,{token:a,cachedAudio:i,originalVolume:e.state.volume});let c=e.state.muted??!1;a.mute(c),e.state.muted=c,e.state.paused?a.pause():t.isPlaying||a.stop()}catch(n){this.gameState.logger.error("AudioManager",`Failed to restore sound (src: "${e.config.src}")`,n)}})}isManaged(e){return this.state.has(e)}preload(e){return this.ready.then(()=>this.sound.load(e.config.src)).then(()=>{}).catch(t=>{this.gameState.logger.weakWarn("AudioManager",`Failed to preload sound (src: "${e.config.src}")`,t)})}reset(){this.state.forEach(e=>{e.token.stop()}),this.state.clear(),this.globalVolume=1,this.isReady&&this.sound.setVolume(1),this.isReady&&this.busTree&&this.busTree.getNodes().forEach(e=>{this.applyBusVolume(this.channels.get(e.id),this.mixer.getEffectiveVolume(e.id),!1)})}setBusVolume(e,t){this.mixer.setVolume(e,t)}getBusVolume(e){return this.mixer.getVolume(e)}getBuses(){return this.mixer.list()}setGroupVolume(e,t){this.setBusVolume(e,t)}getGroupVolume(e){return this.getBusVolume(e)}setGlobalVolume(e){this.globalVolume=e,this.isReady&&this.sound.setVolume(e)}getGlobalVolume(){return this.globalVolume}destroy(){this.reset(),this.busSubscription?.cancel(),this.busSubscription=null,this.sound.destroy()}};ue.MaxChannels=1024,ue.BusRampTimeConstant=.02,ue.BusRampSettle=ue.BusRampTimeConstant*5;var _i=ue;import*as Tl from"html-to-image";var eo=class{constructor(e,t){this.gameState=e;this.notifications=t;this.events=new q}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 S,n=new xe(t);return t.registerSkipController(new H(()=>{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")}};function to(o,e,t){let n={},i={};Object.keys(e).forEach(s=>{let a=s;a==="style"&&e.style?Object.assign(n,e.style):e[a]!==void 0&&a!=="key"&&(i[a]=e[a])}),Object.keys(n).length>0&&Object.assign(o.style,n);let r=t?t(i):i;for(let[s,a]of Object.entries(r))o.getAttribute(s)!==a&&o.setAttribute(s,a)}var hl=4e3,ga={zIndex:0,visibility:"visible"},gl={...ga,zIndex:1},fa={position:"absolute",top:0,left:0,width:"100%",height:"100%",pointerEvents:"none",zIndex:2};function no(){return{zIndex:"auto",visibility:"visible",opacity:1,transform:"none",translate:"none",filter:"none",clipPath:"none",maskImage:"none",WebkitMaskImage:"none",maskSize:"auto",WebkitMaskSize:"auto",maskRepeat:"repeat",WebkitMaskRepeat:"repeat"}}function yl(){return{...no(),visibility:"hidden"}}var io=class{constructor(e){this.gameState=e;this.sceneElements=new Map;this.overlayHost=null;this.running=null}registerScene(e,t){t?this.sceneElements.set(e.getId(),t):this.sceneElements.delete(e.getId())}registerOverlayHost(e){this.overlayHost=e}reset(){this.running?.controller.complete(),this.running=null}skip(){this.running&&(this.gameState.logger.debug("StageTransition","Transition skipped"),this.running.controller.complete())}apply(e,t,n){this.running?.controller.complete();let i=e;typeof i._setDetached=="function"&&i._setDetached(!0);let r=e.createTask(this.gameState),s=e.requestAnimations(r.animations),a=new S().registerSkipController(new H(s.cancel)),c=new xe(a),l=[],u=r.resolve.map(h=>{if(typeof h=="function"){let m=this.createOverlay();return l.push(m),{kind:"overlay",element:m}}return{kind:"scene",sceneId:(h.key==="target"?t.to:t.from).getId(),role:h.key}}),d={task:r,controller:s,roles:t,targets:u,overlays:l,cancelLoadGate:()=>{},stale:!1};this.running=d,s.onUpdate(h=>this.applyFrame(d,h)),s.onComplete(()=>{this.settle(d,[[t.to,no()],[t.from,yl()]]),n(),a.resolve()}),s.onCanceled(()=>{this.settle(d,[[t.from,no()],[t.to,no()]]),c.abort()}),this.applyFrame(d,r.animations.map(h=>h.start));let p=this.waitForSceneReady(t.to);return d.cancelLoadGate=p.cancel,p.promise.then(()=>{d.stale||s.start()}),c}applyFrame(e,t){e.task.resolve.forEach((n,i)=>{let r=e.targets[i],s=r.kind==="overlay"?r.element:this.sceneElements.get(r.sceneId)??null;if(!s)return;let a=typeof n=="function"?n:n.resolver,c=r.kind==="overlay"?fa:r.role==="target"?gl:ga,l=z({style:c},a(...t));to(s,l,vl)})}settle(e,t){e.stale=!0,e.cancelLoadGate(),e.overlays.forEach(n=>n.remove()),e.overlays.length=0,t.forEach(([n,i])=>{let r=this.sceneElements.get(n.getId());r&&Object.assign(r.style,i)}),this.running===e&&(this.running=null)}createOverlay(){let e=document.createElement("div");return e.setAttribute("data-element-type","stage-transition-overlay"),Object.assign(e.style,fa),this.overlayHost?.appendChild(e),e}waitForSceneReady(e){let t=this.sceneElements.get(e.getId());if(!t)return{promise:Promise.resolve(),cancel:()=>{}};let n=()=>{},i=new Promise(s=>{n=this.gameState.schedule(()=>{this.gameState.logger.weakWarn("StageTransition","Timed out waiting for the incoming scene to load"),s()},hl)}),r=Promise.all(Array.from(t.querySelectorAll("img")).map(Sl)).then(()=>{});return{promise:Promise.race([r,i]),cancel:()=>n()}}},ha=["src","width","height"];function vl(o){if(!ha.some(t=>t in o))return o;let e={...o};return ha.forEach(t=>delete e[t]),e}function Sl(o){return o.getAttribute("src")?typeof o.decode=="function"?o.decode().then(()=>{},()=>{}):o.complete?Promise.resolve():new Promise(e=>{let t=()=>{o.removeEventListener("load",t),o.removeEventListener("error",t),e()};o.addEventListener("load",t),o.addEventListener("error",t)}):Promise.resolve()}var oo=class{constructor(e=100,t){this.liveGame=t;this.history=[];this.hooks={onUndo:[],onHistoryLimit:[]};this.maxHistorySize=e}push(e,t,n){let i=Vi(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}}has(e){return this.history.some(t=>t.id===e)}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(),this.liveGame.getGameStateForce?.().logger?.debug("ActionHistory","Undoing",this.history[r].action.type),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 ro=class o{constructor(e){this.history=[];this.cursor=-1;this.resumingAtCursor=!1;this.actionHistoryMgr=e,this.actionHistoryMgr.onHistoryLimit(t=>{this.crossFilter(t)})}push(e){let t=this.history[this.cursor];if(this.resumingAtCursor&&t&&t.action===e.action)return this.history[this.cursor]={...e,token:t.token},this.resumingAtCursor=!1,this;this.resumingAtCursor=!1;let n=this.history[this.cursor+1];return n&&n.action===e.action?this.history[this.cursor+1]={...e,token:n.token}:(this.history.length=this.cursor+1,this.history.push(e)),this.cursor++,this}getHistory(){return this.history.slice(0,this.cursor+1)}getFuture(){return this.history.slice(this.cursor+1)}getCursor(){return this.cursor}getAt(e){return this.history[e]??null}indexOfToken(e){return this.history.findIndex(t=>t.token===e)}setCursor(e){return this.cursor=Math.max(-1,Math.min(e,this.history.length-1)),this.resumingAtCursor=!0,this}canUndo(){return this.cursor>0}canRedo(){return this.cursor<this.history.length-1}getByToken(e){return this.history.find(t=>t.token===e)??null}serialize(){return this.history.slice(0,this.cursor+1).map(e=>o.toSerialized(e))}serializeAll(){return this.history.map(e=>o.toSerialized(e))}load(e,t){this.history=[];for(let n of e){let i=n.actionId!=null?t.get(n.actionId):void 0;i&&this.history.push({token:n.token??Vi(6),action:i,element:n.element,isPending:n.isPending,snapshot:n.snapshot})}this.cursor=this.history.length-1}reset(){this.history=[],this.cursor=-1,this.resumingAtCursor=!1}static toSerialized(e){return{token:e.token,actionId:e.action.getId(),element:e.element,isPending:e.isPending,snapshot:e.snapshot??null}}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(i=>i.id)),n=this.history.slice(0,this.cursor+1).filter(i=>t.has(i.token)).length;this.history=this.history.filter(i=>!t.has(i.token)),this.cursor=Math.max(-1,Math.min(this.cursor-n,this.history.length-1))}};var yn=class extends ${executeAction(e,t){let n=new S().registerSkipController(new H(()=>{c.cancel()})),i=e.timelines.attachTimeline(n),r=this.contentNode.getContent(),s=e.createPresentationSnapshot(),a=null,c=e.createMenu(r,u=>{let d=e.getLiveGame().createStackModel([{type:this.type,node:u.action[0]?.contentNode??null}]);n.resolve({type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[d]}}),a=()=>{d.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,snapshot:e.getLiveGame().captureGameState()}),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(",")}]}`)}};yn.ActionTypes=Gs;var vn=class vn extends ce{constructor(t,n={}){super();this.choices=[];this.prompt=de.isSentence(t)?t:t===null?null:new de(t),this.config=z(vn.defaultConfig,n)}static prompt(t,n={}){return new vn(t!==void 0?t:null,n)}static choose(t,n){return new vn(null,{}).choose(t,n)}choose(t,n){let i=this.chain();return de.isSentence(t)&&n?i.choices.push({prompt:de.toSentence(t),action:this.narrativeToActions(n),config:{}}):(_.isWord(t)||Array.isArray(t)||typeof t=="string")&&n?i.choices.push({prompt:de.toSentence(t),action:this.narrativeToActions(n),config:{}}):typeof t=="object"&&"prompt"in t&&"action"in t?i.choices.push({prompt:de.toSentence(t.prompt),action:this.narrativeToActions(t.action),config:{disabled:t.config?.disabled?j.from(t.config.disabled):void 0,hidden:t.config?.hidden?j.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 He("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=j.from(t),this.chain()}disableIf(t){let n=this.choices[this.choices.length-1];if(!n)throw new He("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=j.from(t),this.chain()}enableWhen(t,n,i){return this.choose({prompt:n,action:i,config:{disabled:j.not(j.from(t))}})}showWhen(t,n,i){return this.choose({prompt:n,action:i,config:{hidden:j.not(j.from(t))}})}fromChained(t){return[new yn(this.chain(),yn.ActionTypes.action,new x().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"?Yt.say(n).getActions():ze.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??{}}))}};vn.defaultConfig={},vn.targetAction=yn;var lr=vn;var yt={shutter:0,shutterColor:"#000",vignette:0,vignetteColor:"#000",vignetteInner:"44%",vignetteOuter:"78%"};function ur(o){return typeof o!="number"||!Number.isFinite(o)?0:Math.max(0,Math.min(1,o))}function ni(o,e){return typeof o=="string"&&o.length>0?o:e}function ya(o){let e=ur(o.shutter);return{backgroundColor:ni(o.shutterColor,yt.shutterColor),clipPath:`inset(0 0 ${100-50*e}% 0)`}}function va(o){let e=ur(o.shutter);return{backgroundColor:ni(o.shutterColor,yt.shutterColor),clipPath:`inset(${100-50*e}% 0 0 0)`}}function Sa(o){let e=ni(o.vignetteInner,yt.vignetteInner),t=ni(o.vignetteOuter,yt.vignetteOuter),n=`radial-gradient(circle at center, transparent ${e}, black ${t})`;return{backgroundColor:ni(o.vignetteColor,yt.vignetteColor),opacity:ur(o.vignette),maskImage:n,WebkitMaskImage:n,maskSize:"100% 100%",WebkitMaskSize:"100% 100%",maskPosition:"center",WebkitMaskPosition:"center",maskRepeat:"no-repeat",WebkitMaskRepeat:"no-repeat",maskMode:"alpha",WebkitMaskMode:"alpha"}}var ut=class ut extends ct{static get DefaultUserConfig(){return ut._defaultUserConfig??(ut._defaultUserConfig=new B({...J.DefaultTransformState.getDefaultConfig(),opacity:1,...yt}))}constructor(e={}){super();let t=ut.DefaultUserConfig.create(e),n=ut.DefaultConfig.create();this.userConfig=t,this.config=n.get(),this.transformState=this.getInitialTransformState()}pan(e,t,n){return this.pos(e,t,n)}darken(e,t,n){let i=Math.max(0,Math.min(1,e));return this.filter(`brightness(${1-i})`,{duration:t,ease:n})}shutter(e,t,n){return this.lens({shutter:ut.clampLens(e)},{duration:t,ease:n})}vignette(e,t,n){return this.lens({vignette:ut.clampLens(e)},{duration:t,ease:n})}lens(e,t){return this.transform(new Z(e,t))}resetCamera(e,t){return this.transform(new Z([{props:{filter:"none"},options:{duration:0}},{props:{position:new st("center"),scaleX:1,scaleY:1,zoom:1,rotation:0,opacity:1,shutter:yt.shutter,vignette:yt.vignette},options:{duration:e,ease:t}},{props:{shutterColor:yt.shutterColor,vignetteColor:yt.vignetteColor,vignetteInner:yt.vignetteInner,vignetteOuter:yt.vignetteOuter},options:{duration:0}}]))}static clampLens(e){return Number.isFinite(e)?Math.max(0,Math.min(1,e)):0}bringToFront(){throw new k(`A camera cannot be brought to front. It is not an element inside a layer, it is what the layers are viewed through, so it has nothing to be in front of \u2014 waiting for it to be added to the stage will not help. Use a camera transform such as Camera.zoom or Camera.pan to change what is in view. (camera: ${this.config.name})`)}reset(){return super.reset(),this.transformState=this.getInitialTransformState(),this}toData(){return{transformState:this.transformState.serialize()}}fromData(e){return this.transformState=J.deserialize(e.transformState),this}copy(){return new ut(this.userConfig.get())}getInitialTransformState(){let[e]=this.userConfig.extract(ut.DefaultUserConfig.keys());return new J(ut.DefaultUserConfig.create(e.get()).get())}};ut._defaultUserConfig=null,ut.DefaultConfig=new B({name:"(camera)"});var ii=ut;var an=class an extends Ln{constructor(t,n={}){super();this.entryScene=null;this.scenes=new Map;this.persistent=[];this.services=new Map;this.elementBaseline=null;this.name=t;let{camera:i,...r}=n;this.config=z(an.defaultConfig,r),this._camera=i??new ii}static empty(){return new an("empty").entry(new gt("empty"))}get camera(){return this._camera}entry(t){return this.entryScene=t,this}registerPersistent(t){return this.persistent.push(t),this}createPersistent(t,n){let i=new Rn(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 He(`Trying to access service ${t} before it's registered, please use "story.registerService" to register the service`);return n}hash(t=!1){return js(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 ie(`Service ${i} serialize method should not return a promise`);if(!Xo(r))throw new ie(`Service ${i} serialize method should return a pure object.
27
+ To prevent unintended behavior and unexpected results, the sound have to be on the music bus (or any bus beneath it). Please use \`Sound.bgm()\` to create the sound.`);let n=this.state?.backgroundImage?this.state.backgroundImage.reset():new I({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 se(this.chain(),"scene:jumpTo",new x().setContent([t])))}_exit(){return new se(this.chain(),"scene:exit",new x().setContent([]))}_transitionToScene(t,n){let i=this.chain();return t?i.chain(new se(i,X.transitionToScene,new x().setContent([t,n]))):i}_init(t){return new se(this.chain(),"scene:init",new x().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)]}};Fe.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"},Fe.DefaultUserConfig=new B({backgroundMusic:null,backgroundMusicFade:0,voices:void 0,background:"#fff",layers:[]}),Fe._defaultSceneConfig=null;var gt=Fe;import*as Ta from"howler";var Zi=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 sl={volume:1,limit:1/0},al=class pa{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={...sl,...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 pa(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}}},da=!1;function cl(o){da=o}function sn(o,e){da||(e!==void 0?console.warn(o,e):console.warn(o))}var ll=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){sn("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){sn("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){sn("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()}},ua=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}},ul=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 ll(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){sn("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){sn("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 ua(this,e);return r.finish(),r}this.volume=o,this._isMuted||(this.gainNode.gain.value=o);let n=new ua(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}},pl=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}},dl=10*1024*1024,ml=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 pl(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}}},fl={volume:1,latencyHint:"interactive",sampleRate:44100,maxChannels:128,silent:!1},ma=class{constructor(o){this.registeredChannels=new Set,this.isReady=!1,this.readyPromise=null,this.destroyed=!1,this.unlockHandler=null,this.options={...fl,...o},cl(!!this.options.silent),this.audioContext=new AudioContext({latencyHint:this.options.latencyHint,sampleRate:this.options.sampleRate}),this.audioCache=new ml(this.audioContext),this.masterChannel=new al("__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=>{sn("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 d=new ul(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?.())};d.once("ended",h),d.once("stop",h)}return d}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<dl?"full":"stream"}catch(t){return sn("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=>{sn("Failed to close AudioContext during destroy().",o)}))}isDestroyed(){return this.destroyed}};var ue=class ue{constructor(e){this.gameState=e;this.state=new Map;this.channels=new Map;this.busTree=null;this.busSubscription=null;this.unknownBuses=new Set;this.globalVolume=1;this.ready=Promise.resolve();this.isReady=!1;this.isInitializing=!1}get mixer(){return this.gameState.game.audioBuses}initialize(){if(this.isReady||this.isInitializing)return;this.mixer.getTree();let e=new ma({maxChannels:ue.MaxChannels});this.sound=e,this.isInitializing=!0,this.ready=e.onceReady().then(()=>{e.setVolume(this.globalVolume),this.realizeBusTree(e),this.isReady=!0,this.isInitializing=!1}).catch(t=>{throw this.isInitializing=!1,this.gameState.logger.error("AudioManager","Failed to initialize audio subsystem",t),t})}realizeBusTree(e){let t=this.mixer.getTree();this.busTree=t,this.channels.clear(),t.getNodes().forEach(n=>{let i=this.mixer.getEffectiveVolume(n.id),r=n.parentId===null?null:this.channels.get(n.parentId)??null,a=(r?r.getChannel(n.id):e.getChannel(n.id))??(r?r.createChannel(n.id,{volume:i}):e.createChannel(n.id,{volume:i}));this.applyBusVolume(a,i,!1),this.channels.set(n.id,a)}),this.busSubscription?.cancel(),this.busSubscription=this.mixer.onVolumeChange((n,i,r)=>{this.applyBusVolume(this.channels.get(n)??null,r,!0)})}applyBusVolume(e,t,n){if(!e)return;let i=ue.readGain(e);if(e.setVolume(t),!n||i===null)return;let r=e.getGainNode().gain,s=e.getVolume();if(typeof r.setTargetAtTime!="function"||typeof r.cancelScheduledValues!="function"||typeof this.sound?.getAudioContext!="function")return;let a=this.sound.getAudioContext().currentTime;r.cancelScheduledValues(a),r.setValueAtTime(i,a),r.setTargetAtTime(s,a,ue.BusRampTimeConstant),r.setValueAtTime(s,a+ue.BusRampSettle)}static readGain(e){if(typeof e.getGainNode!="function")return null;let t=e.getGainNode()?.gain;return typeof t?.value=="number"?t.value:null}channelFor(e){let t=this.channels.get(e.config.type);return t||(this.channels.size>0&&!this.unknownBuses.has(e.config.type)&&(this.unknownBuses.add(e.config.type),this.gameState.logger.weakWarn("AudioManager",`No audio bus "${e.config.type}" is declared; playing on "${tt.sound}" instead.`)),this.channels.get(tt.sound)??null)}static defaultFade(e){return{end:e.state.volume,duration:0}}play(e,t=ue.defaultFade(e)){let n=new S;return this.ready.then(async()=>{this.state.has(e)&&this.state.get(e).token.stop();try{let i=this.channelFor(e),r=await this.sound.load(e.config.src),s=ue.clipRegionOf(e),a=await i.play(r,{volume:0,...ue.playRegionOf(s,e.config.loop),loop:e.config.loop,rate:e.state.rate});e.config.loop&&ue.applyLoopRegion(a,s);let c=e.state.muted??!1;a.mute(c),e.state.muted=c,this.state.set(e,{token:a,cachedAudio:r,originalVolume:t.end}),t.duration>0?await a.fade(0,t.end,t.duration).finished:a.setVolume(t.end),e.state.volume=t.end,e.state.paused=!1,e.config.loop||await new Promise(l=>{a.once("ended",()=>l())}),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=ue.defaultFade(e)){await this.ready,this.state.has(e)&&this.state.get(e).token.stop();try{let n=this.channelFor(e);if(!n)throw new k(`Channel not found for audio bus: "${e.config.type}"`);let i=await this.sound.load(e.config.src),r=ue.clipRegionOf(e),s=await n.play(i,{volume:0,...ue.playRegionOf(r,e.config.loop),loop:e.config.loop,rate:e.state.rate});e.config.loop&&ue.applyLoopRegion(s,r);let a=e.state.muted??!1;return s.mute(a),e.state.muted=a,this.state.set(e,{token:s,cachedAudio:i,originalVolume:t.end}),t.duration>0?s.fade(0,t.end,t.duration):s.setVolume(t.end),e.state.volume=t.end,e.state.paused=!1,s}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 S;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 S;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 S;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 S;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 S;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}seek(e,t){if(!this.state.has(e))return S.resolve(void 0);let n=this.state.get(e),i=ue.clampToRegion(t,ue.clipRegionOf(e));return n.token.seek(i),n.pausePosition!==void 0&&(n.pausePosition=i),S.resolve(void 0)}static clipRegionOf(e){let t=e.config.seek,n=e.config.endTime;if(n===void 0||!Number.isFinite(n)||n<=t)return{startTime:t};let i=e.config.loopStart;return i===void 0||!Number.isFinite(i)?{startTime:t,endTime:n}:{startTime:t,endTime:n,loopStart:i}}static playRegionOf(e,t){return t||e.endTime===void 0?{startTime:e.startTime}:{startTime:e.startTime,endTime:e.endTime}}static applyLoopRegion(e,t){let{startTime:n,endTime:i}=t;if(i===void 0||!Number.isFinite(i)||i<=n||typeof AudioBufferSourceNode>"u")return;let r=e.sourceController;if(typeof r?.getSource!="function")return;let s=r.getSource();if(!(s instanceof AudioBufferSourceNode))return;let a=t.loopStart,c=a!==void 0&&Number.isFinite(a)?Math.min(Math.max(a,n),i):n;s.loop=!0,s.loopStart=c<i?c:n,s.loopEnd=i}static clampToRegion(e,t){let n=Math.max(0,e);return t.endTime===void 0?n:n>=t.endTime?t.startTime:n}setRate(e,t){return this.state.has(e)?(this.state.get(e).token.setRate(t),e.state.rate=t,S.resolve(void 0)):S.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.getBuses().map(e=>[e.id,e.volume])}}fromData(e,t){return e.groups?.forEach(([n,i])=>{this.setBusVolume(n,i)}),e.sounds.forEach(([n,i])=>{let r=t.get(n);if(!r){this.gameState.logger.weakWarn("AudioManager",`Skipped restoring a sound that is not in this story (id: "${n}")`);return}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.channelFor(e),i=await this.sound.load(e.config.src),r=ue.clipRegionOf(e),s=r.endTime!==void 0&&e.config.loop,a=await n.play(i,{volume:e.state.volume,...ue.playRegionOf(r,e.config.loop),startTime:s?r.startTime:t.position,loop:e.config.loop,rate:e.state.rate});e.config.loop&&ue.applyLoopRegion(a,r),s&&Math.abs(t.position-r.startTime)>.01&&a.seek(ue.clampToRegion(t.position,r)),this.state.set(e,{token:a,cachedAudio:i,originalVolume:e.state.volume});let c=e.state.muted??!1;a.mute(c),e.state.muted=c,e.state.paused?a.pause():t.isPlaying||a.stop()}catch(n){this.gameState.logger.error("AudioManager",`Failed to restore sound (src: "${e.config.src}")`,n)}})}isManaged(e){return this.state.has(e)}preload(e){return this.ready.then(()=>this.sound.load(e.config.src)).then(()=>{}).catch(t=>{this.gameState.logger.weakWarn("AudioManager",`Failed to preload sound (src: "${e.config.src}")`,t)})}reset(){this.state.forEach(e=>{e.token.stop()}),this.state.clear(),this.globalVolume=1,this.isReady&&this.sound.setVolume(1),this.isReady&&this.busTree&&this.busTree.getNodes().forEach(e=>{this.applyBusVolume(this.channels.get(e.id),this.mixer.getEffectiveVolume(e.id),!1)})}setBusVolume(e,t){this.mixer.setVolume(e,t)}getBusVolume(e){return this.mixer.getVolume(e)}getBuses(){return this.mixer.list()}setGroupVolume(e,t){this.setBusVolume(e,t)}getGroupVolume(e){return this.getBusVolume(e)}setGlobalVolume(e){this.globalVolume=e,this.isReady&&this.sound.setVolume(e)}getGlobalVolume(){return this.globalVolume}destroy(){this.reset(),this.busSubscription?.cancel(),this.busSubscription=null,this.sound.destroy()}};ue.MaxChannels=1024,ue.BusRampTimeConstant=.02,ue.BusRampSettle=ue.BusRampTimeConstant*5;var _i=ue;import*as Tl from"html-to-image";var eo=class{constructor(e,t){this.gameState=e;this.notifications=t;this.events=new q}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 S,n=new xe(t);return t.registerSkipController(new H(()=>{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")}};function to(o,e,t){let n={},i={};Object.keys(e).forEach(s=>{let a=s;a==="style"&&e.style?Object.assign(n,e.style):e[a]!==void 0&&a!=="key"&&(i[a]=e[a])}),Object.keys(n).length>0&&Object.assign(o.style,n);let r=t?t(i):i;for(let[s,a]of Object.entries(r))o.getAttribute(s)!==a&&o.setAttribute(s,a)}var hl=4e3,ga={zIndex:0,visibility:"visible"},gl={...ga,zIndex:1},fa={position:"absolute",top:0,left:0,width:"100%",height:"100%",pointerEvents:"none",zIndex:2};function no(){return{zIndex:"auto",visibility:"visible",opacity:1,transform:"none",translate:"none",filter:"none",clipPath:"none",maskImage:"none",WebkitMaskImage:"none",maskSize:"auto",WebkitMaskSize:"auto",maskRepeat:"repeat",WebkitMaskRepeat:"repeat"}}function yl(){return{...no(),visibility:"hidden"}}var io=class{constructor(e){this.gameState=e;this.sceneElements=new Map;this.overlayHost=null;this.running=null}registerScene(e,t){t?this.sceneElements.set(e.getId(),t):this.sceneElements.delete(e.getId())}registerOverlayHost(e){this.overlayHost=e}reset(){this.running?.controller.complete(),this.running=null}skip(){this.running&&(this.gameState.logger.debug("StageTransition","Transition skipped"),this.running.controller.complete())}apply(e,t,n){this.running?.controller.complete();let i=e;typeof i._setDetached=="function"&&i._setDetached(!0);let r=e.createTask(this.gameState),s=e.requestAnimations(r.animations),a=new S().registerSkipController(new H(s.cancel)),c=new xe(a),l=[],u=r.resolve.map(h=>{if(typeof h=="function"){let m=this.createOverlay();return l.push(m),{kind:"overlay",element:m}}return{kind:"scene",sceneId:(h.key==="target"?t.to:t.from).getId(),role:h.key}}),d={task:r,controller:s,roles:t,targets:u,overlays:l,cancelLoadGate:()=>{},stale:!1};this.running=d,s.onUpdate(h=>this.applyFrame(d,h)),s.onComplete(()=>{this.settle(d,[[t.to,no()],[t.from,yl()]]),n(),a.resolve()}),s.onCanceled(()=>{this.settle(d,[[t.from,no()],[t.to,no()]]),c.abort()}),this.applyFrame(d,r.animations.map(h=>h.start));let p=this.waitForSceneReady(t.to);return d.cancelLoadGate=p.cancel,p.promise.then(()=>{d.stale||s.start()}),c}applyFrame(e,t){e.task.resolve.forEach((n,i)=>{let r=e.targets[i],s=r.kind==="overlay"?r.element:this.sceneElements.get(r.sceneId)??null;if(!s)return;let a=typeof n=="function"?n:n.resolver,c=r.kind==="overlay"?fa:r.role==="target"?gl:ga,l=z({style:c},a(...t));to(s,l,vl)})}settle(e,t){e.stale=!0,e.cancelLoadGate(),e.overlays.forEach(n=>n.remove()),e.overlays.length=0,t.forEach(([n,i])=>{let r=this.sceneElements.get(n.getId());r&&Object.assign(r.style,i)}),this.running===e&&(this.running=null)}createOverlay(){let e=document.createElement("div");return e.setAttribute("data-element-type","stage-transition-overlay"),Object.assign(e.style,fa),this.overlayHost?.appendChild(e),e}waitForSceneReady(e){let t=this.sceneElements.get(e.getId());if(!t)return{promise:Promise.resolve(),cancel:()=>{}};let n=()=>{},i=new Promise(s=>{n=this.gameState.schedule(()=>{this.gameState.logger.weakWarn("StageTransition","Timed out waiting for the incoming scene to load"),s()},hl)}),r=Promise.all(Array.from(t.querySelectorAll("img")).map(Sl)).then(()=>{});return{promise:Promise.race([r,i]),cancel:()=>n()}}},ha=["src","width","height"];function vl(o){if(!ha.some(t=>t in o))return o;let e={...o};return ha.forEach(t=>delete e[t]),e}function Sl(o){return o.getAttribute("src")?typeof o.decode=="function"?o.decode().then(()=>{},()=>{}):o.complete?Promise.resolve():new Promise(e=>{let t=()=>{o.removeEventListener("load",t),o.removeEventListener("error",t),e()};o.addEventListener("load",t),o.addEventListener("error",t)}):Promise.resolve()}var oo=class{constructor(e=100,t){this.liveGame=t;this.history=[];this.hooks={onUndo:[],onHistoryLimit:[]};this.maxHistorySize=e}push(e,t,n){let i=Vi(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}}has(e){return this.history.some(t=>t.id===e)}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(),this.liveGame.getGameStateForce?.().logger?.debug("ActionHistory","Undoing",this.history[r].action.type),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 ro=class o{constructor(e){this.history=[];this.cursor=-1;this.resumingAtCursor=!1;this.actionHistoryMgr=e,this.actionHistoryMgr.onHistoryLimit(t=>{this.crossFilter(t)})}push(e){let t=this.history[this.cursor];if(this.resumingAtCursor&&t&&t.action===e.action)return this.history[this.cursor]={...e,token:t.token},this.resumingAtCursor=!1,this;this.resumingAtCursor=!1;let n=this.history[this.cursor+1];return n&&n.action===e.action?this.history[this.cursor+1]={...e,token:n.token}:(this.history.length=this.cursor+1,this.history.push(e)),this.cursor++,this}getHistory(){return this.history.slice(0,this.cursor+1)}getFuture(){return this.history.slice(this.cursor+1)}getCursor(){return this.cursor}getAt(e){return this.history[e]??null}indexOfToken(e){return this.history.findIndex(t=>t.token===e)}setCursor(e){return this.cursor=Math.max(-1,Math.min(e,this.history.length-1)),this.resumingAtCursor=!0,this}canUndo(){return this.cursor>0}canRedo(){return this.cursor<this.history.length-1}getByToken(e){return this.history.find(t=>t.token===e)??null}serialize(){return this.history.slice(0,this.cursor+1).map(e=>o.toSerialized(e))}serializeAll(){return this.history.map(e=>o.toSerialized(e))}load(e,t){this.history=[];for(let n of e){let i=n.actionId!=null?t.get(n.actionId):void 0;i&&this.history.push({token:n.token??Vi(6),action:i,element:n.element,isPending:n.isPending,snapshot:n.snapshot})}this.cursor=this.history.length-1}reset(){this.history=[],this.cursor=-1,this.resumingAtCursor=!1}static toSerialized(e){return{token:e.token,actionId:e.action.getId(),element:e.element,isPending:e.isPending,snapshot:e.snapshot??null}}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(i=>i.id)),n=this.history.slice(0,this.cursor+1).filter(i=>t.has(i.token)).length;this.history=this.history.filter(i=>!t.has(i.token)),this.cursor=Math.max(-1,Math.min(this.cursor-n,this.history.length-1))}};var yn=class extends ${executeAction(e,t){let n=new S().registerSkipController(new H(()=>{c.cancel()})),i=e.timelines.attachTimeline(n),r=this.contentNode.getContent(),s=e.createPresentationSnapshot(),a=null,c=e.createMenu(r,u=>{let d=e.getLiveGame().createStackModel([{type:this.type,node:u.action[0]?.contentNode??null}]);n.resolve({type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[d]}}),a=()=>{d.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,snapshot:e.getLiveGame().captureGameState()}),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(",")}]}`)}};yn.ActionTypes=Gs;var vn=class vn extends ce{constructor(t,n={}){super();this.choices=[];this.prompt=de.isSentence(t)?t:t===null?null:new de(t),this.config=z(vn.defaultConfig,n)}static prompt(t,n={}){return new vn(t!==void 0?t:null,n)}static choose(t,n){return new vn(null,{}).choose(t,n)}choose(t,n){let i=this.chain();return de.isSentence(t)&&n?i.choices.push({prompt:de.toSentence(t),action:this.narrativeToActions(n),config:{}}):(_.isWord(t)||Array.isArray(t)||typeof t=="string")&&n?i.choices.push({prompt:de.toSentence(t),action:this.narrativeToActions(n),config:{}}):typeof t=="object"&&"prompt"in t&&"action"in t?i.choices.push({prompt:de.toSentence(t.prompt),action:this.narrativeToActions(t.action),config:{disabled:t.config?.disabled?j.from(t.config.disabled):void 0,hidden:t.config?.hidden?j.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 He("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=j.from(t),this.chain()}disableIf(t){let n=this.choices[this.choices.length-1];if(!n)throw new He("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=j.from(t),this.chain()}enableWhen(t,n,i){return this.choose({prompt:n,action:i,config:{disabled:j.not(j.from(t))}})}showWhen(t,n,i){return this.choose({prompt:n,action:i,config:{hidden:j.not(j.from(t))}})}fromChained(t){return[new yn(this.chain(),yn.ActionTypes.action,new x().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"?Yt.say(n).getActions():ze.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??{}}))}};vn.defaultConfig={},vn.targetAction=yn;var lr=vn;var yt={shutter:0,shutterColor:"#000",vignette:0,vignetteColor:"#000",vignetteInner:"44%",vignetteOuter:"78%"};function ur(o){return typeof o!="number"||!Number.isFinite(o)?0:Math.max(0,Math.min(1,o))}function ni(o,e){return typeof o=="string"&&o.length>0?o:e}function ya(o){let e=ur(o.shutter);return{backgroundColor:ni(o.shutterColor,yt.shutterColor),clipPath:`inset(0 0 ${100-50*e}% 0)`}}function va(o){let e=ur(o.shutter);return{backgroundColor:ni(o.shutterColor,yt.shutterColor),clipPath:`inset(${100-50*e}% 0 0 0)`}}function Sa(o){let e=ni(o.vignetteInner,yt.vignetteInner),t=ni(o.vignetteOuter,yt.vignetteOuter),n=`radial-gradient(circle at center, transparent ${e}, black ${t})`;return{backgroundColor:ni(o.vignetteColor,yt.vignetteColor),opacity:ur(o.vignette),maskImage:n,WebkitMaskImage:n,maskSize:"100% 100%",WebkitMaskSize:"100% 100%",maskPosition:"center",WebkitMaskPosition:"center",maskRepeat:"no-repeat",WebkitMaskRepeat:"no-repeat",maskMode:"alpha",WebkitMaskMode:"alpha"}}var ut=class ut extends ct{static get DefaultUserConfig(){return ut._defaultUserConfig??(ut._defaultUserConfig=new B({...J.DefaultTransformState.getDefaultConfig(),opacity:1,...yt}))}constructor(e={}){super();let t=ut.DefaultUserConfig.create(e),n=ut.DefaultConfig.create();this.userConfig=t,this.config=n.get(),this.transformState=this.getInitialTransformState()}pan(e,t,n){return this.pos(e,t,n)}darken(e,t,n){let i=Math.max(0,Math.min(1,e));return this.filter(`brightness(${1-i})`,{duration:t,ease:n})}shutter(e,t,n){return this.lens({shutter:ut.clampLens(e)},{duration:t,ease:n})}vignette(e,t,n){return this.lens({vignette:ut.clampLens(e)},{duration:t,ease:n})}lens(e,t){return this.transform(new Z(e,t))}resetCamera(e,t){return this.transform(new Z([{props:{filter:"none"},options:{duration:0}},{props:{position:new st("center"),scaleX:1,scaleY:1,zoom:1,rotation:0,opacity:1,shutter:yt.shutter,vignette:yt.vignette},options:{duration:e,ease:t}},{props:{shutterColor:yt.shutterColor,vignetteColor:yt.vignetteColor,vignetteInner:yt.vignetteInner,vignetteOuter:yt.vignetteOuter},options:{duration:0}}]))}static clampLens(e){return Number.isFinite(e)?Math.max(0,Math.min(1,e)):0}bringToFront(){throw new k(`A camera cannot be brought to front. It is not an element inside a layer, it is what the layers are viewed through, so it has nothing to be in front of \u2014 waiting for it to be added to the stage will not help. Use a camera transform such as Camera.zoom or Camera.pan to change what is in view. (camera: ${this.config.name})`)}reset(){return super.reset(),this.transformState.resetTo(this.getInitialTransformState().get()),this}toData(){return{transformState:this.transformState.serialize()}}fromData(e){return this.transformState.resetTo(J.deserialize(e.transformState).get()),this}copy(){return new ut(this.userConfig.get())}getInitialTransformState(){let[e]=this.userConfig.extract(ut.DefaultUserConfig.keys());return new J(ut.DefaultUserConfig.create(e.get()).get())}};ut._defaultUserConfig=null,ut.DefaultConfig=new B({name:"(camera)"});var ii=ut;var an=class an extends Ln{constructor(t,n={}){super();this.entryScene=null;this.scenes=new Map;this.persistent=[];this.services=new Map;this.elementBaseline=null;this.name=t;let{camera:i,...r}=n;this.config=z(an.defaultConfig,r),this._camera=i??new ii}static empty(){return new an("empty").entry(new gt("empty"))}get camera(){return this._camera}entry(t){return this.entryScene=t,this}registerPersistent(t){return this.persistent.push(t),this}createPersistent(t,n){let i=new Rn(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 He(`Trying to access service ${t} before it's registered, please use "story.registerService" to register the service`);return n}hash(t=!1){return js(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 ie(`Service ${i} serialize method should not return a promise`);if(!Xo(r))throw new ie(`Service ${i} serialize method should return a pure object.
28
28
  A pure object should:
29
29
  1. be an object literal
30
30
  2. not have any prototype
@@ -59,7 +59,7 @@ This is likely caused by a nested Layout component or using Page inside a Page.
59
59
  This may be caused by complicated image action behavior that cannot be predicted.
60
60
  To fix this issue, you can manually register the image using scene.preloadImage(YourImageSrc). `),s.current.push(T)),r.get(T)||T}let{transformRef:u,transitionRefs:d,transitionTask:p,initDisplayable:h,applyTransition:f,applyTransform:m,updateStyleSync:y,flush:b,deps:v}=zt({element:o,state:o.transformState,skipTransform:e.game.config.allowSkipImageTransform,skipTransition:e.game.config.allowSkipImageTransition,transitionsProps:T=>{if(c)return(T?T.task.resolve:[null]).map(D=>D&&typeof D=="function"?{style:Lp}:{style:Ep(o.state.darkness)});let A=T?T.transition._getCurrentSrc():Dp(o);return[{style:{willChange:"filter",position:"absolute",transformOrigin:"center",backgroundColor:w.isColor(A)?w.colorToString(A):void 0,transform:"none",top:"auto",left:"auto",right:"auto",bottom:"auto",filter:`brightness(${1-o.state.darkness})`},src:w.isImageSrc(A)?w.srcToURL(A):I.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:T=>T.src?{...T,src:l(T.src)}:T});bt(o,{createWearable:T=>{i(A=>[...A,T])},disposeWearable:T=>{i(A=>A.filter(P=>P.getId()!==T.getId()))},initDisplayable:h,applyTransform:m,applyTransition:f,events:t,updateStyleSync:y,flush:b},[...v]);let g=Tc((T,A)=>{a.current&&(t.emit("event:image.onLoad"),Object.assign(a.current.style,{width:`${T}px`,height:`${A}px`}))},[t]),C=Tc(()=>{t.emit("event:image.onLoad")},[t]);return Dt.createElement(kp.div,{ref:u,className:"absolute w-max h-max","data-element-type":"image"},Dt.createElement("div",{className:"relative h-full w-full",ref:a,"data-image-id":o.getId()},c?d.map(([T,A],P)=>{let D=p?p.task.resolve[P]:null;if(D&&typeof D=="function")return Dt.createElement(Fo,{key:A,ref:T,autoFit:o.config.autoFit});let W=D?D.key==="target"?p.transition._getTargetLayers():p.transition._getPrevLayers():c;return Dt.createElement(Cc,{key:A,ref:T,src:W||c,autoFit:o.config.autoFit,resolveSrc:l,onSizeChanged:P===0?g:void 0,onLoad:P===0?C:void 0})}):d.map(([T,A],P)=>Dt.createElement(Fo,{key:A,ref:T,autoFit:o.config.autoFit,onSizeChanged:P===0?g:void 0,onLoad:P===0?C:void 0})),Dt.createElement("div",{className:Ac("w-full h-full top-0 left-0 absolute")},n.map(T=>Dt.createElement("div",{className:Ac("w-full h-full relative"),key:"wearable-"+T.getId()},Dt.createElement(xc,{image:T,state:e}))))))}var xc=Dt.memo(Rp),wc=xc;import Uo,{useEffect as Pc,useMemo as Hp,useRef as os}from"react";var Ip=/^(?:[a-zA-Z][a-zA-Z\d+.-]*:|\/)/,Mp=/^(?:[a-zA-Z][a-zA-Z\d+.-]*:)?\/\/[^/]*\/?/;function kc(o,e){if(typeof e!="string"||!e.length)return o;if(Ip.test(e)||typeof o!="string"||o.startsWith("data:"))return e;let[t,n]=Np(o.replace(/\\/g,"/")),i=n.replace(/[?#].*$/,""),r=i.slice(0,i.lastIndexOf("/")+1);return t+Gp(r+e.replace(/\\/g,"/"))}function Np(o){let e=Mp.exec(o);return e?[e[0],o.slice(e[0].length)]:o.startsWith("/")?["/",o.slice(1)]:["",o]}function Gp(o){let e=o.split("/"),t=[];for(let n=0;n<e.length;n++){let i=e[n];if(!(i==="."||i===""&&n!==e.length-1)){if(i===".."){t.pop();continue}t.push(i)}}return t.join("/")}var Oo=class{constructor(){this.backends=new Map;this.reportedMissing=new Set}register(e){if(!e||typeof e.name!="string"||!e.name.length)throw new Error("A puppet backend must have a non-empty name.");if(typeof e.mount!="function")throw new Error(`Puppet backend "${e.name}" must implement mount().`);return this.backends.set(e.name,e),this.reportedMissing.delete(e.name),this}get(e){return this.backends.get(e)||null}has(e){return this.backends.has(e)}list(){return Array.from(this.backends.keys())}unregister(e){return this.backends.delete(e)}reportMissing(e,t){return this.reportedMissing.has(e)?!1:(this.reportedMissing.add(e),t(`No puppet backend is registered under "${e}". The element keeps its place on the stage, its transform and its saved state, but draws nothing. Register one with game.registerPuppetBackend({name, mount}) before the game mounts.`),!0)}};function rs({state:o,puppet:e}){let[t]=ae(),{cacheManager:n}=Bt(),i=os(null),r=Hp(()=>e._resolveSize({width:o.game.config.width,height:o.game.config.height}),[e,o.game.config.width,o.game.config.height]),s=os(r);s.current=r;let{transformRef:a,transitionRefs:c,initDisplayable:l,applyTransform:u,applyTransition:d,updateStyleSync:p,deps:h}=zt({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipImageTransform,skipTransition:o.game.config.allowSkipImageTransition,transitionsProps:[{style:{position:"relative",width:`${r.width}px`,height:`${r.height}px`}}]});bt(e,{initDisplayable:l,applyTransform:u,applyTransition:d,updateStyleSync:p,flush:t},[...h]),Pc(()=>{let y=i.current;if(!y)return;let b=o.game,v=e.config.backend,g=b.getPuppetBackend(v);if(!g)return e._setStatus("missing-backend"),b.getPuppetBackendRegistry().reportMissing(v,A=>{o.logger.warn("Puppet",A)}),()=>{e._setStatus("unmounted")};let C;try{C=g.mount(y,{src:e.config.src,options:e.config.options,size:s.current,resolveSrc:m,resolveSibling:A=>m(kc(e.config.src,A)),warn:(A,P)=>{o.logger.warn("Puppet",A,P)}})}catch(A){return e._setStatus("error"),o.logger.error("Puppet",`Backend "${v}" threw while mounting "${e.config.src}"`,A),()=>{e._setStatus("unmounted")}}let T=!1;return e._attachInstance(C),e._setStatus("loading"),Promise.resolve().then(()=>e._applyState()).then(()=>!T&&typeof C.ready=="function"?C.ready():void 0).then(()=>{T||e._setStatus("ready")}).catch(A=>{T||(e._setStatus("error"),o.logger.error("Puppet",`Backend "${v}" failed to load "${e.config.src}"`,A))}),()=>{T=!0,e._attachInstance(null),e._setStatus("unmounted");try{C.dispose()}catch(A){o.logger.error("Puppet",`Backend "${v}" threw while disposing`,A)}}},[]);let f=os(r);Pc(()=>{let y=f.current;if(y.width===r.width&&y.height===r.height)return;f.current=r;let b=e._getInstance();if(!(!b||typeof b.resize!="function"))try{b.resize(r)}catch(v){o.logger.error("Puppet",`Backend "${e.config.backend}" threw while resizing`,v)}},[r]);function m(y){return w.isDataURI(y)?y:n.get(y)||y}return Uo.createElement(Wt.Div,{"data-element-type":"puppet"},Uo.createElement(Wt.mDiv,{tag:"puppet.container",color:"blue",border:"dashed",ref:a,className:"absolute"},c.map(([y,b])=>Uo.createElement("div",{key:b,ref:y,className:e.config.className},Uo.createElement("div",{ref:i,className:"w-full h-full","data-puppet-id":e.getId(),"data-puppet-backend":e.config.backend})))))}function ss({state:o,displayable:e}){return hi.createElement(hi.Fragment,null,e.map(t=>{if(t instanceof gn)return hi.createElement(ns,{state:o,text:t,key:"text-"+t.getId()});if(t instanceof I)return hi.createElement(wc,{state:o,image:t,key:"image-"+t.getId()});if(t instanceof kt)return hi.createElement(rs,{state:o,puppet:t,key:"puppet-"+t.getId()});throw new Error("Unsupported displayable type: "+(t?.constructor?.name||t))}))}import Wo,{useEffect as Fp}from"react";import{motion as Vp}from"motion/react";function Ec({state:o,layer:e,children:t}){let{transformRef:n,transitionRefs:i,initDisplayable:r,applyTransition:s,applyTransform:a,updateStyleSync:c,deps:l}=zt({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipLayersTransform,skipTransition:!1,transitionsProps:[{style:{width:"100%",height:"100%",transformOrigin:"center"}}]});return bt(e,{initDisplayable:r,applyTransition:s,applyTransform:a,updateStyleSync:c},[...l]),Fp(()=>(o.logger.debug("Layer","Layer mounted",e.getId()),()=>{o.logger.debug("Layer","Layer unmounted",e.getId())}),[]),Wo.createElement(Wo.Fragment,null,Wo.createElement(Vp.div,{className:"absolute w-full h-full",ref:n,"data-element-type":"layer","data-layer-id":e.getId(),key:`layer-${e.getId()}`},i.map(([u,d])=>Wo.createElement("div",{className:"relative w-full h-full",ref:u,key:d},t))))}async function Dc(o,e,t,n){let i=e.state.backgroundMusic,r=i&&o.audioManager.isManaged(i)?o.audioManager.stop(i,n):null;if(r&&t===i&&await r,t)try{await o.audioManager.playSoundToken(t,{end:t.state.volume,duration:n}),e.state.backgroundMusic=t}catch{e.state.backgroundMusic=null}else e.state.backgroundMusic=null;r&&await r}import Op from"clsx";import{useEffect as as,useRef as Up}from"react";import cs from"react";function ls({state:o,className:e,elements:t}){let{scene:n,layers:i}=t,r=Up(null);return as(()=>(o.stageTransition.registerScene(n,r.current),()=>{o.stageTransition.registerScene(n,null)}),[]),as(()=>n.events.depends([n.events.on(gt.EventTypes["event:scene.preUnmount"],()=>{if(n.state.backgroundMusic)return o.audioManager.stop(n.state.backgroundMusic,n.config.backgroundMusicFade)})]).cancel,[]),as(()=>(n.events.emit(gt.EventTypes["event:scene.mount"]),o.events.emit(E.EventTypes["event:state.scene.mount"],n),o.logger.debug("Scene","Scene mounted",n.getId()),()=>{n.events.emit(gt.EventTypes["event:scene.unmount"]),o.events.emit(E.EventTypes["event:state.scene.unmount"],n),o.logger.debug("Scene","Scene unmounted",n.getId())}),[]),bt(n,{setBackgroundMusic(s,a){return Dc(o,n,s,a)}}),cs.createElement("div",{className:Op(e,"w-full h-full absolute"),ref:r,"data-element-type":"scene","data-scene-id":n.getId()},[...i.entries()].sort(([s],[a])=>s.state.zIndex-a.state.zIndex).map(([s,a])=>cs.createElement(Ec,{state:o,layer:s,key:s.getId()},cs.createElement(ss,{state:o,displayable:a}))))}import{AnimatePresence as zp}from"motion/react";import{useEffect as $p,useReducer as jp,useRef as gi}from"react";import Wp from"clsx";import $t,{useCallback as us,useMemo as Bp,useRef as Kp}from"react";function ps({prompt:o,choices:e,afterChoose:t,state:n,words:i,renderPrompt:r=!0}){let s=R(),a=Kp([]),c=us(f=>(a.current.push(f),a.current.indexOf(f)),[]),l=us(f=>{let m=a.current.indexOf(f);m!==-1&&a.current.splice(m,1)},[]),u=us(f=>a.current.indexOf(f),[]),d=s.config.menu,p=Bp(()=>e.map(f=>({...f,words:f.prompt.evaluate(Ce.getCtx({gameState:n}))})),[]);function h(f){t(f)}return $t.createElement($t.Fragment,null,$t.createElement(Rr,{value:{evaluated:p,choose:h,gameState:n}},$t.createElement(Mr,{value:{register:c,unregister:l,getIndex:u}},$t.createElement(Ut,{className:"absolute"},r&&o&&$t.createElement(li,{gameState:n,action:{sentence:o,words:i,character:null},useTypeEffect:!1})),$t.createElement(Wt.Div,{color:"green",border:"dashed",className:Wp("absolute"),style:{width:`${s.config.width}px`,height:`${s.config.height}px`}},$t.createElement(d,{items:p.map((f,m)=>m)})))))}function Lc({items:o}){return $t.createElement(fo,{className:"absolute flex flex-col items-center justify-center min-w-full w-full h-full"},o.map(e=>$t.createElement(wo,{key:e,className:"bg-white text-black p-2 mt-2 w-1/2"})))}import qp from"clsx";import yi from"react";var Yp=120;function ds({state:o,className:e,elements:t}){let{scene:n,texts:i,menus:r}=t,s=gi(!1),a=gi({slotKeys:new Map,exitingKeys:new Set,menuPromptIds:new WeakMap,nextKey:0}),c=gi([]),l=gi(null),u=gi(null),[,d]=jp(m=>m+1,0),p=()=>{u.current&&(clearTimeout(u.current),u.current=null)},h=()=>{let m=l.current;if(!m)return;let y=a.current;m.forEach(({slot:b,presenceKey:v})=>{y.slotKeys.get(b)===v&&y.slotKeys.delete(b),y.exitingKeys.add(v)}),l.current=null,u.current=null,c.current=[],d()};$p(()=>()=>{p()},[]);let f=(()=>{let m=a.current,y=i.length>0?i.map(({action:g,onClick:C},T)=>({action:g,slot:T,useTypeEffect:!s.current,onFinished:A=>{A!==void 0&&(s.current=A),C(),o.events.emit(E.EventTypes["event:state.player.lineEnd"]),o.stage.next()}})):r.flatMap((g,C)=>{if(!g.action.prompt||!g.action.words)return[];let T=m.menuPromptIds.get(g);return T||(T=`menu-prompt-${n.getId()}-${m.nextKey++}`,m.menuPromptIds.set(g,T)),[{action:{sentence:g.action.prompt,words:g.action.words,character:null,id:T},slot:C,useTypeEffect:!1}]});if(y.length===0)return!l.current&&c.current.length>0&&(l.current=c.current.map(g=>({...g,active:!1}))),l.current&&!u.current&&(u.current=setTimeout(h,Yp)),l.current??[];p(),l.current=null;let b=new Set(y.map(({slot:g})=>g));for(let[g,C]of Array.from(m.slotKeys))b.has(g)||(m.exitingKeys.add(C),m.slotKeys.delete(g));let v=y.map(({slot:g,...C})=>{let T=m.slotKeys.get(g);return(!T||m.exitingKeys.has(T))&&(T=`say-${n.getId()}-${m.nextKey++}`,m.slotKeys.set(g,T)),{...C,presenceKey:T,slot:g,active:!0}});return c.current=v,v})();return yi.createElement("div",{className:qp(e,"w-full h-full absolute"),"data-element-type":"scene-dialogs"},yi.createElement(zp,{propagate:o.game.config.animationPropagate,onExitComplete:()=>{a.current.exitingKeys.clear()}},f.map(({action:m,onFinished:y,presenceKey:b,active:v,useTypeEffect:g})=>yi.createElement(li,{gameState:o,key:b,action:m,active:v,onFinished:y,useTypeEffect:g}))),r.map(({action:m,onClick:y},b)=>yi.createElement("div",{key:"menu-"+b,"data-element-type":"menu"},yi.createElement(ps,{state:o,prompt:m.prompt,choices:m.choices,renderPrompt:!m.prompt,afterChoose:v=>{s.current=!1,y(v),o.stage.next()},words:m.words}))))}import dn,{useEffect as Qp,useRef as ms}from"react";import{motion as Xp}from"motion/react";function Rc({state:o,camera:e,children:t}){let n=ms(null),i=ms(null),r=ms(null),{transformRef:s,transitionRefs:a,initDisplayable:c,applyTransition:l,applyTransform:u,updateStyleSync:d,deps:p}=zt({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipLayersTransform,skipTransition:!1,companionRefs:[{ref:n,project:Sa},{ref:i,project:ya},{ref:r,project:va}],transitionsProps:[{style:{width:"100%",height:"100%",transformOrigin:"center",overflow:"hidden"}}]});return bt(e,{initDisplayable:c,applyTransition:l,applyTransform:u,updateStyleSync:d},[...p]),Qp(()=>(o.logger.debug("Camera","Camera mounted",e.getId()),()=>{o.logger.debug("Camera","Camera unmounted",e.getId())}),[]),dn.createElement(dn.Fragment,null,dn.createElement(Xp.div,{className:"absolute w-full h-full",ref:s,"data-element-type":"camera"},a.map(([h,f])=>dn.createElement("div",{className:"relative w-full h-full",ref:h,key:f},t))),dn.createElement("div",{className:"absolute w-full h-full","data-element-type":"camera-lens",style:{pointerEvents:"none"}},dn.createElement("div",{className:"absolute w-full h-full",ref:n,"data-element-type":"camera-lens-vignette"}),dn.createElement("div",{className:"absolute w-full h-full",ref:i,"data-element-type":"camera-lens-shutter-top"}),dn.createElement("div",{className:"absolute w-full h-full",ref:r,"data-element-type":"camera-lens-shutter-bottom"})))}import Jp from"react";import{useEffect as fs,useRef as Zp}from"react";import{useCallback as Ic}from"react";function Mc(o){let e=Ic(()=>{if(!o.current)return;let n=o.current;n.style.opacity="1",n.style.pointerEvents="auto",n.style.visibility="visible"},[o]),t=Ic(()=>{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 hs({gameState:o,video:e}){let t=Zp(null),{show:n,hide:i}=Mc(t);fs(()=>o.events.depends([o.events.on(E.EventTypes["event:state.player.skip"],()=>{o.game.config.allowSkipVideo&&(r(),o.logger.log("NarraLeaf-React: Video","Skipped"))})]).cancel,[]),fs(()=>{i(),e.state.display&&n()},[]),fs(()=>{if(!t.current)return;let s=t.current,a=!1,c=new Set,l=()=>new k(`Failed to add event listener, ref is not available
61
61
  at Video.tsx: useEffect`),u=h=>{a||(a=!0,o.mountState(e,{show:()=>{if(!t.current)throw l();n()},hide:()=>{if(!t.current)throw l();i()},play:()=>{if(!t.current)throw l();let f=t.current;return h||f.error?(o.logger.error("NarraLeaf-React: Video","Cannot play a video whose source failed to load: "+e.config.src),Promise.resolve()):(f.currentTime=0,new Promise(m=>{let y=!1,b=null,v=[],g=()=>{y||(y=!0,c.delete(g),b&&b(),v.forEach(C=>C()),m())};c.add(g),b=o.schedule(({retry:C})=>{if(y)return;if(f.readyState<3){let D=()=>{f.removeEventListener("loadeddata",D),C()};f.addEventListener("loadeddata",D),v.push(()=>f.removeEventListener("loadeddata",D));return}let T=()=>g(),A=()=>g(),P=()=>{o.logger.error("NarraLeaf-React: Video","Video playback error: "+e.config.src),g()};f.addEventListener("ended",T),f.addEventListener("stopped",A),f.addEventListener("error",P),v.push(()=>{f.removeEventListener("ended",T),f.removeEventListener("stopped",A),f.removeEventListener("error",P)}),f.play().catch(D=>{o.logger.error("Failed to play video: "+D),g()})},10)}))},pause:()=>{if(!t.current)throw l();t.current.pause()},resume:()=>{if(!t.current)throw l();return t.current.play().catch(f=>{o.logger.error("Failed to resume video: "+f)})},stop:()=>{if(!t.current)throw l();t.current.pause(),t.current.dispatchEvent(new Event("stopped"))},seek:f=>{if(!t.current)throw l();t.current.currentTime=f}}))},d=()=>u(!1),p=()=>{o.logger.error("NarraLeaf-React: Video",`Failed to load video source: ${e.config.src}`+(s.error?` (media error code ${s.error.code})`:"")),u(!0)};return s.addEventListener("canplay",d),s.addEventListener("error",p),s.readyState>=3?u(!1):s.error&&p(),()=>{s.removeEventListener("canplay",d),s.removeEventListener("error",p),c.forEach(h=>h()),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 Jp.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 _p,{useEffect as ed,useRef as td}from"react";var Nc={linear:"linear",easeIn:"cubic-bezier(0.42, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.58, 1)",easeInOut:"cubic-bezier(0.42, 0, 0.58, 1)"};function nd(o,e){return e===void 0?"linear":Array.isArray(e)?`cubic-bezier(${e.join(", ")})`:typeof e=="string"&&Nc[e]?Nc[e]:(o.logger.debug("NarraLeaf-React: Vfx",'Easing has no CSS equivalent, falling back to "ease"',e),"ease")}function gs({gameState:o,vfx:e}){let t=td(null);return ed(()=>{let n=t.current;if(!n)return;let i=!1,r=!1,s=0,a=!1,c=new Set,l=new Set,u=[],d=C=>{n.style.transition="",n.style.opacity=String(C)},p=()=>{n.play().catch(C=>{o.logger.weakWarn("NarraLeaf-React: Vfx","Failed to play vfx video: "+C)})},h=()=>i||n.error?(o.logger.error("NarraLeaf-React: Vfx","Cannot wait for a vfx whose source failed to load: "+e.config.src),Promise.resolve()):n.readyState>=2?Promise.resolve():new Promise(C=>{let T=!1,A=()=>D(),P=()=>{o.logger.error("NarraLeaf-React: Vfx","Failed to load vfx source: "+e.config.src),D()},D=()=>{T||(T=!0,l.delete(D),n.removeEventListener("loadeddata",A),n.removeEventListener("error",P),C())};l.add(D),n.addEventListener("loadeddata",A),n.addEventListener("error",P),(n.readyState>=2||n.error)&&D()}),f=(C,T,A)=>{let P=T?.duration??0,D=++s;return A.instant||P<=0?(d(C),Promise.resolve()):new Promise(W=>{let pe=!1,V=null,fe=()=>{pe||(pe=!0,l.delete(fe),V!==null&&clearTimeout(V),s===D&&t.current&&d(C),W())};l.add(fe),n.style.transition=`opacity ${P}ms ${nd(o,T?.easing)}`,n.offsetWidth,n.style.opacity=String(C),V=setTimeout(fe,P)})},m=C=>{r||(r=!0,i=C,o.mountState(e,{show:async T=>{a=!0;let A={instant:!1};c.add(A);try{if(await h(),!t.current)return;e.state.paused||p(),await f(e.config.opacity,T,A)}finally{c.delete(A)}},hide:async T=>{a=!0;let A={instant:!1};c.add(A);try{await f(0,T,A),t.current&&n.pause()}finally{c.delete(A)}},pause:()=>{n.pause()},resume:()=>{p()},setRate:T=>{n.playbackRate=T}}),e.state.display&&u.push(o.schedule(()=>{!a&&t.current&&d(e.config.opacity)},0)))},y=()=>m(!1),b=()=>{o.logger.error("NarraLeaf-React: Vfx",`Failed to load vfx source: ${e.config.src}`+(n.error?` (media error code ${n.error.code})`:"")),m(!0)},v=o.events.on(E.EventTypes["event:state.player.skip"],()=>{c.size===0&&l.size===0||(c.forEach(C=>{C.instant=!0}),[...l].forEach(C=>C()),o.logger.log("NarraLeaf-React: Vfx","Fade skipped"))}),g=()=>{document.visibilityState==="visible"&&e.state.display&&!e.state.paused&&t.current&&p()};return document.addEventListener("visibilitychange",g),n.style.opacity="0",n.playbackRate=e.config.playbackRate,e.config.muted||o.logger.weakWarn("NarraLeaf-React: Vfx","Vfx is not muted; autoplay may be rejected by the browser. (src: "+e.config.src+")"),e.state.display&&!e.state.paused&&p(),n.addEventListener("canplay",y),n.addEventListener("error",b),n.readyState>=3?m(!1):n.error&&b(),()=>{n.removeEventListener("canplay",y),n.removeEventListener("error",b),document.removeEventListener("visibilitychange",g),v.cancel(),u.forEach(C=>C()),[...l].forEach(C=>C()),n.pause(),o.isStateMounted(e)&&o.unMountState(e)}},[o,e]),_p.createElement("video",{ref:t,src:e.config.src,preload:"auto",muted:e.config.muted,loop:e.config.loop,playsInline:!0,onContextMenu:n=>n.preventDefault(),style:{position:"absolute",inset:0,width:"100%",height:"100%",objectFit:e.config.fit,mixBlendMode:e.config.blendMode,pointerEvents:"none"}})}import id from"clsx";import od,{useCallback as rd,useEffect as Bo,useRef as sd}from"react";function ys({children:o,className:e,gameState:t}){let{ratio:n}=me(),i=R(),[r]=ae(),s=sd(null),a=i.config.minWidth,c=i.config.minHeight,l=rd(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 Bo(()=>{n.setUpdate(()=>{s.current?.requestUpdate()})},[n]),Bo(()=>n.onRequestedUpdate(()=>{s.current?.requestUpdate()}),[n]),Bo(()=>{let u=requestAnimationFrame(()=>{s.current?.requestUpdate()});return()=>{cancelAnimationFrame(u)}},[i.config.aspectRatio,i.config.height,i.config.width,c,a]),Bo(()=>t.events.on(E.EventTypes["event:state.player.requestFlush"],r).cancel,[t,r]),od.createElement(rc,{ref:s,id:i.config.contentContainerId,aspectRatio:i.config.aspectRatio,baseWidth:i.config.width,minWidth:a,minHeight:c,debounceMs:i.config.ratioUpdateInterval,className:id(e),onUpdate:l},o)}import Gc,{useEffect as ad,useRef as cd,useState as Hc}from"react";function vs({src:o,width:e,height:t}){let[n,i]=Hc({x:0,y:0}),[r,s]=Hc(!1),a=cd(null),{ratio:c}=me();return ad(()=>{let l=u=>{if(a.current){let d=a.current.getBoundingClientRect(),p=u.clientX-d.left,h=u.clientY-d.top;i({x:p,y:h}),r||s(!0)}};return window.addEventListener("mousemove",l),()=>{window.removeEventListener("mousemove",l)}},[r]),Gc.createElement(Ut,{ref:a,className:"overflow-hidden absolute"},Gc.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 Fc from"react";import Jt from"react";function Ss({error:o,errorInfo:e}){return R().config.app.debug?Jt.createElement("div",{className:"text-left"},Jt.createElement("h1",null,"NarraLeaf-React cannot initialize the player correctly. (development mode)"),Jt.createElement("p",{className:"text-red-700"},"Message: ",o.message),Jt.createElement("pre",null,"Error Stack: ",o?.stack),Jt.createElement("pre",null,"Component Stack: ",e?.componentStack),Jt.createElement("pre",null,"Digest: ","digest"in e?String(e.digest):"")):Jt.createElement("div",{className:"bg-white w-full h-full"},Jt.createElement("h1",null,"NarraLeaf-React crashed due to an unknown error."),Jt.createElement("p",null,"Please contact the game developer for further assistance."))}var Ko=class extends Fc.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?Fc.createElement(Ss,{error:this.state.error,errorInfo:this.state.errorInfo}):this.props.children}};import Uc from"clsx";import F,{useEffect as Lt,useReducer as Wc,useState as Un}from"react";import{flushSync as Bc}from"react-dom";import{useRef as ld}from"react";import{useEffect as ud}from"react";function Vc({gameState:o}){let e=ld(null);return ud(()=>(e.current=requestAnimationFrame(()=>{setTimeout(()=>{o.events.emit(E.EventTypes["event:state.onRender"])},0)}),()=>{e.current!==null&&cancelAnimationFrame(e.current)}),[o.deps]),null}import vi,{useEffect as pd}from"react";function Ts({gameState:o}){let[e]=ae(),{ratio:t}=me(),n=o.notificationMgr;pd(()=>n.onFlush(()=>{e()}).cancel,[]);let i=o.game.config.notification;return vi.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"},vi.createElement(i,{notifications:n.toArray()}))}function Oc({notifications:o}){return vi.createElement(Po,{className:"absolute top-0 left-0 w-full h-full"},o.map(({id:e,message:t})=>vi.createElement("div",{key:e,className:"absolute top-0 left-0 w-[100px] h-[80px]"},vi.createElement("span",{className:"text-white text-2xl font-bold"},t))))}function Kc({story:o=oi.empty(),width:e,height:t,className:n,onReady:i,onPreloadComplete:r,onPreloadedReady:s,onFirstSceneReady:a,onEnd:c,onError:l,children:u,active:d=!0}){let[p,h]=Wc(M=>M+1,0),[f,m]=Wc(M=>M+1,0),[y,b]=Un(0),v=R(),[g]=Un(()=>new E(v,{update:h,forceUpdate:()=>{g.logger.weakWarn("Player","force update"),Bc(()=>{h()})},forceRemount:()=>{g.logger.weakWarn("Player","force remount"),Bc(()=>{b(M=>M+1),h()})},next:ke})),C=F.createRef(),T=F.createRef(),[A,P]=Un(!1),D=F.useRef(!1),W=F.useRef(null),pe=F.useRef(null),{preloaded:V}=Bt(),[fe,Ue]=Un(!1),Ze=F.useRef(!1),[We,pt]=Un(!1),Ct=F.useRef(!1),L=F.useRef(null),ee=F.useRef(!1),[he]=Un(new Map);function be(M){return{game:v,gameState:g,liveGame:v.getLiveGame(),storable:v.getLiveGame().getStorable(),scene:M}}function ke(){let M=()=>{he.forEach(O=>O.cancel())};if(g.rollLock.isLocked())return;M();let Q=!1,ge=0;for(;!Q;){if(ge++>v.config.maxStackModelLoop)throw new k("Max stack model loop reached");let O=v.getLiveGame().next();if(!O){if(v.getLiveGame().stackModel&&!v.getLiveGame().stackModel.isEmpty())continue;break}if(S.isAwaitable(O)){if(W.current===O)break;W.current=O,O.onSettled(()=>{O.isFailed()||(W.current===O&&(W.current=null),ke())}),O.onFailed(St=>{W.current===O&&(W.current=null),g.logger.error("Player",St)}),Q=!0;break}if(O instanceof xn){if(pe.current===O)break;pe.current=O,O.nextUnlock().then(()=>{pe.current===O&&(pe.current=null),ke()}),Q=!0;break}if(Xe.isCalledActionResult(O)&&O.wait&&Xe.isStackModelsAwaiting(O.wait.type,O.wait.stackModels)){if(W.current===O)break;if(W.current=O,O.wait){let St=Xe.executeStackModelGroup(O.wait.type,O.wait.stackModels);St.then(()=>{W.current===O&&(W.current=null),ke()}),St.onFailed(te=>{W.current===O&&(W.current=null),g.logger.error("Player",te)})}Q=!0;break}g.handle(O)}g.stage.update()}Lt(()=>{g.audioManager.initialize()},[]),Lt(()=>(v.getLiveGame().setGameState(g),o&&!v.getLiveGame().isPlaying()&&v.getLiveGame().loadStory(o),o?.entryScene&&!g.getPreloadingScene()&&!g.getLastScene()&&g.preloadScene(o.entryScene),g.playerCurrent=C.current,g.mainContentNode=T.current,()=>{v.getLiveGame().setGameState(void 0),g.playerCurrent=null}),[v,o]),Lt(()=>rt(()=>{P(!0);let M=g.getLastScene(),Q=[];M?Q.push(M.events.once("event:scene.mount",()=>{g.stage.next()}).cancel):g.stage.next();let ge=g.events.on(E.EventTypes["event:state.end"],()=>{c&&c({game:v,gameState:g,liveGame:v.getLiveGame(),storable:v.getLiveGame().getStorable()})});return g.stage.update(),()=>{M&&Q.forEach(O=>O()),ge.cancel()}}),[]),Lt(()=>rt(()=>{A&&i&&!D.current&&(D.current=!0,g.stage.forceUpdate(),v.hooks.trigger("init",[]),i({game:v,gameState:g,liveGame:v.getLiveGame(),storable:v.getLiveGame().getStorable()}))}),[A]),Lt(()=>rt(()=>{if(fe&&s&&!Ze.current){Ze.current=!0;let M=L.current||g.getLastScene()||g.getPreloadingScene(),Q=be(M);s(Q)}}),[fe]),Lt(()=>rt(()=>{if(We&&!Ct.current){Ct.current=!0;let M=L.current||g.getLastScene()||g.getPreloadingScene(),Q=be(M);v.markPreloadComplete(Q)&&r&&r(Q)}}),[We]),Lt(()=>g.events.on(E.EventTypes["event:state.scene.mount"],M=>{L.current||(L.current=M,m())}).cancel,[]),Lt(()=>{if(!We||!d||ee.current||v.isFirstSceneReady())return;let M=L.current||g.getLastScene();if(!M)return;let Q=null,ge=null,O=!1;ee.current=!0;let St=()=>{O=!0,ee.current=!1;let te=be(M);v.markFirstSceneReady(te)&&a&&a(te)};return typeof requestAnimationFrame=="function"?Q=requestAnimationFrame(()=>{ge=setTimeout(St,0)}):ge=setTimeout(St,0),()=>{O||(ee.current=!1,Q!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(Q),ge!==null&&clearTimeout(ge))}},[d,f,p,We]),Lt(()=>V.events.depends([V.events.on(qe.EventTypes["event:preloaded.ready"],()=>{Ue(!0),g.stage.update(),o&&v.getLiveGame().isPlaying()&&ke()}),V.events.on(qe.EventTypes["event:preloaded.complete"],()=>{pt(!0)})]).cancel,[]),Lt(()=>{g.flushDep=p},[p]);let Pe=e||v.config.width,U=t||v.config.height;return F.createElement(Ko,{onError:l},F.createElement("div",{style:{width:typeof Pe=="number"?`${Pe}px`:Pe,height:typeof U=="number"?`${U}px`:U},className:Uc(n,"__narraleaf_content-player"),ref:C,tabIndex:0},F.createElement(ys,{className:Uc("flex-grow overflow-auto"),gameState:g},F.createElement(Xr,{gameState:g}),F.createElement(Vc,{gameState:g}),F.createElement(Ut,{className:"absolute",ref:T,style:{cursor:g.game.config.cursor?"none":"auto",overflow:g.game.config.showOverflow?"visible":"hidden",isolation:"isolate"}},v.config.cursor&&F.createElement(vs,{src:v.config.cursor,width:v.config.cursorWidth,height:v.config.cursorHeight}),F.createElement(dd,{show:fe&&d,key:y},F.createElement(zr,null,F.createElement(pc,{state:g}),F.createElement(hc,{state:g}),F.createElement(md,{state:g},F.createElement("div",{className:"w-full h-full absolute",style:{isolation:"isolate"},"data-element-type":"scene-group"},g.getSceneElements().map(M=>F.createElement(ls,{key:"scene-"+M.scene.getId(),state:g,elements:M}))),F.createElement(fd,{state:g}),g.getVideos().map((M,Q)=>F.createElement("div",{className:"w-full h-full absolute",key:"video-"+Q,"data-element-type":"video"},F.createElement(hs,{gameState:g,video:M}))),g.getVfx().map(M=>F.createElement("div",{className:"w-full h-full absolute",key:"vfx-"+M.getId(),"data-element-type":"vfx",style:{zIndex:M.config.zIndex}},F.createElement(gs,{gameState:g,vfx:M})))),g.getSceneElements().map(M=>F.createElement(ds,{key:"scene-dialogs-"+M.scene.getId(),state:g,elements:M})),F.createElement(hd,{NvlComponent:v.config.nvlDialog}))),F.createElement(vc,{state:g}),F.createElement(_a,null,u),F.createElement(Ts,{gameState:g})))))}function dd({children:o,show:e}){return F.createElement(F.Fragment,null,e?o:null)}function md({state:o,children:e}){let t=o.getLiveGame().story?.camera??null;return t?F.createElement(Rc,{state:o,camera:t},e):F.createElement(F.Fragment,null,e)}function fd({state:o}){let e=F.useRef(null);return Lt(()=>(o.stageTransition.registerOverlayHost(e.current),()=>{o.stageTransition.registerOverlayHost(null)}),[]),F.createElement("div",{className:"w-full h-full absolute pointer-events-none",ref:e,"data-element-type":"stage-transition-overlay-host"})}function hd({NvlComponent:o}){let{dialogs:e,state:t}=Kt(),i=R().getLiveGame().getGameState(),r=F.useMemo(()=>e.map((s,a)=>{let c=s.sentence.evaluate(Ce.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 F.createElement(o,{dialogs:r})}import"client-only";import Wn from"react";function zc({children:o,game:e}){return Wn.createElement(Wn.Fragment,null,Wn.createElement(Da,null,Wn.createElement(xa,{game:e},Wn.createElement(Qa,null,Wn.createElement(Ea,null,o)))))}var gd=(c=>(c.image="narraleaf:image",c.text="narraleaf:text",c.layer="narraleaf:layer",c.scene="narraleaf:scene",c.video="narraleaf:video",c.vfx="narraleaf:vfx",c.camera="narraleaf:camera",c.puppet="narraleaf:puppet",c))(gd||{});import yd from"clsx";import At,{useEffect as $c,useRef as vd,useState as Sd}from"react";import{motion as Td,useIsPresent as bd}from"motion/react";var Ad={defaultColor:"#000",fontSize:16,fontWeight:400,fontWeightBold:700,fontFamily:"sans-serif"};function Cd({children:o,initial:e,transition:t,...n}){let i=R(),r=Pt(),{ratio:s}=me(),[a]=un(re.Preferences.showDialog),c=vd(null),[l]=Tn("nextAction"),u=bd(),[d,p]=Sd(null);function h(){r.config.gameState.isAdvanceSuspended()||r.requestComplete()}return $c(()=>{if(!window){console.warn(`Failed to add event listener, window is not available
62
- at Say.tsx: onElementClick`);return}let f=y=>{y.repeat||r.config.gameState.isAdvanceSuspended()||i.keyMap.match("nextAction",y.key)&&r.requestComplete()};window.addEventListener("keydown",f);let m=r.events.on(Ne.Events.simulateClick,()=>{c.current&&c.current.click()});return()=>{window.removeEventListener("keydown",f),m.cancel()}},[r,l]),$c(()=>{let f=i.preference.onPreferenceChange(re.Preferences.autoForward,m=>{m&&r.isEnded()?r.tryScheduleAutoForward():r.cancelAutoForward()});return()=>{f.cancel()}},[r]),At.createElement("div",{"data-element-type":"dialog",className:"absolute w-full h-full"},At.createElement("div",{className:yd("absolute bottom-0 w-full h-full",!a&&"invisible pointer-events-auto"),onClick:h,style:{...Hi(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},At.createElement(Yr,{value:d},At.createElement(Td.div,{...n,initial:r.config.suppressInitialAnimation?!1:e,transition:r.config.suppressInitialAnimation&&u?{duration:0}:t},o)),At.createElement("div",{"data-element-type":"dialog-overlay",className:"absolute inset-0 pointer-events-none",ref:p})))}function jc({children:o,...e}){let t=Pt();return!t.config.action.sentence||!t.config.action.words?null:At.createElement(Cd,{...e},o)}var hp=jc;function qc(){return At.createElement(jc,null,At.createElement("div",{className:"dialog-content",style:{display:"flex",alignItems:"flex-start",gap:16,width:"100%",height:"100%"}},At.createElement(Hr,null),At.createElement("div",{className:"dialog-text-content",style:{minWidth:0,flex:"1 1 auto"}},At.createElement(Xt,null),At.createElement(pn,{...Ad}))))}var Si={say:qc,menu:Lc,notification:Oc,nvlDialog:qr};var zo=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 Ti=class{constructor(e={}){this.keyMap=e;this.events=new q}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 Yc=(e=>(e.game="game",e))(Yc||{}),Je=class Je{constructor(e){this.hooks=new Ii;this.liveGame=null;this.sideEffect=[];this.freezeFields=[];this.preference=new ai(Je.DefaultPreference);this.audioBuses=new Xn(()=>this.config.audioBuses??[],na(this.preference));this.keyMap=new Ti({skipAction:["Control"],nextAction:[" "]});this.lifecycleEvents=new q;this.puppetBackends=new Oo;this.preloadCompleteContext=null;this.firstSceneReadyContext=null;this.config=z(Je.DefaultConfig,e),this.plugins=new zo(this),this.router=new ln(this)}configure(e){let[t,n]=$s(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=z(this.config,t),Object.prototype.hasOwnProperty.call(t,"audioBuses")&&this.audioBuses.invalidate(),this.getLiveGame().getGameState()?.events.emit(E.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}registerPuppetBackend(e){return this.puppetBackends.register(e),this}getPuppetBackend(e){return this.puppetBackends.get(e)}listPuppetBackends(){return this.puppetBackends.list()}getPuppetBackendRegistry(){return this.puppetBackends}onPreloadComplete(e){return this.lifecycleEvents.on(Je.LifecycleEventTypes["event:game.preloadComplete"],e)}oncePreloadComplete(e){return this.lifecycleEvents.once(Je.LifecycleEventTypes["event:game.preloadComplete"],e)}whenPreloadComplete(){return this.preloadCompleteContext?Promise.resolve(this.preloadCompleteContext):new Promise(e=>{this.oncePreloadComplete(e)})}isPreloadComplete(){return this.preloadCompleteContext!==null}onFirstSceneReady(e){return this.lifecycleEvents.on(Je.LifecycleEventTypes["event:game.firstSceneReady"],e)}onceFirstSceneReady(e){return this.lifecycleEvents.once(Je.LifecycleEventTypes["event:game.firstSceneReady"],e)}whenFirstSceneReady(){return this.firstSceneReadyContext?Promise.resolve(this.firstSceneReadyContext):new Promise(e=>{this.onceFirstSceneReady(e)})}isFirstSceneReady(){return this.firstSceneReadyContext!==null}markPreloadComplete(e){return this.preloadCompleteContext?!1:(this.preloadCompleteContext=e,this.lifecycleEvents.emit(Je.LifecycleEventTypes["event:game.preloadComplete"],e),!0)}markFirstSceneReady(e){return this.firstSceneReadyContext?!1:(this.firstSceneReadyContext=e,this.lifecycleEvents.emit(Je.LifecycleEventTypes["event:game.firstSceneReady"],e),!0)}getLiveGame(){if(!this.liveGame){let e=this.createLiveGame();return this.liveGame=e,e}return this.liveGame}dispose(){this.audioBuses.dispose(),this.plugins.unregisterAll(),this.liveGame?.dispose(),this.sideEffect.forEach(e=>e())}addSideEffect(e){this.sideEffect.push(e)}createLiveGame(){return new Ht(this)}};Je.defaultSettings={volume:1},Je.DefaultPreference={autoForward:!1,skip:!0,showDialog:!0,gameSpeed:1,cps:10,voiceVolume:1,voiceFadeDuration:0,voiceEndMode:"stop",bgmVolume:1,soundVolume:1,globalVolume:1,skipDelay:0,skipInterval:100},Je.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"},Je.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,allowSkipSceneTransition:!0,allowSkipTextTransform:!0,allowSkipTextTransition:!0,allowSkipLayersTransform:!0,allowSkipVideo:!1,animationPropagate:!1,dialogWidth:1920,dialogHeight:1080*.2,notification:Si.notification,menu:Si.menu,dialog:Si.say,nvlDialog:Si.nvlDialog,onError:e=>{console.error(e)},stage:null,maxStackModelLoop:1e3,maxActionHistory:100,audioBuses:[]},Je.GameSettingsNamespace=Yc,Je.LifecycleEventTypes={"event:game.preloadComplete":"event:game.preloadComplete","event:game.firstSceneReady":"event:game.firstSceneReady"};var re=Je;var $o=class $o extends ${constructor(){super(...arguments);this._jumpTarget=null}setJumpTarget(t){return this._jumpTarget=t,this}getJumpTarget(){return this._jumpTarget}static executeActionsAsync(t,n){let i=t.game.getLiveGame().requestAsyncStackModel([{type:n.type,node:n.contentNode}]);return t.game.getLiveGame().executeAsyncStackModel(i)}checkActionChain(t){if(t.some(n=>!!n.contentNode.getChild()))throw new Error("Invalid action chain. Actions are chained unexpectedly.");return t}executeAction(t,n){let i=this.contentNode,[r]=i.getContent();if(this.type===ne.do)return r.length===0?{type:this.type,node:this.contentNode.getChild()}:[{type:this.type,node:this.contentNode.getChild()},{type:this.type,node:r[0].contentNode}];if(this.type===ne.doAsync){if(r.length===0)return super.executeAction(t,n);let s=$o.executeActionsAsync(t,r[0]);return t.timelines.attachTimeline(s),super.executeAction(t,n)}else if(this.type===ne.any){if(r.length===0)return{type:this.type,node:this.contentNode.getChild()};let s=this.checkActionChain(r).map(a=>t.game.getLiveGame().createStackModel([{type:a.type,node:a.contentNode}]));return{type:this.type,node:this.contentNode.getChild(),wait:{type:"any",stackModels:s}}}else if(this.type===ne.all){if(r.length===0)return{type:this.type,node:this.contentNode.getChild()};let s=this.checkActionChain(r).map(a=>t.game.getLiveGame().createStackModel([{type:a.type,node:a.contentNode}]));return{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:s}}}else if(this.type===ne.allAsync){if(r.length===0)return{type:this.type,node:this.contentNode.getChild()};let s=this.checkActionChain(r).map(a=>t.game.getLiveGame().requestAsyncStackModel([{type:a.type,node:a.contentNode}]));return t.timelines.attachTimeline(S.all(...s.map(a=>t.game.getLiveGame().executeAsyncStackModel(a)))),super.executeAction(t,n)}else if(this.type===ne.repeat){let[s,a]=this.contentNode.getContent();if(a<=0||s.length===0)return super.executeAction(t,n);let c=Xe.createCountLoop(t.game.getLiveGame(),a,this.checkActionChain(s));return t.logger.debug("ControlAction","repeat",s,a),{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[c]}}}else if(this.type===ne.while){let[s,a]=this.contentNode.getContent();if(s.length===0)return super.executeAction(t,n);if(!a.evaluate({gameState:t}).value)return super.executeAction(t,n);let c=Xe.createConditionLoop(t.game.getLiveGame(),a,this.getId(),this.checkActionChain(s));return t.logger.debug("ControlAction","while",s),{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[c]}}}else if(this.type===ne.break){if(!n.stackModel.isLoop())throw new Error("Control.breakLoop() can only be used inside a loop (repeat/while)");return n.stackModel.breakLoop(),{type:this.type,node:null}}else if(this.type===ne.sleep){let[,s]=this.contentNode.getContent();if(t.isFastForwarding())return{type:this.type,node:this.contentNode.getChild()};let a;typeof s=="number"?a=S.delay(s):S.isAwaitable(s)?a=s:a=S.fromPromise(s);let c=new S,l=new xe(a);return t.timelines.attachTimeline(l),a.then(()=>{c.resolve({type:this.type,node:this.contentNode.getChild()})}),c.onSkipControllerRegister(u=>{u.onAbort(()=>{l.abort()})}),c}else if(this.type===ne.waitForClick){if(t.consumeStageClick())return{type:this.type,node:this.contentNode.getChild()};let s=new S,a=new S,c=new xe(a);t.timelines.attachTimeline(c);let l=t.game.preference,u=l.getPreference(re.Preferences.autoForward),d=l.getPreference(re.Preferences.gameSpeed),p=u?t.game.config.autoForwardDelay/d:null,h=!1,f=null,m=null,y=null,b=()=>{m?.cancel(),y?.cancel(),f&&(clearTimeout(f),f=null)},v=()=>{h||(h=!0,b(),a.resolve())};return m=t.events.on(E.EventTypes["event:state.player.stageClick"],v),y=t.events.on(E.EventTypes["event:state.player.skip"],v),p!==null&&(f=setTimeout(v,p)),a.then(()=>{s.resolve({type:this.type,node:this.contentNode.getChild()})}),s.onSkipControllerRegister(g=>{g.onAbort(()=>{h||(h=!0,b(),c.abort())})}),s}else{if(this.type===ne.label)return super.executeAction(t,n);if(this.type===ne.jump){let s=this._jumpTarget;if(!s){let[l]=this.contentNode.getContent();throw new Ve(`Jump target label "${l}" was not resolved. This usually means the story was not constructed before playing.`)}let a=t.getLiveGame(),c=a.getStackModelForce().serialize();return t.actionHistory.push({action:this,stackModel:n.stackModel},l=>{let[u]=a.constructMaps();a.getStackModelForce().deserialize(l,u)},[c]),a.clearMainStack().getStackModelForce().push({type:this.type,node:s.contentNode}),null}}throw new Error("Unknown control action type: "+this.type)}getFutureActions(t,n){if(this.callee.config.allowFutureScene===!1&&n.allowFutureScene===!1)return[...super.getFutureActions(t,n)];if(this.type===ne.break||this.type===ne.waitForClick||this.type===ne.label||this.type===ne.jump)return super.getFutureActions(t,n);let i=this.contentNode.getContent()[0],r=super.getFutureActions(t,n);return[...i??[],...r]}stringify(t,n,i){if(this.type===ne.break)return super.stringifyWithContent("Control","break");if(this.type===ne.waitForClick)return super.stringifyWithContent("Control","waitForClick");if(this.type===ne.label||this.type===ne.jump){let[a]=this.contentNode.getContent(),c=this.type===ne.label?"label":"jump";return super.stringifyWithContent("Control",`${c}(${a})`)}let r=this.contentNode,[s]=r.getContent();return super.stringifyWithContent("Control",s.map(a=>a.stringify(t,n,i)).join(";"))}};$o.ActionTypes=ne;var oe=$o;var je=class o extends ce{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()}static label(t){return new o().label(t)}static jump(t){return new o().jump(t)}do(t){return this.push(oe.ActionTypes.do,t)}doAsync(t){return this.push(oe.ActionTypes.doAsync,t)}any(t){return this.pushUnchained(oe.ActionTypes.any,t)}all(t){return this.pushUnchained(oe.ActionTypes.all,t)}allAsync(t){return this.pushUnchained(oe.ActionTypes.allAsync,t)}repeat(t,n){return this.pushUnchained(oe.ActionTypes.repeat,n,t)}whileLoop(t,n){let i=j.from(t);return this.pushWithLambda(oe.ActionTypes.while,n,i)}breakLoop(){let t=new oe(this.chain(),oe.ActionTypes.break,new x().setContent([]));return this.chain(t)}sleep(t){return this.push(oe.ActionTypes.sleep,[],t)}waitForClick(){let t=new oe(this.chain(),oe.ActionTypes.waitForClick,new x().setContent([]));return this.chain(t)}label(t){let n=new oe(this.chain(),oe.ActionTypes.label,new x().setContent([t]));return this.chain(n)}jump(t){let n=new oe(this.chain(),oe.ActionTypes.jump,new x().setContent([t]));return this.chain(n)}push(t,n,...i){let r=this.narrativeToActions(n),s=new oe(this.chain(),t,new x().setContent([this.construct(r),...i]));return this.chain(s)}pushUnchained(t,n,...i){let r=this.narrativeToActions(n),s=new oe(this.chain(),t,new x().setContent([r,...i]));return this.chain(s)}pushWithLambda(t,n,i){let r=this.narrativeToActions(n),s=new oe(this.chain(),t,new x().setContent([r,i]));return this.chain(s)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?Yt.say(n).getActions():ze.toActions([n]))}};var K=class K extends ct{static get DefaultUserConfig(){return K._defaultUserConfig??(K._defaultUserConfig=new B({name:"(anonymous)",autoInit:!0,src:K.DefaultImagePlaceholder,autoFit:!1,layer:void 0,...J.DefaultTransformState.getDefaultConfig()},{position:e=>N.tryParsePosition(e)}))}static getInitialSrc(e){if(this.isLayeredDefinition(e.src)||this.isTagDefinition(e.src))return[...e.src.defaults];let t=e.src;return w.isStaticImageData(t)?w.srcToURL(t):w.isColor(t)?t:w.isImageSrc(t)?w.srcToURL(t):K.DefaultImagePlaceholder}static isTagSrc(e){return!!e.config.src}static isLayeredSrc(e){return!!e.config.src?.slots}static isSrcDefinitionObject(e){return typeof e=="object"&&e!==null&&!w.isImageSrc(e)&&!w.isColor(e)}static isLayeredDefinition(e){return this.isSrcDefinitionObject(e)&&"layers"in e}static isTagDefinition(e){return this.isSrcDefinitionObject(e)&&"resolve"in e}static isLayerVariants(e){return typeof e=="object"&&e!==null}static isStaticSrc(e){let t=e.userConfig.get().src;return!this.isTagSrc(e)&&(w.isImageSrc(t)||w.isColor(t))}static getSrcURL(e){return typeof e=="string"?e:K.isLayeredSrc(e)?null:K.isTagSrc(e)&&e.config.src.resolve?K.getSrcFromTags(e.state.currentSrc,e.config.src.resolve):K.isStaticSrc(e)?w.isStaticImageData(e.state.currentSrc)?w.srcToURL(e.state.currentSrc):w.isColor(e.state.currentSrc)?null:e.state.currentSrc:null}static getSrcFromTags(e,t){return t(...e)}static getSrcURLs(e,t){let n=e.config.src?.slots;if(!n)return[];let i=new Set(t??e.state.currentSrc);return n.map(r=>K.resolveLayerSlot(r,i))}static resolveLayerSlot(e,t){if(e===null||typeof e=="string")return e;if(typeof e=="function")return e(t);for(let[n,i]of Object.entries(e))if(t.has(n))return i;return null}static getAllLayerSrc(e){let t=e.config.src?.slots;if(!t)return[];let n=[];for(let i of t)if(typeof i=="string")n.push(i);else if(K.isLayerVariants(i))for(let r of Object.values(i))r!==null&&n.push(r);return n}static fromSrc(e){return new K({src:e})}constructor(e={}){super();let t=K.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 je,n=>{if(w.isImageSrc(e)||w.isColor(e)){if(w.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 Se(n,Se.ActionTypes.setAppearance,new x().setContent([e,t?.copy()]));return n.chain(i).chain(this._flush())}})}darken(e,t,n){return this.combineActions(new je,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 ie("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:K.StateSerializer.serialize(this.state),transformState:J.TransformStateSerializer.serialize(this.transformState.get())}}fromData(e){return this.state=K.StateSerializer.deserialize(e.state),this.transformState=J.deserialize(e.transformState),this}_applyTransition(e,t){return new Ie(this.chain(),ye.applyTransition,new x().setContent([e,t]))}_init(e,t){return new Ie(this.chain(),ye.init,new x().setContent([e,t||this.config.layer||null]))}_initWearable(e){return new Se(this.chain(),Se.ActionTypes.initWearable,new x().setContent([e]))}_flush(){return new Se(this.chain(),Se.ActionTypes.flush,new x)}reset(){return super.reset(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(this.userConfig),this}resolveTags(e,t){if(!K.isTagSrc(this))throw new Error(`Tag not defined
62
+ at Say.tsx: onElementClick`);return}let f=y=>{y.repeat||r.config.gameState.isAdvanceSuspended()||i.keyMap.match("nextAction",y.key)&&r.requestComplete()};window.addEventListener("keydown",f);let m=r.events.on(Ne.Events.simulateClick,()=>{c.current&&c.current.click()});return()=>{window.removeEventListener("keydown",f),m.cancel()}},[r,l]),$c(()=>{let f=i.preference.onPreferenceChange(re.Preferences.autoForward,m=>{m&&r.isEnded()?r.tryScheduleAutoForward():r.cancelAutoForward()});return()=>{f.cancel()}},[r]),At.createElement("div",{"data-element-type":"dialog",className:"absolute w-full h-full"},At.createElement("div",{className:yd("absolute bottom-0 w-full h-full",!a&&"invisible pointer-events-auto"),onClick:h,style:{...Hi(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},At.createElement(Yr,{value:d},At.createElement(Td.div,{...n,initial:r.config.suppressInitialAnimation?!1:e,transition:r.config.suppressInitialAnimation&&u?{duration:0}:t},o)),At.createElement("div",{"data-element-type":"dialog-overlay",className:"absolute inset-0 pointer-events-none",ref:p})))}function jc({children:o,...e}){let t=Pt();return!t.config.action.sentence||!t.config.action.words?null:At.createElement(Cd,{...e},o)}var hp=jc;function qc(){return At.createElement(jc,null,At.createElement("div",{className:"dialog-content",style:{display:"flex",alignItems:"flex-start",gap:16,width:"100%",height:"100%"}},At.createElement(Hr,null),At.createElement("div",{className:"dialog-text-content",style:{minWidth:0,flex:"1 1 auto"}},At.createElement(Xt,null),At.createElement(pn,{...Ad}))))}var Si={say:qc,menu:Lc,notification:Oc,nvlDialog:qr};var zo=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 Ti=class{constructor(e={}){this.keyMap=e;this.events=new q}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 Yc=(e=>(e.game="game",e))(Yc||{}),Je=class Je{constructor(e){this.hooks=new Ii;this.liveGame=null;this.sideEffect=[];this.freezeFields=[];this.preference=new ai(Je.DefaultPreference);this.audioBuses=new Xn(()=>this.config.audioBuses??[],na(this.preference));this.keyMap=new Ti({skipAction:["Control"],nextAction:[" "]});this.lifecycleEvents=new q;this.puppetBackends=new Oo;this.preloadCompleteContext=null;this.firstSceneReadyContext=null;this.config=z(Je.DefaultConfig,e),this.plugins=new zo(this),this.router=new ln(this)}configure(e){let[t,n]=$s(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=z(this.config,t),Object.prototype.hasOwnProperty.call(t,"audioBuses")&&this.audioBuses.invalidate(),this.getLiveGame().getGameState()?.events.emit(E.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}registerPuppetBackend(e){return this.puppetBackends.register(e),this}getPuppetBackend(e){return this.puppetBackends.get(e)}listPuppetBackends(){return this.puppetBackends.list()}getPuppetBackendRegistry(){return this.puppetBackends}onPreloadComplete(e){return this.lifecycleEvents.on(Je.LifecycleEventTypes["event:game.preloadComplete"],e)}oncePreloadComplete(e){return this.lifecycleEvents.once(Je.LifecycleEventTypes["event:game.preloadComplete"],e)}whenPreloadComplete(){return this.preloadCompleteContext?Promise.resolve(this.preloadCompleteContext):new Promise(e=>{this.oncePreloadComplete(e)})}isPreloadComplete(){return this.preloadCompleteContext!==null}onFirstSceneReady(e){return this.lifecycleEvents.on(Je.LifecycleEventTypes["event:game.firstSceneReady"],e)}onceFirstSceneReady(e){return this.lifecycleEvents.once(Je.LifecycleEventTypes["event:game.firstSceneReady"],e)}whenFirstSceneReady(){return this.firstSceneReadyContext?Promise.resolve(this.firstSceneReadyContext):new Promise(e=>{this.onceFirstSceneReady(e)})}isFirstSceneReady(){return this.firstSceneReadyContext!==null}markPreloadComplete(e){return this.preloadCompleteContext?!1:(this.preloadCompleteContext=e,this.lifecycleEvents.emit(Je.LifecycleEventTypes["event:game.preloadComplete"],e),!0)}markFirstSceneReady(e){return this.firstSceneReadyContext?!1:(this.firstSceneReadyContext=e,this.lifecycleEvents.emit(Je.LifecycleEventTypes["event:game.firstSceneReady"],e),!0)}getLiveGame(){if(!this.liveGame){let e=this.createLiveGame();return this.liveGame=e,e}return this.liveGame}dispose(){this.audioBuses.dispose(),this.plugins.unregisterAll(),this.liveGame?.dispose(),this.sideEffect.forEach(e=>e())}addSideEffect(e){this.sideEffect.push(e)}createLiveGame(){return new Ht(this)}};Je.defaultSettings={volume:1},Je.DefaultPreference={autoForward:!1,skip:!0,showDialog:!0,gameSpeed:1,cps:10,voiceVolume:1,voiceFadeDuration:0,voiceEndMode:"stop",bgmVolume:1,soundVolume:1,globalVolume:1,skipDelay:0,skipInterval:100},Je.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"},Je.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,allowSkipSceneTransition:!0,allowSkipTextTransform:!0,allowSkipTextTransition:!0,allowSkipLayersTransform:!0,allowSkipVideo:!1,animationPropagate:!1,dialogWidth:1920,dialogHeight:1080*.2,notification:Si.notification,menu:Si.menu,dialog:Si.say,nvlDialog:Si.nvlDialog,onError:e=>{console.error(e)},stage:null,maxStackModelLoop:1e3,maxActionHistory:100,audioBuses:[]},Je.GameSettingsNamespace=Yc,Je.LifecycleEventTypes={"event:game.preloadComplete":"event:game.preloadComplete","event:game.firstSceneReady":"event:game.firstSceneReady"};var re=Je;var $o=class $o extends ${constructor(){super(...arguments);this._jumpTarget=null}setJumpTarget(t){return this._jumpTarget=t,this}getJumpTarget(){return this._jumpTarget}static executeActionsAsync(t,n){let i=t.game.getLiveGame().requestAsyncStackModel([{type:n.type,node:n.contentNode}]);return t.game.getLiveGame().executeAsyncStackModel(i)}checkActionChain(t){if(t.some(n=>!!n.contentNode.getChild()))throw new Error("Invalid action chain. Actions are chained unexpectedly.");return t}executeAction(t,n){let i=this.contentNode,[r]=i.getContent();if(this.type===ne.do)return r.length===0?{type:this.type,node:this.contentNode.getChild()}:[{type:this.type,node:this.contentNode.getChild()},{type:this.type,node:r[0].contentNode}];if(this.type===ne.doAsync){if(r.length===0)return super.executeAction(t,n);let s=$o.executeActionsAsync(t,r[0]);return t.timelines.attachTimeline(s),super.executeAction(t,n)}else if(this.type===ne.any){if(r.length===0)return{type:this.type,node:this.contentNode.getChild()};let s=this.checkActionChain(r).map(a=>t.game.getLiveGame().createStackModel([{type:a.type,node:a.contentNode}]));return{type:this.type,node:this.contentNode.getChild(),wait:{type:"any",stackModels:s}}}else if(this.type===ne.all){if(r.length===0)return{type:this.type,node:this.contentNode.getChild()};let s=this.checkActionChain(r).map(a=>t.game.getLiveGame().createStackModel([{type:a.type,node:a.contentNode}]));return{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:s}}}else if(this.type===ne.allAsync){if(r.length===0)return{type:this.type,node:this.contentNode.getChild()};let s=this.checkActionChain(r).map(a=>t.game.getLiveGame().requestAsyncStackModel([{type:a.type,node:a.contentNode}]));return t.timelines.attachTimeline(S.all(...s.map(a=>t.game.getLiveGame().executeAsyncStackModel(a)))),super.executeAction(t,n)}else if(this.type===ne.repeat){let[s,a]=this.contentNode.getContent();if(a<=0||s.length===0)return super.executeAction(t,n);let c=Xe.createCountLoop(t.game.getLiveGame(),a,this.checkActionChain(s));return t.logger.debug("ControlAction","repeat",s,a),{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[c]}}}else if(this.type===ne.while){let[s,a]=this.contentNode.getContent();if(s.length===0)return super.executeAction(t,n);if(!a.evaluate({gameState:t}).value)return super.executeAction(t,n);let c=Xe.createConditionLoop(t.game.getLiveGame(),a,this.getId(),this.checkActionChain(s));return t.logger.debug("ControlAction","while",s),{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[c]}}}else if(this.type===ne.break){if(!n.stackModel.isLoop())throw new Error("Control.breakLoop() can only be used inside a loop (repeat/while)");return n.stackModel.breakLoop(),{type:this.type,node:null}}else if(this.type===ne.sleep){let[,s]=this.contentNode.getContent();if(t.isFastForwarding())return{type:this.type,node:this.contentNode.getChild()};let a;typeof s=="number"?a=S.delay(s):S.isAwaitable(s)?a=s:a=S.fromPromise(s);let c=new S,l=new xe(a);return t.timelines.attachTimeline(l),a.then(()=>{c.resolve({type:this.type,node:this.contentNode.getChild()})}),c.onSkipControllerRegister(u=>{u.onAbort(()=>{l.abort()})}),c}else if(this.type===ne.waitForClick){if(t.consumeStageClick())return{type:this.type,node:this.contentNode.getChild()};let s=new S,a=new S,c=new xe(a);t.timelines.attachTimeline(c);let l=t.game.preference,u=l.getPreference(re.Preferences.autoForward),d=l.getPreference(re.Preferences.gameSpeed),p=u?t.game.config.autoForwardDelay/d:null,h=!1,f=null,m=null,y=null,b=()=>{m?.cancel(),y?.cancel(),f&&(clearTimeout(f),f=null)},v=()=>{h||(h=!0,b(),a.resolve())};return m=t.events.on(E.EventTypes["event:state.player.stageClick"],v),y=t.events.on(E.EventTypes["event:state.player.skip"],v),p!==null&&(f=setTimeout(v,p)),a.then(()=>{s.resolve({type:this.type,node:this.contentNode.getChild()})}),s.onSkipControllerRegister(g=>{g.onAbort(()=>{h||(h=!0,b(),c.abort())})}),s}else{if(this.type===ne.label)return super.executeAction(t,n);if(this.type===ne.jump){let s=this._jumpTarget;if(!s){let[l]=this.contentNode.getContent();throw new Ve(`Jump target label "${l}" was not resolved. This usually means the story was not constructed before playing.`)}let a=t.getLiveGame(),c=a.getStackModelForce().serialize();return t.actionHistory.push({action:this,stackModel:n.stackModel},l=>{let[u]=a.constructMaps();a.getStackModelForce().deserialize(l,u)},[c]),a.clearMainStack().getStackModelForce().push({type:this.type,node:s.contentNode}),null}}throw new Error("Unknown control action type: "+this.type)}getFutureActions(t,n){if(this.callee.config.allowFutureScene===!1&&n.allowFutureScene===!1)return[...super.getFutureActions(t,n)];if(this.type===ne.break||this.type===ne.waitForClick||this.type===ne.label||this.type===ne.jump)return super.getFutureActions(t,n);let i=this.contentNode.getContent()[0],r=super.getFutureActions(t,n);return[...i??[],...r]}stringify(t,n,i){if(this.type===ne.break)return super.stringifyWithContent("Control","break");if(this.type===ne.waitForClick)return super.stringifyWithContent("Control","waitForClick");if(this.type===ne.label||this.type===ne.jump){let[a]=this.contentNode.getContent(),c=this.type===ne.label?"label":"jump";return super.stringifyWithContent("Control",`${c}(${a})`)}let r=this.contentNode,[s]=r.getContent();return super.stringifyWithContent("Control",s.map(a=>a.stringify(t,n,i)).join(";"))}};$o.ActionTypes=ne;var oe=$o;var je=class o extends ce{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()}static label(t){return new o().label(t)}static jump(t){return new o().jump(t)}do(t){return this.push(oe.ActionTypes.do,t)}doAsync(t){return this.push(oe.ActionTypes.doAsync,t)}any(t){return this.pushUnchained(oe.ActionTypes.any,t)}all(t){return this.pushUnchained(oe.ActionTypes.all,t)}allAsync(t){return this.pushUnchained(oe.ActionTypes.allAsync,t)}repeat(t,n){return this.pushUnchained(oe.ActionTypes.repeat,n,t)}whileLoop(t,n){let i=j.from(t);return this.pushWithLambda(oe.ActionTypes.while,n,i)}breakLoop(){let t=new oe(this.chain(),oe.ActionTypes.break,new x().setContent([]));return this.chain(t)}sleep(t){return this.push(oe.ActionTypes.sleep,[],t)}waitForClick(){let t=new oe(this.chain(),oe.ActionTypes.waitForClick,new x().setContent([]));return this.chain(t)}label(t){let n=new oe(this.chain(),oe.ActionTypes.label,new x().setContent([t]));return this.chain(n)}jump(t){let n=new oe(this.chain(),oe.ActionTypes.jump,new x().setContent([t]));return this.chain(n)}push(t,n,...i){let r=this.narrativeToActions(n),s=new oe(this.chain(),t,new x().setContent([this.construct(r),...i]));return this.chain(s)}pushUnchained(t,n,...i){let r=this.narrativeToActions(n),s=new oe(this.chain(),t,new x().setContent([r,...i]));return this.chain(s)}pushWithLambda(t,n,i){let r=this.narrativeToActions(n),s=new oe(this.chain(),t,new x().setContent([r,i]));return this.chain(s)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?Yt.say(n).getActions():ze.toActions([n]))}};var K=class K extends ct{static get DefaultUserConfig(){return K._defaultUserConfig??(K._defaultUserConfig=new B({name:"(anonymous)",autoInit:!0,src:K.DefaultImagePlaceholder,autoFit:!1,layer:void 0,...J.DefaultTransformState.getDefaultConfig()},{position:e=>N.tryParsePosition(e)}))}static getInitialSrc(e){if(this.isLayeredDefinition(e.src)||this.isTagDefinition(e.src))return[...e.src.defaults];let t=e.src;return w.isStaticImageData(t)?w.srcToURL(t):w.isColor(t)?t:w.isImageSrc(t)?w.srcToURL(t):K.DefaultImagePlaceholder}static isTagSrc(e){return!!e.config.src}static isLayeredSrc(e){return!!e.config.src?.slots}static isSrcDefinitionObject(e){return typeof e=="object"&&e!==null&&!w.isImageSrc(e)&&!w.isColor(e)}static isLayeredDefinition(e){return this.isSrcDefinitionObject(e)&&"layers"in e}static isTagDefinition(e){return this.isSrcDefinitionObject(e)&&"resolve"in e}static isLayerVariants(e){return typeof e=="object"&&e!==null}static isStaticSrc(e){let t=e.userConfig.get().src;return!this.isTagSrc(e)&&(w.isImageSrc(t)||w.isColor(t))}static getSrcURL(e){return typeof e=="string"?e:K.isLayeredSrc(e)?null:K.isTagSrc(e)&&e.config.src.resolve?K.getSrcFromTags(e.state.currentSrc,e.config.src.resolve):K.isStaticSrc(e)?w.isStaticImageData(e.state.currentSrc)?w.srcToURL(e.state.currentSrc):w.isColor(e.state.currentSrc)?null:e.state.currentSrc:null}static getSrcFromTags(e,t){return t(...e)}static getSrcURLs(e,t){let n=e.config.src?.slots;if(!n)return[];let i=new Set(t??e.state.currentSrc);return n.map(r=>K.resolveLayerSlot(r,i))}static resolveLayerSlot(e,t){if(e===null||typeof e=="string")return e;if(typeof e=="function")return e(t);for(let[n,i]of Object.entries(e))if(t.has(n))return i;return null}static getAllLayerSrc(e){let t=e.config.src?.slots;if(!t)return[];let n=[];for(let i of t)if(typeof i=="string")n.push(i);else if(K.isLayerVariants(i))for(let r of Object.values(i))r!==null&&n.push(r);return n}static fromSrc(e){return new K({src:e})}constructor(e={}){super();let t=K.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 je,n=>{if(w.isImageSrc(e)||w.isColor(e)){if(w.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 Se(n,Se.ActionTypes.setAppearance,new x().setContent([e,t?.copy()]));return n.chain(i).chain(this._flush())}})}darken(e,t,n){return this.combineActions(new je,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 ie("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:K.StateSerializer.serialize(this.state),transformState:J.TransformStateSerializer.serialize(this.transformState.get())}}fromData(e){return this.state=K.StateSerializer.deserialize(e.state),this.transformState.resetTo(J.deserialize(e.transformState).get()),this}_applyTransition(e,t){return new Ie(this.chain(),ye.applyTransition,new x().setContent([e,t]))}_init(e,t){return new Ie(this.chain(),ye.init,new x().setContent([e,t||this.config.layer||null]))}_initWearable(e){return new Se(this.chain(),Se.ActionTypes.initWearable,new x().setContent([e]))}_flush(){return new Se(this.chain(),Se.ActionTypes.flush,new x)}reset(){return super.reset(),this.state=this.getInitialState(),this.transformState.resetTo(this.getInitialTransformState(this.userConfig).get()),this}resolveTags(e,t){if(!K.isTagSrc(this))throw new Error(`Tag not defined
63
63
  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}_setAppearanceSync(e){if(w.isImageSrc(e)||w.isColor(e)){if(w.isColor(e)&&!this.config.isBackground)throw new ie("Color src is not allowed for non-background image");this.state.currentSrc=e;return}if(!K.isTagSrc(this))throw this._mixedSrcError();let t=this.state.currentSrc,n=this.resolveTags(t,e);this.state.currentSrc=n}_mixedSrcError(){throw new ie(`Trying to mix src and tags
64
64
  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
65
65
  Wearable must be an Image with isWearable set to true
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "narraleaf-react",
3
- "version": "0.31.1",
3
+ "version": "0.31.2",
4
4
  "description": "A React visual novel player framework",
5
5
  "type": "module",
6
6
  "main": "./dist/main.js",