narraleaf-react 0.8.5 → 0.8.6

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 +18 -18
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -1,9 +1,9 @@
1
1
  var ce={action:"displayable:action",applyTransform:"displayable:applyTransform",applyTransition:"displayable:applyTransition",init:"displayable:init"},Rn={say:"character:say",action:"character:action",setName:"character:setName"},ee={action:"scene:action",init:"scene:init",exit:"scene:exit",jumpTo:"scene:jumpTo",setBackgroundMusic:"scene:setBackgroundMusic",preUnmount:"scene:preUnmount",transitionToScene:"scene:transitionToScene"};var ke={action:"image:action",setSrc:"image:setSrc",flush:"image:flush",initWearable:"image:initWearable",setAppearance:"image:setAppearance",setDarkness:"image:setDarkness"},Di={action:"condition:action"},Ri={action:"script:action"},Li={action:"menu:action"},mt={action:"sound:action",play:"sound:play",stop:"sound:stop",setVolume:"sound:setVolume",setRate:"sound:setRate",pause:"sound:pause",resume:"sound:resume"},Oe={action:"control:action",do:"control:do",doAsync:"control:doAsync",any:"control:any",all:"control:all",allAsync:"control:allAsync",repeat:"control:repeat",sleep:"control:sleep"},Ln={action:"text:action",setText:"text:setText",setFontSize:"text:setFontSize"},Xt={action:"persistent:action",set:"persistent:set",assign:"persistent:assign"},vt={action:"layer:action",setZIndex:"layer:setZIndex"},Nt={action:"video:action",show:"video:show",hide:"video:hide",play:"video:play",pause:"video:pause",resume:"video:resume",stop:"video:stop",seek:"video:seek"};var Ii=(d=>(d[d.string=0]="string",d[d.number=1]="number",d[d.boolean=2]="boolean",d[d.object=3]="object",d[d.array=4]="array",d[d.function=5]="function",d[d.symbol=6]="symbol",d[d.undefined=7]="undefined",d[d.null=8]="null",d[d.date=9]="date",d[d.regexp=10]="regexp",d[d.other=11]="other",d))(Ii||{}),No=function(s){return typeof s=="string"?0:typeof s=="number"?1:typeof s=="boolean"?2:typeof s=="object"?Array.isArray(s)?4:s===null?8:s instanceof Date?9:s instanceof RegExp?10:3:typeof s=="function"?5:typeof s=="symbol"?6:typeof s>"u"?7:11};No.DataTypes=Ii;function R(s,e,...t){let n=(r,a)=>Object.prototype.hasOwnProperty.call(r,a),o={},i=(r,a,c)=>No(a)===3&&No(c)===3?a.constructor!==Object||c.constructor!==Object?c||a:R(a,c):Array.isArray(a)&&Array.isArray(c)?c&&c.length>0?[...c]:[...a]:a===void 0&&Array.isArray(c)?[...c]:c===void 0?Array.isArray(a)?[...a]:a:Array.isArray(c)?[...c]:c;for(let r in s)n(s,r)&&(o[r]=i(r,s[r],e[r]));for(let r in e)n(e,r)&&!n(o,r)&&(typeof e[r]=="object"&&e[r]!==null?e[r].constructor===Object?o[r]=R({},e[r]):Array.isArray(e[r])?o[r]=[...e[r]]:o[r]=e[r]:o[r]=e[r]);if(t.length){let[r,...a]=t;return R(o,r,...a)}return o}var Te=class Te{constructor(e=n=>n,t){this.solved=!1;this.aborted=!1;this.listeners=[];this.onRegisterSkipController=[];this.receiver=e,this.skipController=t,this.__stack=Ho()}static isAwaitable(e){return e instanceof Te}static fromPromise(e){let t=new Te;return e.then(n=>t.resolve(n)),t}static resolve(e){let t=new Te;return t.resolve(e),t}static delay(e){let t=new Te;return setTimeout(()=>t.resolve(),e),t}static create(e){let t=new Te;return e(t),t}static wait(e){let t=new Te;return e.then(()=>t.resolve()),t}static race(e){let t=new Te;return e.length===0?(t.resolve(void 0),t):(e.forEach(n=>{n.then(o=>{e.forEach(i=>{i!==n&&i.skipController?.abort()}),t.resolve(o)})}),t.registerSkipController(new L(()=>{e.forEach(n=>n.skipController?.abort())})),t)}static forward(e,t,n){let o=new Te().registerSkipController(n||new L(()=>t));e.then(()=>o.resolve(t));let i=e.skipController?.onAbort(()=>{o.skipController?.abort(),i?.cancel(),r?.cancel()}),r=o.skipController?.onAbort(()=>{e.skipController?.abort(),i?.cancel(),r?.cancel()});return o}static toPromise(e){return new Promise(t=>{e.then(t)})}static toPromiseForce(e){return new Promise(t=>{e.onSettled(t)})}static any(...e){let t=new Te;return e.forEach(n=>{n.onSettled(()=>t.resolve())}),t}static all(...e){let t=new Te,n=0;return e.forEach(o=>{o.onSettled(()=>{n++,n===e.length&&t.resolve()})}),t}registerSkipController(e){this.skipController=e;for(let t of this.onRegisterSkipController)t(e);return this}resolve(e){if(!this.solved){this.result=this.receiver(e),this.solved=!0,this.skipController&&this.skipController.cancel();for(let t of this.listeners)t(this.result)}}then(e){return this.solved?e(this.result):this.pushListener(e),this}onSettled(e){if(this.solved)e();else{this.pushListener(e);let t=[];return t.push(this.onSkipControllerRegister(n=>{t.push(n.onAbort(()=>{e()}))})),{cancel:()=>{t.forEach(n=>n.cancel()),this.offListener(e)}}}return{cancel:()=>{}}}onSkipControllerRegister(e){return this.skipController?e(this.skipController):this.onRegisterSkipController.push(e),{cancel:()=>{this.offSkipControllerRegister(e)}}}offSkipControllerRegister(e){let t=this.onRegisterSkipController.indexOf(e);return t!==-1&&this.onRegisterSkipController.splice(t,1),this}abort(){return this.aborted=!0,this.skipController?this.skipController.abort():this.result}isSolved(){return this.solved&&!this.aborted}isAborted(){return this.aborted}isSettled(){return this.solved||this.aborted}pushListener(e){return this.listeners.length>=Te.maxListeners&&console.warn("NarraLeaf-React: Awaitable has too many listeners, this may cause performance issues."),this.listeners.push(e),this}offListener(e){let t=this.listeners.indexOf(e);return t!==-1&&this.listeners.splice(t,1),this}};Te.nothing=e=>e,Te.maxListeners=8;var h=Te;function Mi(s){let e=new WeakSet;function t(n){if(n===null||typeof n!="object")return n;if(e.has(n))return;if(e.add(n),Array.isArray(n)){let i=[];for(let r of n)i.push(t(r));return i}let o={};for(let i in n)Object.prototype.hasOwnProperty.call(n,i)&&(o[i]=t(n[i]));return o}return t(s)}function Ct(s){return typeof s=="string"?s:`#${(s.r||0).toString(16).padStart(2,"0")}${(s.g||0).toString(16).padStart(2,"0")}${(s.b||0).toString(16).padStart(2,"0")}${s.a===void 0?"":s.a.toString(16).padStart(2,"0")}`}var F=class{constructor(){this.events={};this.maxListeners=10}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),this.events[e].length>this.maxListeners&&console.warn(`NarraLeaf-React: Event ${e} has more than ${this.maxListeners} listeners (total: ${this.events[e].length}), this may cause performance issues.`),this.emit("event:EventDispatcher.register",e,t),{type:e,listener:t,cancel:()=>{this.off(e,t)}}}depends(e){return{cancel:()=>{e.forEach(t=>t.cancel())}}}off(e,t){this.events[e]&&(this.events[e]=this.events[e].filter(n=>n!==t))}emit(e,...t){if(!this.events[e])return 0;let n=this.events[e].length;return this.events[e].forEach(o=>{o(...t)}),n}once(e,t){let n=(...o)=>{t(...o),this.off(e,n)};return this.on(e,n)}async any(e,...t){if(this.events[e]||(this.events[e]=[]),this.events[e].length>0){await Promise.all(this.events[e].map(n=>n(...t)));return}return new Promise(n=>{let o="event:EventDispatcher.register",i=this.on(o,(r,a)=>{if(r===e){this.off(o,i);let c=a?.(...t);c!==null&&typeof c=="object"&&c.then?c.then(n):n(c)}}).listener})}setMaxListeners(e){return this.maxListeners=e,this}hasListeners(e){return this.events[e]?.length>0}clear(){this.events={}}};function Ho(s=1){let e=new Error().stack;return e?e.split(`
2
2
  `).slice(s+1).join(`
3
- `).trim():""}function Kn(s){return new Promise(e=>setTimeout(e,s))}var Un=class Un{constructor(e){this.abortHandler=e;this.events=new F;this.aborted=!1}abort(...e){this.aborted||(this.aborted=!0,this.abortHandler(...e),this.events.emit(Un.EventTypes["event:skipController.abort"]))}isAborted(){return this.aborted}cancel(){this.aborted=!0}onAbort(e){return this.events.on("event:skipController.abort",e)}};Un.EventTypes={"event:skipController.abort":"event:skipController.abort"};var L=Un;var Jt=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}},Ht=class{constructor(){this.locks=[]}unlock(e){return e.unlock(),this.off(e),e}register(e){let t=e||new Jt;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 Fn(s,e,t={}){return s?e:t}function Gi(s,e){if(e<=0)return s;let t=null;return function(...n){t&&clearTimeout(t),t=setTimeout(()=>{s(...n)},e)}}var In=class{constructor(){this.taskToken=null}scheduleTask(e,t){this.taskToken&&this.taskToken.cancel();let n=!1,o=setTimeout(()=>{n||e()},t);return this.taskToken={cancel:()=>{clearTimeout(o),n=!0},isCancelled:()=>n},this.taskToken}cancelTask(){return this.taskToken&&(this.taskToken.cancel(),this.taskToken=null),this}};function Ni(s,e){let t=[];for(let n=0;n<Math.max(s.length,e.length);n++)n<s.length&&t.push(s[n]),n<e.length&&t.push(e[n]);return t}async function Hi(s,e){return new Promise((t,n)=>{fetch(s,e).then(o=>o.blob()).then(o=>{let i=new FileReader;i.onload=()=>{t(i.result)},i.readAsDataURL(o)}).catch(n)})}var Yt=class{constructor(e,t){this.concurrency=e;this.delay=t;this.tasks=[]}addTask(e){this.tasks.push(e)}async start(){let e=async()=>{if(this.tasks.length===0)return;let t=this.tasks.splice(0,this.concurrency);await Promise.all(t.map(n=>n())),await Kn(this.delay),await e()};await e()}};function Me(s){let e,t=Promise.resolve().then(()=>{e=s()});return()=>{t.then(()=>{e&&e()})}}function Ui(s,e){let t={};for(let n in s)e.includes(n)||(t[n]=s[n]);return t}var be=class s{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},o={...this.deserializer,...t};return new s(n,o)}};function Ki(s){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(s)}var ft=class extends h{constructor(t){super();this.tasks=[];t&&this.registerSkipController(t)}addTask(t){return t?(this.tasks.push(t),this):this}abort(){this.current&&this.current.abort(),this.tasks.forEach(([t,n])=>{n&&n.abort()}),super.abort()}resolve(){}run(){return this.current?this:(this.onTaskComplete(),this)}onTaskComplete(){if(this.tasks.length===0){super.resolve();return}let[t,n]=this.tasks.shift(),o=new h(h.nothing,n);this.current=o,this.current.then(()=>this.onTaskComplete()),t(o)}};function Fi(s){return s.constructor.name==="AsyncFunction"||Object.prototype.toString.call(s)==="[object AsyncFunction]"}function Uo(s){let e={};for(let t in s)s[t]!==void 0&&(e[t]=s[t]);return e}function Ko(s,e=new WeakSet){if(s===null||typeof s!="object"||Array.isArray(s)||s instanceof Date||s instanceof RegExp||Object.getPrototypeOf(s)!==Object.prototype||e.has(s))return!1;e.add(s);for(let t in s)if(Object.prototype.hasOwnProperty.call(s,t)){let n=s[t];if(n!==null&&typeof n=="object"&&!Ko(n,e)||typeof n=="function"||typeof n=="symbol")return!1}return!0}var Mn=class{constructor(e=""){this.prefix=e;this.counter=0}next(){return`${this.prefix?this.prefix+"-":""}${this.counter++}`}};function Oi(s=16){let e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=t.length;for(let o=0;o<s;o++)e+=t.charAt(Math.floor(Math.random()*n));return e}function Wi(s=16){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",t="";for(let n=0;n<s;n++)t+=e[Math.floor(Math.random()*e.length)];return t}var Gn=class{constructor(e=""){this.prefix=e;this.counter=0}generateId(){return`${this.prefix?this.prefix+"-":""}${this.counter++}`}},Nn=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 o=n.map(i=>i(...t));return()=>{o.forEach(i=>i&&i())}}rawTrigger(e,t){let n=this.hooks[e];if(!n)return()=>{};let o=n.map(i=>i(...t()));return()=>{o.forEach(i=>i&&i())}}};var Hn=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 Vi(s,e){let t={},n=[];for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&(e.includes(o)?n.push(o):t[o]=s[o]);return[t,n]}function zi(s){let e=3421674724,t=2216829733;for(let n=0;n<s.length;n++){let o=s.charCodeAt(n);e^=o;let i=e>>>0,r=t>>>0,a=435,c=16777216,l=i*a>>>0,f=i*c+r*a>>>0,p=r*c+(f>>>0)>>>0;e=l,t=p}return("00000000"+t.toString(16)).slice(-8)+("00000000"+e.toString(16)).slice(-8)}var Zt=class{constructor(e,t,n){this.callee=e,this.type=t,this.contentNode=n,this.__stack=Ho(),this._id=""}executeAction(e,t){return{type:this.type,node:this.contentNode.getChild()}}getId(){return this._id}setId(e){this._id=e}setContent(e){return this.contentNode.setContent(e),this}setContentNode(e){return this.contentNode=e,this}getFutureActions(e,t){let n=this.contentNode.getChild();return n&&n.action?[n.action]:[]}};Zt.ActionTypes={action:"action"};var M=class extends Zt{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 h(o=>o);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 Fo=class{constructor(e){this.type=e,this.content=void 0}setContent(e){return this.content=e,this}getContent(){return this.content}},S=class s extends Fo{static create(e){return new s().setContent(e)}static forEachParent(e,t){let n=new Set,o=e;for(;o&&!n.has(o);)n.add(o),t(o),o=o.getParent()}static forEachChild(e,t){let n=new Set,o=e;for(;o&&!n.has(o);)n.add(o),t(o),o=o.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 On={center:"center",left:"left",right:"right"};import{animate as ts}from"motion/react";var _t=(n=>(n.Left="left",n.Center="center",n.Right="right",n))(_t||{}),$i={left:"33.33%",center:"50%",right:"66.66%"},Ge=class Ge{static isUnknown(e){return e===Ge.Unknown}static D2PositionToCSS(e,t=!1,n=!1){let o=this.calc(e.y,e.yoffset),i=this.calc(e.x,e.xoffset),r=n?{bottom:o}:{top:o},a=t?{right:i}:{left:i};return this.wrap({...r,...a})}static calc(e,t){return!e||Ge.isUnknown(e)?"auto":t===void 0||Ge.isUnknown(t)?`calc(${e} + 0px)`:`calc(${typeof e=="number"?`${e}px`:e} + ${t}px)`}static toCoord2D(e){if(Ne.isCommonPositionType(e))return Ae.fromCommonPosition(e);if(Ae.isCoord2DPosition(e))return e;if(xt.isAlignPosition(e))return Ae.fromAlignPosition(e);if(typeof e=="object"&&["x","y","xoffset","yoffset"].some(t=>t in e)){let t=e;return new Ae(t)}else throw new Error("Invalid position type")}static orUnknown(e){return Ge.isUnknown(e)||e===void 0?Ge.Unknown:e}static mergePosition(e,t){let n=this.toCoord2D(e),o=this.toCoord2D(t);return Ae.merge(n,o)}static serializePosition(e){let t=this.toCoord2D(e);return{x:Ge.isUnknown(t.x)?0:t.x,y:Ge.isUnknown(t.y)?0:t.y,xoffset:Ge.isUnknown(t.xoffset)?0:t.xoffset,yoffset:Ge.isUnknown(t.yoffset)?0:t.yoffset}}static isRawCommonPositionType(e){return Object.values(_t).includes(e)}static isRawCoord2DPosition(e){return typeof e=="object"&&("x"in e||"y"in e||"xoffset"in e||"yoffset"in e)}static isRawAlignPosition(e){return typeof e=="object"&&("xalign"in e||"yalign"in e||"xoffset"in e||"yoffset"in e)}static isRawPosition(e){return this.isRawCommonPositionType(e)||this.isRawCoord2DPosition(e)||this.isRawAlignPosition(e)}static isPosition(e){return e instanceof Ne||e instanceof Ae||e instanceof xt}static rawPositionToCoord2D(e){if(this.isRawCommonPositionType(e))return Ae.fromCommonPosition(new Ne(e));if(this.isRawCoord2DPosition(e))return new Ae(e);if(this.isRawAlignPosition(e))return Ae.fromAlignPosition(e);throw new Error("Invalid position type")}static tryParsePosition(e){if(this.isPosition(e))return e;if(this.isRawPosition(e))return this.rawPositionToCoord2D(e);throw new Error("Invalid position type")}static wrap(e){return{left:"auto",top:"auto",right:"auto",bottom:"auto",...e}}};Ge.Unknown=Symbol("Unknown");var v=Ge,Wn=class Wn{static isCommonPositionType(e){return e instanceof Wn}constructor(e){this.position=e}toCSS(){return{x:$i[this.position],y:"50%",xoffset:0,yoffset:0}}};Wn.Positions=_t;var Ne=Wn,Ae=class s{static isCoord2DPosition(e){return e instanceof s}static fromCommonPosition(e){return new s({x:$i[e.position],y:"50%"})}static fromAlignPosition(e){let t=n=>!n||v.isUnknown(n)?v.Unknown:`${n*100}%`;return new s({x:t(e.xalign),y:t(e.yalign),xoffset:e.xoffset,yoffset:e.yoffset})}static merge(e,t){return new s({x:v.isUnknown(t.x)?e.x:t.x,y:v.isUnknown(t.y)?e.y:t.y,xoffset:v.isUnknown(t.xoffset)?e.xoffset:t.xoffset,yoffset:v.isUnknown(t.yoffset)?e.yoffset:t.yoffset})}constructor(e,t){typeof e=="object"?(this.x=v.orUnknown(e.x),this.y=v.orUnknown(e.y),this.xoffset=v.orUnknown(e.xoffset),this.yoffset=v.orUnknown(e.yoffset)):(this.x=v.orUnknown(e),this.y=v.orUnknown(t),this.xoffset=v.Unknown,this.yoffset=v.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}}},xt=class s{static isAlignPosition(e){return e instanceof s}constructor(e,t){typeof e=="object"?(this.xalign=v.orUnknown(e.xalign),this.yalign=v.orUnknown(e.yalign),this.xoffset=v.orUnknown(e.xoffset),this.yoffset=v.orUnknown(e.yoffset)):(this.xalign=v.orUnknown(e),this.yalign=v.orUnknown(t),this.xoffset=v.Unknown,this.yoffset=v.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:v.isUnknown(this.xalign)?this.xalign:`${this.xalign*100}%`,y:v.isUnknown(this.yalign)?this.yalign:`${this.yalign*100}%`,xoffset:this.xoffset,yoffset:this.yoffset}}};var N=class s{constructor(e,t){this.defaultConfig=e;this.handlers=t||{}}create(e={}){return new Oo(this.mergeWithDefaultConfig(e))}copy(){return new s(R({},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)?R({},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}},Oo=class s{constructor(e){this.config=e}get(){return this.config}copy(){return new s(R({},this.config))}join(e){let t=Ui(this.config,Object.keys(e));return new s(Object.assign(t,e instanceof s?e.get():e))}extract(e){let t={},n={};for(let o of e)t[o]=this.config[o];for(let o in this.config)e.includes(o)||(n[o]=this.config[o]);return[new s(t),new s(n)]}assign(e){return new s(Object.assign({},this.config,e))}};var ns={[On.left]:"25.33%",[On.center]:"50%",[On.right]:"75.66%"},We=class We{constructor(e={}){this.state={};this.locked=null;this.frozen=!1;this.state=e}static deserialize(e){return new We(We.TransformStateSerializer.deserialize(e))}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?v.toCoord2D(v.tryParsePosition(e||t)):v.mergePosition(v.tryParsePosition(e),v.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=We.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 Uo(O.constructStyle(e,this.state,t))}toStyle(e,t){return Uo(O.constructStyle(e,this.state,t))}serialize(){return We.TransformStateSerializer.serialize(this.state)}clone(){return new We(We.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=We.mergeState(this.state,t),this}forceOverwrite(e){return this.state=e,this}};We.DefaultTransformState=new N({scaleX:1,scaleY:1,zoom:1,rotation:0,position:new Ne("center"),opacity:0,alt:""}),We.TransformStateSerializer=new be({position:e=>v.serializePosition(v.tryParsePosition(e))},{position:e=>v.toCoord2D(e)});var re=We,ie=class ie{constructor(e,t){this.sequences=[];this.stagedChanges=[];if(Array.isArray(e))this.sequences.push(...e),this.config=Object.assign({},ie.defaultConfig,t||{});else{let[n,o]=[e,t||ie.defaultOptions];this.sequences.push({props:n,options:o||ie.defaultOptions}),this.config=Object.assign({},ie.defaultConfig)}}static isPosition(e){return Ne.isCommonPositionType(e)||Ae.isCoord2DPosition(e)||xt.isAlignPosition(e)}static immediate(e){return new ie(e,{duration:0,ease:"linear"})}static left(e,t){return new ie({position:Ne.Positions.Left},{duration:e,ease:t})}static right(e,t){return new ie({position:Ne.Positions.Right},{duration:e,ease:t})}static center(e,t){return new ie({position:Ne.Positions.Center},{duration:e,ease:t})}static create(e){return new ie([],e)}static positionToCSS(e,t,n){return e?v.isRawPosition(e)?v.D2PositionToCSS(v.rawPositionToCoord2D(e),n,t):v.D2PositionToCSS(e.toCSS(),n,t):{}}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?v.toCoord2D(v.tryParsePosition(e||t)):v.mergePosition(v.tryParsePosition(e),v.tryParsePosition(t))}static mergeState(e,t){let n=this.mergePosition(e.position,t.position);return{...R(e,t),position:n}}static propToCSSTransform(e,t,n){let{invertY:o,invertX:i}=e.getStory().getInversionConfig(),{translate:r=[]}=n||{},a=t.zoom??1,c=function(d,g,u){return typeof d>"u"?typeof u<"u"?g(u):"":g(d)},l=r[0]||(i?"":"-")+"50%",f=r[1]||(o?"":"-")+"50%";return[`translate(${l}, ${f})`,c(t.rotation,d=>`rotate(${d}deg)`,0),c(t.scaleX,d=>`scaleX(${d*a})`,1),c(t.scaleY,d=>`scaleY(${d*a})`,1)].filter(Boolean).join(" ")}static constructStyle(e,t,n){let{invertY:o,invertX:i}=e.getStory().getInversionConfig(),{overwrite:r}=n||{};return{...ie.positionToCSS(t.position,o,i),opacity:t.opacity,color:"fontColor"in t&&t.fontColor?Ct(t.fontColor):void 0,transform:ie.propToCSSTransform(e,t),...r?r(t):{}}}animate(e,{gameState:t,ref:n,overwrites:o}){if(!n.current)throw new Error("No ref found when animating.");this.commit();let{finalState:i,sequences:r,options:a}=this.constructAnimation({gameState:t,transformState:e,overwrites:o,current:n.current});r.length||t.logger.warn("Transform","No sequences to animate.");let c=!1,l=e.lock(),f=ts(r,a),p=()=>{e.overwrite(l,i.get()).unlock(l),f.complete(),c=!0},d=new h().registerSkipController(new L(p)),g=()=>{c||e.overwrite(l,i.get()).unlock(l),c=!0,t.logger.debug("Transform","Transform Completed",e.toStyle(t,o)),d.resolve()};return f.then(g,u=>{t.logger.error("Failed to animate transform. "+(u?.toString?.()||""))}),f.play(),t.logger.debug("Transform","Ready to animate transform.",{finalState:i,sequences:r,options:a},this),d}repeat(e){let t=this.copy();return t.config.repeat||(t.config.repeat=1),t.config.repeat*=e,t}getOptions(e){if(!e)return{...ie.defaultOptions};let{duration:t,ease:n,delay:o,at:i}=e;return{duration:this.toSeconds(t,void 0),ease:n,delay:this.toSeconds(o,void 0),at:this.atToSeconds(i)}}constructAnimation({gameState:e,transformState:t,overwrites:n={},current:o}){let i=t.clone(),r=i.lock(),a=this.sequences.map(({props:c,options:l})=>{let f=i.assign(r,c).toFramesDefinition(e,n);return[o,f,this.getOptions(l)]});return{finalState:i.unlock(r).freeze(),sequences:a,options:this.getSequenceOptions()}}getSequenceOptions(){let{repeat:e,repeatDelay:t}=this.config;return{repeat:e,repeatDelay:this.toSeconds(t,void 0)}}copy(){return new ie(this.sequences,this.config)}commit(e){if(!this.stagedChanges.length)return this;let t=this.constructCommit(this.stagedChanges,this.getSequenceOptions());return this.sequences.push({props:t.props,options:{...this.getSequenceOptions(),...e}}),this.stagedChanges=[],this}zoom(e){return this.pushChange({key:"zoom",props:e})}scaleX(e){return this.pushChange({key:"scaleX",props:e})}scaleY(e){return this.pushChange({key:"scaleY",props:e})}scale(e,t){return this.pushChange({key:"scaleX",props:e}).pushChange({key:"scaleY",props:t})}rotation(e){return this.pushChange({key:"rotation",props:e})}position(e){return this.pushChange({key:"position",props:e})}opacity(e){return this.pushChange({key:"opacity",props:e})}fontColor(e){return this.pushChange({key:"fontColor",props:e})}constructCommit(e,t){let n={props:{},options:t};for(let o of e)n.props[o.key]=o.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 X("Invalid at definition. At definition must be a number or a string in the format of `+n` or `-n`.");let[o,i,r]=n,a=Number(r);if(isNaN(a))throw new X("Invalid number in at definition.");let c=a/1e3;return i==="+"?`+${c}`:`-${c}`}};ie.defaultConfig={sync:!0},ie.defaultOptions={duration:0,ease:"linear"},ie.CommonImagePositionMap=ns;var O=ie;var CC={};var Vn=class{constructor(){this.id=""}setId(e){this.id=e}getId(){return this.id}reset(){}fromData(e){return this}construct(e){for(let t=0;t<e.length;t++){let n=e[t];t!==0&&e[t-1]?.contentNode.setChild(n.contentNode)}return e}};var zn=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 se=class s{constructor(e,t){this.awaitable=e;this.guard=t;this.children=[];this._onResolved=[];this._onCancelled=[];this._onTimelineRegistered=[];this._ableToAttach=!0;this._status="pending";e.onSettled(()=>{this.resolveStatus()}),Me(()=>{this.preventAttach()})}static proxy(e){let t=new h,n=new h,o=new s(n);return o.onTimelineRegistered(()=>{n.resolve()}).onSettled(()=>{let[i,r]=o.catSettled();e(i,r)}),t.onSkipControllerRegister(i=>{i.onAbort(()=>{o.abort()})}),[t,o]}static any(e){if(e.length===0)throw new A("Cannot create an 'any' timeline with no awaitables.");let t=new h,n=new h,o=new s(n),i=!1;for(let r of e)o.attachChild(r),r.then(a=>{i||(i=!0,t.resolve(a))});return t.onSkipControllerRegister(r=>{r.onAbort(()=>{o.abort()})}),[t,o]}static all(e){if(e.length===0)throw new A("Cannot create an 'all' timeline with no awaitables.");let t=new h,n=new h,o=new s(n),i=new Array(e.length),r=0;for(let a=0;a<e.length;a++){let c=e[a];o.attachChild(c),c.then(l=>{i[a]=l,r++,r===e.length&&t.resolve(i)})}return t.onSkipControllerRegister(a=>{a.onAbort(()=>{o.abort()})}),[t,o]}static sequence(e,t){let n=t,o=null,i=new h,r=()=>{if(o){let a;o.onSkipControllerRegister(c=>{a=c.onAbort(()=>{i.abort()})}),o.then(c=>{a?.cancel(),n=c,o=e(c),o?Me(()=>r()):i.resolve(n)})}else i.resolve(n)};return i.registerSkipController(new L(()=>(o&&o.abort(),t))),o=e(t),o?Me(()=>r()):Me(()=>i.resolve(n)),i}get status(){return this._status}isSettled(){return this._status!=="pending"}isResolved(){return this._status==="resolved"}isCancelled(){return this._status==="cancelled"}onResolved(e){this._onResolved.push(e)}onCancelled(e){this._onCancelled.push(e)}onSettled(e){this.isSettled()?Me(e):(this.onResolved(e),this.onCancelled(e))}abort(){this.isSettled()||(this.awaitable.abort(),this.setStatus("cancelled",this.emitEvents.bind(this)),this.children.forEach(e=>e.abort()))}attachChild(e){if(!this._ableToAttach)throw new A(`Attaching to this timeline violates the timeline's state.
3
+ `).trim():""}function Kn(s){return new Promise(e=>setTimeout(e,s))}var Un=class Un{constructor(e){this.abortHandler=e;this.events=new F;this.aborted=!1}abort(...e){this.aborted||(this.aborted=!0,this.abortHandler(...e),this.events.emit(Un.EventTypes["event:skipController.abort"]))}isAborted(){return this.aborted}cancel(){this.aborted=!0}onAbort(e){return this.events.on("event:skipController.abort",e)}};Un.EventTypes={"event:skipController.abort":"event:skipController.abort"};var L=Un;var Jt=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}},Ht=class{constructor(){this.locks=[]}unlock(e){return e.unlock(),this.off(e),e}register(e){let t=e||new Jt;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 Fn(s,e,t={}){return s?e:t}function Gi(s,e){if(e<=0)return s;let t=null;return function(...n){t&&clearTimeout(t),t=setTimeout(()=>{s(...n)},e)}}var In=class{constructor(){this.taskToken=null}scheduleTask(e,t){this.taskToken&&this.taskToken.cancel();let n=!1,o=setTimeout(()=>{n||e()},t);return this.taskToken={cancel:()=>{clearTimeout(o),n=!0},isCancelled:()=>n},this.taskToken}cancelTask(){return this.taskToken&&(this.taskToken.cancel(),this.taskToken=null),this}};function Ni(s,e){let t=[];for(let n=0;n<Math.max(s.length,e.length);n++)n<s.length&&t.push(s[n]),n<e.length&&t.push(e[n]);return t}async function Hi(s,e){return new Promise((t,n)=>{fetch(s,e).then(o=>o.blob()).then(o=>{let i=new FileReader;i.onload=()=>{t(i.result)},i.readAsDataURL(o)}).catch(n)})}var Yt=class{constructor(e,t){this.concurrency=e;this.delay=t;this.tasks=[]}addTask(e){this.tasks.push(e)}async start(){let e=async()=>{if(this.tasks.length===0)return;let t=this.tasks.splice(0,this.concurrency);await Promise.all(t.map(n=>n())),await Kn(this.delay),await e()};await e()}};function Me(s){let e,t=Promise.resolve().then(()=>{e=s()});return()=>{t.then(()=>{e&&e()})}}function Ui(s,e){let t={};for(let n in s)e.includes(n)||(t[n]=s[n]);return t}var be=class s{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},o={...this.deserializer,...t};return new s(n,o)}};function Ki(s){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(s)}var ft=class extends h{constructor(t){super();this.tasks=[];t&&this.registerSkipController(t)}addTask(t){return t?(this.tasks.push(t),this):this}abort(){this.current&&this.current.abort(),this.tasks.forEach(([t,n])=>{n&&n.abort()}),super.abort()}resolve(){}run(){return this.current?this:(this.onTaskComplete(),this)}onTaskComplete(){if(this.tasks.length===0){super.resolve();return}let[t,n]=this.tasks.shift(),o=new h(h.nothing,n);this.current=o,this.current.then(()=>this.onTaskComplete()),t(o)}};function Fi(s){return s.constructor.name==="AsyncFunction"||Object.prototype.toString.call(s)==="[object AsyncFunction]"}function Uo(s){let e={};for(let t in s)s[t]!==void 0&&(e[t]=s[t]);return e}function Ko(s,e=new WeakSet){if(s===null||typeof s!="object"||Array.isArray(s)||s instanceof Date||s instanceof RegExp||Object.getPrototypeOf(s)!==Object.prototype||e.has(s))return!1;e.add(s);for(let t in s)if(Object.prototype.hasOwnProperty.call(s,t)){let n=s[t];if(n!==null&&typeof n=="object"&&!Ko(n,e)||typeof n=="function"||typeof n=="symbol")return!1}return!0}var Mn=class{constructor(e=""){this.prefix=e;this.counter=0}next(){return`${this.prefix?this.prefix+"-":""}${this.counter++}`}};function Oi(s=16){let e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=t.length;for(let o=0;o<s;o++)e+=t.charAt(Math.floor(Math.random()*n));return e}function Wi(s=16){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",t="";for(let n=0;n<s;n++)t+=e[Math.floor(Math.random()*e.length)];return t}var Gn=class{constructor(e=""){this.prefix=e;this.counter=0}generateId(){return`${this.prefix?this.prefix+"-":""}${this.counter++}`}},Nn=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 o=n.map(i=>i(...t));return()=>{o.forEach(i=>i&&i())}}rawTrigger(e,t){let n=this.hooks[e];if(!n)return()=>{};let o=n.map(i=>i(...t()));return()=>{o.forEach(i=>i&&i())}}};var Hn=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 Vi(s,e){let t={},n=[];for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&(e.includes(o)?n.push(o):t[o]=s[o]);return[t,n]}function zi(s){let e=3421674724,t=2216829733;for(let n=0;n<s.length;n++){let o=s.charCodeAt(n);e^=o;let i=e>>>0,r=t>>>0,a=435,c=16777216,l=i*a>>>0,f=i*c+r*a>>>0,p=r*c+(f>>>0)>>>0;e=l,t=p}return("00000000"+t.toString(16)).slice(-8)+("00000000"+e.toString(16)).slice(-8)}var Zt=class{constructor(e,t,n){this.callee=e,this.type=t,this.contentNode=n,this.__stack=Ho(),this._id=""}executeAction(e,t){return{type:this.type,node:this.contentNode.getChild()}}getId(){return this._id}setId(e){this._id=e}setContent(e){return this.contentNode.setContent(e),this}setContentNode(e){return this.contentNode=e,this}getFutureActions(e,t){let n=this.contentNode.getChild();return n&&n.action?[n.action]:[]}};Zt.ActionTypes={action:"action"};var M=class extends Zt{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 h(o=>o);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 Fo=class{constructor(e){this.type=e,this.content=void 0}setContent(e){return this.content=e,this}getContent(){return this.content}},S=class s extends Fo{static create(e){return new s().setContent(e)}static forEachParent(e,t){let n=new Set,o=e;for(;o&&!n.has(o);)n.add(o),t(o),o=o.getParent()}static forEachChild(e,t){let n=new Set,o=e;for(;o&&!n.has(o);)n.add(o),t(o),o=o.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 On={center:"center",left:"left",right:"right"};import{animate as ts}from"motion/react";var _t=(n=>(n.Left="left",n.Center="center",n.Right="right",n))(_t||{}),$i={left:"33.33%",center:"50%",right:"66.66%"},Ge=class Ge{static isUnknown(e){return e===Ge.Unknown}static D2PositionToCSS(e,t=!1,n=!1){let o=this.calc(e.y,e.yoffset),i=this.calc(e.x,e.xoffset),r=n?{bottom:o}:{top:o},a=t?{right:i}:{left:i};return this.wrap({...r,...a})}static calc(e,t){return!e||Ge.isUnknown(e)?"auto":t===void 0||Ge.isUnknown(t)?`calc(${e} + 0px)`:`calc(${typeof e=="number"?`${e}px`:e} + ${t}px)`}static toCoord2D(e){if(Ne.isCommonPositionType(e))return Ae.fromCommonPosition(e);if(Ae.isCoord2DPosition(e))return e;if(xt.isAlignPosition(e))return Ae.fromAlignPosition(e);if(typeof e=="object"&&["x","y","xoffset","yoffset"].some(t=>t in e)){let t=e;return new Ae(t)}else throw new Error("Invalid position type")}static orUnknown(e){return Ge.isUnknown(e)||e===void 0?Ge.Unknown:e}static mergePosition(e,t){let n=this.toCoord2D(e),o=this.toCoord2D(t);return Ae.merge(n,o)}static serializePosition(e){let t=this.toCoord2D(e);return{x:Ge.isUnknown(t.x)?0:t.x,y:Ge.isUnknown(t.y)?0:t.y,xoffset:Ge.isUnknown(t.xoffset)?0:t.xoffset,yoffset:Ge.isUnknown(t.yoffset)?0:t.yoffset}}static isRawCommonPositionType(e){return Object.values(_t).includes(e)}static isRawCoord2DPosition(e){return typeof e=="object"&&("x"in e||"y"in e||"xoffset"in e||"yoffset"in e)}static isRawAlignPosition(e){return typeof e=="object"&&("xalign"in e||"yalign"in e||"xoffset"in e||"yoffset"in e)}static isRawPosition(e){return this.isRawCommonPositionType(e)||this.isRawCoord2DPosition(e)||this.isRawAlignPosition(e)}static isPosition(e){return e instanceof Ne||e instanceof Ae||e instanceof xt}static rawPositionToCoord2D(e){if(this.isRawCommonPositionType(e))return Ae.fromCommonPosition(new Ne(e));if(this.isRawCoord2DPosition(e))return new Ae(e);if(this.isRawAlignPosition(e))return Ae.fromAlignPosition(e);throw new Error("Invalid position type")}static tryParsePosition(e){if(this.isPosition(e))return e;if(this.isRawPosition(e))return this.rawPositionToCoord2D(e);throw new Error("Invalid position type")}static wrap(e){return{left:"auto",top:"auto",right:"auto",bottom:"auto",...e}}};Ge.Unknown=Symbol("Unknown");var v=Ge,Wn=class Wn{static isCommonPositionType(e){return e instanceof Wn}constructor(e){this.position=e}toCSS(){return{x:$i[this.position],y:"50%",xoffset:0,yoffset:0}}};Wn.Positions=_t;var Ne=Wn,Ae=class s{static isCoord2DPosition(e){return e instanceof s}static fromCommonPosition(e){return new s({x:$i[e.position],y:"50%"})}static fromAlignPosition(e){let t=n=>!n||v.isUnknown(n)?v.Unknown:`${n*100}%`;return new s({x:t(e.xalign),y:t(e.yalign),xoffset:e.xoffset,yoffset:e.yoffset})}static merge(e,t){return new s({x:v.isUnknown(t.x)?e.x:t.x,y:v.isUnknown(t.y)?e.y:t.y,xoffset:v.isUnknown(t.xoffset)?e.xoffset:t.xoffset,yoffset:v.isUnknown(t.yoffset)?e.yoffset:t.yoffset})}constructor(e,t){typeof e=="object"?(this.x=v.orUnknown(e.x),this.y=v.orUnknown(e.y),this.xoffset=v.orUnknown(e.xoffset),this.yoffset=v.orUnknown(e.yoffset)):(this.x=v.orUnknown(e),this.y=v.orUnknown(t),this.xoffset=v.Unknown,this.yoffset=v.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}}},xt=class s{static isAlignPosition(e){return e instanceof s}constructor(e,t){typeof e=="object"?(this.xalign=v.orUnknown(e.xalign),this.yalign=v.orUnknown(e.yalign),this.xoffset=v.orUnknown(e.xoffset),this.yoffset=v.orUnknown(e.yoffset)):(this.xalign=v.orUnknown(e),this.yalign=v.orUnknown(t),this.xoffset=v.Unknown,this.yoffset=v.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:v.isUnknown(this.xalign)?this.xalign:`${this.xalign*100}%`,y:v.isUnknown(this.yalign)?this.yalign:`${this.yalign*100}%`,xoffset:this.xoffset,yoffset:this.yoffset}}};var H=class s{constructor(e,t){this.defaultConfig=e;this.handlers=t||{}}create(e={}){return new Oo(this.mergeWithDefaultConfig(e))}copy(){return new s(R({},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)?R({},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}},Oo=class s{constructor(e){this.config=e}get(){return this.config}copy(){return new s(R({},this.config))}join(e){let t=Ui(this.config,Object.keys(e));return new s(Object.assign(t,e instanceof s?e.get():e))}extract(e){let t={},n={};for(let o of e)t[o]=this.config[o];for(let o in this.config)e.includes(o)||(n[o]=this.config[o]);return[new s(t),new s(n)]}assign(e){return new s(Object.assign({},this.config,e))}};var ns={[On.left]:"25.33%",[On.center]:"50%",[On.right]:"75.66%"},We=class We{constructor(e={}){this.state={};this.locked=null;this.frozen=!1;this.state=e}static deserialize(e){return new We(We.TransformStateSerializer.deserialize(e))}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?v.toCoord2D(v.tryParsePosition(e||t)):v.mergePosition(v.tryParsePosition(e),v.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=We.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 Uo(O.constructStyle(e,this.state,t))}toStyle(e,t){return Uo(O.constructStyle(e,this.state,t))}serialize(){return We.TransformStateSerializer.serialize(this.state)}clone(){return new We(We.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=We.mergeState(this.state,t),this}forceOverwrite(e){return this.state=e,this}};We.DefaultTransformState=new H({scaleX:1,scaleY:1,zoom:1,rotation:0,position:new Ne("center"),opacity:0,alt:""}),We.TransformStateSerializer=new be({position:e=>v.serializePosition(v.tryParsePosition(e))},{position:e=>v.toCoord2D(e)});var re=We,ie=class ie{constructor(e,t){this.sequences=[];this.stagedChanges=[];if(Array.isArray(e))this.sequences.push(...e),this.config=Object.assign({},ie.defaultConfig,t||{});else{let[n,o]=[e,t||ie.defaultOptions];this.sequences.push({props:n,options:o||ie.defaultOptions}),this.config=Object.assign({},ie.defaultConfig)}}static isPosition(e){return Ne.isCommonPositionType(e)||Ae.isCoord2DPosition(e)||xt.isAlignPosition(e)}static immediate(e){return new ie(e,{duration:0,ease:"linear"})}static left(e,t){return new ie({position:Ne.Positions.Left},{duration:e,ease:t})}static right(e,t){return new ie({position:Ne.Positions.Right},{duration:e,ease:t})}static center(e,t){return new ie({position:Ne.Positions.Center},{duration:e,ease:t})}static create(e){return new ie([],e)}static positionToCSS(e,t,n){return e?v.isRawPosition(e)?v.D2PositionToCSS(v.rawPositionToCoord2D(e),n,t):v.D2PositionToCSS(e.toCSS(),n,t):{}}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?v.toCoord2D(v.tryParsePosition(e||t)):v.mergePosition(v.tryParsePosition(e),v.tryParsePosition(t))}static mergeState(e,t){let n=this.mergePosition(e.position,t.position);return{...R(e,t),position:n}}static propToCSSTransform(e,t,n){let{invertY:o,invertX:i}=e.getStory().getInversionConfig(),{translate:r=[]}=n||{},a=t.zoom??1,c=function(d,g,u){return typeof d>"u"?typeof u<"u"?g(u):"":g(d)},l=r[0]||(i?"":"-")+"50%",f=r[1]||(o?"":"-")+"50%";return[`translate(${l}, ${f})`,c(t.rotation,d=>`rotate(${d}deg)`,0),c(t.scaleX,d=>`scaleX(${d*a})`,1),c(t.scaleY,d=>`scaleY(${d*a})`,1)].filter(Boolean).join(" ")}static constructStyle(e,t,n){let{invertY:o,invertX:i}=e.getStory().getInversionConfig(),{overwrite:r}=n||{};return{...ie.positionToCSS(t.position,o,i),opacity:t.opacity,color:"fontColor"in t&&t.fontColor?Ct(t.fontColor):void 0,transform:ie.propToCSSTransform(e,t),...r?r(t):{}}}animate(e,{gameState:t,ref:n,overwrites:o}){if(!n.current)throw new Error("No ref found when animating.");this.commit();let{finalState:i,sequences:r,options:a}=this.constructAnimation({gameState:t,transformState:e,overwrites:o,current:n.current});r.length||t.logger.warn("Transform","No sequences to animate.");let c=!1,l=e.lock(),f=ts(r,a),p=()=>{e.overwrite(l,i.get()).unlock(l),f.complete(),c=!0},d=new h().registerSkipController(new L(p)),g=()=>{c||e.overwrite(l,i.get()).unlock(l),c=!0,t.logger.debug("Transform","Transform Completed",e.toStyle(t,o)),d.resolve()};return f.then(g,u=>{t.logger.error("Failed to animate transform. "+(u?.toString?.()||""))}),f.play(),t.logger.debug("Transform","Ready to animate transform.",{finalState:i,sequences:r,options:a},this),d}repeat(e){let t=this.copy();return t.config.repeat||(t.config.repeat=1),t.config.repeat*=e,t}getOptions(e){if(!e)return{...ie.defaultOptions};let{duration:t,ease:n,delay:o,at:i}=e;return{duration:this.toSeconds(t,void 0),ease:n,delay:this.toSeconds(o,void 0),at:this.atToSeconds(i)}}constructAnimation({gameState:e,transformState:t,overwrites:n={},current:o}){let i=t.clone(),r=i.lock(),a=this.sequences.map(({props:c,options:l})=>{let f=i.assign(r,c).toFramesDefinition(e,n);return[o,f,this.getOptions(l)]});return{finalState:i.unlock(r).freeze(),sequences:a,options:this.getSequenceOptions()}}getSequenceOptions(){let{repeat:e,repeatDelay:t}=this.config;return{repeat:e,repeatDelay:this.toSeconds(t,void 0)}}copy(){return new ie(this.sequences,this.config)}commit(e){if(!this.stagedChanges.length)return this;let t=this.constructCommit(this.stagedChanges,this.getSequenceOptions());return this.sequences.push({props:t.props,options:{...this.getSequenceOptions(),...e}}),this.stagedChanges=[],this}zoom(e){return this.pushChange({key:"zoom",props:e})}scaleX(e){return this.pushChange({key:"scaleX",props:e})}scaleY(e){return this.pushChange({key:"scaleY",props:e})}scale(e,t){return this.pushChange({key:"scaleX",props:e}).pushChange({key:"scaleY",props:t})}rotation(e){return this.pushChange({key:"rotation",props:e})}position(e){return this.pushChange({key:"position",props:e})}opacity(e){return this.pushChange({key:"opacity",props:e})}fontColor(e){return this.pushChange({key:"fontColor",props:e})}constructCommit(e,t){let n={props:{},options:t};for(let o of e)n.props[o.key]=o.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 X("Invalid at definition. At definition must be a number or a string in the format of `+n` or `-n`.");let[o,i,r]=n,a=Number(r);if(isNaN(a))throw new X("Invalid number in at definition.");let c=a/1e3;return i==="+"?`+${c}`:`-${c}`}};ie.defaultConfig={sync:!0},ie.defaultOptions={duration:0,ease:"linear"},ie.CommonImagePositionMap=ns;var O=ie;var CC={};var Vn=class{constructor(){this.id=""}setId(e){this.id=e}getId(){return this.id}reset(){}fromData(e){return this}construct(e){for(let t=0;t<e.length;t++){let n=e[t];t!==0&&e[t-1]?.contentNode.setChild(n.contentNode)}return e}};var zn=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 se=class s{constructor(e,t){this.awaitable=e;this.guard=t;this.children=[];this._onResolved=[];this._onCancelled=[];this._onTimelineRegistered=[];this._ableToAttach=!0;this._status="pending";e.onSettled(()=>{this.resolveStatus()}),Me(()=>{this.preventAttach()})}static proxy(e){let t=new h,n=new h,o=new s(n);return o.onTimelineRegistered(()=>{n.resolve()}).onSettled(()=>{let[i,r]=o.catSettled();e(i,r)}),t.onSkipControllerRegister(i=>{i.onAbort(()=>{o.abort()})}),[t,o]}static any(e){if(e.length===0)throw new A("Cannot create an 'any' timeline with no awaitables.");let t=new h,n=new h,o=new s(n),i=!1;for(let r of e)o.attachChild(r),r.then(a=>{i||(i=!0,t.resolve(a))});return t.onSkipControllerRegister(r=>{r.onAbort(()=>{o.abort()})}),[t,o]}static all(e){if(e.length===0)throw new A("Cannot create an 'all' timeline with no awaitables.");let t=new h,n=new h,o=new s(n),i=new Array(e.length),r=0;for(let a=0;a<e.length;a++){let c=e[a];o.attachChild(c),c.then(l=>{i[a]=l,r++,r===e.length&&t.resolve(i)})}return t.onSkipControllerRegister(a=>{a.onAbort(()=>{o.abort()})}),[t,o]}static sequence(e,t){let n=t,o=null,i=new h,r=()=>{if(o){let a;o.onSkipControllerRegister(c=>{a=c.onAbort(()=>{i.abort()})}),o.then(c=>{a?.cancel(),n=c,o=e(c),o?Me(()=>r()):i.resolve(n)})}else i.resolve(n)};return i.registerSkipController(new L(()=>(o&&o.abort(),t))),o=e(t),o?Me(()=>r()):Me(()=>i.resolve(n)),i}get status(){return this._status}isSettled(){return this._status!=="pending"}isResolved(){return this._status==="resolved"}isCancelled(){return this._status==="cancelled"}onResolved(e){this._onResolved.push(e)}onCancelled(e){this._onCancelled.push(e)}onSettled(e){this.isSettled()?Me(e):(this.onResolved(e),this.onCancelled(e))}abort(){this.isSettled()||(this.awaitable.abort(),this.setStatus("cancelled",this.emitEvents.bind(this)),this.children.forEach(e=>e.abort()))}attachChild(e){if(!this._ableToAttach)throw new A(`Attaching to this timeline violates the timeline's state.
4
4
  Timeline attaching is only allowed synchronously after the timeline is created.
5
5
  Current _ableToAttach: `+this._ableToAttach);let t=h.isAwaitable(e)?new s(e,this.guard):e;return this.children.push(t),this.guard&&t.setGuard(this.guard),t.onSettled(()=>{this.resolveStatus()}),this}setGuard(e){return this.guard=e,this}catSettled(){return this.children.reduce(([e,t],n)=>(n.isResolved()?e.push(n):n.isCancelled()&&t.push(n),[e,t]),[[],[]])}onTimelineRegistered(e){return this._onTimelineRegistered.push(e),this}resolveStatus(){this.awaitable.solved&&this.children.every(e=>e.isSettled())?this.setStatus("resolved",this.emitEvents.bind(this)):this.awaitable.skipController?.isAborted()&&this.setStatus("cancelled",this.emitEvents.bind(this))}emitEvents(){this.isResolved()?this._onResolved.forEach(e=>e()):this.isCancelled()&&this._onCancelled.forEach(e=>e()),this._onResolved=[],this._onCancelled=[]}setStatus(e,t){if(this.isSettled()){this.guard&&this.guard.warn("unexpectedTimelineStatusChange",`Trying to resolve a settled timeline: ${this._status} -> ${e}`);return}e!==this._status&&t?(this._status=e,t()):this._status=e}preventAttach(){this._ableToAttach=!1,this._onTimelineRegistered.forEach(e=>e())}},$n=class{constructor(e){this.guard=e;this.timelines=[]}attachTimeline(e){this.cleanupSettled();let t=e instanceof se?e:new se(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 en=class en extends M{static executeActionsAsync(e,t){return e.game.getLiveGame().requestAsyncStackModel([{type:t.type,node:t.contentNode}]).execute()}checkActionChain(e){if(e.some(t=>!!t.contentNode.getChild()))throw new Error("Invalid action chain. Actions are chained unexpectedly.");return e}executeAction(e,t){let n=this.contentNode,[o]=n.getContent();if(this.type===Oe.do)return[{type:this.type,node:this.contentNode.getChild()},{type:this.type,node:o[0].contentNode}];if(this.type===Oe.doAsync){let i=en.executeActionsAsync(e,o[0]);return e.timelines.attachTimeline(i),super.executeAction(e,t)}else if(this.type===Oe.any){if(o.length===0)return{type:this.type,node:this.contentNode.getChild()};let i=this.checkActionChain(o).map(r=>e.game.getLiveGame().requestAsyncStackModel([{type:r.type,node:r.contentNode}]));return{type:this.type,node:this.contentNode.getChild(),wait:{type:"any",stackModels:i}}}else if(this.type===Oe.all){if(o.length===0)return{type:this.type,node:this.contentNode.getChild()};let i=this.checkActionChain(o).map(r=>e.game.getLiveGame().requestAsyncStackModel([{type:r.type,node:r.contentNode}]));return{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:i}}}else if(this.type===Oe.allAsync){if(o.length===0)return{type:this.type,node:this.contentNode.getChild()};let i=this.checkActionChain(o).map(r=>e.game.getLiveGame().requestAsyncStackModel([{type:r.type,node:r.contentNode}]));return e.timelines.attachTimeline(h.all(...i.map(r=>r.execute()))),super.executeAction(e,t)}else if(this.type===Oe.repeat){let[i,r]=this.contentNode.getContent();if(r<=0)return super.executeAction(e,t);let a=se.sequence(c=>{if(c>=r)return null;let l=en.executeActionsAsync(e,i[0]);return e.timelines.attachTimeline(l),h.forward(l,c+1)},0);return e.logger.debug("ControlAction","repeat",i,r),h.forward(a,{type:this.type,node:this.contentNode.getChild()})}else if(this.type===Oe.sleep){let[,i]=this.contentNode.getContent(),r;typeof i=="number"?r=h.delay(i):h.isAwaitable(i)?r=i:r=h.fromPromise(i);let a=new h,c=new se(r);return e.timelines.attachTimeline(c),r.then(()=>{a.resolve({type:this.type,node:this.contentNode.getChild()})}),a.onSkipControllerRegister(l=>{l.onAbort(()=>{c.abort()})}),a}throw new Error("Unknown control action type: "+this.type)}getFutureActions(e,t){if(this.callee.config.allowFutureScene===!1&&t.allowFutureScene===!1)return[...super.getFutureActions(e,t)];let n=this.contentNode.getContent()[0],o=super.getFutureActions(e,t);return[...n,...o]}stringify(e,t,n){let o=this.contentNode,[i]=o.getContent();return super.stringifyWithContent("Control",i.map(r=>r.stringify(e,t,n)).join(";"))}};en.ActionTypes=Oe;var te=en;var ji=Symbol("_Chained"),qi;qi=ji;var Wo=class Wo{constructor(e){this[qi]=!0;this.__actions=[];this.__self=e}static isChained(e){return e&&e[ji]}static toActions(e){return e.flat(2).map(t=>Wo.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()}},fe=Wo,Ut=class extends Vn{chain(e){let t=fe.isChained(this)?this:this.proxy(this,new fe(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(o,i){if(i in t)return t[i];let r=o[i];return typeof r=="function"?r.bind(n):r},set:function(o,i,r){return o[i]=r,!0}});return n}combineActions(e,t){let n=t(this.chain().newChain()),o=new te(e.chain(),te.ActionTypes.do,new S().setContent([this.construct(fe.toActions([n]))]));return this.chain(o)}};var q=class extends Ut{constructor(){super()}toData(){return null}fromChained(e){return e.getActions()}};var Se=class s{static from(e){return s.isPauseConstructor(e)?new s:e}static wait(e){return new s({duration:e})}static isPause(e){return this.isPauseConstructor(e)||e instanceof s}static isPauseConstructor(e){return e===s}constructor(e={}){this.config=e}};var le=class le{static isWord(e){return e instanceof le}static color(e,t){return le.isWord(e)?e.copy().assign({color:t}):new le(e,{color:t})}static bold(e){return le.isWord(e)?e.copy().assign({bold:!0}):new le(e,{bold:!0})}static italic(e){return le.isWord(e)?e.copy().assign({italic:!0}):new le(e,{italic:!0})}static getText(e){return e.filter(t=>!t.isPause()).map(t=>t.toString()).join("")}constructor(e,t={}){this.text=e,this.config=R(le.defaultConfig,t)}evaluate(e){if(Se.isPause(this.text))return[this];if(typeof this.text=="function"){let t=this.text(e);return Array.isArray(t)?t.map(n=>le.isWord(n)?n.inherit(this.config).evaluate(e):new le(n,this.config)).flat():le.isWord(t)?t.inherit(this.config).evaluate(e):[new le(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=R(this.config,e),this}copy(){return new le(this.text,this.config)}isPause(){return Se.isPause(this.text)}toString(){return typeof this.text=="string"?this.text:""}};le.defaultConfig={},le.defaultColor="#000";var U=le;var Pe=class extends M{executeAction(e,t){let n={action:this,stackModel:t.stackModel};if(this.type===mt.play){let[o]=this.contentNode.getContent(),i=this.callee.toData(),r=h.forward(e.audioManager.play(this.callee,o),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(r),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[i]),r}else if(this.type===mt.stop){let[o]=this.contentNode.getContent(),i=this.callee.toData(),r=h.forward(e.audioManager.stop(this.callee,o.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(r),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[i]),r}else if(this.type===mt.setVolume){let[o,i]=this.contentNode.getContent(),r=this.callee.toData(),a=h.forward(e.audioManager.setVolume(this.callee,o,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(a),e.actionHistory.push(n,c=>{c&&this.callee.fromData(c)},[r]),a}else if(this.type===mt.setRate){let[o]=this.contentNode.getContent(),i=this.callee.toData(),r=h.forward(e.audioManager.setRate(this.callee,o),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(r),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[i]),r}else if(this.type===mt.pause){let[o]=this.contentNode.getContent(),i=this.callee.toData(),r=h.forward(e.audioManager.pause(this.callee,o.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(r),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[i]),r}else if(this.type===mt.resume){let[o]=this.contentNode.getContent(),i=this.callee.toData(),r=h.forward(e.audioManager.resume(this.callee,o.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(r),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[i]),r}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("SoundAction")}};Pe.ActionTypes=mt;var tn=(n=>(n.Voice="voice",n.Bgm="bgm",n.Sound="sound",n))(tn||{}),Y=class Y extends q{static toSound(e){return e==null?null:typeof e=="string"?new Y({src:e}):e}static isSound(e){return e instanceof Y}static voice(e){let t=typeof e=="string"?{src:e}:e;return new Y({...t,type:"voice"})}static bgm(e){let t=typeof e=="string"?{src:e}:e;return new Y({...t,type:"bgm"})}static sound(e){let t=typeof e=="string"?{src:e}:e;return new Y({...t,type:"sound"})}constructor(e={}){super();let t=typeof e=="string"?{src:e}:e,n=Y.DefaultUserConfig.create(t),[o]=n.extract(Y.DefaultConfig.keys());this.config=o.get(),this.state=this.getInitialState(n),this.userConfig=n}play(e){if(this.config.type==="bgm")throw new ue(`Sound (src: ${this.config.src}) is marked as bgm, but it is being played as a normal sound.
6
- To prevent unintended behavior, the sound marked as bgm cannot be played using \`play()\`.`);return this.pushAction(Pe.ActionTypes.play,[{end:this.state.volume,duration:e||0}])}stop(e){return this.pushAction(Pe.ActionTypes.stop,[{end:0,duration:e||0}])}setVolume(e,t){return this.pushAction(Pe.ActionTypes.setVolume,[e,t||0])}setRate(e){return this.pushAction(Pe.ActionTypes.setRate,[e])}pause(e){return this.pushAction(Pe.ActionTypes.pause,[{end:0,duration:e||0}])}resume(e){return this.pushAction(Pe.ActionTypes.resume,[{end:this.state.volume,duration:e||0}])}getSrc(){return this.config.src}toData(){return{state:Y.StateSerializer.serialize(this.state)}}fromData(e){return this.state=Y.StateSerializer.deserialize(e.state),this}copy(){return new Y(this.userConfig.get())}reset(){return this.state=this.getInitialState(this.userConfig),this}getInitialState(e){return Y.DefaultState.create({...e.get()}).get()}pushAction(e,t){return this.chain(new Pe(this.chain(),e,new S().setContent(t)))}};Y.noSound="data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgA",Y.DefaultUserConfig=new N({src:Y.noSound,loop:!1,volume:1,streaming:!1,rate:1,seek:0,type:"sound"}),Y.DefaultConfig=new N({src:Y.noSound,loop:!1,streaming:!1,seek:0,type:"sound"}),Y.DefaultState=new N({volume:1,rate:1,paused:!1}),Y.StateSerializer=new be;var ve=Y;var Ce=class Ce{static isSentence(e){return e instanceof Ce}static toSentence(e){return Ce.isSentence(e)?e:new Ce(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 U.isWord(e)?e:new U(e)}static formatStaticWord(e,t){return Array.isArray(e)?e.map(n=>this.formatStaticWord(n,t)).flat(2):[U.isWord(e)?e:new U(e,t)]}static isSentencePrompt(e){return Array.isArray(e)?e.every(Ce.isSingleWord):Ce.isSingleWord(e)}static isSingleWord(e){return typeof e=="string"||U.isWord(e)||Se.isPause(e)||typeof e=="function"}constructor(e,t={}){this.text=Ce.format(e),this.config=R(Ce.defaultConfig,{...t,voice:ve.toSound(t.voice)}),this.state=Mi(Ce.defaultState)}toData(){return null}fromData(e){return this.state=R(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 o=this.text[n].evaluate(e);t.push(...Ce.formatStaticWord(o))}return t}copy(){return new Ce([...this.text],this.config)}};Ce.defaultConfig={pause:!0,voice:null,character:null,voiceId:null},Ce.defaultState={};var ne=Ce;var Bn=class Bn extends M{static getVoice(e,t){let n=e.getLastScene();if(!n)throw new Error("No scene found when trying to play voice");let{voiceId:o,voice:i}=t.config;return!o&&!i?null:ve.toSound(n.getVoice(o)||i)}executeAction(e,t){if(this.type===Rn.say){let n=new h(f=>f).registerSkipController(new L(()=>{c.cancel()})),o=new se(n),i=this.contentNode.getContent(),r=Bn.getVoice(e,i);if(r){let f=e.audioManager.play(r);o.attachChild(f)}let a=e.idManager.generateId(),c=e.createDialog(a,i,()=>{if(r){let f=e.audioManager.stop(r);e.timelines.attachTimeline(f)}e.gameHistory.resolvePending(l),n.resolve({type:this.type,node:this.contentNode.getChild()})});e.getLiveGame().setLastDialog(c.text,this.callee.state.name),e.timelines.attachTimeline(o);let{id:l}=e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:o},()=>{if(r&&e.audioManager.isPlaying(r)){let f=e.audioManager.stop(r);o.attachChild(f)}c.cancel()});return e.gameHistory.push({token:l,action:this,element:{type:"say",text:c.text,voice:r?r.getSrc():null,character:this.callee.state.name},isPending:!0}),n}else if(this.type===Rn.setName){let n=this.callee.state.name;return this.callee.state.name=this.contentNode.getContent()[0],e.actionHistory.push({action:this,stackModel:t.stackModel},o=>{this.callee.state.name=o},[n]),super.executeAction(e,t)}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("CharacterAction")}};Bn.ActionTypes=Rn;var nt=Bn;var nn=class nn extends q{constructor(e,t={}){super(),this.config=R(nn.defaultConfig,t),this.state={name:e||""};let n=this,o=function(i,r,...a){return n.call(i,r,...a)};return new Proxy(o,{get(i,r){return n[r]},set(i,r,a){return n[r]=a,!0},has(i,r){return r in n}})}say(e,t,...n){if(Array.isArray(e)&&e.every(c=>typeof c=="string")&&[t,...n].length>0&&[t,...n].every(c=>ne.isSingleWord(c))){let c=e,l=ne.format([t,...n]),f=new ne(Ni(c,l),{character:this}),p=new nt(this.chain(),nt.ActionTypes.say,new S().setContent(f));return this.chain(p)}let o=t||{},i=e,r=Array.isArray(i)?new ne(i,{...o,character:this}):(ne.isSentence(i)?i:new ne(i,{...o,character:this})).copy();r.setCharacter(this);let a=new nt(this.chain(),nt.ActionTypes.say,new S().setContent(r));return this.chain(a)}setName(e){let t=new nt(this.chain(),nt.ActionTypes.setName,new S().setContent([e]));return this.chain(t)}apply(e,t,...n){return this.say.apply(this,[e,t,...n])}call(e,t,...n){return Array.isArray(e)&&"raw"in e?t&&ne.isSingleWord(t)?this.say(e,t,...n):this.say(e):typeof e=="string"?this.say(e,t):ne.isSentence(e)?this.say(e):this.say(e,t)}};nn.defaultCharacterColor="#000",nn.defaultConfig={};var jn=nn,gt=new jn(null);var Ve=class s extends q{constructor(t={}){super();this.config=t}static do(t){return new s().do(t)}static doAsync(t){return new s().doAsync(t)}static any(t){return new s().any(t)}static all(t){return new s().all(t)}static allAsync(t){return new s().allAsync(t)}static repeat(t,n){return new s().repeat(t,n)}static sleep(t){return new s().sleep(t)}do(t){return this.push(te.ActionTypes.do,t)}doAsync(t){return this.push(te.ActionTypes.doAsync,t)}any(t){return this.pushUnchained(te.ActionTypes.any,t)}all(t){return this.pushUnchained(te.ActionTypes.all,t)}allAsync(t){return this.pushUnchained(te.ActionTypes.allAsync,t)}repeat(t,n){return this.push(te.ActionTypes.repeat,n,t)}sleep(t){return this.push(te.ActionTypes.sleep,[],t)}push(t,n,...o){let i=this.narrativeToActions(n),r=new te(this.chain(),t,new S().setContent([this.construct(i),...o]));return this.chain(r)}pushUnchained(t,n,...o){let i=this.narrativeToActions(n),r=new te(this.chain(),t,new S().setContent([i,...o]));return this.chain(r)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?gt.say(n).getActions():fe.toActions([n]))}};var pe=class extends M{executeAction(e,t){if(this.type===ce.applyTransform){let[n]=this.contentNode.getContent(),o=this.callee;return this.applyTransform(e,o,n,t)}else if(this.type===ce.applyTransition){let[n,o]=this.contentNode.getContent(),i=this.callee,r=o?o(n):n;return this.applyTransition(e,i,r,t)}else if(this.type===ce.init){let[n,o,i]=this.contentNode.getContent(),r=this.callee;return this.initDisplayable(e,n,r,o||null,i,t)}throw this.unknownTypeError()}applyTransform(e,t,n,o,i){let r=new h().registerSkipController(new L(()=>(e.logger.info("Displayable Transition","Skipped"),super.executeAction(e,o)))),a=e.getExposedStateForce(t),c=t.transformState.clone(),l=a.applyTransform(n,()=>{i?.(),r.resolve(super.executeAction(e,o))}),f=e.timelines.attachTimeline(r).attachChild(l);return e.actionHistory.push({action:this,stackModel:o.stackModel,timeline:f},p=>{r.isSettled()||r.abort(),l.abort(),t.transformState.forceOverwrite(p.state)},[c]),r}applyTransition(e,t,n,o,i){let r=new h().registerSkipController(new L(()=>(e.logger.info("Displayable Transition","Skipped"),super.executeAction(e,o)))),c=e.getExposedStateForce(t).applyTransition(n,()=>{i?.(),r.resolve(super.executeAction(e,o))}),l=e.timelines.attachTimeline(r).attachChild(c);return e.actionHistory.push({action:this,stackModel:o.stackModel,timeline:l},()=>{r.isSettled()||r.abort(),c.abort()}),r}initDisplayable(e,t,n,o,i=!0,r){if(i!==!1){let l=e.findElementByDisplayable(this.callee,o);l&&e.disposeDisplayable(n,l.scene,o),e.createDisplayable(n,t,o)}e.flush();let a=new h().registerSkipController(new L(()=>super.executeAction(e,r)));e.getExposedStateAsync(n,l=>{l.initDisplayable(()=>{a.resolve(super.executeAction(e,r))})});let c=e.timelines.attachTimeline(a);return e.actionHistory.push({action:this,stackModel:r.stackModel,timeline:c},()=>{i!==!1&&e.findElementByDisplayable(n,o)&&e.disposeDisplayable(n,t,o)}),a}stringify(e,t,n){return super.stringifyWithName("DisplayableAction")}};pe.ActionTypes=ce;var wt=class wt{constructor(){this.src=[];this.future=[]}static catSrc(e){let t=new Set,n=new Set,o=new Set;return e.forEach(({type:i,src:r})=>{i===wt.SrcTypes.image?t.add(r):i===wt.SrcTypes.video?n.add(r):o.add(r)}),{image:Array.from(t),video:Array.from(n),audio:Array.from(o)}}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(ae,ee.jumpTo)){let n=t.contentNode.getContent()[0],i=e.getScene(n,!0).state.backgroundImage;if(b.isImageURL(i.config.src))return{type:"image",src:i.config.src,activeType:"once"}}else if(t instanceof z){let n=t;if(t.is(z,ke.setSrc)){let o=t.contentNode.getContent()[0];if(b.isImageSrc(o))return{type:"image",src:b.srcToURL(o),activeType:"scene"}}else{if(t.type===ke.initWearable)return{type:"image",src:t.contentNode.getContent()[0],activeType:"scene"};if(t.type===ke.setAppearance){let o=t.contentNode.getContent()[0];if(!n.callee.config.src||typeof n.callee.config.src?.resolve!="function")throw n.callee._invalidSrcHandlerError();if(I.isTagSrc(n.callee)&&o.length===n.callee.config.src.groups.length)return{type:"image",src:I.getSrcFromTags(o,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||b.isStaticImageData(e)){if(e instanceof I){if(!b.isImageURL(e.state.currentSrc))return this;if(this.isSrcRegistered(I.getSrcURL(e)))return this}else if(this.isSrcRegistered(b.srcToURL(e.src)))return this;this.src.push({type:"image",src:b.isStaticImageData(e)?b.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===wt.SrcTypes.audio?t===n.src.getSrc():n.type===wt.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)}};wt.SrcTypes={image:"image",video:"video",audio:"audio"};var ge=wt;var qe=class extends q{constructor(){super(...arguments);this.srcManager=new ge}pos(t,n,o){return this.transform(new O({position:t},{duration:n,ease:o}))}zoom(t,n,o){return this.transform(new O({zoom:t},{duration:n,ease:o}))}scaleX(t,n,o){return this.transform(new O({scaleX:t},{duration:n,ease:o}))}scaleY(t,n,o){return this.transform(new O({scaleY:t},{duration:n,ease:o}))}scale(t,n,o,i){return this.transform(new O({scaleX:t,scaleY:n},{duration:o,ease:i}))}scaleXY(t,n,o,i){return this.scale(t,n,o,i)}rotate(t,n,o){return this.transform(new O({rotation:t},{duration:n,ease:o}))}opacity(t,n,o){return this.transform(new O({opacity:t},{duration:n,ease:o}))}transform(t){let n=this.chain(),o=new pe(n,ce.applyTransform,new S().setContent([t.copy()]));return n.chain(o)}show(t){let n=this.chain(),o=t instanceof O?t.copy():new O({opacity:1},t),i=new pe(n,ce.applyTransform,new S().setContent([o]));return n.chain(i)}hide(t){let n=this.chain(),o=t instanceof O?t.copy():new O({opacity:0},t),i=new pe(n,ce.applyTransform,new S().setContent([o]));return n.chain(i)}};var W=class W extends qe{static getInitialSrc(e){if(this.isTagDefinition(e.src))return[...e.src.defaults];let t=e.src;return b.isStaticImageData(t)?b.srcToURL(t):b.isColor(t)?t:b.isImageSrc(t)?b.srcToURL(t):W.DefaultImagePlaceholder}static isTagSrc(e){return!!e.config.src}static isTagDefinition(e){return typeof e=="object"&&e!==null&&!b.isImageSrc(e)&&!b.isColor(e)&&"defaults"in e}static isStaticSrc(e){let t=e.userConfig.get().src;return!this.isTagSrc(e)&&(b.isImageSrc(t)||b.isColor(t))}static getSrcURL(e){return typeof e=="string"?e:W.isTagSrc(e)?W.getSrcFromTags(e.state.currentSrc,e.config.src.resolve):W.isStaticSrc(e)?b.isStaticImageData(e.state.currentSrc)?b.srcToURL(e.state.currentSrc):b.isColor(e.state.currentSrc)?null:e.state.currentSrc:null}static getSrcFromTags(e,t){return t(...e)}static fromSrc(e){return new W({src:e})}constructor(e={}){super();let t=W.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 Ve,n=>{if(b.isImageSrc(e)||b.isColor(e)){if(b.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 o=new z(n,z.ActionTypes.setAppearance,new S().setContent([e,t?.copy()]));return n.chain(o).chain(this._flush())}})}darken(e,t,n){return this.combineActions(new Ve,o=>o.chain(this._setDarkness(o,e,t,n)))}addWearable(e){let t=Array.isArray(e)?e:[e];for(let n of t){if(n===this)throw new X("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:W.StateSerializer.serialize(this.state),transformState:re.TransformStateSerializer.serialize(this.transformState.get())}}fromData(e){return this.state=W.StateSerializer.deserialize(e.state),this.transformState=re.deserialize(e.transformState),this}_applyTransition(e,t){return new pe(this.chain(),ce.applyTransition,new S().setContent([e,t]))}_init(e,t){return new pe(this.chain(),ce.init,new S().setContent([e,t||this.config.layer||null]))}_initWearable(e){return new z(this.chain(),z.ActionTypes.initWearable,new S().setContent([e]))}_flush(){return new z(this.chain(),z.ActionTypes.flush,new S)}reset(){return this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(this.userConfig),this}resolveTags(e,t){if(!W.isTagSrc(this))throw new Error(`Tag not defined
6
+ To prevent unintended behavior, the sound marked as bgm cannot be played using \`play()\`.`);return this.pushAction(Pe.ActionTypes.play,[{end:this.state.volume,duration:e||0}])}stop(e){return this.pushAction(Pe.ActionTypes.stop,[{end:0,duration:e||0}])}setVolume(e,t){return this.pushAction(Pe.ActionTypes.setVolume,[e,t||0])}setRate(e){return this.pushAction(Pe.ActionTypes.setRate,[e])}pause(e){return this.pushAction(Pe.ActionTypes.pause,[{end:0,duration:e||0}])}resume(e){return this.pushAction(Pe.ActionTypes.resume,[{end:this.state.volume,duration:e||0}])}getSrc(){return this.config.src}toData(){return{state:Y.StateSerializer.serialize(this.state)}}fromData(e){return this.state=Y.StateSerializer.deserialize(e.state),this}copy(){return new Y(this.userConfig.get())}reset(){return this.state=this.getInitialState(this.userConfig),this}getInitialState(e){return Y.DefaultState.create({...e.get()}).get()}pushAction(e,t){return this.chain(new Pe(this.chain(),e,new S().setContent(t)))}};Y.noSound="data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgA",Y.DefaultUserConfig=new H({src:Y.noSound,loop:!1,volume:1,streaming:!1,rate:1,seek:0,type:"sound"}),Y.DefaultConfig=new H({src:Y.noSound,loop:!1,streaming:!1,seek:0,type:"sound"}),Y.DefaultState=new H({volume:1,rate:1,paused:!1}),Y.StateSerializer=new be;var ve=Y;var Ce=class Ce{static isSentence(e){return e instanceof Ce}static toSentence(e){return Ce.isSentence(e)?e:new Ce(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 U.isWord(e)?e:new U(e)}static formatStaticWord(e,t){return Array.isArray(e)?e.map(n=>this.formatStaticWord(n,t)).flat(2):[U.isWord(e)?e:new U(e,t)]}static isSentencePrompt(e){return Array.isArray(e)?e.every(Ce.isSingleWord):Ce.isSingleWord(e)}static isSingleWord(e){return typeof e=="string"||U.isWord(e)||Se.isPause(e)||typeof e=="function"}constructor(e,t={}){this.text=Ce.format(e),this.config=R(Ce.defaultConfig,{...t,voice:ve.toSound(t.voice)}),this.state=Mi(Ce.defaultState)}toData(){return null}fromData(e){return this.state=R(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 o=this.text[n].evaluate(e);t.push(...Ce.formatStaticWord(o))}return t}copy(){return new Ce([...this.text],this.config)}};Ce.defaultConfig={pause:!0,voice:null,character:null,voiceId:null},Ce.defaultState={};var ne=Ce;var Bn=class Bn extends M{static getVoice(e,t){let n=e.getLastScene();if(!n)throw new Error("No scene found when trying to play voice");let{voiceId:o,voice:i}=t.config;return!o&&!i?null:ve.toSound(n.getVoice(o)||i)}executeAction(e,t){if(this.type===Rn.say){let n=new h(f=>f).registerSkipController(new L(()=>{c.cancel()})),o=new se(n),i=this.contentNode.getContent(),r=Bn.getVoice(e,i);if(r){let f=e.audioManager.play(r);o.attachChild(f)}let a=e.idManager.generateId(),c=e.createDialog(a,i,()=>{if(r){let f=e.audioManager.stop(r);e.timelines.attachTimeline(f)}e.gameHistory.resolvePending(l),n.resolve({type:this.type,node:this.contentNode.getChild()})});e.getLiveGame().setLastDialog(c.text,this.callee.state.name),e.timelines.attachTimeline(o);let{id:l}=e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:o},()=>{if(r&&e.audioManager.isPlaying(r)){let f=e.audioManager.stop(r);o.attachChild(f)}c.cancel()});return e.gameHistory.push({token:l,action:this,element:{type:"say",text:c.text,voice:r?r.getSrc():null,character:this.callee.state.name},isPending:!0}),n}else if(this.type===Rn.setName){let n=this.callee.state.name;return this.callee.state.name=this.contentNode.getContent()[0],e.actionHistory.push({action:this,stackModel:t.stackModel},o=>{this.callee.state.name=o},[n]),super.executeAction(e,t)}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("CharacterAction")}};Bn.ActionTypes=Rn;var nt=Bn;var nn=class nn extends q{constructor(e,t={}){super(),this.config=R(nn.defaultConfig,t),this.state={name:e||""};let n=this,o=function(i,r,...a){return n.call(i,r,...a)};return new Proxy(o,{get(i,r){return n[r]},set(i,r,a){return n[r]=a,!0},has(i,r){return r in n}})}say(e,t,...n){if(Array.isArray(e)&&e.every(c=>typeof c=="string")&&[t,...n].length>0&&[t,...n].every(c=>ne.isSingleWord(c))){let c=e,l=ne.format([t,...n]),f=new ne(Ni(c,l),{character:this}),p=new nt(this.chain(),nt.ActionTypes.say,new S().setContent(f));return this.chain(p)}let o=t||{},i=e,r=Array.isArray(i)?new ne(i,{...o,character:this}):(ne.isSentence(i)?i:new ne(i,{...o,character:this})).copy();r.setCharacter(this);let a=new nt(this.chain(),nt.ActionTypes.say,new S().setContent(r));return this.chain(a)}setName(e){let t=new nt(this.chain(),nt.ActionTypes.setName,new S().setContent([e]));return this.chain(t)}apply(e,t,...n){return this.say.apply(this,[e,t,...n])}call(e,t,...n){return Array.isArray(e)&&"raw"in e?t&&ne.isSingleWord(t)?this.say(e,t,...n):this.say(e):typeof e=="string"?this.say(e,t):ne.isSentence(e)?this.say(e):this.say(e,t)}};nn.defaultCharacterColor="#000",nn.defaultConfig={};var jn=nn,gt=new jn(null);var Ve=class s extends q{constructor(t={}){super();this.config=t}static do(t){return new s().do(t)}static doAsync(t){return new s().doAsync(t)}static any(t){return new s().any(t)}static all(t){return new s().all(t)}static allAsync(t){return new s().allAsync(t)}static repeat(t,n){return new s().repeat(t,n)}static sleep(t){return new s().sleep(t)}do(t){return this.push(te.ActionTypes.do,t)}doAsync(t){return this.push(te.ActionTypes.doAsync,t)}any(t){return this.pushUnchained(te.ActionTypes.any,t)}all(t){return this.pushUnchained(te.ActionTypes.all,t)}allAsync(t){return this.pushUnchained(te.ActionTypes.allAsync,t)}repeat(t,n){return this.push(te.ActionTypes.repeat,n,t)}sleep(t){return this.push(te.ActionTypes.sleep,[],t)}push(t,n,...o){let i=this.narrativeToActions(n),r=new te(this.chain(),t,new S().setContent([this.construct(i),...o]));return this.chain(r)}pushUnchained(t,n,...o){let i=this.narrativeToActions(n),r=new te(this.chain(),t,new S().setContent([i,...o]));return this.chain(r)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?gt.say(n).getActions():fe.toActions([n]))}};var pe=class extends M{executeAction(e,t){if(this.type===ce.applyTransform){let[n]=this.contentNode.getContent(),o=this.callee;return this.applyTransform(e,o,n,t)}else if(this.type===ce.applyTransition){let[n,o]=this.contentNode.getContent(),i=this.callee,r=o?o(n):n;return this.applyTransition(e,i,r,t)}else if(this.type===ce.init){let[n,o,i]=this.contentNode.getContent(),r=this.callee;return this.initDisplayable(e,n,r,o||null,i,t)}throw this.unknownTypeError()}applyTransform(e,t,n,o,i){let r=new h().registerSkipController(new L(()=>(e.logger.info("Displayable Transition","Skipped"),super.executeAction(e,o)))),a=e.getExposedStateForce(t),c=t.transformState.clone(),l=a.applyTransform(n,()=>{i?.(),r.resolve(super.executeAction(e,o))}),f=e.timelines.attachTimeline(r).attachChild(l);return e.actionHistory.push({action:this,stackModel:o.stackModel,timeline:f},p=>{r.isSettled()||r.abort(),l.abort(),t.transformState.forceOverwrite(p.state)},[c]),r}applyTransition(e,t,n,o,i){let r=new h().registerSkipController(new L(()=>(e.logger.info("Displayable Transition","Skipped"),super.executeAction(e,o)))),c=e.getExposedStateForce(t).applyTransition(n,()=>{i?.(),r.resolve(super.executeAction(e,o))}),l=e.timelines.attachTimeline(r).attachChild(c);return e.actionHistory.push({action:this,stackModel:o.stackModel,timeline:l},()=>{r.isSettled()||r.abort(),c.abort()}),r}initDisplayable(e,t,n,o,i=!0,r){if(i!==!1){let l=e.findElementByDisplayable(this.callee,o);l&&e.disposeDisplayable(n,l.scene,o),e.createDisplayable(n,t,o)}e.flush();let a=new h().registerSkipController(new L(()=>super.executeAction(e,r)));e.getExposedStateAsync(n,l=>{l.initDisplayable(()=>{a.resolve(super.executeAction(e,r))})});let c=e.timelines.attachTimeline(a);return e.actionHistory.push({action:this,stackModel:r.stackModel,timeline:c},()=>{i!==!1&&e.findElementByDisplayable(n,o)&&e.disposeDisplayable(n,t,o)}),a}stringify(e,t,n){return super.stringifyWithName("DisplayableAction")}};pe.ActionTypes=ce;var wt=class wt{constructor(){this.src=[];this.future=[]}static catSrc(e){let t=new Set,n=new Set,o=new Set;return e.forEach(({type:i,src:r})=>{i===wt.SrcTypes.image?t.add(r):i===wt.SrcTypes.video?n.add(r):o.add(r)}),{image:Array.from(t),video:Array.from(n),audio:Array.from(o)}}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(ae,ee.jumpTo)){let n=t.contentNode.getContent()[0],i=e.getScene(n,!0).state.backgroundImage;if(b.isImageURL(i.config.src))return{type:"image",src:i.config.src,activeType:"once"}}else if(t instanceof z){let n=t;if(t.is(z,ke.setSrc)){let o=t.contentNode.getContent()[0];if(b.isImageSrc(o))return{type:"image",src:b.srcToURL(o),activeType:"scene"}}else{if(t.type===ke.initWearable)return{type:"image",src:t.contentNode.getContent()[0],activeType:"scene"};if(t.type===ke.setAppearance){let o=t.contentNode.getContent()[0];if(!n.callee.config.src||typeof n.callee.config.src?.resolve!="function")throw n.callee._invalidSrcHandlerError();if(I.isTagSrc(n.callee)&&o.length===n.callee.config.src.groups.length)return{type:"image",src:I.getSrcFromTags(o,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||b.isStaticImageData(e)){if(e instanceof I){if(!b.isImageURL(e.state.currentSrc))return this;if(this.isSrcRegistered(I.getSrcURL(e)))return this}else if(this.isSrcRegistered(b.srcToURL(e.src)))return this;this.src.push({type:"image",src:b.isStaticImageData(e)?b.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===wt.SrcTypes.audio?t===n.src.getSrc():n.type===wt.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)}};wt.SrcTypes={image:"image",video:"video",audio:"audio"};var ge=wt;var qe=class extends q{constructor(){super(...arguments);this.srcManager=new ge}pos(t,n,o){return this.transform(new O({position:t},{duration:n,ease:o}))}zoom(t,n,o){return this.transform(new O({zoom:t},{duration:n,ease:o}))}scaleX(t,n,o){return this.transform(new O({scaleX:t},{duration:n,ease:o}))}scaleY(t,n,o){return this.transform(new O({scaleY:t},{duration:n,ease:o}))}scale(t,n,o,i){return this.transform(new O({scaleX:t,scaleY:n},{duration:o,ease:i}))}scaleXY(t,n,o,i){return this.scale(t,n,o,i)}rotate(t,n,o){return this.transform(new O({rotation:t},{duration:n,ease:o}))}opacity(t,n,o){return this.transform(new O({opacity:t},{duration:n,ease:o}))}transform(t){let n=this.chain(),o=new pe(n,ce.applyTransform,new S().setContent([t.copy()]));return n.chain(o)}show(t){let n=this.chain(),o=t instanceof O?t.copy():new O({opacity:1},t),i=new pe(n,ce.applyTransform,new S().setContent([o]));return n.chain(i)}hide(t){let n=this.chain(),o=t instanceof O?t.copy():new O({opacity:0},t),i=new pe(n,ce.applyTransform,new S().setContent([o]));return n.chain(i)}};var W=class W extends qe{static getInitialSrc(e){if(this.isTagDefinition(e.src))return[...e.src.defaults];let t=e.src;return b.isStaticImageData(t)?b.srcToURL(t):b.isColor(t)?t:b.isImageSrc(t)?b.srcToURL(t):W.DefaultImagePlaceholder}static isTagSrc(e){return!!e.config.src}static isTagDefinition(e){return typeof e=="object"&&e!==null&&!b.isImageSrc(e)&&!b.isColor(e)&&"defaults"in e}static isStaticSrc(e){let t=e.userConfig.get().src;return!this.isTagSrc(e)&&(b.isImageSrc(t)||b.isColor(t))}static getSrcURL(e){return typeof e=="string"?e:W.isTagSrc(e)?W.getSrcFromTags(e.state.currentSrc,e.config.src.resolve):W.isStaticSrc(e)?b.isStaticImageData(e.state.currentSrc)?b.srcToURL(e.state.currentSrc):b.isColor(e.state.currentSrc)?null:e.state.currentSrc:null}static getSrcFromTags(e,t){return t(...e)}static fromSrc(e){return new W({src:e})}constructor(e={}){super();let t=W.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 Ve,n=>{if(b.isImageSrc(e)||b.isColor(e)){if(b.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 o=new z(n,z.ActionTypes.setAppearance,new S().setContent([e,t?.copy()]));return n.chain(o).chain(this._flush())}})}darken(e,t,n){return this.combineActions(new Ve,o=>o.chain(this._setDarkness(o,e,t,n)))}addWearable(e){let t=Array.isArray(e)?e:[e];for(let n of t){if(n===this)throw new X("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:W.StateSerializer.serialize(this.state),transformState:re.TransformStateSerializer.serialize(this.transformState.get())}}fromData(e){return this.state=W.StateSerializer.deserialize(e.state),this.transformState=re.deserialize(e.transformState),this}_applyTransition(e,t){return new pe(this.chain(),ce.applyTransition,new S().setContent([e,t]))}_init(e,t){return new pe(this.chain(),ce.init,new S().setContent([e,t||this.config.layer||null]))}_initWearable(e){return new z(this.chain(),z.ActionTypes.initWearable,new S().setContent([e]))}_flush(){return new z(this.chain(),z.ActionTypes.flush,new S)}reset(){return this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(this.userConfig),this}resolveTags(e,t){if(!W.isTagSrc(this))throw new Error(`Tag not defined
7
7
  Tag must be defined in the image config`);let n=this.constructTagMap(this.config.src.groups),o=new Map,i=[];this.config.src.groups.forEach(a=>{o.set(a,null)});let r=a=>{a.forEach(c=>{let l=n.get(c);l&&o.set(l,c)})};return r(e),r(t),this.config.src.groups.forEach(a=>{let c=o.get(a);if(!c)throw new Error(`Invalid Tag Group. Tag group "${a.join(", ")}" is not resolved`);i.push(c)}),i}_mixedSrcError(){throw new X(`Trying to mix src and tags
8
8
  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
9
9
  Wearable must be an Image with isWearable set to true
@@ -13,7 +13,7 @@ Image below violates the rule:
13
13
  Tag "${i}" is conflicting with another tag
14
14
  Error found in config.tag.defaults`);if(!n.has(i))throw new Error(`Tag not found
15
15
  Tag "${i}" is not defined in tagDefinitions
16
- Error found in config.tag.defaults`);n.get(i)?.forEach(r=>o.add(r))}}return this}constructTagMap(e){let t=new Map;for(let n of e)for(let o of n)t.set(o,n);return t}_setDarkness(e,t,n,o){return new z(e,z.ActionTypes.setDarkness,new S().setContent([t,n,o]))}};W.DefaultImagePlaceholder="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='1' height='1'></svg>",W.StateSerializer=new be,W.DefaultUserConfig=new N({name:"(anonymous)",autoInit:!0,src:W.DefaultImagePlaceholder,autoFit:!1,layer:void 0,...re.DefaultTransformState.getDefaultConfig()},{position:e=>v.tryParsePosition(e)}),W.DefaultImageConfig=new N({wearables:[],isWearable:!1,name:"(anonymous)",autoInit:!0,src:null,autoFit:!1,layer:void 0,isBackground:!1}),W.DefaultImageState=new N({currentSrc:W.DefaultImagePlaceholder,darkness:0});var I=W;var kt=(t=>(t[t.Number=0]="Number",t[t.HexColor=1]="HexColor",t))(kt||{});import{animate as os}from"motion/react";var Qe=class{requestAnimations(e){let t=e.map(p=>p.start),n=[],o=0,i=[],r=[],a=[];return{onUpdate:p=>(i.push(p),{cancel:()=>{let d=i.indexOf(p);d!==-1&&i.splice(d,1)}}),onComplete:p=>(r.push(p),{cancel:()=>{let d=r.indexOf(p);d!==-1&&r.splice(d,1)}}),onCanceled:p=>(a.push(p),{cancel:()=>{let d=a.indexOf(p);d!==-1&&a.splice(d,1)}}),complete:()=>{o!==e.length&&n.forEach(p=>p.complete())},start:()=>{if(n.length>0)throw new Error("Animation controllers are already started");e.forEach((p,d)=>{n.push(this.requestMotion(p,{onComplete:()=>{t[d]=p.end,i.forEach(g=>g(t)),o++,o===e.length&&r.forEach(g=>g())},onUpdate:g=>{t[d]=g,i.forEach(u=>u(t))}}))})},cancel:()=>{n.forEach(p=>p.cancel()),a.forEach(p=>p())}}}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 os(e.start,e.end,{duration:e.duration/1e3,onUpdate:n=>{t.onUpdate&&t.onUpdate(n)},onComplete:()=>{t.onComplete&&t.onComplete()},ease:e.ease})}};Qe.AnimationType=kt;var ot=class extends Qe{_setPrevSrc(e){return this._prevSrc=e,this}_setTargetSrc(e){return this._targetSrc=e,this}_setCurrentSrc(e){return this._currentSrc=e,this}_getPrevSrc(){return this._prevSrc}_getTargetSrc(){return this._targetSrc}_getCurrentSrc(){return this._currentSrc}requestAnimations(e){let t=super.requestAnimations(e);return t.onComplete(()=>{this._setCurrentSrc(this._getTargetSrc())}),t}asPrev(e){return super.asPrev((...t)=>R(e(...t),this._srcToProps(this._prevSrc)))}asTarget(e){return super.asTarget((...t)=>R(e(...t),this._srcToProps(this._targetSrc)))}_srcToProps(e){if(b.isColor(e))return{src:I.DefaultImagePlaceholder,style:{backgroundColor:b.isRGBAColor(e)?b.RGBAColorToHex(e):e}};if(b.isImageSrc(e))return{src:b.srcToURL(e)};throw new X("Image transition src cannot be identified, using: "+e)}};var qn=class s extends ot{constructor(t,n,o,i){super();this.prevDarkness=t;this.targetDarkness=n;this.duration=o;this.easing=i}createTask(){return{animations:[{type:0,start:this.prevDarkness,end:this.targetDarkness,duration:this.duration,ease:this.easing}],resolve:[this.asTarget(t=>({style:{filter:`brightness(${1-t})`}})),this.asPrev(()=>({style:{opacity:0},height:0,width:0}))]}}copy(){return new s(this.prevDarkness,this.targetDarkness,this.duration,this.easing)}};var on=class on extends M{static resolveTagSrc(e,t){if(!I.isTagSrc(e))throw e._mixedSrcError();let n=e.state.currentSrc,o=e.resolveTags(n,t);return I.getSrcFromTags(o,e.config.src.resolve)}static resolveCurrentSrc(e){if(I.isStaticSrc(e))return b.isImageSrc(e.state.currentSrc)?b.srcToURL(e.state.currentSrc):e.state.currentSrc;if(I.isTagSrc(e))return I.getSrcFromTags(e.state.currentSrc,e.config.src.resolve);throw e._mixedSrcError()}executeAction(e,t){if(this.type===ke.initWearable){let[n]=this.contentNode.getContent(),o=e.getExposedStateForce(this.callee),i=new h(r=>r);return o.createWearable(n),e.getExposedStateAsync(n,r=>{r.initDisplayable(()=>{i.resolve(super.executeAction(e,t))})}),e.actionHistory.push({action:this,stackModel:t.stackModel},r=>{o.disposeWearable(r)},[n]),i}else if(this.type===ke.setSrc){let n=this.contentNode.getContent()[0];if(b.isColor(n)&&!this.callee.config.isBackground)throw new X("Color src is not allowed for non-background image");let o=this.callee.state.currentSrc;return this.callee.state.currentSrc=n,e.logger.debug("Image Set Src",n),e.actionHistory.push({action:this,stackModel:t.stackModel},i=>{this.callee.state.currentSrc=i},[o]),e.stage.update(),super.executeAction(e,t)}else{if(this.type===ke.flush)return super.executeAction(e,t);if(this.type===ke.setAppearance){let[n,o]=this.contentNode.getContent();if(!I.isTagSrc(this.callee))throw this.callee._mixedSrcError();let i=this.callee.state.currentSrc,r=this.callee.resolveTags(i,n),a=[...i],c=I.getSrcFromTags(r,this.callee.config.src.resolve),l=()=>{this.callee.state.currentSrc=a};if(e.logger.debug("Image - Set Appearance",r,c),o){let f=new h(u=>u).registerSkipController(new L(()=>super.executeAction(e,t)));o._setPrevSrc(on.resolveCurrentSrc(this.callee))._setTargetSrc(c);let d=e.getExposedStateForce(this.callee).applyTransition(o,()=>{this.callee.state.currentSrc=r,f.resolve(super.executeAction(e,t))}),g=e.timelines.attachTimeline(f).attachChild(d);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:g},l,[]),f}return this.callee.state.currentSrc=r,e.actionHistory.push({action:this,stackModel:t.stackModel},l),super.executeAction(e,t)}else if(this.type===ke.setDarkness){let[n,o,i]=this.contentNode.getContent(),r=this.callee.state.darkness,a=()=>{this.callee.state.darkness=r},c=e.getExposedStateForce(this.callee);if(o&&i){let l=on.resolveCurrentSrc(this.callee),f=new h(u=>u),p=new qn(r,n,o,i)._setPrevSrc(l)._setTargetSrc(l),d=c.applyTransition(p,()=>{this.callee.state.darkness=n,f.resolve(super.executeAction(e,t))}),g=e.timelines.attachTimeline(f).attachChild(d);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:g},()=>{f.isSettled()||f.abort(),d.abort(),a()}),f}return this.callee.state.darkness=n,e.actionHistory.push({action:this,stackModel:t.stackModel},a),c.updateStyleSync(),super.executeAction(e,t)}}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("ImageAction")}};on.ActionTypes=ke;var z=on;var it=class it extends M{static handleSceneInit(e,t,n,o){return n.isSceneActive(e)?t:(n.registerSrcManager(e.srcManager).addScene(e).flush(),e.local.init(n.getStorable()),n.getExposedStateAsync(e,i=>{it.initBackgroundMusic(e,i),o.resolve(t),n.logger.debug("Scene Action","Scene init")}),o)}static initBackgroundMusic(e,t){e.state.backgroundMusic&&t.setBackgroundMusic(e.state.backgroundMusic,e.config.backgroundMusicFade)}static createSceneSnapshot(e,t){let n=t.findElementByScene(e);if(!n)throw new X("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,o=t.findElementByScene(n);o&&t.removeElement(o);let i=t.fromElementSnapshot(e.element);t.addElement(i),n.local.getNamespace(t.getStorable()).load(e.local),e.state&&n.fromData(e.state),e.background&&n.background.fromData(e.background)}applyTransition(e,t,n){let o=new h().registerSkipController(new L(()=>(e.logger.info("Background Transition","Skipped"),super.executeAction(e,n))));return e.getExposedStateForce(this.callee.background).applyTransition(t,()=>{o.resolve(super.executeAction(e,n))}),e.timelines.attachTimeline(o),o}exit(e){e.offSrcManager(this.callee.srcManager).removeScene(this.callee),this.callee.state.backgroundImage.reset()}executeAction(e,t){if(this.type===ee.action)return super.executeAction(e,t);if(this.is(it,"scene:init")){let n=new h(r=>r),o=e.timelines.attachTimeline(n);e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:o},()=>{this.exit(e)},[]);let i={type:this.type,node:this.contentNode.getChild()};return it.handleSceneInit(this.callee,i,e,h.forward(n,i))}else if(this.type===ee.exit){let n=it.createSceneSnapshot(this.callee,e);return e.actionHistory.push({action:this,stackModel:t.stackModel},o=>{let i=new h(r=>r);e.timelines.attachTimeline(i),it.handleSceneInit(this.callee,{type:this.type,node:this.contentNode.getChild()},e,i),it.restoreSceneSnapshot(o,e)},[n]),e.getStorable().removeNamespace(this.callee.local.getNamespaceName()),this.exit(e),super.executeAction(e,t)}else if(this.type===ee.jumpTo){let n=this.contentNode.getContent()[0],o=e.getStory().getScene(n);if(!o)throw this._sceneNotFoundError(this.getSceneName(n));let i=e.getLiveGame().getStackModelForce().serialize();e.actionHistory.push({action:this,stackModel:t.stackModel},a=>{let[c]=e.getLiveGame().constructMaps();e.getLiveGame().getStackModelForce().deserialize(a,c)},[i]);let r=o.getSceneRoot().contentNode;return e.getLiveGame().clearMainStack().getStackModelForce().push({type:this.type,node:r}),null}else if(this.type===ee.setBackgroundMusic){let[n,o]=this.contentNode.getContent(),i=this.callee,r=e.getExposedStateForce(i),a=i.state.backgroundMusic;return e.actionHistory.push({action:this,stackModel:t.stackModel},c=>{c&&r.setBackgroundMusic(c,0)},[a]),r.setBackgroundMusic(n,o||0),this.callee.state.backgroundMusic=n,super.executeAction(e,t)}else{if(this.type===ee.preUnmount)return this.callee.events.emit("event:scene.preUnmount"),super.executeAction(e,t);if(this.type===ee.transitionToScene){let[n,o,i]=this.contentNode.getContent();return n._setPrevSrc(z.resolveCurrentSrc(this.callee.background)),o?n._setTargetSrc(z.resolveCurrentSrc(o.background)):i&&n._setTargetSrc(i),this.applyTransition(e,n,t)}}throw new Error("Unknown scene action type: "+this.type)}getFutureActions(e,t={}){if(this.type===ee.jumpTo&&t.allowFutureScene!==!1){let o=this.contentNode.getContent()[0],i=e.getScene(o,!0);i.isSceneRootConstructed()||i.constructSceneRoot(e);let r=e.getScene(o,!0).getSceneRoot()?.contentNode;return r?.action?[r.action]:[]}let n=this.contentNode.getChild()?.action;return n?[n]:[]}_sceneNotFoundError(e){return new X(`Scene with name ${e} not found
16
+ Error found in config.tag.defaults`);n.get(i)?.forEach(r=>o.add(r))}}return this}constructTagMap(e){let t=new Map;for(let n of e)for(let o of n)t.set(o,n);return t}_setDarkness(e,t,n,o){return new z(e,z.ActionTypes.setDarkness,new S().setContent([t,n,o]))}};W.DefaultImagePlaceholder="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='1' height='1'></svg>",W.StateSerializer=new be,W.DefaultUserConfig=new H({name:"(anonymous)",autoInit:!0,src:W.DefaultImagePlaceholder,autoFit:!1,layer:void 0,...re.DefaultTransformState.getDefaultConfig()},{position:e=>v.tryParsePosition(e)}),W.DefaultImageConfig=new H({wearables:[],isWearable:!1,name:"(anonymous)",autoInit:!0,src:null,autoFit:!1,layer:void 0,isBackground:!1}),W.DefaultImageState=new H({currentSrc:W.DefaultImagePlaceholder,darkness:0});var I=W;var kt=(t=>(t[t.Number=0]="Number",t[t.HexColor=1]="HexColor",t))(kt||{});import{animate as os}from"motion/react";var Qe=class{requestAnimations(e){let t=e.map(p=>p.start),n=[],o=0,i=[],r=[],a=[];return{onUpdate:p=>(i.push(p),{cancel:()=>{let d=i.indexOf(p);d!==-1&&i.splice(d,1)}}),onComplete:p=>(r.push(p),{cancel:()=>{let d=r.indexOf(p);d!==-1&&r.splice(d,1)}}),onCanceled:p=>(a.push(p),{cancel:()=>{let d=a.indexOf(p);d!==-1&&a.splice(d,1)}}),complete:()=>{o!==e.length&&n.forEach(p=>p.complete())},start:()=>{if(n.length>0)throw new Error("Animation controllers are already started");e.forEach((p,d)=>{n.push(this.requestMotion(p,{onComplete:()=>{t[d]=p.end,i.forEach(g=>g(t)),o++,o===e.length&&r.forEach(g=>g())},onUpdate:g=>{t[d]=g,i.forEach(u=>u(t))}}))})},cancel:()=>{n.forEach(p=>p.cancel()),a.forEach(p=>p())}}}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 os(e.start,e.end,{duration:e.duration/1e3,onUpdate:n=>{t.onUpdate&&t.onUpdate(n)},onComplete:()=>{t.onComplete&&t.onComplete()},ease:e.ease})}};Qe.AnimationType=kt;var ot=class extends Qe{_setPrevSrc(e){return this._prevSrc=e,this}_setTargetSrc(e){return this._targetSrc=e,this}_setCurrentSrc(e){return this._currentSrc=e,this}_getPrevSrc(){return this._prevSrc}_getTargetSrc(){return this._targetSrc}_getCurrentSrc(){return this._currentSrc}requestAnimations(e){let t=super.requestAnimations(e);return t.onComplete(()=>{this._setCurrentSrc(this._getTargetSrc())}),t}asPrev(e){return super.asPrev((...t)=>R(e(...t),this._srcToProps(this._prevSrc)))}asTarget(e){return super.asTarget((...t)=>R(e(...t),this._srcToProps(this._targetSrc)))}_srcToProps(e){if(b.isColor(e))return{src:I.DefaultImagePlaceholder,style:{backgroundColor:b.isRGBAColor(e)?b.RGBAColorToHex(e):e}};if(b.isImageSrc(e))return{src:b.srcToURL(e)};throw new X("Image transition src cannot be identified, using: "+e)}};var qn=class s extends ot{constructor(t,n,o,i){super();this.prevDarkness=t;this.targetDarkness=n;this.duration=o;this.easing=i}createTask(){return{animations:[{type:0,start:this.prevDarkness,end:this.targetDarkness,duration:this.duration,ease:this.easing}],resolve:[this.asTarget(t=>({style:{filter:`brightness(${1-t})`}})),this.asPrev(()=>({style:{opacity:0},height:0,width:0}))]}}copy(){return new s(this.prevDarkness,this.targetDarkness,this.duration,this.easing)}};var on=class on extends M{static resolveTagSrc(e,t){if(!I.isTagSrc(e))throw e._mixedSrcError();let n=e.state.currentSrc,o=e.resolveTags(n,t);return I.getSrcFromTags(o,e.config.src.resolve)}static resolveCurrentSrc(e){if(I.isStaticSrc(e))return b.isImageSrc(e.state.currentSrc)?b.srcToURL(e.state.currentSrc):e.state.currentSrc;if(I.isTagSrc(e))return I.getSrcFromTags(e.state.currentSrc,e.config.src.resolve);throw e._mixedSrcError()}executeAction(e,t){if(this.type===ke.initWearable){let[n]=this.contentNode.getContent(),o=e.getExposedStateForce(this.callee),i=new h(r=>r);return o.createWearable(n),e.getExposedStateAsync(n,r=>{r.initDisplayable(()=>{i.resolve(super.executeAction(e,t))})}),e.actionHistory.push({action:this,stackModel:t.stackModel},r=>{o.disposeWearable(r)},[n]),i}else if(this.type===ke.setSrc){let n=this.contentNode.getContent()[0];if(b.isColor(n)&&!this.callee.config.isBackground)throw new X("Color src is not allowed for non-background image");let o=this.callee.state.currentSrc;return this.callee.state.currentSrc=n,e.logger.debug("Image Set Src",n),e.actionHistory.push({action:this,stackModel:t.stackModel},i=>{this.callee.state.currentSrc=i},[o]),e.stage.update(),super.executeAction(e,t)}else{if(this.type===ke.flush)return super.executeAction(e,t);if(this.type===ke.setAppearance){let[n,o]=this.contentNode.getContent();if(!I.isTagSrc(this.callee))throw this.callee._mixedSrcError();let i=this.callee.state.currentSrc,r=this.callee.resolveTags(i,n),a=[...i],c=I.getSrcFromTags(r,this.callee.config.src.resolve),l=()=>{this.callee.state.currentSrc=a};if(e.logger.debug("Image - Set Appearance",r,c),o){let f=new h(u=>u).registerSkipController(new L(()=>super.executeAction(e,t)));o._setPrevSrc(on.resolveCurrentSrc(this.callee))._setTargetSrc(c);let d=e.getExposedStateForce(this.callee).applyTransition(o,()=>{this.callee.state.currentSrc=r,f.resolve(super.executeAction(e,t))}),g=e.timelines.attachTimeline(f).attachChild(d);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:g},l,[]),f}return this.callee.state.currentSrc=r,e.actionHistory.push({action:this,stackModel:t.stackModel},l),super.executeAction(e,t)}else if(this.type===ke.setDarkness){let[n,o,i]=this.contentNode.getContent(),r=this.callee.state.darkness,a=()=>{this.callee.state.darkness=r},c=e.getExposedStateForce(this.callee);if(o&&i){let l=on.resolveCurrentSrc(this.callee),f=new h(u=>u),p=new qn(r,n,o,i)._setPrevSrc(l)._setTargetSrc(l),d=c.applyTransition(p,()=>{this.callee.state.darkness=n,f.resolve(super.executeAction(e,t))}),g=e.timelines.attachTimeline(f).attachChild(d);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:g},()=>{f.isSettled()||f.abort(),d.abort(),a()}),f}return this.callee.state.darkness=n,e.actionHistory.push({action:this,stackModel:t.stackModel},a),c.updateStyleSync(),super.executeAction(e,t)}}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("ImageAction")}};on.ActionTypes=ke;var z=on;var it=class it extends M{static handleSceneInit(e,t,n,o){return n.isSceneActive(e)?t:(n.registerSrcManager(e.srcManager).addScene(e).flush(),e.local.init(n.getStorable()),n.getExposedStateAsync(e,i=>{it.initBackgroundMusic(e,i),o.resolve(t),n.logger.debug("Scene Action","Scene init")}),o)}static initBackgroundMusic(e,t){e.state.backgroundMusic&&t.setBackgroundMusic(e.state.backgroundMusic,e.config.backgroundMusicFade)}static createSceneSnapshot(e,t){let n=t.findElementByScene(e);if(!n)throw new X("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,o=t.findElementByScene(n);o&&t.removeElement(o);let i=t.fromElementSnapshot(e.element);t.addElement(i),n.local.getNamespace(t.getStorable()).load(e.local),e.state&&n.fromData(e.state),e.background&&n.background.fromData(e.background)}applyTransition(e,t,n){let o=new h().registerSkipController(new L(()=>(e.logger.info("Background Transition","Skipped"),super.executeAction(e,n))));return e.getExposedStateForce(this.callee.background).applyTransition(t,()=>{o.resolve(super.executeAction(e,n))}),e.timelines.attachTimeline(o),o}exit(e){e.offSrcManager(this.callee.srcManager).removeScene(this.callee),this.callee.state.backgroundImage.reset()}executeAction(e,t){if(this.type===ee.action)return super.executeAction(e,t);if(this.is(it,"scene:init")){let n=new h(r=>r),o=e.timelines.attachTimeline(n);e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:o},()=>{this.exit(e)},[]);let i={type:this.type,node:this.contentNode.getChild()};return it.handleSceneInit(this.callee,i,e,h.forward(n,i))}else if(this.type===ee.exit){let n=it.createSceneSnapshot(this.callee,e);return e.actionHistory.push({action:this,stackModel:t.stackModel},o=>{let i=new h(r=>r);e.timelines.attachTimeline(i),it.handleSceneInit(this.callee,{type:this.type,node:this.contentNode.getChild()},e,i),it.restoreSceneSnapshot(o,e)},[n]),e.getStorable().removeNamespace(this.callee.local.getNamespaceName()),this.exit(e),super.executeAction(e,t)}else if(this.type===ee.jumpTo){let n=this.contentNode.getContent()[0],o=e.getStory().getScene(n);if(!o)throw this._sceneNotFoundError(this.getSceneName(n));let i=e.getLiveGame().getStackModelForce().serialize();e.actionHistory.push({action:this,stackModel:t.stackModel},a=>{let[c]=e.getLiveGame().constructMaps();e.getLiveGame().getStackModelForce().deserialize(a,c)},[i]);let r=o.getSceneRoot().contentNode;return e.getLiveGame().clearMainStack().getStackModelForce().push({type:this.type,node:r}),null}else if(this.type===ee.setBackgroundMusic){let[n,o]=this.contentNode.getContent(),i=this.callee,r=e.getExposedStateForce(i),a=i.state.backgroundMusic;return e.actionHistory.push({action:this,stackModel:t.stackModel},c=>{c&&r.setBackgroundMusic(c,0)},[a]),r.setBackgroundMusic(n,o||0),this.callee.state.backgroundMusic=n,super.executeAction(e,t)}else{if(this.type===ee.preUnmount)return this.callee.events.emit("event:scene.preUnmount"),super.executeAction(e,t);if(this.type===ee.transitionToScene){let[n,o,i]=this.contentNode.getContent();return n._setPrevSrc(z.resolveCurrentSrc(this.callee.background)),o?n._setTargetSrc(z.resolveCurrentSrc(o.background)):i&&n._setTargetSrc(i),this.applyTransition(e,n,t)}}throw new Error("Unknown scene action type: "+this.type)}getFutureActions(e,t={}){if(this.type===ee.jumpTo&&t.allowFutureScene!==!1){let o=this.contentNode.getContent()[0],i=e.getScene(o,!0);i.isSceneRootConstructed()||i.constructSceneRoot(e);let r=e.getScene(o,!0).getSceneRoot()?.contentNode;return r?.action?[r.action]:[]}let n=this.contentNode.getChild()?.action;return n?[n]:[]}_sceneNotFoundError(e){return new X(`Scene with name ${e} not found
17
17
  Make sure you have registered the scene using story.register
18
18
  Action: (id: ${this.getId()}) ${this.type}
19
19
  At: ${this.__stack}`)}getSceneName(e){return typeof e=="string"?e:e.config.name}stringify(e,t,n){if(this.type===ee.jumpTo){if(t.has(this))return super.stringifyWithContent("Scene","[[recursive]]");t.add(this);let[o]=this.contentNode.getContent();return super.stringifyWithContent("Scene",`jumpTo {${o.stringify(e,t,n)}}`)}return super.stringifyWithName("SceneAction")}};it.ActionTypes=ee;var ae=it;var Vo=class s{static isHexString(e){return typeof e!="string"?!1:/^#[0-9A-F]{6}$/i.test(e)}static fromHex(e){let t=e.slice(1),n=parseInt(t.slice(0,2),16),o=parseInt(t.slice(2,4),16),i=parseInt(t.slice(4,6),16),r=t.length===8?parseInt(t.slice(6,8),16)/255:1;return new s(n,o,i,r)}constructor(e,t,n,o=1){this.r=e,this.g=t,this.b=n,this.a=o}toString(){return`rgba(${this.r}, ${this.g}, ${this.b}, ${this.a})`}toHex(){return"#"+this.r.toString(16)+this.g.toString(16)+this.b.toString(16)}},ze=class ze{static srcToURL(e){return typeof e=="string"?e:e.src}static staticImageDataToSrc(e){return typeof e=="string"?e:e.src}static isStaticImageData(e){return e?.src!==void 0&&typeof e.src=="string"}static isExternalSrc(e){return e.startsWith("http://")||e.startsWith("https://")}static isImageSrc(e){return typeof e=="string"&&!this.isColor(e)||ze.isStaticImageData(e)}static isImageURL(e){return typeof e=="string"&&!this.isColor(e)}static isColor(e){return ze.isHexString(e)||ze.isNamedColor(e)||ze.isRGBAColor(e)}static isNamedColor(e){return Ki(e)}static isRGBAColor(e){return e&&typeof e=="object"&&"r"in e&&"g"in e&&"b"in e}static RGBAColorToHex(e){let t=e.r.toString(16).padStart(2,"0"),n=e.g.toString(16).padStart(2,"0"),o=e.b.toString(16).padStart(2,"0"),i=e.a?Math.round(e.a*255).toString(16).padStart(2,"0"):"";return`#${t}${n}${o}${i}`}static colorToString(e){if(ze.isHexString(e))return e;if(ze.isNamedColor(e))return e;if(ze.isRGBAColor(e))return ze.RGBAColorToHex(e);throw new Error("Unknown color type")}static isHexString(e){return typeof e!="string"?!1:/^#([0-9A-F]{3}|[0-9A-F]{6}|[0-9A-F]{4}|[0-9A-F]{8})$/i.test(e)}static toBackgroundSrc(e){return typeof e=="string"?e:e.src}static isDataURI(e){return e.startsWith("data:")}static offset(e,t,n={invertX:!1,invertY:!1}){let[o,i]=e,[r,a]=t,c=this.calc(o,r),l=this.calc(i,a),f=n.invertX?{right:c}:{left:c},p=n.invertY?{bottom:l}:{top:l};return{left:"auto",right:"auto",top:"auto",bottom:"auto",...f,...p}}static calc(e,t){let n=typeof e=="string"?e:`${e}px`;if(t===void 0)return`calc(${n} + 0px)`;let o=typeof t=="string"?"+":t<0?"-":"+",i=typeof t=="string"?t:`${Math.abs(t)}px`;return`calc(${n} ${o} ${i})`}static formatLength(e){return typeof e=="number"?`${e}px`:e}static toPixel(e){return typeof e=="number"?e:parseFloat(e)}};ze.RGBColor=Vo;var b=ze,zo=class s extends Error{static isUseError(e){return e instanceof s}constructor(e,t,n="UseError"){super(e),this.props=t,this.name=n}},ue=class s extends zo{static isWarning(e){return e instanceof s}constructor(e,t){super(e,{info:t},"StaticScriptWarning")}},Qn=class{constructor(e){this.scene=e}run(e){let t=new Map,n=new Map,o=[],i=new Set,r=this.scene.getAllChildren(e,this.scene.getSceneRoot());if(!r.length)return null;for(o.push(r[0]);o.length;){let a=o.shift();this.checkAction(e,a,{imageStates:t,scenes:n},i);let c=a.contentNode.getChild();c&&c.action&&o.push(c.action)}return t}checkAction(e,t,{imageStates:n,scenes:o},i){if(t instanceof z)n.has(t.callee)||n.set(t.callee,{isDisposed:!1,usedExternalSrc:!1}),this.checkImage(n.get(t.callee),t);else if(t instanceof ae){let r=t.callee;if(o.has(r.config.name)){if(o.get(r.config.name)!==r){let a=`Scene with name: ${r.config.name} is duplicated
@@ -21,17 +21,17 @@ Scene: ${r.config.name}
21
21
 
22
22
  At: ${t.__stack}`;throw new ue(a)}}else o.set(r.config.name,r);if(t.type===ee.jumpTo){let a=t.contentNode.getContent()[0],c=e.getScene(a,!0);if(i.has(c))return;i.add(c)}}}checkImage(e,t){if(t.type===ke.setSrc){let o=t.contentNode.getContent()[0];b.isImageURL(o)&&b.isExternalSrc(o)&&(e.usedExternalSrc=!0)}}},X=class s extends Error{static toMessage(e,t){let n=[];return n.push(...Array.isArray(e)?e:[e]),t&&n.push(...Array.isArray(t)?t.map(s.getActionTrace):[s.getActionTrace(t)]),n.join("")}static getActionTrace(e){return`
23
23
  Using action (id: ${e.getId()})
24
- at: ${e.__stack}`}constructor(e,t){super(s.toMessage(e,t)),this.name="RuntimeScriptError"}},A=class extends Error{constructor(e){super(e),this.name="RuntimeGameError"}},he=class extends Error{constructor(e){super(e),this.name="RuntimeInternalError"}};function is(s,e){return U.color(s,e)}function rs(s){return U.bold(s)}function ss(s){return U.italic(s)}var Xe=class extends M{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 o=this.contentNode.getContent(),i=r=>{let a=r.condition?n?r.condition.toString():"Lambda(unknown)":"null",c=r.action?r.action.map(l=>l.stringify(e,t,n)).join(";"):"null";return`(${a}) {${c}}`};return super.stringifyWithContent("Condition",`if ${i(o.If)} ${o.ElseIf.length>0?`else if ${o.ElseIf.map(i).join(";")} `:""}${o.Else?`else {${i(o.Else)}}`:""}`)}};Xe.ActionTypes=Di;var H=class s{static isLambda(e){return e instanceof s&&"handler"in e}static isLambdaHandler(e){return typeof e=="function"}static from(e){return s.isLambda(e)?e:new s(e)}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,$:o=>n.getNamespace(o)}}toString(){return`Lambda(${this.handler.toString()})`}},$o=class s extends q{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 s().createIfCondition(t,n)}ElseIf(t,n){if(this.conditions.Else.action)throw new ue(`ELSE condition already set
25
- You are trying to set an ELSE-IF condition after an ELSE condition`);return this.conditions.ElseIf.push({condition:H.from(t),action:this.construct(Array.isArray(n)?n:[n])}),this.chain()}Else(t){if(this.conditions.Else.action)throw new ue(`ELSE condition already set
26
- 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 o={gameState:n};if(t.If.condition?.evaluate(o)?.value)return t.If.action||null;for(let r of t.ElseIf)if(r.condition?.evaluate(o)?.value)return r.action||null;return t.Else.action||null}fromChained(t){return[Reflect.construct(Xe,[this,Xe.ActionTypes.action,new S().setContent(t.conditions)])]}construct(t,n,o){let i=this.narrativeToActions(t);for(let r=0;r<i.length;r++){let a=i[r].contentNode,c=i[r+1]?.contentNode;c&&a.setChild(c),r===i.length-1&&n&&a.setChild(n),r===0&&o&&o.setChild(a)}return i}_getFutureActions(){return fe.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=H.from(t),this.conditions.If.action=this.construct(n);let o=this.chain(),i=new Xe(o,Xe.ActionTypes.action,new S().setContent(this.conditions));return o.chain(i)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?gt.say(n).getActions():fe.toActions([n]))}};var Pt=class extends M{executeAction(e,t){let n=new h().registerSkipController(new L(()=>{a.cancel()})),o=e.timelines.attachTimeline(n),i=this.contentNode.getContent(),r=null,a=e.createMenu(i,l=>{let f=e.getLiveGame().createStackModel([{type:this.type,node:l.action[0]?.contentNode??null}]);n.resolve({type:this.type,node:null,wait:{type:"all",stackModels:[f]}}),r=()=>{f.reset()},e.gameHistory.updateByToken(c,p=>{p&&p.element.type==="menu"&&(p.element.selected=l.evaluated,p.isPending=!1)})}),{id:c}=e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:o},()=>{a.cancel(),r?.()});return e.gameHistory.push({token:c,action:this,element:{type:"menu",text:a.prompt,selected:null},isPending:!0}),[{type:this.type,node:this.contentNode.getChild()},n]}getFutureActions(e,t){let n=this.contentNode.getContent();return[...this.callee._getFutureActions(n.choices),...super.getFutureActions(e,t)]}stringify(e,t,n){let o=this.contentNode.getContent(),i=o.choices.map(r=>`{${r.action.map(c=>c.stringify(e,t,n)).join(";")}}`);return super.stringifyWithContent("Menu",`(${o.prompt}) {[${i.join(",")}]}`)}};Pt.ActionTypes=Li;var Et=class Et extends q{constructor(t,n={}){super();this.choices=[];this.prompt=ne.isSentence(t)?t:t===null?null:new ne(t),this.config=R(Et.defaultConfig,n)}static prompt(t,n={}){return new Et(t!==void 0?t:null,n)}static choose(t,n){return new Et(null,{}).choose(t,n)}choose(t,n){let o=this.chain();return ne.isSentence(t)&&n?o.choices.push({prompt:ne.toSentence(t),action:this.narrativeToActions(n),config:{}}):(U.isWord(t)||Array.isArray(t)||typeof t=="string")&&n?o.choices.push({prompt:ne.toSentence(t),action:this.narrativeToActions(n),config:{}}):typeof t=="object"&&"prompt"in t&&"action"in t?o.choices.push({prompt:ne.toSentence(t.prompt),action:this.narrativeToActions(t.action),config:{disabled:t.config?.disabled?H.from(t.config.disabled):void 0,hidden:t.config?.hidden?H.from(t.config.hidden):void 0}}):console.warn("No valid choice added to menu, ",{arg0:t,arg1:n}),o}hideIf(t){let n=this.choices[this.choices.length-1];if(!n)throw new ue("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=H.from(t),this.chain()}disableIf(t){let n=this.choices[this.choices.length-1];if(!n)throw new ue("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=H.from(t),this.chain()}enableWhen(t,n,o){return this.choose({prompt:n,action:o,config:{disabled:H.from(t)}})}showWhen(t,n,o){return this.choose({prompt:n,action:o,config:{hidden:H.from(t)}})}fromChained(t){return[new Pt(this.chain(),Pt.ActionTypes.action,new S().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"?gt.say(n).getActions():fe.toActions([n])))}constructNodes(t,n,o){for(let i=0;i<t.length;i++){let r=t[i].contentNode,a=t[i+1]?.contentNode;a&&r.setChild(a),i===this.choices.length-1&&n&&r.setChild(n),i===0&&o&&o.setChild(r)}return t}constructChoices(){return this.choices.map(t=>({action:this.constructNodes(t.action),prompt:t.prompt,config:t.config??{}}))}};Et.defaultConfig={},Et.targetAction=Pt;var Bo=Et;var Kt=class extends Ut{constructor(){super()}fromChained(e){return e.getActions()}forEachChild(e,t,n,o={}){let i=new Set,r=[];for(Array.isArray(t)?r.push(...t):r.push(t);r.length;){let a=r.shift();if(i.has(a))continue;i.add(a),n(a);let c=a.getFutureActions(e,o).filter(l=>!i.has(l));r.push(...c)}}getAllChildren(e,t,n={}){let o=[];return this.forEachChild(e,t,i=>o.push(i),n),o}getAllChildrenMap(e,t){let n=new Map;return this.forEachChild(e,t,o=>n.set(o.getId(),o)),n}getAllElementMap(e,t,n={}){let o=new Map;return this.forEachChild(e,t,i=>o.set(i.callee.getId(),i.callee),n),o}getAllChildrenElements(e,t,n={}){return Array.from(new Set(this.getAllChildren(e,t,n).map(o=>o.callee)))}toData(){return null}constructNodes(e,t){for(let n=0;n<e.length;n++){let o=e[n];n===0&&t?t.setChild(o.contentNode):n>0&&e[n-1].contentNode?.setChild(o.contentNode)}return e.length?e[0].contentNode:null}};var ht=class extends M{executeAction(e,t){let n={action:this,stackModel:t.stackModel};if(this.type===Ln.setText){let o=this.callee.state.text;return this.callee.state.text=this.contentNode.getContent()[0],e.getExposedStateForce(this.callee).flush(),e.actionHistory.push(n,i=>{this.callee.state.text=i},[o]),super.executeAction(e,t)}else if(this.type===Ln.setFontSize){let o=this.callee.state.fontSize;return this.callee.state.fontSize=this.contentNode.getContent()[0],e.getExposedStateForce(this.callee).flush(),e.actionHistory.push(n,i=>{this.callee.state.fontSize=i},[o]),super.executeAction(e,t)}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("TextAction")}};ht.ActionTypes=Ln;var rn=class extends Qe{_setElement(e){return this._element=e,this}getTextState(){if(this._element===void 0)throw new A(`Trying to access text state, but element is not set
27
- This should not happen, please report this issue to the developers`);return this._element.state}};var Xn=class s extends rn{constructor(t,n,o){super();this.textSize=t;this.duration=n;this.easing=o}createTask(){return{animations:[{type:0,start:this.getTextState().fontSize,end:this.textSize,duration:this.duration,ease:this.easing}],resolve:[this.asTarget(t=>({style:{fontSize:`${t}px`}}))]}}copy(){return new s(this.textSize,this.duration,this.easing)}};var xe=class xe extends qe{constructor(e,t={}){super();let n=typeof e=="string"?{...t,text:e}:e,o=xe.DefaultUserConfig.create(n),i=xe.DefaultTextConfig.create(o.get());this.userConfig=o,this.config=i.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(o)}setText(e){let t=this.chain(),n=new ht(t,ht.ActionTypes.setText,new S().setContent([e]));return t.chain(n)}setFontColor(e,t=0,n){return this.transform(new O({fontColor:e},{duration:t,ease:n}))}setFontSize(e,t=0,n){return this.combineActions(new Ve,o=>{if(t){let r=new Xn(e,t,n);o.chain(this._applyTransition(o,r))}let i=new ht(o,ht.ActionTypes.setFontSize,new S().setContent([e]));return o.chain(i)})}useLayer(e){return this.userConfig.get().layer=e,Object.assign(this.config,{layer:e}),this}toData(){return{state:xe.StateSerializer.serialize(this.state),transformState:this.transformState.serialize()}}fromData(e){return this.state=xe.StateSerializer.deserialize(e.state),this.transformState=re.deserialize(e.transformState),this}_init(e){return new pe(this.chain(),ce.init,new S().setContent([e||null,this.config.layer||null]))}reset(){this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(this.userConfig)}getInitialTransformState(e){let[t]=e.extract(xe.DefaultTextTransformState.keys());return new re(xe.DefaultTextTransformState.create(t.get()).get())}_applyTransition(e,t){return new pe(e,ce.applyTransition,new S().setContent([t,n=>n._setElement(this)]))}getInitialState(){return xe.DefaultTextState.create({fontSize:this.userConfig.get().fontSize,text:this.userConfig.get().text}).get()}};xe.DefaultUserConfig=new N({alignX:"center",alignY:"center",className:"",fontSize:16,fontColor:"#000000",text:""}),xe.DefaultTextConfig=new N({alignX:"center",alignY:"center",className:"",layer:void 0}),xe.DefaultTextState=new N({fontSize:16,display:!1,text:""}),xe.DefaultTextTransformState=new N({fontColor:"#000000",...re.DefaultTransformState.getDefaultConfig()}),xe.StateSerializer=new be;var Dt=xe;var sn=class sn extends M{executeAction(e,t){let n=this;if(n.is(sn,"persistent:set")){let[o,i]=n.contentNode.getContent(),r=e.getStorable().getNamespace(n.callee.getNamespaceName()),a=r.get(o);if(typeof i=="function"){let c=r.get(o);r.set(o,i(c))}else r.set(o,i);return e.actionHistory.push({action:this,stackModel:t.stackModel},c=>{r.set(o,c)},[a]),super.executeAction(e,t)}else if(n.is(sn,"persistent:assign")){let[o]=n.contentNode.getContent(),i=e.getStorable().getNamespace(n.callee.getNamespaceName()),r={},a=typeof o=="function"?o(i.getContent()):o;return Object.keys(a).forEach(c=>{r[c]=i.get(c),i.set(c,a[c])}),e.actionHistory.push({action:this,stackModel:t.stackModel},c=>{Object.keys(c).forEach(l=>{i.set(l,c[l])})},[r]),super.executeAction(e,t)}throw this.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("PersistentAction")}};sn.ActionTypes=Xt;var Jn=sn;var rt=class s{static isSerializable(e){return["number","string","boolean"].includes(typeof e)||e instanceof Date||e==null?!0:Array.isArray(e)?e.every(s.isSerializable):typeof e=="object"?Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every(s.isSerializable):!1}constructor(e,t,n){this.name=e,this.key=n||e,this.content=R({},t),this.defaultContent=t}set(e,t){return s.isSerializable(t)?(this.content[e]=t,this):(console.warn(`Value "${t}" in key "${String(e)}" is not serializable, and will not be set
24
+ at: ${e.__stack}`}constructor(e,t){super(s.toMessage(e,t)),this.name="RuntimeScriptError"}},A=class extends Error{constructor(e){super(e),this.name="RuntimeGameError"}},he=class extends Error{constructor(e){super(e),this.name="RuntimeInternalError"}};function is(s,e){return U.color(s,e)}function rs(s){return U.bold(s)}function ss(s){return U.italic(s)}var Xe=class extends M{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 o=this.contentNode.getContent(),i=r=>{let a=r.condition?n?r.condition.toString():"Lambda(unknown)":"null",c=r.action?r.action.map(l=>l.stringify(e,t,n)).join(";"):"null";return`(${a}) {${c}}`};return super.stringifyWithContent("Condition",`if ${i(o.If)} ${o.ElseIf.length>0?`else if ${o.ElseIf.map(i).join(";")} `:""}${o.Else?`else {${i(o.Else)}}`:""}`)}};Xe.ActionTypes=Di;var G=class s{static isLambda(e){return e instanceof s&&"handler"in e}static isLambdaHandler(e){return typeof e=="function"}static from(e){return s.isLambda(e)?e:new s(e)}static not(e){return new s(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,$:o=>n.getNamespace(o)}}toString(){return`Lambda(${this.handler.toString()})`}},$o=class s extends q{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 s().createIfCondition(t,n)}ElseIf(t,n){if(this.conditions.Else.action)throw new ue(`ELSE condition already set
25
+ You are trying to set an ELSE-IF condition after an ELSE condition`);return this.conditions.ElseIf.push({condition:G.from(t),action:this.construct(Array.isArray(n)?n:[n])}),this.chain()}Else(t){if(this.conditions.Else.action)throw new ue(`ELSE condition already set
26
+ 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 o={gameState:n};if(t.If.condition?.evaluate(o)?.value)return t.If.action||null;for(let r of t.ElseIf)if(r.condition?.evaluate(o)?.value)return r.action||null;return t.Else.action||null}fromChained(t){return[Reflect.construct(Xe,[this,Xe.ActionTypes.action,new S().setContent(t.conditions)])]}construct(t,n,o){let i=this.narrativeToActions(t);for(let r=0;r<i.length;r++){let a=i[r].contentNode,c=i[r+1]?.contentNode;c&&a.setChild(c),r===i.length-1&&n&&a.setChild(n),r===0&&o&&o.setChild(a)}return i}_getFutureActions(){return fe.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=G.from(t),this.conditions.If.action=this.construct(n);let o=this.chain(),i=new Xe(o,Xe.ActionTypes.action,new S().setContent(this.conditions));return o.chain(i)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?gt.say(n).getActions():fe.toActions([n]))}};var Pt=class extends M{executeAction(e,t){let n=new h().registerSkipController(new L(()=>{a.cancel()})),o=e.timelines.attachTimeline(n),i=this.contentNode.getContent(),r=null,a=e.createMenu(i,l=>{let f=e.getLiveGame().createStackModel([{type:this.type,node:l.action[0]?.contentNode??null}]);n.resolve({type:this.type,node:null,wait:{type:"all",stackModels:[f]}}),r=()=>{f.reset()},e.gameHistory.updateByToken(c,p=>{p&&p.element.type==="menu"&&(p.element.selected=l.evaluated,p.isPending=!1)})}),{id:c}=e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:o},()=>{a.cancel(),r?.()});return e.gameHistory.push({token:c,action:this,element:{type:"menu",text:a.prompt,selected:null},isPending:!0}),[{type:this.type,node:this.contentNode.getChild()},n]}getFutureActions(e,t){let n=this.contentNode.getContent();return[...this.callee._getFutureActions(n.choices),...super.getFutureActions(e,t)]}stringify(e,t,n){let o=this.contentNode.getContent(),i=o.choices.map(r=>`{${r.action.map(c=>c.stringify(e,t,n)).join(";")}}`);return super.stringifyWithContent("Menu",`(${o.prompt}) {[${i.join(",")}]}`)}};Pt.ActionTypes=Li;var Et=class Et extends q{constructor(t,n={}){super();this.choices=[];this.prompt=ne.isSentence(t)?t:t===null?null:new ne(t),this.config=R(Et.defaultConfig,n)}static prompt(t,n={}){return new Et(t!==void 0?t:null,n)}static choose(t,n){return new Et(null,{}).choose(t,n)}choose(t,n){let o=this.chain();return ne.isSentence(t)&&n?o.choices.push({prompt:ne.toSentence(t),action:this.narrativeToActions(n),config:{}}):(U.isWord(t)||Array.isArray(t)||typeof t=="string")&&n?o.choices.push({prompt:ne.toSentence(t),action:this.narrativeToActions(n),config:{}}):typeof t=="object"&&"prompt"in t&&"action"in t?o.choices.push({prompt:ne.toSentence(t.prompt),action:this.narrativeToActions(t.action),config:{disabled:t.config?.disabled?G.from(t.config.disabled):void 0,hidden:t.config?.hidden?G.from(t.config.hidden):void 0}}):console.warn("No valid choice added to menu, ",{arg0:t,arg1:n}),o}hideIf(t){let n=this.choices[this.choices.length-1];if(!n)throw new ue("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=G.from(t),this.chain()}disableIf(t){let n=this.choices[this.choices.length-1];if(!n)throw new ue("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=G.from(t),this.chain()}enableWhen(t,n,o){return this.choose({prompt:n,action:o,config:{disabled:G.not(G.from(t))}})}showWhen(t,n,o){return this.choose({prompt:n,action:o,config:{hidden:G.not(G.from(t))}})}fromChained(t){return[new Pt(this.chain(),Pt.ActionTypes.action,new S().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"?gt.say(n).getActions():fe.toActions([n])))}constructNodes(t,n,o){for(let i=0;i<t.length;i++){let r=t[i].contentNode,a=t[i+1]?.contentNode;a&&r.setChild(a),i===this.choices.length-1&&n&&r.setChild(n),i===0&&o&&o.setChild(r)}return t}constructChoices(){return this.choices.map(t=>({action:this.constructNodes(t.action),prompt:t.prompt,config:t.config??{}}))}};Et.defaultConfig={},Et.targetAction=Pt;var Bo=Et;var Kt=class extends Ut{constructor(){super()}fromChained(e){return e.getActions()}forEachChild(e,t,n,o={}){let i=new Set,r=[];for(Array.isArray(t)?r.push(...t):r.push(t);r.length;){let a=r.shift();if(i.has(a))continue;i.add(a),n(a);let c=a.getFutureActions(e,o).filter(l=>!i.has(l));r.push(...c)}}getAllChildren(e,t,n={}){let o=[];return this.forEachChild(e,t,i=>o.push(i),n),o}getAllChildrenMap(e,t){let n=new Map;return this.forEachChild(e,t,o=>n.set(o.getId(),o)),n}getAllElementMap(e,t,n={}){let o=new Map;return this.forEachChild(e,t,i=>o.set(i.callee.getId(),i.callee),n),o}getAllChildrenElements(e,t,n={}){return Array.from(new Set(this.getAllChildren(e,t,n).map(o=>o.callee)))}toData(){return null}constructNodes(e,t){for(let n=0;n<e.length;n++){let o=e[n];n===0&&t?t.setChild(o.contentNode):n>0&&e[n-1].contentNode?.setChild(o.contentNode)}return e.length?e[0].contentNode:null}};var ht=class extends M{executeAction(e,t){let n={action:this,stackModel:t.stackModel};if(this.type===Ln.setText){let o=this.callee.state.text;return this.callee.state.text=this.contentNode.getContent()[0],e.getExposedStateForce(this.callee).flush(),e.actionHistory.push(n,i=>{this.callee.state.text=i},[o]),super.executeAction(e,t)}else if(this.type===Ln.setFontSize){let o=this.callee.state.fontSize;return this.callee.state.fontSize=this.contentNode.getContent()[0],e.getExposedStateForce(this.callee).flush(),e.actionHistory.push(n,i=>{this.callee.state.fontSize=i},[o]),super.executeAction(e,t)}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("TextAction")}};ht.ActionTypes=Ln;var rn=class extends Qe{_setElement(e){return this._element=e,this}getTextState(){if(this._element===void 0)throw new A(`Trying to access text state, but element is not set
27
+ This should not happen, please report this issue to the developers`);return this._element.state}};var Xn=class s extends rn{constructor(t,n,o){super();this.textSize=t;this.duration=n;this.easing=o}createTask(){return{animations:[{type:0,start:this.getTextState().fontSize,end:this.textSize,duration:this.duration,ease:this.easing}],resolve:[this.asTarget(t=>({style:{fontSize:`${t}px`}}))]}}copy(){return new s(this.textSize,this.duration,this.easing)}};var xe=class xe extends qe{constructor(e,t={}){super();let n=typeof e=="string"?{...t,text:e}:e,o=xe.DefaultUserConfig.create(n),i=xe.DefaultTextConfig.create(o.get());this.userConfig=o,this.config=i.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(o)}setText(e){let t=this.chain(),n=new ht(t,ht.ActionTypes.setText,new S().setContent([e]));return t.chain(n)}setFontColor(e,t=0,n){return this.transform(new O({fontColor:e},{duration:t,ease:n}))}setFontSize(e,t=0,n){return this.combineActions(new Ve,o=>{if(t){let r=new Xn(e,t,n);o.chain(this._applyTransition(o,r))}let i=new ht(o,ht.ActionTypes.setFontSize,new S().setContent([e]));return o.chain(i)})}useLayer(e){return this.userConfig.get().layer=e,Object.assign(this.config,{layer:e}),this}toData(){return{state:xe.StateSerializer.serialize(this.state),transformState:this.transformState.serialize()}}fromData(e){return this.state=xe.StateSerializer.deserialize(e.state),this.transformState=re.deserialize(e.transformState),this}_init(e){return new pe(this.chain(),ce.init,new S().setContent([e||null,this.config.layer||null]))}reset(){this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(this.userConfig)}getInitialTransformState(e){let[t]=e.extract(xe.DefaultTextTransformState.keys());return new re(xe.DefaultTextTransformState.create(t.get()).get())}_applyTransition(e,t){return new pe(e,ce.applyTransition,new S().setContent([t,n=>n._setElement(this)]))}getInitialState(){return xe.DefaultTextState.create({fontSize:this.userConfig.get().fontSize,text:this.userConfig.get().text}).get()}};xe.DefaultUserConfig=new H({alignX:"center",alignY:"center",className:"",fontSize:16,fontColor:"#000000",text:""}),xe.DefaultTextConfig=new H({alignX:"center",alignY:"center",className:"",layer:void 0}),xe.DefaultTextState=new H({fontSize:16,display:!1,text:""}),xe.DefaultTextTransformState=new H({fontColor:"#000000",...re.DefaultTransformState.getDefaultConfig()}),xe.StateSerializer=new be;var Dt=xe;var sn=class sn extends M{executeAction(e,t){let n=this;if(n.is(sn,"persistent:set")){let[o,i]=n.contentNode.getContent(),r=e.getStorable().getNamespace(n.callee.getNamespaceName()),a=r.get(o);if(typeof i=="function"){let c=r.get(o);r.set(o,i(c))}else r.set(o,i);return e.actionHistory.push({action:this,stackModel:t.stackModel},c=>{r.set(o,c)},[a]),super.executeAction(e,t)}else if(n.is(sn,"persistent:assign")){let[o]=n.contentNode.getContent(),i=e.getStorable().getNamespace(n.callee.getNamespaceName()),r={},a=typeof o=="function"?o(i.getContent()):o;return Object.keys(a).forEach(c=>{r[c]=i.get(c),i.set(c,a[c])}),e.actionHistory.push({action:this,stackModel:t.stackModel},c=>{Object.keys(c).forEach(l=>{i.set(l,c[l])})},[r]),super.executeAction(e,t)}throw this.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("PersistentAction")}};sn.ActionTypes=Xt;var Jn=sn;var rt=class s{static isSerializable(e){return["number","string","boolean"].includes(typeof e)||e instanceof Date||e==null?!0:Array.isArray(e)?e.every(s.isSerializable):typeof e=="object"?Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every(s.isSerializable):!1}constructor(e,t,n){this.name=e,this.key=n||e,this.content=R({},t),this.defaultContent=t}set(e,t){return s.isSerializable(t)?(this.content[e]=t,this):(console.warn(`Value "${t}" in key "${String(e)}" is not serializable, and will not be set
28
28
  at namespace "${this.name}"`),this.content[e]=t,this)}get(e){return this.content[e]}equals(e,t){return this.content[e]===t}assign(e){return Object.entries(e).forEach(([t,n])=>{this.set(t,n)}),this}reset(){return this.content=R({},this.defaultContent),this}getContent(){return this.content}toData(){return this.serialize()}load(e){if(!e){console.warn("No data to load");return}this.content=e}serialize(){let e={};return Object.entries(this.content).forEach(([t,n])=>{e[t]=this.wrap(n)}),e}deserialize(e){if(!e){console.warn("No data to load");return}Object.entries(e).forEach(([t,n])=>{this.content[t]=this.unwrap(n)})}toTypeName(e){return e instanceof Date?"date":"any"}wrap(e){let t={any:o=>({type:"any",data:o}),date:o=>({type:"date",data:o.toString()})},n=this.toTypeName(e);return t[n](e)}unwrap(e){return{any:n=>n.data,date:n=>new Date(n.data)}[e.type](e)}},an=class{constructor(){this.namespaces={}}addNamespace(e){if(!this.namespaces[e.key])return this.namespaces[e.key]=e,this}getNamespace(e){if(!this.namespaces[e])throw new A(`Namespace ${e} is not initialized, did you forget to register it?
29
- Use \`story.registerPersistent\` to register a persistent namespace`);return this.namespaces[e]}setNamespace(e,t){return this.namespaces[e]=t,this}hasNamespace(e){return!!this.namespaces[e]}removeNamespace(e){return delete this.namespaces[e],this}getNamespaces(){return this.namespaces}keys(){return Object.keys(this.namespaces)}values(){return Object.values(this.namespaces)}entries(){return Object.entries(this.namespaces)}toData(){return this.entries().reduce((e,[t,n])=>(e[t]=n.toData(),e),{})}load(e){if(!e){console.warn("No data to load");return}Object.entries(e).forEach(([t,n])=>{this.namespaces[t]?this.namespaces[t].load(n):this.namespaces[t]=new rt(t,n)})}clear(){return this.namespaces={},this}};var Zn=class Zn extends q{constructor(e,t){super(),this.namespace=this.prefix(e),this.defaultContent=t}init(e){e.hasNamespace(this.namespace)||e.addNamespace(new rt(this.namespace,this.defaultContent))}getNamespace(e){return e.getNamespace(this.namespace)}set(e,t){return this.chain(this.createAction(Xt.set,[e,t]))}assign(e){return this.chain(this.createAction(Xt.assign,[e]))}equals(e,t){return new H(n=>{let o=n.storable.getNamespace(this.namespace),i=H.isLambda(t)||H.isLambdaHandler(t)?H.from(t).evaluate(n).value:t;return o.equals(e,i)})}notEquals(e,t){return new H(n=>{let o=n.storable.getNamespace(this.namespace),i=H.isLambda(t)||H.isLambdaHandler(t)?H.from(t).evaluate(n).value:t;return!o.equals(e,i)})}isTrue(e){return new H(({storable:t})=>t.getNamespace(this.namespace).equals(e,!0))}isFalse(e){return new H(({storable:t})=>t.getNamespace(this.namespace).equals(e,!1))}isNotNull(e){return new H(({storable:t})=>{let n=t.getNamespace(this.namespace).get(e);return n!=null})}toWord(e){return new U(({storable:t})=>[String(t.getNamespace(this.namespace).get(e))])}get(e){return this.toWord(e)}conditional(e,t,n){return new U(o=>H.from(e).evaluate(o).value?t:n)}evaluate(e,t){return new H(({storable:n})=>t(n.getNamespace(this.namespace).get(e)))}getNamespaceName(){return this.namespace}prefix(e,t=Zn.NamespacePrefix){return t+":"+String(e)}createAction(e,t){return new Jn(this.chain(),e,S.create(t))}};Zn.NamespacePrefix="persistent";var Ft=Zn,_n=class _n extends Ft{constructor(e){super(e,{}),this.namespace=this.prefix(e,_n.LocalNamespacePrefix)}init(e){e.removeNamespace(this.namespace).addNamespace(new rt(this.namespace,this.defaultContent))}};_n.LocalNamespacePrefix="local";var Yn=_n;var Ot=class extends M{executeAction(e,t){if(this.type===vt.action)return super.executeAction(e,t);if(this.type===vt.setZIndex){let[n]=this.contentNode.getContent(),o=this.callee.state.zIndex;return this.callee.state.zIndex=n,e.actionHistory.push({action:this,stackModel:t.stackModel},i=>{this.callee.state.zIndex=i},[o]),e.stage.update(),super.executeAction(e,t)}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("LayerAction")}};Ot.ActionTypes=vt;var He=class He extends qe{constructor(e,t={}){super();let n=He.DefaultUserConfig.create(t),o=He.DefaultConfig.create({...n.get(),name:e});this.userConfig=n,this.config=o.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 Ot(this.chain(),vt.setZIndex,new S().setContent([e])))}toData(){return{state:He.StateSerializer.serialize(this.state)}}fromData(e){return this.state=He.StateSerializer.deserialize(e.state),this}copy(){return new He(this.config.name,this.userConfig.get())}setName(e){return this.config.name=e,this}_init(e){return[new Ot(this.chain(),vt.action,new S),new pe(this.chain(),ce.init,new S().setContent([e,null,!1]))]}getInitialState(){return He.DefaultState.create({zIndex:this.config.zIndex}).get()}getInitialTransformState(){let[e]=this.userConfig.extract(re.DefaultTransformState.keys());return new re(re.DefaultTransformState.create(e.get()).get())}};He.DefaultUserConfig=new N({zIndex:0,...re.DefaultTransformState.getDefaultConfig(),opacity:1}),He.DefaultConfig=new N({name:"(anonymous)",zIndex:0}),He.StateSerializer=new be,He.DefaultState=new N({zIndex:0});var Wt=He;var de=class de extends Kt{constructor(t,n){super();this.srcManager=new ge;this.events=new F;this.actions=[];this._futureActions_=[];let o=de.DefaultSceneConfig.getDefaultConfig().defaultBackgroundLayer.copy().setName("[[Background Layer of "+t+"]]"),i=de.DefaultSceneConfig.getDefaultConfig().defaultDisplayableLayer.copy().setName("[[Displayable Layer of "+t+"]]"),r=de.DefaultUserConfig.create(n),a=de.DefaultSceneConfig.create({...r.get(),name:t,layers:[...r.get().layers,o,i],defaultBackgroundLayer:o,defaultDisplayableLayer:i});this.userConfig=r,this.config=a.get(),this.state=this.getInitialState(),this.localPersistent=new Yn(t)}static validateVoice(t){if(t.config.type!=="voice"&&t.config.type!=="sound")throw new ue(`Voice must be a voice, but got ${t.config.type}.
29
+ Use \`story.registerPersistent\` to register a persistent namespace`);return this.namespaces[e]}setNamespace(e,t){return this.namespaces[e]=t,this}hasNamespace(e){return!!this.namespaces[e]}removeNamespace(e){return delete this.namespaces[e],this}getNamespaces(){return this.namespaces}keys(){return Object.keys(this.namespaces)}values(){return Object.values(this.namespaces)}entries(){return Object.entries(this.namespaces)}toData(){return this.entries().reduce((e,[t,n])=>(e[t]=n.toData(),e),{})}load(e){if(!e){console.warn("No data to load");return}Object.entries(e).forEach(([t,n])=>{this.namespaces[t]?this.namespaces[t].load(n):this.namespaces[t]=new rt(t,n)})}clear(){return this.namespaces={},this}};var Zn=class Zn extends q{constructor(e,t){super(),this.namespace=this.prefix(e),this.defaultContent=t}init(e){e.hasNamespace(this.namespace)||e.addNamespace(new rt(this.namespace,this.defaultContent))}getNamespace(e){return e.getNamespace(this.namespace)}set(e,t){return this.chain(this.createAction(Xt.set,[e,t]))}assign(e){return this.chain(this.createAction(Xt.assign,[e]))}equals(e,t){return new G(n=>{let o=n.storable.getNamespace(this.namespace),i=G.isLambda(t)||G.isLambdaHandler(t)?G.from(t).evaluate(n).value:t;return o.equals(e,i)})}notEquals(e,t){return new G(n=>{let o=n.storable.getNamespace(this.namespace),i=G.isLambda(t)||G.isLambdaHandler(t)?G.from(t).evaluate(n).value:t;return!o.equals(e,i)})}isTrue(e){return new G(({storable:t})=>t.getNamespace(this.namespace).equals(e,!0))}isFalse(e){return new G(({storable:t})=>t.getNamespace(this.namespace).equals(e,!1))}isNotNull(e){return new G(({storable:t})=>{let n=t.getNamespace(this.namespace).get(e);return n!=null})}toWord(e){return new U(({storable:t})=>[String(t.getNamespace(this.namespace).get(e))])}get(e){return this.toWord(e)}conditional(e,t,n){return new U(o=>G.from(e).evaluate(o).value?t:n)}evaluate(e,t){return new G(({storable:n})=>t(n.getNamespace(this.namespace).get(e)))}getNamespaceName(){return this.namespace}prefix(e,t=Zn.NamespacePrefix){return t+":"+String(e)}createAction(e,t){return new Jn(this.chain(),e,S.create(t))}};Zn.NamespacePrefix="persistent";var Ft=Zn,_n=class _n extends Ft{constructor(e){super(e,{}),this.namespace=this.prefix(e,_n.LocalNamespacePrefix)}init(e){e.removeNamespace(this.namespace).addNamespace(new rt(this.namespace,this.defaultContent))}};_n.LocalNamespacePrefix="local";var Yn=_n;var Ot=class extends M{executeAction(e,t){if(this.type===vt.action)return super.executeAction(e,t);if(this.type===vt.setZIndex){let[n]=this.contentNode.getContent(),o=this.callee.state.zIndex;return this.callee.state.zIndex=n,e.actionHistory.push({action:this,stackModel:t.stackModel},i=>{this.callee.state.zIndex=i},[o]),e.stage.update(),super.executeAction(e,t)}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("LayerAction")}};Ot.ActionTypes=vt;var He=class He extends qe{constructor(e,t={}){super();let n=He.DefaultUserConfig.create(t),o=He.DefaultConfig.create({...n.get(),name:e});this.userConfig=n,this.config=o.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 Ot(this.chain(),vt.setZIndex,new S().setContent([e])))}toData(){return{state:He.StateSerializer.serialize(this.state)}}fromData(e){return this.state=He.StateSerializer.deserialize(e.state),this}copy(){return new He(this.config.name,this.userConfig.get())}setName(e){return this.config.name=e,this}_init(e){return[new Ot(this.chain(),vt.action,new S),new pe(this.chain(),ce.init,new S().setContent([e,null,!1]))]}getInitialState(){return He.DefaultState.create({zIndex:this.config.zIndex}).get()}getInitialTransformState(){let[e]=this.userConfig.extract(re.DefaultTransformState.keys());return new re(re.DefaultTransformState.create(e.get()).get())}};He.DefaultUserConfig=new H({zIndex:0,...re.DefaultTransformState.getDefaultConfig(),opacity:1}),He.DefaultConfig=new H({name:"(anonymous)",zIndex:0}),He.StateSerializer=new be,He.DefaultState=new H({zIndex:0});var Wt=He;var de=class de extends Kt{constructor(t,n){super();this.srcManager=new ge;this.events=new F;this.actions=[];this._futureActions_=[];let o=de.DefaultSceneConfig.getDefaultConfig().defaultBackgroundLayer.copy().setName("[[Background Layer of "+t+"]]"),i=de.DefaultSceneConfig.getDefaultConfig().defaultDisplayableLayer.copy().setName("[[Displayable Layer of "+t+"]]"),r=de.DefaultUserConfig.create(n),a=de.DefaultSceneConfig.create({...r.get(),name:t,layers:[...r.get().layers,o,i],defaultBackgroundLayer:o,defaultDisplayableLayer:i});this.userConfig=r,this.config=a.get(),this.state=this.getInitialState(),this.localPersistent=new Yn(t)}static validateVoice(t){if(t.config.type!=="voice"&&t.config.type!=="sound")throw new ue(`Voice must be a voice, but got ${t.config.type}.
30
30
  To prevent unintended behavior and unexpected results, the sound have to be marked as voice. Please use \`Sound.voice()\` to create the sound.`)}static isScene(t){return t instanceof de}static getScene(t,n){return typeof n=="string"?t.getScene(n):n}static getStateSerializer(t){return new be({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(Ve.do([this.background.char(t,n)]))}jumpTo(t,n={}){return this.combineActions(new Ve({allowFutureScene:!1}),o=>{let r=R({unloadScene:!0},n instanceof Qe?{transition:n}:n);return o.chain(new ae(o,"scene:preUnmount",new S().setContent([]))).chain(this._initScene(t))._transitionToScene(r.transition,t.state.backgroundImage.state.currentSrc),r.unloadScene&&o.chain(this._exit()),o})._jumpTo(t)}setBackgroundMusic(t,n){return this.chain(new ae(this.chain(),ee.setBackgroundMusic,new S().setContent([t,n])))}action(t){return this.actions=t,this}preloadImage(t){if(!b.isImageSrc(t))throw new Error("Invalid image source: "+t);return(Array.isArray(t)?t:[t]).forEach(o=>{this.srcManager.register({type:"image",src:o})}),this}toData(){return{state:de.getStateSerializer(this).serialize(this.state)}}fromData(t){return this.state=de.getStateSerializer(this).deserialize(t.state),this}constructSceneRoot(t){this.sceneRoot=new ae(this.chain(),"scene:action",new S);let n=this.actions,i=this.narrativeToActions(typeof n=="function"?n(this):n).map(u=>fe.isChained(u)?u.fromChained(u):u).flat(2),r=[],a=[];this.getAllChildrenElements(t,i,{allowFutureScene:!1}).forEach(u=>{fe.isChained(u)||(u instanceof I?r.push(u):u instanceof Dt&&a.push(u))});let c=[],l=[],f=new Map;r.forEach(u=>{u.config.isWearable?l.push(u):u.config.autoInit&&c.push(u);for(let C of u.config.wearables){if(f.get(C)&&f.get(C)!==u)throw new Error(`Wearable image cannot be used multiple times
31
31
  Maybe you bind the same wearable image to multiple parent images
32
32
  Parent Conflict (src: `+f.get(C)?.state.currentSrc+`)
33
33
  Current Parent (src: `+u.state.currentSrc+")");f.set(C,u)}});let p=[...this._initScene(this),...c.map(u=>u._init(this)),...l.map(u=>{if(!f.has(u))throw new Error("Wearable image must have a parent image");return f.get(u)._initWearable(u)}),...a.map(u=>u._init()),...i],d=super.constructNodes(p),g=new S(this.sceneRoot,void 0,d||void 0).setContent(this);return d?.setParent(g),this.sceneRoot?.setContentNode(g),this._futureActions_=p,this}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?gt.say(n).getActions():fe.toActions([n]))}isSceneRootConstructed(){return!!this.sceneRoot}registerSrc(t,n=new Set){if(!this.sceneRoot)return;let o=new Set,i=new Set,r=[this.sceneRoot],a=new Set;for(;r.length;){let c=r.shift();if(!o.has(c)){if(o.add(c),c instanceof ae){let l=c.callee;if(b.isImageSrc(l.state.backgroundImage.state.currentSrc)&&this.srcManager.register({type:"image",src:b.srcToURL(l.state.backgroundImage.state.currentSrc)}),c.type===ee.jumpTo){let f=c,p=de.getScene(t,f.contentNode.getContent()[0]);if(!p)throw c._sceneNotFoundError(c.getSceneName(f.contentNode.getContent()[0]));let d=ge.getPreloadableSrc(t,c);if(d&&this.srcManager.register(d),i.has(f)||n.has(p))continue;i.add(f),a.add(p),n.add(p)}}else if(c instanceof z){let l=ge.getPreloadableSrc(t,c);l&&this.srcManager.register(l)}else if(c instanceof Pe)this.srcManager.register(c.callee);else if(c instanceof te){let f=c.getFutureActions(t,{allowFutureScene:!0});r.push(...f)}else c instanceof pe&&this.srcManager.register(c.callee.srcManager.getSrc());r.push(...c.getFutureActions(t,{allowFutureScene:!0}))}}a.forEach(c=>{c.registerSrc(t,n),this.srcManager.registerFuture(c.srcManager)})}assignActionId(t){this.getAllChildren(t,this.sceneRoot||[],{allowFutureScene:!0}).forEach((o,i)=>{o.setId(`a-${i}`)})}assignElementId(t){this.getAllChildrenElements(t,this.sceneRoot||[]).forEach((o,i)=>{o.setId(`e-${i}`)})}getVoice(t){if(!t)return null;let n=this.config.voices;if(n){if(typeof n=="function"){let o=n(t);return typeof o=="string"||de.validateVoice(o),o}return n[t]||null}return null}getSceneRoot(){if(!this.sceneRoot)throw new Error("Scene root is not constructed");return this.sceneRoot}stringify(t,n,o){return super.getAllChildren(t,this.sceneRoot||[],{allowFutureScene:!0}).map(i=>i.stringify(t,n,o)).join(";")}reset(){this.state.backgroundImage.reset(),this.state.backgroundMusic?.reset(),this.state=this.getInitialState()}getInitialState(){let t=this.userConfig.get();if(t.backgroundMusic&&t.backgroundMusic.config.type!=="bgm")throw new ue(`[Scene: ${this.config.name}] Background music must be a bgm, but got ${t.backgroundMusic.config.type}.
34
- To prevent unintended behavior and unexpected results, the sound have to be marked as bgm. Please use \`Sound.bgm()\` to create the sound.`);return de.DefaultSceneState.create().assign({backgroundImage: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),...t.backgroundMusic?{backgroundMusic:this.state?.backgroundMusic?this.state.backgroundMusic.reset():t.backgroundMusic}:{}}).get()}_jumpTo(t){return this.chain(new ae(this.chain(),"scene:jumpTo",new S().setContent([t])))}_exit(){return new ae(this.chain(),"scene:exit",new S().setContent([]))}_transitionToScene(t,n){let o=this.chain();if(t&&n){let i=this.state.backgroundImage.char(n,t);o.chain(i.getActions())}return o}_init(t){return new ae(this.chain(),"scene:init",new S().setContent([t]))}_initScene(t){return[t._init(t),...t.config.layers.flatMap(n=>n._init(t)),...t._initBackground(t,t.config.defaultBackgroundLayer)]}_initBackground(t,n){return[t.state.backgroundImage._init(t,n)]}};de.EventTypes={"event:scene.remove":"event:scene.remove","event:scene.load":"event:scene.load","event:scene.unload":"event:scene.unload","event:scene.mount":"event:scene.mount","event:scene.unmount":"event:scene.unmount","event:scene.preUnmount":"event:scene.preUnmount","event:scene.imageLoaded":"event:scene.imageLoaded"},de.DefaultUserConfig=new N({backgroundMusic:null,backgroundMusicFade:0,voices:void 0,background:"#fff",layers:[]}),de.DefaultSceneConfig=new N({name:"",backgroundMusicFade:0,voices:null,layers:[],defaultBackgroundLayer:new Wt("[[Background Layer]]",{zIndex:-1}),defaultDisplayableLayer:new Wt("[[Displayable Layer]]",{zIndex:0})},{voices:t=>{let n=i=>typeof i=="object"&&i!==null,o=i=>typeof i=="function";if(!t)return null;if(n(t)&&Object.values(t).forEach(i=>{ve.isSound(i)&&de.validateVoice(i)}),o(t))return t;throw new ue(`Invalid voices config: ${t}`)}}),de.DefaultSceneState=new N({backgroundImage:new I,backgroundMusic:null});var Ee=de;var yt=class extends M{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")}};yt.ActionTypes=Ri;var we=class s extends q{static getCtx({gameState:e}){let t=e.game.getLiveGame(),n=t.getStorable();return{gameState:e,game:e.game,liveGame:t,storable:n,$:o=>n.getNamespace(o)}}static execute(e){return new s(e)}constructor(e){super(),this.handler=e;let t=this.chain(),n=new yt(t,yt.ActionTypes.action,new S().setContent(this));return this.chain(n)}execute({gameState:e}){return this.handler(s.getCtx({gameState:e}))}fromChained(e){return[new yt(this.chain(),yt.ActionTypes.action,new S().setContent(e))]}};var st=class st extends Kt{constructor(t,n=st.defaultConfig){super();this.entryScene=null;this.scenes=new Map;this.persistent=[];this.services=new Map;this.name=t,this.config=R(st.defaultConfig,n)}static empty(){return new st("empty").entry(new Ee("empty"))}entry(t){return this.entryScene=t,this}registerPersistent(t){return this.persistent.push(t),this}createPersistent(t,n){let o=new Ft(t,n);return this.registerPersistent(o),o}registerService(t,n){return this.services.set(t,n),this}getService(t){let n=this.services.get(t);if(!n)throw new ue(`Trying to access service ${t} before it's registered, please use "story.registerService" to register the service`);return n}hash(t=!1){return zi(this.stringify(t))}stringify(t=!1){return this.entryScene?.stringify(this,new Set,t)||""}serializeServices(){let t={};return this.services.forEach((n,o)=>{if(!n.serialize||typeof n.serialize!="function")return;let i=n.serialize();if(i!==null){{if(i instanceof Promise)throw new X(`Service ${o} serialize method should not return a promise`);if(!Ko(i))throw new X(`Service ${o} serialize method should return a pure object.
34
+ To prevent unintended behavior and unexpected results, the sound have to be marked as bgm. Please use \`Sound.bgm()\` to create the sound.`);return de.DefaultSceneState.create().assign({backgroundImage: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),...t.backgroundMusic?{backgroundMusic:this.state?.backgroundMusic?this.state.backgroundMusic.reset():t.backgroundMusic}:{}}).get()}_jumpTo(t){return this.chain(new ae(this.chain(),"scene:jumpTo",new S().setContent([t])))}_exit(){return new ae(this.chain(),"scene:exit",new S().setContent([]))}_transitionToScene(t,n){let o=this.chain();if(t&&n){let i=this.state.backgroundImage.char(n,t);o.chain(i.getActions())}return o}_init(t){return new ae(this.chain(),"scene:init",new S().setContent([t]))}_initScene(t){return[t._init(t),...t.config.layers.flatMap(n=>n._init(t)),...t._initBackground(t,t.config.defaultBackgroundLayer)]}_initBackground(t,n){return[t.state.backgroundImage._init(t,n)]}};de.EventTypes={"event:scene.remove":"event:scene.remove","event:scene.load":"event:scene.load","event:scene.unload":"event:scene.unload","event:scene.mount":"event:scene.mount","event:scene.unmount":"event:scene.unmount","event:scene.preUnmount":"event:scene.preUnmount","event:scene.imageLoaded":"event:scene.imageLoaded"},de.DefaultUserConfig=new H({backgroundMusic:null,backgroundMusicFade:0,voices:void 0,background:"#fff",layers:[]}),de.DefaultSceneConfig=new H({name:"",backgroundMusicFade:0,voices:null,layers:[],defaultBackgroundLayer:new Wt("[[Background Layer]]",{zIndex:-1}),defaultDisplayableLayer:new Wt("[[Displayable Layer]]",{zIndex:0})},{voices:t=>{let n=i=>typeof i=="object"&&i!==null,o=i=>typeof i=="function";if(!t)return null;if(n(t)&&Object.values(t).forEach(i=>{ve.isSound(i)&&de.validateVoice(i)}),o(t))return t;throw new ue(`Invalid voices config: ${t}`)}}),de.DefaultSceneState=new H({backgroundImage:new I,backgroundMusic:null});var Ee=de;var yt=class extends M{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")}};yt.ActionTypes=Ri;var we=class s extends q{static getCtx({gameState:e}){let t=e.game.getLiveGame(),n=t.getStorable();return{gameState:e,game:e.game,liveGame:t,storable:n,$:o=>n.getNamespace(o)}}static execute(e){return new s(e)}constructor(e){super(),this.handler=e;let t=this.chain(),n=new yt(t,yt.ActionTypes.action,new S().setContent(this));return this.chain(n)}execute({gameState:e}){return this.handler(s.getCtx({gameState:e}))}fromChained(e){return[new yt(this.chain(),yt.ActionTypes.action,new S().setContent(e))]}};var st=class st extends Kt{constructor(t,n=st.defaultConfig){super();this.entryScene=null;this.scenes=new Map;this.persistent=[];this.services=new Map;this.name=t,this.config=R(st.defaultConfig,n)}static empty(){return new st("empty").entry(new Ee("empty"))}entry(t){return this.entryScene=t,this}registerPersistent(t){return this.persistent.push(t),this}createPersistent(t,n){let o=new Ft(t,n);return this.registerPersistent(o),o}registerService(t,n){return this.services.set(t,n),this}getService(t){let n=this.services.get(t);if(!n)throw new ue(`Trying to access service ${t} before it's registered, please use "story.registerService" to register the service`);return n}hash(t=!1){return zi(this.stringify(t))}stringify(t=!1){return this.entryScene?.stringify(this,new Set,t)||""}serializeServices(){let t={};return this.services.forEach((n,o)=>{if(!n.serialize||typeof n.serialize!="function")return;let i=n.serialize();if(i!==null){{if(i instanceof Promise)throw new X(`Service ${o} serialize method should not return a promise`);if(!Ko(i))throw new X(`Service ${o} serialize method should return a pure object.
35
35
  A pure object should:
36
36
  1. be an object literal
37
37
  2. not have any prototype
@@ -39,7 +39,7 @@ A pure object should:
39
39
  4. sub objects should also be pure objects or serializable data
40
40
  Return null if nothing needs to be saved. For more information, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#description
41
41
  Returned value ${i} violates the above rules`)}t[o]=i}}),t}deserializeServices(t){this.services.forEach((n,o)=>{!n.deserialize||typeof n.deserialize!="function"||t[o]&&n.deserialize(t[o])})}getScene(t,n=!1,o){if(Ee.isScene(t))return t;let i=this.scenes.get(t)||null;if(!i&&n)throw Reflect.construct(o||X,[`Scene with name ${t} not found`]);return i}constructStory(){let t=this.entryScene;if(!t)throw new Error("Story must have an entry scene");return this.constructSceneRoots(t),t.registerSrc(this),t.assignActionId(this),t.assignElementId(this),this.runStaticCheck(t),this}getAllElementStates(){return this.getAllChildrenElements(this,this.entryScene?.getSceneRoot()||[]).map(n=>({id:n.getId(),data:n.toData()})).filter(n=>!!n.data)}constructSceneRoots(t){let n=new Set,o=[],i=0;for(t.constructSceneRoot(this),o.push(t.getSceneRoot());o.length;){if(i++,i>st.MAX_DEPTH)throw new Error(`Max depth reached while constructing scene roots (max depth: ${st.MAX_DEPTH})`);let r=o.shift();if(Ee.isScene(r.callee)){if(n.has(r.callee))continue;r.callee.isSceneRootConstructed()||r.callee.constructSceneRoot(this),n.add(r.callee)}let a=r.getFutureActions(this,{allowFutureScene:!0});o.push(...a)}return this}initPersistent(t){return this.persistent.forEach(n=>{n.init(t)}),this}getInversionConfig(){let{origin:t}=this.config;return{invertY:t==="bottom left"||t==="bottom right",invertX:t==="bottom right"||t==="top right"}}runStaticCheck(t){return new Qn(t).run(this)}};st.defaultConfig={origin:"bottom left"},st.MAX_DEPTH=32767;var cn=st;var eo=class extends M{executeAction(e,t){let[n,o]=this.contentNode.getContent(),i=this.callee.triggerAction(we.getCtx({gameState:e}),n,o);return h.isAwaitable(i)?h.forward(i,{type:this.type,node:this.contentNode?.getChild()}):super.executeAction(e,t)}stringify(e,t,n){return super.stringifyWithName("ServiceAction")}};var jo=class extends q{constructor(){super(...arguments);this._handlers={}}on(t,n){return this._registerActionHandler(t,n),this}trigger(t,...n){let o=this.chain();return o.chain(this._createAction(o,t,n))}triggerAction(t,n,o){let i=this._handlers[n];if(!i){t.gameState.logger.warn(`(in User-Defined Service) Trying to trigger action ${n} before it's registered, please use "service.on" to register the action`);return}if(Fi(i)){let r=[],a=new h().registerSkipController(new L(()=>{for(let l of r)l?.()}));return i({...t,onAbort:l=>{r.push(l)}},...o).then(()=>a.resolve()),a}i({...t,onAbort:()=>{}},...o)}_registerActionHandler(t,n){this._handlers[t]=n}_createAction(t,n,o){return new eo(t,"service:action",new S().setContent([n,o]))}},qo=class extends jo{},ln=class extends qo{};var Je=class Je extends M{executeAction(e,t){let n=this,o=this.callee,i={action:n,stackModel:t.stackModel};if(n.is(Je,"video:play"))return this.changeStateAsync(e,r=>r.play(),t);if(n.is(Je,"video:pause"))return this.changeState(e,r=>r.pause(),t);if(n.is(Je,"video:stop"))return this.changeState(e,r=>r.stop(),t);if(n.is(Je,"video:seek"))return this.changeState(e,r=>r.seek(n.contentNode.getContent()[0]),t);if(n.is(Je,"video:show")){let r=o.state.display;return e.isVideoAdded(o)||(e.addVideo(o),e.stage.update()),o.state.display=!0,e.actionHistory.push(i,a=>{o.state.display=a},[r]),this.changeState(e,a=>a.show(),t)}else if(n.is(Je,"video:hide")){let r=o.state.display;return this.changeState(e,a=>{o.state.display=!1,e.actionHistory.push(i,c=>{o.state.display=c},[r]),a.hide(),e.removeVideo(o),e.stage.update()},t)}else if(n.is(Je,"video:resume"))return this.changeState(e,r=>r.resume(),t);throw this.unknownTypeError()}changeStateBase(e,t,n){if(!e.isVideoAdded(this.callee))throw new A(`Video is being used before it is added to the game
42
- Use video.show() to add the video to the game`);let o=this.callee,i=new h,r=e.getExposedStateAsync(o,async a=>{e.logger.debug("Video Component state exposed",a),await t(a),i.resolve(super.executeAction(e,n))});return i.registerSkipController(new L(r.cancel)),i}changeState(e,t,n){return this.changeStateBase(e,t,n)}changeStateAsync(e,t,n){return this.changeStateBase(e,t,n)}stringify(e,t,n){return super.stringifyWithName("VideoAction")}};Je.ActionTypes=Nt;var to=Je;var Vt=class Vt extends q{constructor(e){super();let t=Vt.DefaultVideoConfig.create(e);if(this.config=t.get(),this.state=this.getInitialState(),!this.config.src)throw new X("Video must have a src")}show(){return this.chain(this.createAction(Nt.show,[]))}hide(){return this.chain(this.createAction(Nt.hide,[]))}play(){return this.chain(this.createAction(Nt.play,[]))}toData(){return{state:{display:this.state.display}}}fromData(e){let{state:t}=e;return this.state={display:t.display},this}reset(){return this.state=this.getInitialState(),this}getInitialState(){return Vt.DefaultVideoState.create().get()}createAction(e,t){return new to(this.chain(),e,S.create(t))}};Vt.DefaultVideoConfig=new N({src:"",muted:!1}),Vt.DefaultVideoState=new N({display:!1});var Qo=Vt;import*as Qi from"howler";var no=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 o=[],i=[],r=[];return this.prefix?(o.push(`%c${this.prefix} [${t}]`),i.push(`color: ${e}`)):(o.push(`%c[${t}]`),i.push(`color: ${e}`)),n.forEach(a=>{typeof a=="string"?(o.push(`%c${a}`),i.push(`color: ${e}`)):(o.push("%O"),r.push(a),i.push(""))}),[o.join(" ")].concat(i,r)}};import*as Xo from"howler";var oo=class{constructor(e){this.gameState=e;this.state=new Map;this.tasks=new Map;this.groups=new Map;Object.values(tn).forEach(t=>{this.groups.set(t,{volume:1,sounds:new Set})}),this.setupGroupVolume()}play(e,t={end:1,duration:0}){this.state.has(e)&&this.abortTask(this.getState(e).group);let{group:n,token:o,onPlayTask:i,onEndTask:r}=this.initSound(e),a=this.groups.get(e.config.type)?.volume??1,c=t.end*a;return this.state.set(e,{group:n,token:o,originalVolume:t.end}),this.pushTask(n,new ft().addTask(i).addTask(this.fadeTo(n,o,{...t,start:0,end:c})).addTask(this.createTask(l=>{e.state.volume=t.end,e.state.paused=!1,l()})).addTask(r).run())}stop(e,t=0){let n=this.getState(e);return this.abortTask(n.group),t===0?(n.group.stop(n.token),h.resolve(void 0)):this.pushTask(n.group,new ft().addTask(this.fadeTo(n.group,n.token,{start:e.state.volume,end:0,duration:t})).addTask(this.createTask(o=>{n.group.volume(e.state.volume,n.token),o()})).addTask(this.stopSound(n.group,n.token)).run())}setVolume(e,t,n=0){let o=this.getState(e);this.abortTask(o.group),o.originalVolume=t;let i=this.groups.get(e.config.type)?.volume??1,r=t*i;return n===0?(o.group.volume(r,o.token),h.resolve(void 0)):this.pushTask(o.group,new ft().addTask(this.fadeTo(o.group,o.token,{start:e.state.volume,end:r,duration:n})).addTask(this.createTask(a=>{e.state.volume=t,a()})).run())}pause(e,t=0){let n=this.getState(e);return this.abortTask(n.group),t===0?(n.group.pause(n.token),h.resolve(void 0)):this.pushTask(n.group,new ft().addTask(this.fadeTo(n.group,n.token,{start:e.state.volume,end:0,duration:t})).addTask(this.pauseSound(n.group,n.token)).addTask(this.createTask(o=>{this.applyEffectiveVolume(e),e.state.paused=!0,o()})).run())}resume(e,t=0){let n=this.getState(e);if(this.abortTask(n.group),t===0)return n.group.play(n.token),h.resolve(void 0);let o=this.groups.get(e.config.type)?.volume??1,i=n.originalVolume*o;return this.pushTask(n.group,new ft().addTask(this.fadeTo(n.group,n.token,{start:0,end:i,duration:t})).addTask(this.resumeSound(n.group,n.token)).addTask(this.createTask(r=>{e.state.paused=!1,r()})).run())}setRate(e,t){let n=this.getState(e);return this.abortTask(n.group),n.group.rate(t,n.token),e.state.rate=t,h.resolve(void 0)}getPosition(e){let t=this.getState(e);return t.group.seek(t.token)}isPlaying(e){if(!this.isManaged(e))return!1;let t=this.getState(e);return t.group.playing(t.token)}toData(){return{sounds:[...this.state.entries()].map(([e,t])=>[e.getId(),{isPlaying:t.group.playing(t.token),position:t.group.seek(t.token)}]),groups:[...this.groups.entries()].map(([e,t])=>[e,t.volume])}}fromData(e,t){return e.groups?.forEach(([n,o])=>{let i=this.groups.get(n);i&&(i.volume=o,i.sounds.forEach(r=>{this.applyEffectiveVolume(r)}))}),e.sounds.forEach(([n,o])=>{let i=t.get(n);if(!i)throw new A(`Sound not found (id: "${n}")
42
+ Use video.show() to add the video to the game`);let o=this.callee,i=new h,r=e.getExposedStateAsync(o,async a=>{e.logger.debug("Video Component state exposed",a),await t(a),i.resolve(super.executeAction(e,n))});return i.registerSkipController(new L(r.cancel)),i}changeState(e,t,n){return this.changeStateBase(e,t,n)}changeStateAsync(e,t,n){return this.changeStateBase(e,t,n)}stringify(e,t,n){return super.stringifyWithName("VideoAction")}};Je.ActionTypes=Nt;var to=Je;var Vt=class Vt extends q{constructor(e){super();let t=Vt.DefaultVideoConfig.create(e);if(this.config=t.get(),this.state=this.getInitialState(),!this.config.src)throw new X("Video must have a src")}show(){return this.chain(this.createAction(Nt.show,[]))}hide(){return this.chain(this.createAction(Nt.hide,[]))}play(){return this.chain(this.createAction(Nt.play,[]))}toData(){return{state:{display:this.state.display}}}fromData(e){let{state:t}=e;return this.state={display:t.display},this}reset(){return this.state=this.getInitialState(),this}getInitialState(){return Vt.DefaultVideoState.create().get()}createAction(e,t){return new to(this.chain(),e,S.create(t))}};Vt.DefaultVideoConfig=new H({src:"",muted:!1}),Vt.DefaultVideoState=new H({display:!1});var Qo=Vt;import*as Qi from"howler";var no=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 o=[],i=[],r=[];return this.prefix?(o.push(`%c${this.prefix} [${t}]`),i.push(`color: ${e}`)):(o.push(`%c[${t}]`),i.push(`color: ${e}`)),n.forEach(a=>{typeof a=="string"?(o.push(`%c${a}`),i.push(`color: ${e}`)):(o.push("%O"),r.push(a),i.push(""))}),[o.join(" ")].concat(i,r)}};import*as Xo from"howler";var oo=class{constructor(e){this.gameState=e;this.state=new Map;this.tasks=new Map;this.groups=new Map;Object.values(tn).forEach(t=>{this.groups.set(t,{volume:1,sounds:new Set})}),this.setupGroupVolume()}play(e,t={end:1,duration:0}){this.state.has(e)&&this.abortTask(this.getState(e).group);let{group:n,token:o,onPlayTask:i,onEndTask:r}=this.initSound(e),a=this.groups.get(e.config.type)?.volume??1,c=t.end*a;return this.state.set(e,{group:n,token:o,originalVolume:t.end}),this.pushTask(n,new ft().addTask(i).addTask(this.fadeTo(n,o,{...t,start:0,end:c})).addTask(this.createTask(l=>{e.state.volume=t.end,e.state.paused=!1,l()})).addTask(r).run())}stop(e,t=0){let n=this.getState(e);return this.abortTask(n.group),t===0?(n.group.stop(n.token),h.resolve(void 0)):this.pushTask(n.group,new ft().addTask(this.fadeTo(n.group,n.token,{start:e.state.volume,end:0,duration:t})).addTask(this.createTask(o=>{n.group.volume(e.state.volume,n.token),o()})).addTask(this.stopSound(n.group,n.token)).run())}setVolume(e,t,n=0){let o=this.getState(e);this.abortTask(o.group),o.originalVolume=t;let i=this.groups.get(e.config.type)?.volume??1,r=t*i;return n===0?(o.group.volume(r,o.token),h.resolve(void 0)):this.pushTask(o.group,new ft().addTask(this.fadeTo(o.group,o.token,{start:e.state.volume,end:r,duration:n})).addTask(this.createTask(a=>{e.state.volume=t,a()})).run())}pause(e,t=0){let n=this.getState(e);return this.abortTask(n.group),t===0?(n.group.pause(n.token),h.resolve(void 0)):this.pushTask(n.group,new ft().addTask(this.fadeTo(n.group,n.token,{start:e.state.volume,end:0,duration:t})).addTask(this.pauseSound(n.group,n.token)).addTask(this.createTask(o=>{this.applyEffectiveVolume(e),e.state.paused=!0,o()})).run())}resume(e,t=0){let n=this.getState(e);if(this.abortTask(n.group),t===0)return n.group.play(n.token),h.resolve(void 0);let o=this.groups.get(e.config.type)?.volume??1,i=n.originalVolume*o;return this.pushTask(n.group,new ft().addTask(this.fadeTo(n.group,n.token,{start:0,end:i,duration:t})).addTask(this.resumeSound(n.group,n.token)).addTask(this.createTask(r=>{e.state.paused=!1,r()})).run())}setRate(e,t){let n=this.getState(e);return this.abortTask(n.group),n.group.rate(t,n.token),e.state.rate=t,h.resolve(void 0)}getPosition(e){let t=this.getState(e);return t.group.seek(t.token)}isPlaying(e){if(!this.isManaged(e))return!1;let t=this.getState(e);return t.group.playing(t.token)}toData(){return{sounds:[...this.state.entries()].map(([e,t])=>[e.getId(),{isPlaying:t.group.playing(t.token),position:t.group.seek(t.token)}]),groups:[...this.groups.entries()].map(([e,t])=>[e,t.volume])}}fromData(e,t){return e.groups?.forEach(([n,o])=>{let i=this.groups.get(n);i&&(i.volume=o,i.sounds.forEach(r=>{this.applyEffectiveVolume(r)}))}),e.sounds.forEach(([n,o])=>{let i=t.get(n);if(!i)throw new A(`Sound not found (id: "${n}")
43
43
  NarraLeaf cannot find the element with the id from the saved game`);this.soundFromData(i,o)}),this}soundFromData(e,t){let n=this.getState(e);n.group.playing(n.token)&&n.group.stop(n.token);let o=this.initSound(e);this.state.set(e,o),o.group.seek(t.position,o.token),e.state.paused?o.group.pause(o.token):t.isPlaying||o.group.stop(o.token)}isManaged(e){return this.state.has(e)}reset(){this.state.forEach(e=>{e.group.stop(e.token)}),this.state.clear(),this.tasks.forEach(e=>{e.awaitable.abort()}),this.tasks.clear(),this.groups.forEach(e=>{e.volume=1,e.sounds.clear()}),this.setupGroupVolume()}setGroupVolume(e,t){let n=this.groups.get(e);if(!n)throw new A(`Sound group not found (type: "${e}")`);n.volume=t,n.sounds.forEach(o=>{this.applyEffectiveVolume(o)})}setGlobalVolume(e){Xo.Howler.volume(e)}getGlobalVolume(){return Xo.Howler.volume()}getGroupVolume(e){return this.groups.get(e)?.volume??1}setupGroupVolume(){let{soundVolume:e,bgmVolume:t,voiceVolume:n}=this.gameState.game.preference.getPreferences();this.setGroupVolume("sound",e),this.setGroupVolume("bgm",t),this.setGroupVolume("voice",n)}initSound(e){if(this.state.has(e))return this.state.get(e);let t=this.groups.get(e.config.type);t&&t.sounds.add(e);let n=this,[o,i]=this.wrapTask(),[r,a]=this.wrapTask(),c=this.groups.get(e.config.type)?.volume??1,l=e.state.volume*c,f=Reflect.construct(this.gameState.getHowl(),[this.getHowlConfig(e,{volume:l,onend(){r.resolve()},onplay(){o.resolve()},onloaderror(g,u){let C=u,T={1:"The fetching process for the media resource was aborted by the user agent at the user's request.",2:"A network error of some description caused the user agent to stop fetching the media resource, after the resource was established to be usable.",3:"An error of some description occurred while decoding the media resource, after the resource was established to be usable.",4:"The media resource indicated by the src attribute or assigned media provider object was not suitable."};n.gameState.logger.error("AudioManager",`Failed to load sound (src: "${e.config.src}")
44
44
  ${T[C]}
45
45
  For more information, see https://github.com/goldfire/howler.js?tab=readme-ov-file#onloaderror-function`)}})]),p=f.play(),d={group:f,token:p,originalVolume:e.state.volume};return this.state.set(e,d),f.seek(e.config.seek,p).rate(e.state.rate,p),e.state.paused&&f.pause(p),{...d,onPlayTask:i,onEndTask:a}}pushTask(e,t){return this.tasks.set(e,{awaitable:t}),t}getState(e){if(!this.state.has(e))throw new A(`Sound not initialized (src: "${e.config.src}")`);return this.state.get(e)}abortTask(e){let t=this.tasks.get(e);t&&(t.awaitable.abort(),this.tasks.delete(e))}fadeTo(e,t,n){let o,i,r=n.start??e.volume(),a=n.end??e.volume(),c=n.duration,l=new L(()=>{e.volume(a,t),o()});return[p=>{e.volume(r,t),e.fade(r,a,c,t),o=()=>{p.isSolved()||(i&&(i(),i=void 0),p.resolve())},i=this.gameState.schedule(()=>{i=void 0,o()},c)},l]}stopSound(e,t){return[()=>{e.stop(t)}]}pauseSound(e,t){return[()=>{e.pause(t)}]}resumeSound(e,t){return[()=>{e.play(t)}]}getHowlConfig(e,t={}){return{src:e.config.src,volume:e.state.volume,loop:e.config.loop,rate:e.state.rate,html5:e.config.streaming,...t}}createTask(e){return[t=>{e(t.resolve.bind(t))}]}wrapTask(){let e=new h;return[e,[t=>{e.isSolved()?t.resolve():e.then(()=>{t.resolve()})}]]}applyEffectiveVolume(e){if(!this.isManaged(e))return;let t=this.getState(e),n=this.groups.get(e.config.type)?.volume??1,o=t.originalVolume*n;t.group.volume(o,t.token)}};import*as as from"html-to-image";var io=class{constructor(e,t){this.gameState=e;this.notifications=t;this.events=new F}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 h,n=new se(t);return t.registerSkipController(new L(()=>{this.removeNotification(e)})),this.addNotification(e),e.duration&&this.gameState.schedule(()=>{t.resolve(),this.removeNotification(e)},e.duration),this.gameState.timelines.attachTimeline(n),t}onFlush(e){return this.events.on("event:notifications.flush",e)}toArray(){return[...this.notifications]}flush(){this.events.emit("event:notifications.flush")}};var ro=class{constructor(e=100,t){this.liveGame=t;this.history=[];this.hooks={onUndo:[],onHistoryLimit:[]};this.maxHistorySize=e}push(e,t,n){let o=Oi(6),{action:i,timeline:r,stackModel:a}=e,c=this.liveGame.getStackModelForce().serialize(!1);if(this.history.push({action:i,id:o,args:n||[],undo:t,timeline:r,rootStackSnapshot:c,stackModel:a}),this.history.length>this.maxHistorySize){let l=this.history.splice(0,this.history.length-this.maxHistorySize);this.hooks.onHistoryLimit.forEach(f=>f(l))}return{id:o}}undoUntil(e){let t=-1;for(let i=this.history.length-1;i>=0;i--)if(this.history[i].id===e){t=i;break}if(t===-1)return null;let n=[];for(let i=this.history.length-1;i>=t;i--)this.history[i].timeline&&!this.history[i].timeline.isSettled()&&this.history[i].timeline.abort(),console.log("NarraLeaf-React [ActionHistory] Undoing",this.history[i].action.type,this.history[i]),this.history[i].undo?.(...this.history[i].args||[]),n.push(this.history[i]);this.history.length=t,this.hooks.onUndo.forEach(i=>i(n));let o=this.liveGame.getStackModelForce().serialize();if(o){let[i]=this.liveGame.constructMaps();this.liveGame.getStackModelForce().deserialize(o,i)}return n[n.length-1]||null}undo(e){if(!this.ableToUndo(e))return null;let t=e.getHistory(),n;for(let o=t.length-1;o>=0;o--)if(t[o].isPending!==!0){n=t[o];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 so=class{constructor(e){this.history=[];this.actionHistoryMgr=e,this.actionHistoryMgr.onUndo(t=>{this.crossFilter(t)}),this.actionHistoryMgr.onHistoryLimit(t=>{this.crossFilter(t)})}push(e){return this.history.push(e),this}getHistory(){return this.history}reset(){this.history=[]}updateByToken(e,t){let n=this.history.find(o=>o.token===e);t(n||null)}resolvePending(e){let t=this.history.find(n=>n.token===e);t&&(t.isPending=!1)}crossFilter(e){let t=new Set(e.map(n=>n.id));this.history=this.history.filter(n=>!t.has(n.token))}};var zt=class zt{constructor(e,t){this.state={sounds:[],videos:[],srcManagers:[],elements:[]};this.currentHandling=null;this.playerCurrent=null;this.mainContentNode=null;this.exposedState=new Map;this.preloadingScene=null;this.flushDep=0;this.rollLock=new Jt;this.htmlToImage=as;this.pageRouter=null;this.stage=t,this.game=e,this.events=new F,this.logger=new no(e,"NarraLeaf-React"),this.audioManager=new oo(this),this.guard=new zn(e.config.app.guard).observe(this),this.timelines=new $n(this.guard),this.notificationMgr=new io(this,[]),this.idManager=new Gn,this.actionHistory=new ro(e.config.maxActionHistory,this.game.getLiveGame()),this.gameHistory=new so(this.actionHistory)}get deps(){return this.flushDep}addVideo(e){return this.state.videos.push(e),this}removeVideo(e){let t=this.state.videos.indexOf(e);return t===-1?(this.logger.weakWarn("Video not found when removing",e.getId()),this):(this.state.videos.splice(t,1),this)}isVideoAdded(e){return this.state.videos.includes(e)}getVideos(){return this.state.videos}findElementByScene(e){return this.state.elements.find(t=>t.scene===e)||null}findElementByDisplayable(e,t=null){return this.state.elements.find(n=>{if(t)return n.layers.get(t)?.includes(e)||!1;for(let o of n.layers.values())if(o.includes(e))return!0;return!1})||null}getLiveGame(){return this.game.getLiveGame()}removeElement(e){let t=this.state.elements.indexOf(e);return t===-1?(this.logger.weakWarn("Element not found when removing",e.scene.getId()),this):(this.logger.debug("GameState","Removing element",e.scene.getId()),this.state.elements.splice(t,1),this)}preloadScene(e){let t=Ee.isScene(e)?e:e.entryScene;if(!t)throw new A("Trying to preload a story but the story is not loaded");return this.preloadingScene=t,this.events.emit(zt.EventTypes["event:state:flushPreloadedScenes"]),this}getPreloadingScene(){return this.preloadingScene}addElement(e){return this.state.elements.push(e),this.logger.debug("GameState","Adding element",e.scene.getId()),this}addScene(e){return this.sceneExists(e)?this:(this.state.elements.unshift({scene:e,texts:[],menus:[],layers:new Map(e.config.layers.map(t=>[t,[]]))}),this.logger.debug("GameState","Adding scene",e.getId()),this)}flush(){return this.stage.update(),this}popScene(){let e=this.state.elements.pop();return e?(this.removeElements(e.scene),this.logger.debug("GameState","Popping scene",e.scene.getId()),this):this}removeScene(e){return this.removeElements(e),this.logger.debug("GameState","Removing scene",e.getId()),this}getSceneElements(){return this.state.elements}getLastScene(){return this.state.elements[this.state.elements.length-1]?.scene||null}sceneExists(e){return e?this.state.elements.some(t=>t.scene===e):!!this.getLastScene()}isSceneActive(e){for(let{scene:t}of this.state.elements)if(t===e)return!0;return!1}wait(e){return new Promise(t=>setTimeout(t,e))}schedule(e,t){let n=[],o=setTimeout(()=>{e({retry:()=>{this.schedule(e,0)},onCleanup:i=>{n.push(i)}})},t);return()=>{n.forEach(i=>i()),clearTimeout(o)}}notify(e){this.notificationMgr.addNotification(e)}handle(e){if(this.currentHandling===e)return this;switch(this.currentHandling=e,e.type){case"condition:action":break}return this}createDialog(e,t,n,o){let i=this.findElementByScene(this.getLastSceneIfNot(o))?.texts;if(!i)throw this.sceneNotFound();let r=t.evaluate(we.getCtx({gameState:this}));this.game.getLiveGame().events.emit(Tt.EventTypes["event:character.prompt"],{character:t.config.character,sentence:t,text:U.getText(r)});let a=this.createWaitableAction({character:t.config.character,sentence:t,id:e,words:r},()=>{i.splice(i.indexOf(a),1),n&&n()});return i.push(a),this.stage.update(),{cancel:()=>{let c=i.indexOf(a);c!==-1&&i.splice(c,1)},text:U.getText(r)}}createMenu(e,t,n){if(!e.choices.length)throw new Error("Menu must have at least one choice");let o=this.findElementByScene(this.getLastSceneIfNot(n))?.menus;if(!o)throw this.sceneNotFound();let i=e.prompt?.evaluate(we.getCtx({gameState:this}))||null,r=this.createWaitableAction({...e,words:i},a=>{o.splice(o.indexOf(r),1),t&&t(a),this.game.getLiveGame().events.emit(Tt.EventTypes["event:menu.choose"],{sentence:a.prompt,text:a.evaluated})});return o.push(r),{cancel:()=>{let a=o.indexOf(r);a!==-1&&o.splice(a,1)},prompt:i?U.getText(i):null}}createDisplayable(e,t=null,n=null){let o=this.getLastSceneIfNot(t),i=this.findElementByScene(o);if(!i)throw this.sceneNotFound();let r=i.layers.get(n||o.config.defaultDisplayableLayer);if(!r)throw this.layerNotFound();return r.push(e),this}disposeDisplayable(e,t=null,n=null){let o=this.getLastSceneIfNot(t),i=this.findElementByScene(o)?.layers.get(n||o.config.defaultDisplayableLayer);if(!i)throw this.layerNotFound();let r=i.indexOf(e);if(r===-1)throw new A(`Displayables not found when disposing. (disposing: ${e.getId()})`);return i.splice(r,1),this}forceReset(){this.state.elements.forEach(({scene:e})=>{this.offSrcManager(e.srcManager),this.removeScene(e),e.events.clear()}),this.state.elements=[],this.state.srcManagers=[],this.state.videos=[],this.audioManager.reset(),this.timelines.abortAll(),this.gameHistory.reset(),this.actionHistory.reset(),this.logger.debug("GameState","Force reset")}getHowl(){return Qi.Howl}registerSrcManager(e){return this.state.srcManagers.push(e),this}offSrcManager(e){return this.state.srcManagers=this.state.srcManagers.filter(t=>t!==e),this}getStorable(){return this.game.getLiveGame().getStorable()}getSceneByName(e){return this.game.getLiveGame().story?.getScene(e)||null}getStory(){if(!this.game.getLiveGame().story)throw new A("Story not loaded");return this.game.getLiveGame().story}setInterval(e,t){return setInterval(e,t)}clearInterval(e){clearInterval(e)}setTimeout(e,t){return setTimeout(e,t)}clearTimeout(e){clearTimeout(e)}forceAnimation(){let[e,t]=se.proxy(h.nothing),n=[];return Array.from(this.exposedState.keys()).forEach(o=>{o instanceof qe&&n.push(o)}),n.forEach(o=>{let i=this.getExposedStateForce(o),r=i.applyTransform(O.immediate({}),()=>{});t.attachChild(r),i.updateStyleSync()}),this.timelines.attachTimeline(t),e}mountState(e,t){if(this.exposedState.has(e))throw new he("State already mounted");if(!e)throw new he("Invalid state key");return this.exposedState.set(e,t),this.events.emit(zt.EventTypes["event.state.onExpose"],e,t),{unMount:()=>{this.unMountState(e)}}}unMountState(e){return this.exposedState.has(e)||this.guard.warn("invalidExposedStateUnmounting","State not found when unmounting"),this.exposedState.delete(e),this}initVideo(e){return this.state.videos.push(e),this}isStateMounted(e){return this.exposedState.has(e)}getExposedState(e){return this.exposedState.get(e)||null}getExposedStateForce(e){let t=this.getExposedState(e);if(!t)throw new A("State not found, key: "+e);return t}getExposedStateAsync(e,t){let n=this.getExposedState(e);if(n)return{cancel:this.schedule(()=>{t(n)},0)};{let o=this.events.on(zt.EventTypes["event.state.onExpose"],(i,r)=>{i===e&&(t(r),o.cancel())});return o}}dispose(){this.forceReset()}toData(){return{scenes:this.state.elements.map(e=>({sceneId:e.scene.getId(),elements:{layers:Object.fromEntries(Array.from(e.layers.entries()).map(([t,n])=>[t.getId(),n.map(o=>o.getId())]))}})),audio:this.audioManager.toData(),videos:this.state.videos.map(e=>[e.getId(),e.toData()])}}loadData(e,t){if(this.state.elements=[],!this.game.getLiveGame().story)throw new Error("No story loaded");let{scenes:o,audio:i,videos:r}=e;o.forEach(({sceneId:a,elements:c})=>{this.logger.debug("Loading scene: "+a);let l=t.get(a);if(!l)throw new A("Scene not found, id: "+a+`
@@ -50,16 +50,16 @@ NarraLeaf cannot find the element with the id from the saved game
50
50
  This may be caused by the damage of the saved game file or the change of the story file`);return t.get(r)})]}))}};zt.EventTypes={"event:state.end":"event:state.end","event:state.player.skip":"event:state.player.skip","event:state.player.requestFlush":"event:state.player.requestFlush","event.state.onExpose":"event.state.onExpose","event:state.onRender":"event:state.onRender","event:state:flushPreloadedScenes":"event:state:flushPreloadedScenes"};var K=zt;var De=class s{constructor(e,t=void 0){this.liveGame=e;this.__tag=void 0;this.waitingAction=null;this.__tag=t,this.stack=new Hn().addPushValidator(n=>{let o=this.stack.peek();if(n===o)throw new he("StackModel: Unexpected self-push in stack.");if(s.isCalledActionResult(o)){if(o.wait&&s.isStackModelsAwaiting(o.wait.type,o.wait.stackModels))throw new he("StackModel: Unexpected waiting action in stack. (is calledActionResult: true, wait: true)")}else if(h.isAwaitable(o)&&!o.isSettled())throw new he("StackModel: Unexpected unsettled Awaitable in stack.");if(!s.isCalledActionResult(n)&&!h.isAwaitable(n))throw new he("StackModel: Unexpected non-CalledActionResult or Awaitable in stack.");return!0})}static isStackModel(e){return e instanceof s}static createStackModel(e,t,n){let o=new s(e);return o.deserialize(t,n),o}static isCalledActionResult(e){return!!e&&!this.isStackModel(e)&&!h.isAwaitable(e)&&"type"in e}static fromAction(e){return{type:e.type,node:e.contentNode}}static executeStackModelGroup(e,t){return e==="any"?h.any(...t.map(n=>n.execute())):h.all(...t.map(n=>n.execute()))}static isStackModelsAwaiting(e,t){if(t.length===0)throw new Error("StackModel: StackModels are empty.");return e==="any"?t.every(n=>!n.isEmpty()):t.some(n=>!n.isEmpty())}rollNext(){if(this.stack.isEmpty())return null;let e=this.stack.peek();if(h.isAwaitable(e)&&!e.isSettled())return e;if(s.isCalledActionResult(e)&&e.wait){let n=e.wait.stackModels;if(!n.length)throw new Error("StackModel: Waiting action contains empty stackModels.");if(s.isStackModelsAwaiting(e.wait.type,n))return n.forEach(o=>o.rollNext()),e}this.waitingAction=null;let t=this.stack.pop();if(h.isAwaitable(t)){let n=t.result;if(n)return this.stack.push(n),this.liveGame.getGameStateForce().logger.debug("next action (resolved awaitable)",n.node?.action),n}else return this.waitingAction=t,this.executeActions(t);return null}execute(){let e=new h,t=null,n=!1;return(async()=>{let i=0;for(;!n;){if(i++>this.liveGame.game.config.maxStackModelLoop)throw new Error("StackModel: Suspiciously long waiting loop.");if(this.stack.isEmpty()){n=!0;break}let r=this.rollNext();if(r){if(h.isAwaitable(r)){if(r.isSettled())continue;t=r,await r}else if(s.isCalledActionResult(r))if(r.wait)t=s.executeStackModelGroup(r.wait.type,r.wait.stackModels),await t;else continue}}})().then(()=>e.resolve()),e.onSkipControllerRegister(i=>{i.onAbort(()=>{t&&(n=!0,t.abort())})}),e}abortStackTop(){if(this.stack.isEmpty())return null;let e=this.stack.peek();return e&&h.isAwaitable(e)?(this.stack.pop().abort(),this.waitingAction=null):s.isCalledActionResult(e)&&e.wait&&(e.wait.stackModels.forEach(t=>t.abortStackTop()),this.waitingAction=null),this.waitingAction}getTopSync(){if(this.stack.isEmpty())return null;let e=!1;for(let t=this.stack.size()-1;t>=0;t--){let n=this.stack.get(t);if(n){if(s.isCalledActionResult(n))return n;if(e)throw new he("StackModel: Unexpected non-CalledActionResult in stack.")}else return null;e=!0}return null}executeActions(e){if(!e.node?.action)return null;let t=this.liveGame.executeAction(this.liveGame.getGameStateForce(),e.node.action,{stackModel:this}),n=o=>o?h.isAwaitable(o)?(this.liveGame.getGameStateForce().logger.debug("next action (executed awaitable)",o),this.stack.push(o),o):o.node?.action?(this.liveGame.getGameStateForce().logger.debug("next action (executed)",o),this.stack.push(o),o):null:null;if(Array.isArray(t)){let o=null;for(let i of t){let r=n(i);r&&(o=r)}return o}else{let o=n(t);if(o)return o}return null}isWaiting(){let e=this.stack.peek();return e?h.isAwaitable(e)?!e.isSettled():s.isCalledActionResult(e)&&e.wait?s.isStackModelsAwaiting(e.wait.type,e.wait.stackModels):!1:!1}serialize(e=!0){let t=o=>{if(s.isCalledActionResult(o)){let i=o.node?.action?.getId()??null,r=o.node?.action?.type??null;return o.wait?.stackModels?{type:"link",actionType:r,action:i,stacks:o.wait.stackModels.map(a=>a.serialize()),stackWaitType:o.wait.type}:{type:"action",actionType:r,action:i}}return null},n=this.stack.map(t).filter(function(o){return o!==null});if(e&&this.waitingAction){let o=t(this.waitingAction);o&&n.push(o)}return n}reset(){this.stack.forEach(e=>{s.isCalledActionResult(e)?e.wait?.stackModels.forEach(t=>t.reset()):h.isAwaitable(e)&&e.abort()}),this.waitingAction&&this.waitingAction.wait?.stackModels.forEach(e=>e.reset()),this.waitingAction=null,this.stack.clear()}deserialize(e,t){this.reset();for(let n of e)if(n.type==="action"){if(!n.action)continue;let{actionType:o,action:i}=n,r=t.get(i);if(!r)throw new Error(`Action not found: ${i}`);this.stack.push({type:o,node:r.contentNode,wait:null})}else if(n.type==="link"){let{actionType:o,action:i,stacks:r,stackWaitType:a}=n;if(a==null)throw new Error(`Missing stackWaitType for link action: ${i}`);this.stack.push({type:o,node:i?t.get(i)?.contentNode??null:null,wait:{type:a,stackModels:r.map(c=>s.createStackModel(this.liveGame,c,t))}})}return this}isEmpty(){return this.stack.isEmpty()}push(...e){return this.stack.push(...e),this}};var at=class at{constructor(e){this.events=new F;this.story=null;this.gameLock=new Ht;this.currentSavedGame=null;this.gameState=void 0;this.stackModel=null;this.asyncStackModels=new Set;this.lastDialog=null;this.mapCache=null;this.game=e,this._storable=new an,this.initNamespaces()}initNamespaces(){return this._storable.clear().addNamespace(new rt(at.GameSpacesKey.game,at.DefaultNamespaces.game)),this.story&&this.story.initPersistent(this._storable),this}getStorable(){return this._storable}get storable(){return this._storable}loadStory(e){return this.story=e.constructStory(),this}serialize(){this.assertGameState();let e=this.gameState,t=this.story;if(!t)throw new Error("No story loaded");if(!this.currentSavedGame||!this.stackModel)throw new Error("Failed when trying to serialize the game: The game has not started");let n=this._storable.toData(),o=e.toData(),i=t.getAllElementStates(),r=this.stackModel.serialize(),a=Array.from(this.asyncStackModels).map(c=>c.serialize());return{name:this.currentSavedGame.name,meta:{created:this.currentSavedGame.meta.created,updated:Date.now(),id:this.currentSavedGame.meta.id,lastSentence:this.lastDialog?.sentence||null,lastSpeaker:this.lastDialog?.speaker||null,storyHash:t.hash()},game:{store:n,stage:o,elementStates:i,stackModel:r,asyncStackModels:a,services:t.serializeServices()}}}deserialize(e){if(!e)throw new Error("No saved game provided when trying to deserialize game state");this.assertGameState();let t=this.gameState,n=this.story;if(!n)throw new Error("No story loaded");t.rollLock.lock(),this.reset(),t.stage.forceRemount();let{game:{store:o,stage:i,elementStates:r,services:a,stackModel:c,asyncStackModels:l}}=e,[f,p]=this.constructMaps();this._storable.clear().load(o),r.forEach(({id:d,data:g})=>{t.logger.debug("restore element",d);let u=p.get(d);if(!u)throw new Error("Element not found, id: "+d+`
51
51
  NarraLeaf cannot find the element with the id from the saved game`);u.reset(),u.fromData(g)}),this.currentSavedGame=e,t.loadData(i,p),this.stackModel.deserialize(c,f),l.forEach(d=>this.asyncStackModels.add(De.createStackModel(this,d,f))),this.asyncStackModels.forEach(d=>t.timelines.attachTimeline(d.execute())),n.deserializeServices(a),t.events.once(K.EventTypes["event:state.onRender"],()=>{t.schedule(()=>{t.rollLock.unlock(),t.stage.next()},0)}),t.stage.forceUpdate()}getHistory(){return this.assertGameState(),this.gameState.gameHistory.getHistory()}undo(e){if(this.assertGameState(),!this.gameState.actionHistory.ableToUndo(this.gameState.gameHistory)){this.gameState.logger.warn("LiveGame.undo","No action to undo");return}let t=this.gameLock.register().lock();this.stackModel.abortStackTop();let n=e?this.gameState.actionHistory.undoUntil(e):this.gameState.actionHistory.undo(this.gameState.gameHistory);if(n){let[o]=this.constructMaps(),{rootStackSnapshot:i,stackModel:r}=n;this.stackModel.deserialize(i,o),r===this.stackModel&&this.stackModel.push(De.fromAction(n.action)),this.gameLock.off(t.unlock()),this.gameState.logger.info("LiveGame.undo","Undo until",e,"action",n),this.gameState.stage.forceUpdate(),this.gameState.stage.next(),this.gameState.schedule(()=>{this.gameState&&this.gameState.forceAnimation()},0)}else this.gameState.logger.warn("LiveGame.undo","No action found"),this.gameLock.off(t.unlock())}dispose(){this.events.clear(),this.gameState?.dispose()}notify(e,t=3e3){this.assertGameState();let n=this.gameState.idManager.generateId(),o=this.gameState.notificationMgr.consume({id:n,message:e,duration:t}),i=h.toPromiseForce(o);return{cancel:()=>{o.abort()},promise:i}}skipDialog(){this.assertGameState(),this.gameState.events.emit(K.EventTypes["event:state.player.skip"],!0)}assertScreenshot(){this.assertGameState(),this.assertPlayerElement()}capturePng(){return this.assertScreenshot(),this.gameState.htmlToImage.toPng(this.gameState.mainContentNode,this.getScreenshotOptions())}captureJpeg(){return this.assertScreenshot(),this.gameState.htmlToImage.toJpeg(this.gameState.mainContentNode,this.getScreenshotOptions())}captureSvg(){return this.assertScreenshot(),this.gameState.htmlToImage.toSvg(this.gameState.mainContentNode,this.getScreenshotOptions())}capturePngBlob(){return this.assertScreenshot(),this.assertGameState(),this.assertPlayerElement(),this.gameState.htmlToImage.toBlob(this.gameState.mainContentNode,this.getScreenshotOptions())}onCharacterPrompt(e){return this.events.on(at.EventTypes["event:character.prompt"],e)}onMenuChoose(e){return this.events.on(at.EventTypes["event:menu.choose"],e)}newGame(){this.assertGameState();let e=this.gameState,t=e.logger.group("LiveGame (newGame)",!0);this.reset(),this.initNamespaces();let n=this.getNewSavedGame();n.name="NewGame-"+Date.now(),this.currentSavedGame=n;let o=this.story?.entryScene?.getSceneRoot();o?this.stackModel.push(De.fromAction(o)):e.logger.warn("No scene root found");let i=this.story?.getAllElementMap(this.story,this.story?.entryScene?.getSceneRoot()||[]);return i?i.forEach(r=>{e.logger.debug("reset element",r),r.reset()}):e.logger.warn("No elements found"),e.stage.forceUpdate(),e.stage.next(),t.end(),this}waitForRouterExit(){let e=null;return{promise:new Promise(t=>{e=this.game.router.onceExitComplete(()=>{t()})}),cancel:()=>{e&&e.cancel()}}}waitForPageMount(){let e=null;return{promise:new Promise(t=>{e=this.game.router.oncePageMount(()=>{t()})}),cancel:()=>{e&&e.cancel()}}}requestFullScreen(e){this.assertGameState();let t="LiveGame.requestFullScreen";try{let n=this.gameState.playerCurrent;if(!n){this.gameState.logger.warn(t,"No player element found");return}if(n.requestFullscreen)return n.requestFullscreen(e);this.gameState.logger.warn(t,"Fullscreen is not supported")}catch(n){this.gameState.logger.error(t,n)}}exitFullScreen(){this.assertGameState();let e="LiveGame.exitFullScreen";try{if(document.exitFullscreen)return document.exitFullscreen();this.gameState.logger.warn(e,"Fullscreen is not supported")}catch(t){this.gameState.logger.error(e,t)}}constructMaps(){let e=this.story;if(!e)throw new Error("No story loaded");if(this.mapCache)return this.mapCache;let t=new Map,n=new Map;return e.forEachChild(e,e.entryScene?.getSceneRoot()||[],o=>{t.set(o.getId(),o),n.set(o.callee.getId(),o.callee)},{allowFutureScene:!0}),this.mapCache=[t,n],this.mapCache}getScreenshotOptions(){return{quality:this.game.config.screenshotQuality}}onPlayerEvent(e,t,n){this.assertPlayerElement();let o=this.gameState.playerCurrent;return o?(o.addEventListener(e,t,n),{cancel:()=>o.removeEventListener(e,t,n)}):(this.gameState.logger.warn("LiveGame.onEvent","No player element found"),{cancel:()=>{}})}onWindowEvent(e,t,n){return window.addEventListener(e,t,n),{cancel:()=>window.removeEventListener(e,t,n)}}reset(){this.assertGameState();let e=this.gameState;this.resetStackModels(),this.stackModel.reset(),this.currentSavedGame=null,this.lastDialog=null,e.forceReset()}next(){this.assertGameState();let e=this.gameState;if(this.gameLock.isLocked())return this.gameLock;if(!this.story)throw new Error("No story loaded");return this.stackModel.isEmpty()?(e.logger.weakWarn("Game Actions","Action stack is empty"),this.currentSavedGame?e.events.emit("event:state.end"):this.currentSavedGame=null,null):this.stackModel.rollNext()}setLastDialog(e,t){this.lastDialog={sentence:e,speaker:t}}requestAsyncStackModel(e){this.assertGameState();let t=new De(this);return this.asyncStackModels.add(t),t.push(...e),t}createStackModel(e){let t=new De(this);return t.push(...e),t}resetStackModels(){this.asyncStackModels.forEach(e=>e.reset()),this.asyncStackModels.clear()}isPlaying(){return this.stackModel&&!this.stackModel.isEmpty()}executeAction(e,t,n){if(!this.stackModel)throw new Error("Stack model is not initialized");let o=t.executeAction(e,n);return h.isAwaitable(o)?o:o||null}setGameState(e){if(e&&this.gameState)throw new he("GameState already set");return this.gameState=e,e&&!this.stackModel&&(this.stackModel=new De(this,"$root")),this}getGameState(){return this.gameState}getGameStateForce(){if(!this.gameState)throw new he("GameState not set");return this.gameState}getAllPredictableActions(e,t,n){let o=t?.contentNode||null,i=[],r=[],a=new Set;for(;(o||r.length)&&!(n&&i.length>=n);){if(o||(o=r.pop().contentNode),[Xe].some(c=>o?.action&&o.action instanceof c)){o=null;continue}if(o.action&&o.action.is(ae,ee.jumpTo)){let[c]=o.action.contentNode.getContent(),l=e.getScene(c);if(!l)throw o.action._sceneNotFoundError(o.action.getSceneName(c));if(a.has(l)){o=null;continue}a.add(l),o=l.getSceneRoot()?.contentNode||null;continue}else if(o.action&&o.action.is(te,Oe.do)){let[c]=o.action.contentNode.getContent();o.getChild()?.action&&r.push(o.getChild().action),o=c[0]?.contentNode||null}o.action&&i.push(o.action),o=o.getChild()}return i}clearMainStack(){if(!this.stackModel)throw new he("No stack model found");return this.stackModel.reset(),this}getStackModelForce(){if(!this.stackModel)throw new he("No stack model found");return this.stackModel}getNewSavedGame(){return{name:"",meta:{created:Date.now(),updated:Date.now(),id:Wi(),lastSentence:null,lastSpeaker:null,storyHash:this.story?.hash()||""},game:{store:{},stage:{scenes:[],audio:{sounds:[],groups:[]},videos:[]},elementStates:[],services:{},stackModel:[],asyncStackModels:[]}}}assertGameState(){if(!this.gameState)throw new A("No game state found, make sure you call this method in effect hooks or event handlers")}assertPlayerElement(){if(this.assertGameState(),!this.gameState.playerCurrent)throw new A("Player Element Not Mounted")}};at.DefaultNamespaces={game:{}},at.GameSpacesKey={game:"game"},at.EventTypes={"event:character.prompt":"event:character.prompt","event:menu.choose":"event:menu.choose"};var Tt=at;var un=class un{constructor(e){this.settings=e;this.events=new F;this.events.setMaxListeners(64)}setPreference(e,t){this.settings[e]=t,this.events.emit(un.EventTypes["event:game.preference.change"],e,t)}getPreference(e){return this.settings[e]}getPreferences(){return this.settings}onPreferenceChange(e,t){return this.events.on(un.EventTypes["event:game.preference.change"],(n,o)=>{typeof e=="string"?e===n&&t&&t(o):e(n,o)})}importPreferences(e){for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&this.setPreference(t,e[t])}exportPreferences(){let e={};for(let t in this.settings)Object.prototype.hasOwnProperty.call(this.settings,t)&&(e[t]=this.settings[t]);return e}togglePreference(e){if(typeof this.settings[e]!="boolean")throw new Error(`Preference ${e} is not a boolean`);this.setPreference(e,!this.getPreference(e))}};un.EventTypes={"event:game.preference.change":"event:game.preference.change"};var pn=un;import"client-only";import Sr,{useEffect as ua,useRef as ai}from"react";import"client-only";import Xi,{useContext as cs,useState as ls}from"react";var Ji=Xi.createContext(null);function Yi({children:s,game:e}){"use client";let t=new Q({}),[n]=ls(e||t);return Xi.createElement(Ji,{value:n},s)}function w(){let s=cs(Ji);if(!s)throw new Error("useGame must be used within a GameProvider");return s}import us,{createContext as ps,useContext as Zi}from"react";var _i="/",ao=class ao{constructor(e,t=ao.rootPath){this.events=new F;this.currentPath="";this.currentQuery={};this.history=[];this.historyIndex=-1;this.mountedPaths=new Set;this.defaultHandlerPaths=new Set;this.unmountingPaths=new Set;this.updateSyncHooks=new Set;this.transitioning=!1;this.game=e;let{path:n,query:o}=this.parseUrl(t);this.currentPath=n,this.currentQuery=o,this.history.push(t),this.historyIndex=0}getCurrentPath(){return this.currentPath}getPathname(){return this.currentPath}getCurrentQuery(){return{...this.currentQuery}}getQueryParams(){return this.getCurrentQuery()}getCurrentUrl(){return this.buildUrl(this.currentPath,this.currentQuery)}parseUrl(e){let[t,n]=e.split("?"),o={};if(n){let i=n.split("&");for(let r of i){let[a,c]=r.split("=");a&&(o[decodeURIComponent(a)]=c?decodeURIComponent(c):"")}}return{path:t||"/",query:o}}buildUrl(e,t){if(Object.keys(t).length===0)return e;let n=Object.entries(t).map(([o,i])=>`${encodeURIComponent(o)}=${encodeURIComponent(i)}`).join("&");return`${e}?${n}`}getQueryParam(e){return this.currentQuery[e]}setQueryParam(e,t){return this.currentQuery[e]=t,this.updateHistory(),this.emitOnChange(),this}setQueryParams(e){return Object.assign(this.currentQuery,e),this.updateHistory(),this.emitOnChange(),this}removeQueryParam(e){return delete this.currentQuery[e],this.updateHistory(),this.emitOnChange(),this}clearQueryParams(){return this.currentQuery={},this.updateHistory(),this.emitOnChange(),this}hasQueryParam(e){return e in this.currentQuery}getQueryParamKeys(){return Object.keys(this.currentQuery)}getQueryParamCount(){return Object.keys(this.currentQuery).length}getHistory(){return[...this.history]}getHistoryIndex(){return this.historyIndex}canGoBack(){return this.historyIndex>0}canGoForward(){return this.historyIndex<this.history.length-1}navigate(e,t){let{path:n,query:o}=this.parseUrl(e),i=this.resolvePath(n),r={...o,...t};if(this.currentPath===i)return this.currentQuery=r,this.historyIndex>=0&&(this.history[this.historyIndex]=this.buildUrl(i,r)),this.emitOnChange(),this;this.historyIndex<this.history.length-1&&(this.history.length=this.historyIndex+1);let a=this.buildUrl(i,r);return this.history.push(a),this.history.length>this.game.config.maxRouterHistory&&(this.history.shift(),this.historyIndex--),this.historyIndex++,this.currentPath=i,this.currentQuery=r,this.emitOnChange(),this.requestPageTransition(),this}back(){if(this.canGoBack()){this.historyIndex--;let{path:e,query:t}=this.parseUrl(this.history[this.historyIndex]);this.currentPath=e,this.currentQuery=t,this.emitOnChange(),this.requestPageTransition()}return this}forward(){if(this.canGoForward()){this.historyIndex++;let{path:e,query:t}=this.parseUrl(this.history[this.historyIndex]);this.currentPath=e,this.currentQuery=t,this.emitOnChange(),this.requestPageTransition()}return this}replace(e,t){let{path:n,query:o}=this.parseUrl(e),i=this.resolvePath(n),r={...o,...t};return this.currentPath=i,this.currentQuery=r,this.historyIndex>=0?this.history[this.historyIndex]=this.buildUrl(i,r):(this.history.push(this.buildUrl(i,r)),this.historyIndex=0),this.emitOnChange(),this}clear(){return this.currentPath="",this.currentQuery={},this.history=[],this.historyIndex=-1,this.emitOnChange(),this.requestPageTransition(),this}cleanHistory(){return this.history=this.currentPath?[this.buildUrl(this.currentPath,this.currentQuery)]:[],this.historyIndex=this.currentPath?0:-1,this}parsePath(e){return e.split("/").filter(t=>t.length>0)}buildPath(e){return"/"+e.join("/")}getParentPath(e){let t=this.parsePath(e);return t.length<=1?"":this.buildPath(t.slice(0,-1))}matchPath(e,t){let n=this.parsePath(e),o=this.parsePath(t);if(n.length<o.length)return!1;for(let i=0;i<o.length;i++){let r=n[i],a=o[i];if(a!=="*"){if(a.startsWith(":"))continue;if(r!==a)return!1}}return!0}exactMatch(e,t){let n=this.parsePath(e),o=this.parsePath(t);if(n.length!==o.length)return!1;for(let i=0;i<o.length;i++){let r=n[i],a=o[i];if(a!=="*"){if(a.startsWith(":"))continue;if(r!==a)return!1}}return!0}extractParams(e,t){let n={},o=this.parsePath(e),i=this.parsePath(t);if(o.length!==i.length)return n;for(let r=0;r<i.length;r++){let a=i[r];if(a.startsWith(":")){let c=a.slice(1);n[c]=o[r]}}return n}onExitComplete(e){return this.events.on("event:router.onExitComplete",e)}onceExitComplete(e){return this.events.once("event:router.onExitComplete",e)}onPageMount(e){return this.events.on("event:router.onPageMount",e)}oncePageMount(e){return this.events.once("event:router.onPageMount",e)}onUpdate(e){return this.updateSyncHooks.add(e),{cancel:()=>{this.updateSyncHooks.delete(e)}}}emitUpdateSync(){this.updateSyncHooks.forEach(e=>e())}mount(e){if(this.mountedPaths.has(e))throw new A(`Path ${e} is already mounted. This may be caused by multiple capture segments in the same path.`);return this.mountedPaths.add(e),{cancel:()=>{this.unmount(e)}}}unmount(e){this.mountedPaths.delete(e)}mountDefaultHandler(e){if(this.defaultHandlerPaths.has(e))throw new A(`Default handler path ${e} is already mounted.`);return this.defaultHandlerPaths.add(e),{cancel:()=>{this.unmountDefaultHandler(e)}}}unmountDefaultHandler(e){this.defaultHandlerPaths.delete(e)}emitOnPageMount(){this.events.emit("event:router.onPageMount")}onRootExitComplete(e){return this.events.on("event:router.onExitComplete",e)}isActive(){return this.currentPath!==""}onChange(e){return this.events.on("event:router.onChange",e)}emitOnChange(){this.events.emit("event:router.onChange")}resolvePath(e){let t=e.split("?")[0];if(t.startsWith("/"))return t;if(t==="")return this.currentPath;let n=this.parsePath(this.currentPath),o=t.split("/"),i=[];i.push(...n);for(let r=0;r<o.length;r++){let a=o[r];a===""||a==="."||(a===".."?i.length>0&&i.pop():i.push(a))}return this.buildPath(i)}normalizePath(e){let t=e.replace(/\/\/+/g,"/").replace(/\/$/,"");return t===""?"/":(t.startsWith("/"),t)}joinPath(e,...t){let n=this.normalizePath(e),r=[n.startsWith("/")?n:"/"+n,...t.filter(a=>a.length>0)].join("/");return this.normalizePath(r)}updateHistory(){this.historyIndex>=0&&(this.history[this.historyIndex]=this.buildUrl(this.currentPath,this.currentQuery))}requestPageTransition(){let e=()=>{this.transitioning=!0,this.emitUpdateSync(),this.emitOnChange()},t=()=>{this.events.emit("event:router.onTransitionEnd"),this.transitioning=!1,this.emitUpdateSync(),this.emitOnChange(),this.events.emit("event:router.onExitComplete")};if(e(),this.isPathsUnmounting()){let n=this.events.on("event:router.onPathUnmount",()=>{this.isPathsUnmounting()||(n.cancel(),Me(()=>{t()}))})}else Me(()=>{t()})}registerUnmountingPath(e){this.unmountingPaths.add(e)}isPathsUnmounting(){return this.unmountingPaths.size>0}unregisterUnmountingPath(e){this.unmountingPaths.delete(e),this.events.emit("event:router.onPathUnmount")}isTransitioning(){return this.transitioning}createToken(e){return Symbol(e)}};ao.rootPath=_i;var St=ao,Jo=ps(null);function er({children:s}){let e=w();return us.createElement(Jo,{value:{router:e.router}},s)}function Ye(){if(!Zi(Jo))throw new Error("useRouter must be used within a RouterProvider");return Zi(Jo).router}import nr from"react";import Ts from"clsx";import ds,{createContext as ms,useContext as fs,useEffect as gs,useReducer as hs,useState as ys}from"react";var ct=class ct{constructor(){this.state={width:0,height:0,minWidth:800,minHeight:450,paused:!1,scale:0};this.events=new F().setMaxListeners(1/0);this.lockers=[];this.updater=null}update(e,t,n){this.state.width=e,this.state.height=t,this.state.scale=n,this.events.emit(ct.EventTypes["event:aspectRatio.update"],e,t)}updateMin(e,t){this.state.minWidth=e,this.state.minHeight=t}lock(){let e=Symbol();return this.lockers.push(e),e}unlock(e){if(e&&!this.lockers.includes(e))throw new Error("Locker not found");return this.lockers=this.lockers.filter(t=>t!==e),this.triggerUpdate(),null}isLocked(){return!!this.lockers.length}getStyle(){return{width:`${this.state.width}px`,height:`${this.state.height}px`}}setUpdate(e){this.updater=e}pause(){this.state.paused=!0,this.events.emit(ct.EventTypes["event:aspectRatio.pause"])}resume(){this.state.paused=!1,this.events.emit(ct.EventTypes["event:aspectRatio.resume"])}onUpdate(e){return this.events.on(ct.EventTypes["event:aspectRatio.update"],e).cancel}requestUpdate(){this.events.emit(ct.EventTypes["event:aspectRatio.requestUpdate"])}onRequestedUpdate(e){return this.events.on(ct.EventTypes["event:aspectRatio.requestUpdate"],e).cancel}triggerUpdate(){this.updater&&this.updater()}};ct.EventTypes={"event:aspectRatio.update":"event:aspectRatio.update","event:aspectRatio.pause":"event:aspectRatio.pause","event:aspectRatio.resume":"event:aspectRatio.resume","event:aspectRatio.requestUpdate":"event:aspectRatio.requestUpdate"};var Yo=ct,Zo=ms(null);function tr({children:s}){"use client";let[e]=ys(()=>new Yo);return ds.createElement(Zo,{value:{ratio:e}},s)}function Z(){let s=fs(Zo),[,e]=hs(n=>n+1,0);if(!Zo||!s)throw new Error("useRatio must be used within a RatioProvider");let{ratio:t}=s;return gs(()=>t.onUpdate(()=>{e()}),[]),s}function Ze({children:s,className:e,style:t,ref:n,...o}){let{ratio:i}=Z(),r=i.getStyle();return nr.createElement("div",{className:Ts("inset-0",e),style:{width:"100%",height:"100%",minWidth:`${i.state.minWidth}px`,minHeight:`${i.state.minHeight}px`},...o},nr.createElement("div",{style:{...r,position:"relative",...t||{}},...o||{},ref:n},s))}import Ss,{useEffect as bs}from"react";function $e(s){let e=w(),[t,n]=Ss.useState(e.preference.getPreference(s)),o=i=>{e.preference.setPreference(s,i),n(i)};return bs(()=>e.preference.onPreferenceChange(s,n).cancel,[s,e.preference,n]),[t,o]}import _o from"react";import co from"react";import or from"clsx";function lo({children:s,className:e,style:t,...n}){let{ratio:o}=Z(),i=w();return co.createElement(Ze,{className:or("absolute pointer-events-none w-full h-full"),style:{transform:`scale(${o.state.scale})`,transformOrigin:"left top",width:i.config.width,height:i.config.height,pointerEvents:"none"},"data-element-type":"full",...n},co.createElement("div",{className:"absolute inset-0 w-full h-full"},co.createElement("div",{className:"inset-0 w-full h-full"},co.createElement("div",{className:or("pointer-events-auto-rest",e),style:t},s))))}function As({children:s,className:e,style:t}){return _o.createElement(_o.Fragment,null,_o.createElement(lo,{style:t,className:e,"data-element-type":"stage","data-code-source":"Stage.tsx"},s))}import ir from"clsx";import rr from"react";function uo({className:s,children:e,...t}){let{ratio:n}=Z();return rr.createElement("div",{style:{transform:`scale(${n.state.scale})`,transformOrigin:"left top"},className:ir("w-full h-full")},rr.createElement("div",{className:ir("z-20",s),...t},e))}import Ue,{useState as sr}from"react";import{motion as vs}from"motion/react";function po({children:s,border:e="solid",color:t="red",tag:n,borderWidth:o=1,as:i="div",ref:r,...a}){let c=w(),[l,f]=sr(!1);if(!c.config.app.inspector)return Ue.createElement(i,{...a,ref:r},s);let p={...a,onMouseEnter:()=>f(!0),onMouseLeave:()=>f(!1),style:{...a.style||{},outline:`${o}px ${e} ${t}`,zIndex:l?1e3:"auto"}};return Ue.createElement(i,{...p,ref:r},n&&l&&Ue.createElement("span",{className:"absolute top-0 left-0 bg-white text-black border-2 border-black text-sm"},n),s)}function Cs({border:s="solid",color:e="red",tag:t,borderWidth:n=1,as:o="img",...i}){let r=w(),[a,c]=sr(!1);if(!r.config.app.inspector)return Ue.createElement(o,{...i});let l={...i,onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),style:{...i.style||{},outline:`${s} ${n}px ${e}`,zIndex:a?1e3:"auto"}};return Ue.createElement("div",null,Ue.createElement(o,{...l}),t&&a&&Ue.createElement("span",{className:"absolute top-0 left-0 bg-white text-black border-2 border-black"},t))}function xs(s){return Ue.createElement(po,{...s,as:"div"})}function ws(s){return Ue.createElement(po,{...s,as:"span"})}function ks(s){return Ue.createElement(Cs,{...s,as:"img"})}function Ps(s){return Ue.createElement(po,{...s,as:"button"})}function Es(s){return Ue.createElement(po,{...s,as:vs.div,ref:s.ref,layout:s.layout})}var Ds={Div:xs,Span:ws,Button:Ps,Img:ks,mDiv:Es},Rt=Ds;import lr from"clsx";import Lt,{useEffect as ti,useRef as Gs,useState as Ns}from"react";import{useEffect as Rs,useState as Ls}from"react";function B(s){let[e,t]=Ls(0);Rs(()=>{n()},s??[]);function n(){t(o=>o+1)}return[n,e]}import ar from"react";var ei=ar.createContext(null);function lt(){let s=ar.useContext(ei);if(!s)throw new Error("useDialogContext must be used within a DialogContext");return s}import mo,{useLayoutEffect as cr,useMemo as Is,useState as Ms}from"react";var Be=class Be{constructor(e){this.events=new F;this._forceSkipped=!1;this._idle=!1;this.config=e,this._state="pending",this.autoForwardScheduler=new In,this._count=0}get state(){return this._state}get deps(){return[this._count]}isIdle(){return this._idle}setIdle(e){this._idle=e}requestComplete(){this.state==="ended"?this.safeEmit(Be.Events.complete):this.safeEmit(Be.Events.requestComplete)}forceSkip(){this.state==="ended"?this.emitComplete():(this._forceSkipped=!0,this.safeEmit(Be.Events.forceSkip))}dispatchComplete(){if(this.state==="ended"){this.config.gameState.logger.weakWarn("DialogState","Dialog is already ended. Cannot dispatch complete.");return}if(!this.events.hasListeners(Be.Events.complete)){this.config.gameState.logger.weakWarn("DialogState","No listener for complete event. Cannot dispatch complete.");return}let e=this.config.gameState.game.preference;return this._state="ended",e.getPreference(Q.Preferences.autoForward)&&this.scheduleAutoForward(),this.emitComplete(),this}emitComplete(){return this.safeEmit(Be.Events.complete),this.emitFlush(),this}isEnded(){return this.state==="ended"}setPause(e){this.isEnded()||(e?this._state="paused":this._state="pending")}isForceSkipped(){return this._forceSkipped}tryScheduleAutoForward(){this.isEnded()&&this.scheduleAutoForward()}cancelAutoForward(){this.autoForwardScheduler.cancelTask()}emitFlush(){return this._count++,this.events.emit(Be.Events.onFlush),this}onFlush(e){return this.events.on(Be.Events.onFlush,e)}safeEmit(e,...t){return this.events.emit(e,...t)===0&&this.config.gameState.logger.weakWarn("DialogState",`Failed to emit event: ${e}. Target Component is not mounted.`),this}scheduleAutoForward(){let e=this.config.gameState.game.preference;!e.getPreference(Q.Preferences.autoForward)||this.state!=="ended"||this.autoForwardScheduler.cancelTask().scheduleTask(()=>{this.events.emit(Be.Events.simulateClick)},this.config.gameState.game.config.autoForwardDelay/e.getPreference(Q.Preferences.gameSpeed))}};Be.Events={requestComplete:"event:dialog.requestComplete",complete:"event:dialog.complete",forceSkip:"event:dialog.forceSkip",onFlush:"event:dialog.onFlush",simulateClick:"event:dialog.simulateClick"};var Re=Be;function dn({action:s,onFinished:e,useTypeEffect:t=!0,gameState:n}){let o=Is(()=>s.sentence?.evaluate(we.getCtx({gameState:n})),[s.sentence,n]),[i]=Ms(()=>new Re({useTypeEffect:t,action:s,evaluatedWords:o||[],gameState:n})),r=n.game.config.dialog;return cr(()=>(n.logger.debug("NarraLeaf-React: Say","dialogState",i),i.events.on(Re.Events.complete,a=>{n.logger.log("NarraLeaf-React: Say","Complete",i.isIdle()),i.isIdle()||a?e?.(!1):i.setIdle(!0)}).cancel),[i]),cr(()=>n.events.on(K.EventTypes["event:state.player.skip"],a=>{a?(i.setIdle(!0),i.forceSkip()):i.isIdle()?e?.(!0):i.forceSkip()}).cancel,[i]),mo.createElement(mo.Fragment,null,mo.createElement(ei,{value:i,key:s.id},mo.createElement(r,null)))}function*ur(s){let e=[...s];for(let t=0;t<e.length;t++){let n=e[t];if(Se.isPause(n.text)){yield Se.from(n.text);continue}for(let o=0;o<n.text.length;o++){let i=n.text[o];i===`
52
52
  `?yield`
53
- `:yield{text:i,config:n.config,tag:t,tag2:o,cps:n.config.cps}}}}function pr({defaultColor:s,className:e,style:t,dialog:n,...o}){let i=w(),r=i.getLiveGame().getGameState(),a=Gs(null),[c,l]=Ns(()=>n&&!n.config.useTypeEffect?g(n.config.evaluatedWords):[]),[f,p]=B();if(!n)throw new Error("Dialog state is required");ti(()=>{if(!(!n.config.action.sentence||a.current))return r.logger.info("Initializing the sentence",n,a.current),r.schedule(({onCleanup:m})=>{if(!n.config.useTypeEffect){n.dispatchComplete();return}l([]),a.current=d(),f(),a.current.onComplete(()=>{n.dispatchComplete()}),m(()=>{a.current?.timeline?.abort()})},0)},[]),ti(()=>n.events.depends([n.events.on(Re.Events.requestComplete,()=>{a.current?.interact()}),n.events.on(Re.Events.forceSkip,()=>{n.isEnded()||a.current?.forceSkip()})]).cancel,[n,p]),ti(()=>i.preference.events.depends([i.preference.onPreferenceChange(Q.Preferences.gameSpeed,()=>{a.current?.update()}),i.preference.onPreferenceChange(Q.Preferences.autoForward,()=>{a.current?.update()}),i.preference.onPreferenceChange(Q.Preferences.cps,()=>{a.current?.update()})]).cancel,[]);function d(){let m=new h,y=new se(m).setGuard(r.guard),G=new Set,ye=new Set,et=new Set,Gt=ur(n.config.evaluatedWords),Ke=null,At=[],Fe=[],dt=()=>{At.forEach(E=>E()),At.length=0},tt=()=>{if(Fe.length!==0)return{done:!1,value:Fe.shift()};let{done:E,value:D}=Gt.next();return{done:E,value:D}},oe=E=>{let D=J=>{E(J),ye.delete(D)};return ye.add(D),{cancel:()=>{ye.delete(D)}}},k=E=>{l(D=>{let J=D[D.length-1];return J&&J!==`
53
+ `:yield{text:i,config:n.config,tag:t,tag2:o,cps:n.config.cps}}}}function pr({defaultColor:s,className:e,style:t,dialog:n,...o}){let i=w(),r=i.getLiveGame().getGameState(),a=Gs(null),[c,l]=Ns(()=>n&&!n.config.useTypeEffect?g(n.config.evaluatedWords):[]),[f,p]=B();if(!n)throw new Error("Dialog state is required");ti(()=>{if(!(!n.config.action.sentence||a.current))return r.logger.info("Initializing the sentence",n,a.current),r.schedule(({onCleanup:m})=>{if(!n.config.useTypeEffect){n.dispatchComplete();return}l([]),a.current=d(),f(),a.current.onComplete(()=>{n.dispatchComplete()}),m(()=>{a.current?.timeline?.abort()})},0)},[]),ti(()=>n.events.depends([n.events.on(Re.Events.requestComplete,()=>{a.current?.interact()}),n.events.on(Re.Events.forceSkip,()=>{n.isEnded()||a.current?.forceSkip()})]).cancel,[n,p]),ti(()=>i.preference.events.depends([i.preference.onPreferenceChange(Q.Preferences.gameSpeed,()=>{a.current?.update()}),i.preference.onPreferenceChange(Q.Preferences.autoForward,()=>{a.current?.update()}),i.preference.onPreferenceChange(Q.Preferences.cps,()=>{a.current?.update()})]).cancel,[]);function d(){let m=new h,y=new se(m).setGuard(r.guard),N=new Set,ye=new Set,et=new Set,Gt=ur(n.config.evaluatedWords),Ke=null,At=[],Fe=[],dt=()=>{At.forEach(E=>E()),At.length=0},tt=()=>{if(Fe.length!==0)return{done:!1,value:Fe.shift()};let{done:E,value:D}=Gt.next();return{done:E,value:D}},oe=E=>{let D=J=>{E(J),ye.delete(D)};return ye.add(D),{cancel:()=>{ye.delete(D)}}},k=E=>{l(D=>{let J=D[D.length-1];return J&&J!==`
54
54
  `&&E!==`
55
55
  `&&J.tag===E.tag?[...D.slice(0,-1),{...E,text:J.text+E.text,config:E.config}]:[...D,E]})},V=(E=!1)=>{let D=!1;for(;!D;){let{done:J,value:$}=tt();if(J){D=!0;break}if(Se.isPause($)){if(E)continue;D=!0,Fe.push($);break}else $===`
56
- `?l(me=>[...me,$]):typeof $=="object"&&"text"in $&&!G.has($)&&(G.add($),k($))}Ke&&!Ke.isSettled()?Ke.abort():(et.forEach(J=>J()),m.resolve())};return r.schedule(async E=>{let D=!1,J=!1;for(;!D;){let{done:$,value:me}=tt();if($){D=J=!0;break}let wn=new h;if(r.timelines.attachTimeline(wn),wn.registerSkipController(new L(()=>{dt(),D=!0,E.retry()})),wn.onSettled(()=>{dt()}),Ke=wn,Se.isPause(me)){let kn=Se.from(me),Pn=i.preference.getPreference(Q.Preferences.gameSpeed);if(kn.config.duration){let En=kn.config.duration/Pn;await Kn(En)}else{let En=i.preference.getPreference(Q.Preferences.autoForward),Dn=h.race([h.create(Zr=>{let _r=oe(es=>{es(),Zr.resolve()});At.push(()=>_r.cancel())}),...En?[h.delay(i.config.autoForwardDefaultPause/Pn)]:[]]);r.timelines.attachTimeline(Dn),await h.wait(Dn)}}else{if(me!==`
57
- `&&G.has(me))continue;G.add(me),k(me);let{gameSpeed:kn,cps:Pn}=i.preference.getPreferences(),Dn=1e3/((typeof me=="object"&&"cps"in me&&me.cps!==void 0?me.cps:Pn)*kn);await Kn(Dn)}}J&&(et.forEach($=>$()),m.resolve())},0),{getToken:()=>m,interact:()=>{let E=!1;ye.forEach(D=>D(()=>E=!0)),!E&&V()},update:()=>{Ke&&Ke.abort()},forceSkip:()=>{V(!0)},timeline:y,onComplete:E=>(et.add(E),{cancel:()=>{et.delete(E)}})}}function g(m){let y=ur(m),G=[];for(let ye of y)Se.isPause(ye)||G.push(ye);return G}let u=n.config.action.sentence;if(!u)return null;let C={fontWeight:u.config.bold?i.config.fontWeightBold:i.config.fontWeight,fontSize:u.config.fontSize??i.config.fontSize,color:Ct(u.config.color??i.config.defaultTextColor),fontFamily:u.config.fontFamily??i.config.fontFamily,fontStyle:u.config.italic?"italic":void 0},T=m=>({fontWeight:m.config.bold||u.config.bold?i.config.fontWeightBold:i.config.fontWeight,fontSize:m.config.fontSize??u.config.fontSize??i.config.fontSize,color:Ct(m.config.color??u.config.color??s??i.config.defaultTextColor),fontFamily:m.config.fontFamily??u.config.fontFamily??i.config.fontFamily,fontStyle:m.config.italic??u.config.italic?"italic":void 0}),P=(m,y)=>m===`
56
+ `?l(me=>[...me,$]):typeof $=="object"&&"text"in $&&!N.has($)&&(N.add($),k($))}Ke&&!Ke.isSettled()?Ke.abort():(et.forEach(J=>J()),m.resolve())};return r.schedule(async E=>{let D=!1,J=!1;for(;!D;){let{done:$,value:me}=tt();if($){D=J=!0;break}let wn=new h;if(r.timelines.attachTimeline(wn),wn.registerSkipController(new L(()=>{dt(),D=!0,E.retry()})),wn.onSettled(()=>{dt()}),Ke=wn,Se.isPause(me)){let kn=Se.from(me),Pn=i.preference.getPreference(Q.Preferences.gameSpeed);if(kn.config.duration){let En=kn.config.duration/Pn;await Kn(En)}else{let En=i.preference.getPreference(Q.Preferences.autoForward),Dn=h.race([h.create(Zr=>{let _r=oe(es=>{es(),Zr.resolve()});At.push(()=>_r.cancel())}),...En?[h.delay(i.config.autoForwardDefaultPause/Pn)]:[]]);r.timelines.attachTimeline(Dn),await h.wait(Dn)}}else{if(me!==`
57
+ `&&N.has(me))continue;N.add(me),k(me);let{gameSpeed:kn,cps:Pn}=i.preference.getPreferences(),Dn=1e3/((typeof me=="object"&&"cps"in me&&me.cps!==void 0?me.cps:Pn)*kn);await Kn(Dn)}}J&&(et.forEach($=>$()),m.resolve())},0),{getToken:()=>m,interact:()=>{let E=!1;ye.forEach(D=>D(()=>E=!0)),!E&&V()},update:()=>{Ke&&Ke.abort()},forceSkip:()=>{V(!0)},timeline:y,onComplete:E=>(et.add(E),{cancel:()=>{et.delete(E)}})}}function g(m){let y=ur(m),N=[];for(let ye of y)Se.isPause(ye)||N.push(ye);return N}let u=n.config.action.sentence;if(!u)return null;let C={fontWeight:u.config.bold?i.config.fontWeightBold:i.config.fontWeight,fontSize:u.config.fontSize??i.config.fontSize,color:Ct(u.config.color??i.config.defaultTextColor),fontFamily:u.config.fontFamily??i.config.fontFamily,fontStyle:u.config.italic?"italic":void 0},T=m=>({fontWeight:m.config.bold||u.config.bold?i.config.fontWeightBold:i.config.fontWeight,fontSize:m.config.fontSize??u.config.fontSize??i.config.fontSize,color:Ct(m.config.color??u.config.color??s??i.config.defaultTextColor),fontFamily:m.config.fontFamily??u.config.fontFamily??i.config.fontFamily,fontStyle:m.config.italic??u.config.italic?"italic":void 0}),P=(m,y)=>m===`
58
58
  `?Lt.createElement("br",{key:y}):Lt.createElement(Rt.Span,{tag:`say.word.${y}`,key:y,style:{...T(m),...Fn(i.config.app.debug,{outline:"1px dashed red"})},className:lr("inline-block break-all",m.config.className)},m.config.ruby?Lt.createElement("ruby",{className:"align-bottom inline-block"},Lt.createElement("rt",{className:"block text-center"},m.config.ruby),m.text):m.text);return Lt.createElement("div",{...o,className:lr("whitespace-pre-wrap",e),style:{...t,...C}},c.map(P))}function dr(s){return Lt.createElement(pr,{...s,key:s.dialog?.config.action.id})}function ni(s){let e=lt();return Lt.createElement(pr,{...s,dialog:e,key:e.config.action.id})}var Hs=ni;import go,{useEffect as Us,useLayoutEffect as Ks,useMemo as gr,useRef as Fs,useState as Os}from"react";import fo from"react";var oi=fo.createContext(null);function mr(){let s=fo.useContext(oi);if(!s)throw new Error("useUIMenuContext must be used within a UIMenuContext");return s}var ii=fo.createContext(null);function fr(){let s=fo.useContext(ii);if(!s)throw new Error("useUIListContext must be used within a UIListContext");return s}function ho({className:s,style:e,bindKey:t}){let n=Fs(null),{register:o,unregister:i,getIndex:r}=fr(),[a,c]=Os(-1),{choose:l,evaluated:f,gameState:p}=mr(),d=a===-1?null:f[a],g=gr(()=>we.getCtx({gameState:p}),[p]),{hidden:u,disabled:C}=gr(()=>{if(!d)return{hidden:!1,disabled:!1};let m=d.config.hidden?.evaluate(g)?.value??!1,y=!m&&(d.config.disabled?.evaluate(g)?.value??!1);return{hidden:m,disabled:y}},[d,g]);Ks(()=>{if(!n.current)return;let m=n;o(m);let y=r(m);return c(y),n.current.dataset.index=y.toString(),()=>i(m)},[o,i,r]),Us(()=>{if(!t)return;let m=y=>{y.key.toLowerCase()===t.toLowerCase()&&!y.ctrlKey&&!y.metaKey&&(y.preventDefault(),y.stopPropagation(),T())};return window.addEventListener("keydown",m,!0),()=>{window.removeEventListener("keydown",m,!0)}},[t]);function T(){if(a===-1||!f[a]||u||C)return;let m=f[a];l({...m,evaluated:U.getText(m.words||[])})}let P=d&&!u;return go.createElement(go.Fragment,null,go.createElement("button",{className:s,style:{...e,display:P?e?.display??void 0:"none"},onClick:T,ref:n,disabled:C},P&&go.createElement(dr,{dialog:new Re({useTypeEffect:!1,action:{sentence:d.prompt,words:d.words,character:null},gameState:p,evaluatedWords:d.words})})))}import yo from"react";import{AnimatePresence as Ws}from"motion/react";function To({children:s,...e}){let t=Ws;return yo.createElement(yo.Fragment,null,yo.createElement("div",{...e},yo.createElement(t,null,s)))}import So from"react";function bo({...s}){let{config:e}=lt(),t=w();return So.createElement(So.Fragment,null,So.createElement("div",{...s},So.createElement("span",{style:{color:Ct(e.action.character?.config.color||t.config.defaultNametagColor)}},e.action.character?.state.name)))}import{useEffect as Vs}from"react";function zs(){let s=lt(),[e]=B(s.deps),t=U.getText(s.config.evaluatedWords);return Vs(()=>s.events.on(Re.Events.onFlush,()=>{e()}).cancel,[s]),{done:s.isEnded(),text:t,isNarrator:s.config.action.character===null||s.config.action.character.state.name===""}}import ri,{createContext as ta,useContext as na,useEffect as Tr,useRef as oa}from"react";import{useState as $s}from"react";function Ao(s){let[e]=$s(s);return e}import{AnimatePresence as Bs}from"motion/react";var vo=Bs;import hn,{createContext as Js,useContext as Ys,useEffect as Zs,useRef as _s}from"react";import{useEffect as mn,useLayoutEffect as js}from"react";function qs(){let s=Ye(),[e]=B();return mn(()=>s.onChange(e).cancel,[]),s.getPathname()}function Qs(){let{router:s,path:e}=gn(),[t]=B();return mn(()=>s.onChange(t).cancel,[]),s.extractParams(s.getCurrentPath(),e)}function Xs(){let s=Ye(),[e]=B();return mn(()=>s.onChange(e).cancel,[]),s.getQueryParams()}function Co(s,e){let t=Ye();js(()=>t.onUpdate(()=>s(t)).cancel,e),mn(()=>{s(t)},[])}function fn(){let s=Ye(),[e]=B();return mn(()=>s.onChange(e).cancel,[]),e}var hr=Js(null);function yn({children:s,path:e,consumedBy:t}){let o={router:Ye(),path:e,consumedBy:t};return hn.createElement(hr,{value:o},s)}function gn(){let s=Ys(hr);if(!s)throw new Error("useLayout must be used within a LayoutRouterProvider");if(s.path===null)throw new A(`Invalid useLayout call: Trying to access layout without a parent.
59
- This is likely caused by a nested Layout component or using Page inside a Page. `);return s}function ea({children:s,name:e,propagate:t}){let n=w(),[o]=B(),{path:i,router:r,consumedBy:a}=gn(),c=r.joinPath(i,e),l=Ao(()=>r.createToken(c+"@layout")),f=r.getCurrentPath(),p=_s(!1),d=u=>{p.current=u,o()},g=r.matchPath(f,c);if(fn(),Co(u=>{let C=u.matchPath(u.getCurrentPath(),c);if(p.current&&!C){if(!s){d(!1);return}u.registerUnmountingPath(l)}C&&u.isPathsUnmounting()&&u.unregisterUnmountingPath(l),C&&!p.current&&!u.isTransitioning()&&d(!0)},[g,s]),Zs(()=>{if(!g)return;let u=r.mount(c);return()=>{u.cancel()}},[c,r,g]),a)throw new A("[PageRouter] Layout is consumed by a different layout. This is likely caused by a nested layout inside a layout.");return hn.createElement(yn,{path:c},hn.createElement(vo,{mode:"wait",propagate:t??n.config.animationPropagate,onExitComplete:()=>{r.unregisterUnmountingPath(l),d(!1)}},g&&p.current&&s))}function yr({children:s}){return fn(),hn.createElement(yn,{path:St.rootPath},hn.createElement(lo,{"data-layout-path":St.rootPath,key:St.rootPath},s))}var si=ta(null);function ia(){return na(si)}function ra({children:s,name:e}){let[t]=B(),{path:n,router:o,consumedBy:i}=gn(),r=ia(),a=r?.name??e,c=a??n+"@default",l=a?o.joinPath(n,a):n,f=Ao(()=>o.createToken(l+"@page")),p=o.getCurrentPath(),d=!a,g=oa(!1),u=m=>{g.current=m,t()},C=d&&o.exactMatch(p,n)||o.exactMatch(p,l);if(i&&i!==c)throw new A("[PageRouter] Layout Context is consumed by a different page. This is likely caused by a nested page/layout inside a page.");fn(),Co(m=>{let y=d&&m.exactMatch(m.getCurrentPath(),n)||m.exactMatch(m.getCurrentPath(),l);if(g.current&&!y){if(!s){u(!1);return}m.registerUnmountingPath(f)}y&&m.isPathsUnmounting()&&m.unregisterUnmountingPath(f),y&&!g.current&&!m.isTransitioning()&&u(!0)},[C,s]),Tr(()=>{if(!C)return;let m=d?o.mountDefaultHandler(l):o.mount(l);return o.emitOnPageMount(),()=>{m.cancel()}},[l,C]),Tr(()=>()=>{o.unregisterUnmountingPath(f),u(!1)},[]);let T=ri.createElement(yn,{path:n,consumedBy:c},ri.createElement(vo,{mode:"wait",onExitComplete:()=>{o.unregisterUnmountingPath(f),u(!1)}},C&&g.current&&s));return(m=>r?ri.createElement(si,{value:{name:null}},m):m)(T)}import{useEffect as sa,useState as aa}from"react";function Tn(s){let e=w(),[t,n]=aa(e.keyMap.getKeyBinding(s)),o=i=>{e.keyMap.setKeyBinding(s,i),n(i)};return sa(()=>e.keyMap.onKeyBindingChange(s,n).cancel,[s,e.keyMap,n]),[t,o]}function ca(){return w().getLiveGame()}var Sn=(t=>(t.skipAction="skipAction",t.nextAction="nextAction",t))(Sn||{});function br({state:s}){let e=w(),t=Ye(),n=ai(null),o=ai(null),i=ai(!1),[r]=$e(Q.Preferences.skipDelay),[a]=$e(Q.Preferences.skipInterval),[c]=Tn("skipAction");return ua(()=>{if(!e.getLiveGame().gameState.playerCurrent){s.logger.warn("KeyEventAnnouncer","Failed to listen to playerElement events");return}if(!window){s.logger.warn("KeyEventAnnouncer","Failed to listen to window events");return}let f=()=>{o.current&&(clearTimeout(o.current),o.current=null),n.current&&(clearInterval(n.current),n.current=null),i.current=!1},p=g=>{if(e.keyMap.match("skipAction",g.key)&&e.preference.getPreference(Q.Preferences.skip)&&!i.current){s.logger.verbose("KeyEventAnnouncer","Skipping");let u=()=>{n.current=setInterval(()=>{s.events.emit(K.EventTypes["event:state.player.skip"],!1)},a)};f(),s.events.emit(K.EventTypes["event:state.player.skip"],!1),i.current=!0,r===0?u():o.current=setTimeout(u,r)}},d=g=>{e.keyMap.match("skipAction",g.key)&&f()};if(e.config.useWindowListener){let g=e.getLiveGame().onWindowEvent("keydown",p).cancel,u=e.getLiveGame().onWindowEvent("keyup",d).cancel;return()=>{f(),g(),u()}}else{let g=e.getLiveGame().onPlayerEvent("keydown",p).cancel,u=e.getLiveGame().onPlayerEvent("keyup",d).cancel;return()=>{f(),g(),u()}}},[t,r,a,c]),Sr.createElement(Sr.Fragment,null)}import{useEffect as bn}from"react";function ci({gameState:s}){let e=s.audioManager,[t]=$e("voiceVolume"),[n]=$e("bgmVolume"),[o]=$e("soundVolume"),[i,r]=$e("globalVolume");return bn(()=>{r(e.getGlobalVolume())},[]),bn(()=>{e.setGroupVolume("voice",t)},[t]),bn(()=>{e.setGroupVolume("bgm",n)},[n]),bn(()=>{e.setGroupVolume("sound",o)},[o]),bn(()=>{e.setGlobalVolume(i)},[i]),null}import{useEffect as pa}from"react";function li({ref:s}){let{ratio:e}=Z();return pa(()=>{let t=s.current;if(!t)return;let n=new ResizeObserver(()=>{e.requestUpdate()});return n.observe(t),()=>{n.disconnect()}},[s.current]),null}import{useEffect as wo,useRef as fa}from"react";import ui,{createContext as da,useContext as ma,useState as Ar}from"react";var It=class It{constructor(){this.preloaded=[];this.events=new F}add(e){let t=this.getSrc(e);return t&&this.has(t)?this:(this.preloaded.push(e),this.events.emit(It.EventTypes["event:preloaded.add"],e),this.events.emit(It.EventTypes["event:preloaded.change"]),this)}get(e){return this.preloaded.find(t=>this.getSrc(t)===e)}has(e){return Array.isArray(e)?e.every(t=>this.has(t)):this.preloaded.some(t=>this.getSrc(t)===e)}remove(e){if(Array.isArray(e)){let n=e.map(o=>this.getSrc(o));return this.preloaded=this.preloaded.filter(o=>!n.includes(this.getSrc(o))),this}let t=this.getSrc(e);return this.preloaded=this.preloaded.filter(n=>this.getSrc(n)!==t),this.events.emit(It.EventTypes["event:preloaded.remove"],e),this.events.emit(It.EventTypes["event:preloaded.change"]),this}clear(){return this.preloaded=[],this}getSrc(e){return ge.getSrc(e)}};It.EventTypes={"event:preloaded.add":"event:preloaded.add","event:preloaded.remove":"event:preloaded.remove","event:preloaded.change":"event:preloaded.change","event:preloaded.mount":"event:preloaded.mount","event:preloaded.ready":"event:preloaded.ready","event:preloaded.unmount":"event:preloaded.unmount"};var Le=It;var xo=class s{constructor(e){this.game=e;this.src=new Map;this.preloadTasks=new Map;this.game.addSideEffect(()=>{this.abortAll(),this.src.clear()})}static getImage(e,t,n){return Hi(e,{...n,signal:t})}has(e){return this.src.has(e)}add(e,t){return this.src.set(e,t),this}remove(e){return this.src.delete(e),this}get(e){return this.src.get(e)}clear(){return this.src.clear(),this}size(){return this.src.size}isPreloading(e){return this.preloadTasks.has(e)}preload(e,t){if(this.src.has(t)||this.preloadTasks.has(t)){let p={abort:()=>{},onFinished:()=>p,onErrored:()=>p};return p}let n=t,o={};this.game.hooks.rawTrigger("preloadImage",()=>[n,(p,d)=>{n=p,o={...o,...d}}]);let i=new AbortController,r=i.signal,a=[],l={promise:s.getImage(n,r,o).then(p=>{this.preloadTasks.delete(t),p&&this.add(t,p)}).catch(p=>{e.logger.error("ImageCacheManager",`Failed to preload image: ${t}`,`Reason: ${p}`),a.forEach(d=>d(p))}),controller:i};this.preloadTasks.set(t,l);let f={abort:()=>{i.abort(),this.preloadTasks.delete(t)},onFinished:p=>(l.promise.then(p),f),onErrored:p=>(a.push(p),f)};return f}abortAll(){this.preloadTasks.forEach(e=>{e.controller.abort()}),this.preloadTasks.clear()}abort(e){let t=this.preloadTasks.get(e);t&&(t.controller.abort(),this.preloadTasks.delete(e))}preloadedSrc(){return Array.from(this.src.values())}filter(e){for(let t of this.src.keys())e.includes(t)||this.src.delete(t);return this}};var pi=da(null);function vr({children:s}){let e=w(),[t]=Ar(()=>new Le),[n]=Ar(()=>new xo(e));return ui.createElement(ui.Fragment,null,ui.createElement(pi,{value:{preloaded:t,cacheManager:n}},s))}function $t(){if(!pi)throw new Error("usePreloaded must be used within a PreloadedProvider");return ma(pi)}function Cr({state:s}){let{preloaded:e,cacheManager:t}=$t(),n=w(),o=fa(new Set),[i]=B(),r="Preload",a=s.getLastScene()||s.getPreloadingScene(),c=n.getLiveGame().stackModel?.getTopSync()?.node?.action||null,l=n.getLiveGame().story;function f(){s.logger.debug(r,"Preload unmounted"),e.events.emit(Le.EventTypes["event:preloaded.unmount"])}return wo(()=>s.events.on(K.EventTypes["event:state:flushPreloadedScenes"],()=>{i()}).cancel,[]),wo(()=>{if(typeof fetch>"u")return e.events.emit(Le.EventTypes["event:preloaded.ready"]),s.logger.warn(r,"Fetch is not supported in this environment, skipping preload"),f;if(!n.config.preloadAllImages)return e.events.emit(Le.EventTypes["event:preloaded.ready"]),s.logger.debug(r,"Preload all images is disabled, skipping preload"),f;if(n.config.forceClearCache&&(t.clear(),s.logger.weakWarn(r,"Cache cleared")),!l||!a)return s.logger.weakWarn(r,"Story/Scene not found, skipping preload"),f;let p=performance.now(),d=ge.catSrc([...a.srcManager?.src||[],...a.srcManager?.getFutureSrc()||[]]),g=new Yt(n.config.preloadConcurrency,n.config.preloadDelay),u=[],C=s.logger.group(r,!0),T=[];s.logger.debug(r,"preloading:",d,a);for(let P of d.image){let m=ge.getSrc(P);if(m){if(u.push(m),t.has(m)||t.isPreloading(m)||T.includes(m)){s.logger.debug(r,`Image already loaded (${d.image.indexOf(P)+1}/${d.image.length})`,m),T.push(m);continue}T.push(m),g.addTask(()=>new Promise(y=>{t.preload(s,m).onFinished(()=>{s.logger.debug(r,`Image loaded (${d.image.indexOf(P)+1}/${d.image.length})`,m),y()}).onErrored(()=>{s.logger.weakError(r,`Failed to preload image (${d.image.indexOf(P)+1}/${d.image.length})`,m),y()})}))}}return C.end(),g.start().then(()=>{s.logger.info(r,"Image preload",`loaded ${t.size()} images in ${performance.now()-p}ms`),n.config.waitForPreload&&e.events.emit(Le.EventTypes["event:preloaded.ready"]),t.filter(u)}),n.config.waitForPreload||e.events.emit(Le.EventTypes["event:preloaded.ready"]),e.events.emit(Le.EventTypes["event:preloaded.mount"]),f},[a,l]),wo(()=>{o.current.clear()},[a]),wo(()=>{if(typeof fetch>"u"||n.config.preloadAllImages)return;if(!l){s.logger.weakWarn(r,"Story not found, skipping preload");return}let p=performance.now(),d=n.getLiveGame().getAllPredictableActions(l,c,n.config.maxPreloadActions).map(m=>ge.getPreloadableSrc(l,m)).filter(function(m){return m!==null});d.filter(function(m){return m?.activeType==="scene"}).forEach(m=>{o.current.has(m)||o.current.add(m)});let u=ge.catSrc([...o.current,...d]),C=new Yt(n.config.preloadConcurrency,n.config.preloadDelay),T=[],P=s.logger.group(r);s.logger.debug(r,"preloading:",u);for(let m of u.image){let y=ge.getSrc(m);if(y){if(T.push(y),t.has(y)||t.isPreloading(y)){s.logger.debug(r,`Image already loaded (${u.image.indexOf(m)+1}/${u.image.length})`,y);continue}C.addTask(()=>new Promise(G=>{t.preload(s,y).onFinished(()=>{s.logger.debug(r,`Image loaded (${u.image.indexOf(m)+1}/${u.image.length})`,y),G()}).onErrored(()=>{s.logger.weakError(r,`Failed to preload image (${u.image.indexOf(m)+1}/${u.image.length})`,y),G()})}))}}P.end(),C.start().then(()=>{s.logger.info(r,"Image preload (quick reload)",`loaded ${t.size()} images in ${performance.now()-p}ms`),t.filter(T)})},[c,l]),null}import ga from"clsx";import _e,{useCallback as di,useMemo as ha,useRef as ya}from"react";function mi({prompt:s,choices:e,afterChoose:t,state:n,words:o}){let i=w(),r=ya([]),a=di(g=>(r.current.push(g),r.current.indexOf(g)),[]),c=di(g=>{let u=r.current.indexOf(g);u!==-1&&r.current.splice(u,1)},[]),l=di(g=>r.current.indexOf(g),[]),f=i.config.menu,p=ha(()=>e.map(g=>({...g,words:g.prompt.evaluate(we.getCtx({gameState:n}))})),[]);function d(g){t(g)}return _e.createElement(_e.Fragment,null,_e.createElement(oi,{value:{evaluated:p,choose:d,gameState:n}},_e.createElement(ii,{value:{register:a,unregister:c,getIndex:l}},_e.createElement(Ze,{className:"absolute"},s&&_e.createElement(dn,{gameState:n,action:{sentence:s,words:o,character:null},useTypeEffect:!1})),_e.createElement(Rt.Div,{color:"green",border:"dashed",className:ga("absolute"),style:{width:`${i.config.width}px`,height:`${i.config.height}px`}},_e.createElement(f,{items:p.map((g,u)=>u)})))))}function xr({items:s}){return _e.createElement(uo,{className:"absolute flex flex-col items-center justify-center min-w-full w-full h-full"},s.map(e=>_e.createElement(ho,{key:e,className:"bg-white text-black p-2 mt-2 w-1/2"})))}import Ro from"react";import ko from"react";import fi,{useEffect as wr,useLayoutEffect as kr,useRef as Pr,useState as gi}from"react";function Bt({element:s,state:e,skipTransform:t,skipTransition:n,overwriteDefinition:o,onTransform:i,onTransition:r,transitionsProps:a=[],propOverwrite:c}){let[l,f]=gi(null),[p,d]=gi(null),g=fi.useRef(null),[u]=gi(()=>new Mn("displayable.refGroup")),C=Pr(u.next()),T=Pr(tt()),m=w().getLiveGame().getGameState(),y=typeof a=="function"?a(l):a,[G]=B([p,l,T]);wr(()=>m.events.depends([m.events.on(K.EventTypes["event:state.player.skip"],dt)]).cancel,[p,l,T]),kr(()=>{if(ye(),!l)return;if(T.current.some(([_])=>!_.current))throw new A("Displayable: Trying to access transition groups before they are mounted");let{controller:k,task:V}=l;return k.onUpdate(_=>{T.current.forEach(([Ie],je)=>{let E=V.resolve[je],D=typeof E=="function"?E:E.resolver;if(!D)throw new A(`Displayable: Trying to resolve element props but found no resolver. (reading: transitionTask.task.resolve[${je}])`);let J=D(..._),$=R(y[je]||y[y.length-1]||{},J);Gt(Ie,c?c($):$)})}).cancel},[l]),wr(()=>{if(!g.current)throw new Error(`Scope not ready. Using element: ${s.constructor.name}`)},[]),kr(()=>{let k=e.toStyle(m,o);Object.assign(g.current.style,k),m.logger.debug("Displayable","Initial style applied",g.current,k)},[]);function ye(){let k=typeof a=="function"?a(l):a;if(!T.current||!T.current.length)throw new A("Displayable: Transition group refs are not initialized correctly");if(T.current.some(([V])=>!V.current))throw new A("Displayable: Trying to access transition groups before they are mounted");T.current.forEach(([V],x)=>{if(!V.current)throw new A("Displayable: Trying to assign properties to unmounted element");Gt(V,k[x]||k[k.length-1]||{})})}function et(k){m.logger.debug("Displayable","Transform applied",e.toStyle(m,o),g.current),G(),i?.(k)}function Gt(k,V){if(!k.current)throw new A("Displayable: Trying to assign properties to unmounted element");let x=k.current,_={},Ie={};Object.keys(V).forEach(E=>{let D=E;D==="style"&&V.style?Object.assign(_,V.style):V[D]!==void 0&&D!=="key"&&(Ie[D]=V[D])}),Object.keys(_).length>0&&Object.assign(x.style,_);let je=c?c(Ie):Ie;for(let[E,D]of Object.entries(je))x.getAttribute(E)!==D&&x.setAttribute(E,D)}function Ke(k,V){p&&(p.abort(),d(null));let x=k.animate(e,{gameState:m,ref:g,overwrites:o}),_=new se(x);return m.timelines.attachTimeline(_),x.onSkipControllerRegister(Ie=>{Ie.onAbort(()=>{_.abort(),d(null)})}),d(x),x.then(()=>{d(null),et(k),V()}),_}function At(k,V){l&&l.controller.complete();let x=k.createTask(m),_=k.requestAnimations(x.animations),Ie=new h().registerSkipController(new L(_.cancel)),je=new se(Ie);Ie.skipController.onAbort(()=>{_.cancel()}),_.onCanceled(()=>{je.abort(),f(null),m.logger.debug("Displayable","Transition cancelled",k)}),m.timelines.attachTimeline(je),f({task:x,controller:_,transition:k,resolve:V});let E;if(T.current=x.resolve.map(J=>{let $=fi.createRef(),me=typeof J=="function"?void 0:J.key;if(!me)return[$,u.next()];if(me==="target")return E=u.next(),[$,E];if(me==="current")return[$,C.current];throw new A("Displayable: Invalid key type")}),!E)throw new A("Displayable: No target key found");C.current=E;let D=T.current.map(([J])=>{let $=J.current;return $?.waitForLoad?$.waitForLoad():Promise.resolve()});return Promise.all(D).then(()=>{_.start(),_.onComplete(()=>{oe(),f(null),r?.(k),V(),Ie.resolve()})}),je}function Fe(k){return m.logger.debug("initDisplayable",s),Ke(O.immediate(e.get()),k)}function dt(){t&&p&&(p.abort(),d(null),m.logger.debug("transform skipped")),n&&l&&(l.controller.complete(),m.logger.debug("transition skipped"))}function tt(){return[[fi.createRef(),C.current]]}function oe(){T.current.forEach(([k])=>{k.current=null}),T.current=tt()}return{transformRef:g,transitionRefs:T.current,isTransforming:!!p,transitionTask:l,initDisplayable:Fe,applyTransform:Ke,applyTransition:At,updateStyleSync:ye,deps:[p,l,T]}}import{useEffect as Ta}from"react";function bt(s,e,t=[]){let o=w().getLiveGame().getGameState();return Ta(()=>{let i=typeof e=="function"?e():e;return o.mountState(s,i).unMount},[...t]),[]}function hi({state:s,text:e}){let{ratio:t}=Z(),[n]=B(),{transformRef:o,transitionRefs:i,initDisplayable:r,applyTransform:a,applyTransition:c,updateStyleSync:l,deps:f,isTransforming:p}=Bt({element:e,state:e.transformState,skipTransform:s.game.config.allowSkipTextTransform,skipTransition:s.game.config.allowSkipTextTransition,overwriteDefinition:{overwrite:d=>({width:"fit-content",transform:O.propToCSSTransform(s,d,{translate:[e.config.alignX==="left"?"0%":e.config.alignX==="right"?"-100%":void 0,e.config.alignY==="top"?"100%":e.config.alignY==="bottom"?"0%":void 0]})})},transitionsProps:[{style:{width:"fit-content",whiteSpace:"nowrap",transform:`scale(${t.state.scale})`,transformOrigin:`${e.config.alignX} ${e.config.alignY}`,fontSize:`${e.state.fontSize}px`}}]});return bt(e,{initDisplayable:r,applyTransform:a,applyTransition:c,flush:n,updateStyleSync:l},[...f]),ko.createElement(Rt.Div,{"data-element-type":"text"},ko.createElement(Rt.mDiv,{tag:"text.container",color:"green",border:"dashed",layout:p,ref:o,className:"absolute"},i.map(([d,g])=>ko.createElement("span",{key:g,ref:d,className:e.config.className},ko.createElement("span",null,e.state.text)))))}import jt,{useRef as Rr,useState as Lr}from"react";import Po,{useEffect as yi,useRef as Eo,forwardRef as Sa}from"react";var Er=Sa(({onSizeChanged:s,onLoad:e,autoFit:t=!1},n)=>{let o=Eo(null),{ratio:i}=Z(),[r,a]=Po.useState(()=>i.state.width),[c,l]=Po.useState(()=>i.state.height),f=w(),p=Eo(!1),d=Eo(null),g=Eo(null);Po.useImperativeHandle(n,()=>o.current,[]),yi(()=>{o.current&&Object.defineProperties(o.current,{isLoaded:{value:()=>p.current,configurable:!0},waitForLoad:{value:()=>p.current?Promise.resolve():(d.current||(d.current=new Promise(T=>{g.current=T})),d.current),configurable:!0}})},[]),yi(()=>(u(),i.onUpdate(u)),[s]),yi(()=>{let T=new MutationObserver(P=>{P.forEach(m=>{m.type==="attributes"&&m.attributeName==="src"&&o.current&&u()})});return o.current&&T.observe(o.current,{attributes:!0}),()=>{T.disconnect()}},[s]);function u(){if(o.current&&o.current.naturalWidth)if(o.current.naturalWidth*o.current.naturalHeight===1){let T=i.state.width,P=i.state.height,m=`${T} / ${P}`;a(T),l(P),o.current.style.aspectRatio=m,s&&s(T,P)}else{let T=t?f.config.width/o.current.naturalWidth:1,P=o.current.naturalWidth*i.state.scale*T,m=o.current.naturalHeight*i.state.scale*T;a(P),l(m),o.current.style.aspectRatio="auto",s&&s(P,m)}}function C(){u(),p.current=!0,g.current&&(g.current(),g.current=null,d.current=null),e&&e()}return Po.createElement("img",{ref:o,onLoad:C,width:r,height:c,alt:""})});Er.displayName="AspectScaleImage";var Dr=Er;import Ir from"clsx";import{motion as ba}from"motion/react";function Do({image:s,state:e}){let[t]=Lr(()=>new F),[n,o]=Lr([]),{cacheManager:i}=$t(),r=Rr([]),a=Rr(null),{transformRef:c,transitionRefs:l,isTransforming:f,initDisplayable:p,applyTransition:d,applyTransform:g,updateStyleSync:u,deps:C}=Bt({element:s,state:s.transformState,skipTransform:e.game.config.allowSkipImageTransform,skipTransition:e.game.config.allowSkipImageTransition,transitionsProps:m=>{let y=m?m.transition._getCurrentSrc():s.state.currentSrc;return[{style:{willChange:"filter",position:"absolute",transformOrigin:"center",backgroundColor:b.isColor(y)?b.colorToString(y):void 0,transform:"none",top:"auto",left:"auto",right:"auto",bottom:"auto",filter:`brightness(${1-s.state.darkness})`},src:b.isImageSrc(y)?b.srcToURL(y):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:m=>m.src?(!b.isDataURI(m.src)&&!i.has(m.src)&&!i.isPreloading(m.src)&&!r.current.includes(m.src)&&(e.game.getLiveGame().getGameState()?.logger.warn("Image",`Image not preloaded: "${m.src}".
59
+ This is likely caused by a nested Layout component or using Page inside a Page. `);return s}function ea({children:s,name:e,propagate:t}){let n=w(),[o]=B(),{path:i,router:r,consumedBy:a}=gn(),c=r.joinPath(i,e),l=Ao(()=>r.createToken(c+"@layout")),f=r.getCurrentPath(),p=_s(!1),d=u=>{p.current=u,o()},g=r.matchPath(f,c);if(fn(),Co(u=>{let C=u.matchPath(u.getCurrentPath(),c);if(p.current&&!C){if(!s){d(!1);return}u.registerUnmountingPath(l)}C&&u.isPathsUnmounting()&&u.unregisterUnmountingPath(l),C&&!p.current&&!u.isTransitioning()&&d(!0)},[g,s]),Zs(()=>{if(!g)return;let u=r.mount(c);return()=>{u.cancel()}},[c,r,g]),a)throw new A("[PageRouter] Layout is consumed by a different layout. This is likely caused by a nested layout inside a layout.");return hn.createElement(yn,{path:c},hn.createElement(vo,{mode:"wait",propagate:t??n.config.animationPropagate,onExitComplete:()=>{r.unregisterUnmountingPath(l),d(!1)}},g&&p.current&&s))}function yr({children:s}){return fn(),hn.createElement(yn,{path:St.rootPath},hn.createElement(lo,{"data-layout-path":St.rootPath,key:St.rootPath},s))}var si=ta(null);function ia(){return na(si)}function ra({children:s,name:e}){let[t]=B(),{path:n,router:o,consumedBy:i}=gn(),r=ia(),a=r?.name??e,c=a??n+"@default",l=a?o.joinPath(n,a):n,f=Ao(()=>o.createToken(l+"@page")),p=o.getCurrentPath(),d=!a,g=oa(!1),u=m=>{g.current=m,t()},C=d&&o.exactMatch(p,n)||o.exactMatch(p,l);if(i&&i!==c)throw new A("[PageRouter] Layout Context is consumed by a different page. This is likely caused by a nested page/layout inside a page.");fn(),Co(m=>{let y=d&&m.exactMatch(m.getCurrentPath(),n)||m.exactMatch(m.getCurrentPath(),l);if(g.current&&!y){if(!s){u(!1);return}m.registerUnmountingPath(f)}y&&m.isPathsUnmounting()&&m.unregisterUnmountingPath(f),y&&!g.current&&!m.isTransitioning()&&u(!0)},[C,s]),Tr(()=>{if(!C)return;let m=d?o.mountDefaultHandler(l):o.mount(l);return o.emitOnPageMount(),()=>{m.cancel()}},[l,C]),Tr(()=>()=>{o.unregisterUnmountingPath(f),u(!1)},[]);let T=ri.createElement(yn,{path:n,consumedBy:c},ri.createElement(vo,{mode:"wait",onExitComplete:()=>{o.unregisterUnmountingPath(f),u(!1)}},C&&g.current&&s));return(m=>r?ri.createElement(si,{value:{name:null}},m):m)(T)}import{useEffect as sa,useState as aa}from"react";function Tn(s){let e=w(),[t,n]=aa(e.keyMap.getKeyBinding(s)),o=i=>{e.keyMap.setKeyBinding(s,i),n(i)};return sa(()=>e.keyMap.onKeyBindingChange(s,n).cancel,[s,e.keyMap,n]),[t,o]}function ca(){return w().getLiveGame()}var Sn=(t=>(t.skipAction="skipAction",t.nextAction="nextAction",t))(Sn||{});function br({state:s}){let e=w(),t=Ye(),n=ai(null),o=ai(null),i=ai(!1),[r]=$e(Q.Preferences.skipDelay),[a]=$e(Q.Preferences.skipInterval),[c]=Tn("skipAction");return ua(()=>{if(!e.getLiveGame().gameState.playerCurrent){s.logger.warn("KeyEventAnnouncer","Failed to listen to playerElement events");return}if(!window){s.logger.warn("KeyEventAnnouncer","Failed to listen to window events");return}let f=()=>{o.current&&(clearTimeout(o.current),o.current=null),n.current&&(clearInterval(n.current),n.current=null),i.current=!1},p=g=>{if(e.keyMap.match("skipAction",g.key)&&e.preference.getPreference(Q.Preferences.skip)&&!i.current){s.logger.verbose("KeyEventAnnouncer","Skipping");let u=()=>{n.current=setInterval(()=>{s.events.emit(K.EventTypes["event:state.player.skip"],!1)},a)};f(),s.events.emit(K.EventTypes["event:state.player.skip"],!1),i.current=!0,r===0?u():o.current=setTimeout(u,r)}},d=g=>{e.keyMap.match("skipAction",g.key)&&f()};if(e.config.useWindowListener){let g=e.getLiveGame().onWindowEvent("keydown",p).cancel,u=e.getLiveGame().onWindowEvent("keyup",d).cancel;return()=>{f(),g(),u()}}else{let g=e.getLiveGame().onPlayerEvent("keydown",p).cancel,u=e.getLiveGame().onPlayerEvent("keyup",d).cancel;return()=>{f(),g(),u()}}},[t,r,a,c]),Sr.createElement(Sr.Fragment,null)}import{useEffect as bn}from"react";function ci({gameState:s}){let e=s.audioManager,[t]=$e("voiceVolume"),[n]=$e("bgmVolume"),[o]=$e("soundVolume"),[i,r]=$e("globalVolume");return bn(()=>{r(e.getGlobalVolume())},[]),bn(()=>{e.setGroupVolume("voice",t)},[t]),bn(()=>{e.setGroupVolume("bgm",n)},[n]),bn(()=>{e.setGroupVolume("sound",o)},[o]),bn(()=>{e.setGlobalVolume(i)},[i]),null}import{useEffect as pa}from"react";function li({ref:s}){let{ratio:e}=Z();return pa(()=>{let t=s.current;if(!t)return;let n=new ResizeObserver(()=>{e.requestUpdate()});return n.observe(t),()=>{n.disconnect()}},[s.current]),null}import{useEffect as wo,useRef as fa}from"react";import ui,{createContext as da,useContext as ma,useState as Ar}from"react";var It=class It{constructor(){this.preloaded=[];this.events=new F}add(e){let t=this.getSrc(e);return t&&this.has(t)?this:(this.preloaded.push(e),this.events.emit(It.EventTypes["event:preloaded.add"],e),this.events.emit(It.EventTypes["event:preloaded.change"]),this)}get(e){return this.preloaded.find(t=>this.getSrc(t)===e)}has(e){return Array.isArray(e)?e.every(t=>this.has(t)):this.preloaded.some(t=>this.getSrc(t)===e)}remove(e){if(Array.isArray(e)){let n=e.map(o=>this.getSrc(o));return this.preloaded=this.preloaded.filter(o=>!n.includes(this.getSrc(o))),this}let t=this.getSrc(e);return this.preloaded=this.preloaded.filter(n=>this.getSrc(n)!==t),this.events.emit(It.EventTypes["event:preloaded.remove"],e),this.events.emit(It.EventTypes["event:preloaded.change"]),this}clear(){return this.preloaded=[],this}getSrc(e){return ge.getSrc(e)}};It.EventTypes={"event:preloaded.add":"event:preloaded.add","event:preloaded.remove":"event:preloaded.remove","event:preloaded.change":"event:preloaded.change","event:preloaded.mount":"event:preloaded.mount","event:preloaded.ready":"event:preloaded.ready","event:preloaded.unmount":"event:preloaded.unmount"};var Le=It;var xo=class s{constructor(e){this.game=e;this.src=new Map;this.preloadTasks=new Map;this.game.addSideEffect(()=>{this.abortAll(),this.src.clear()})}static getImage(e,t,n){return Hi(e,{...n,signal:t})}has(e){return this.src.has(e)}add(e,t){return this.src.set(e,t),this}remove(e){return this.src.delete(e),this}get(e){return this.src.get(e)}clear(){return this.src.clear(),this}size(){return this.src.size}isPreloading(e){return this.preloadTasks.has(e)}preload(e,t){if(this.src.has(t)||this.preloadTasks.has(t)){let p={abort:()=>{},onFinished:()=>p,onErrored:()=>p};return p}let n=t,o={};this.game.hooks.rawTrigger("preloadImage",()=>[n,(p,d)=>{n=p,o={...o,...d}}]);let i=new AbortController,r=i.signal,a=[],l={promise:s.getImage(n,r,o).then(p=>{this.preloadTasks.delete(t),p&&this.add(t,p)}).catch(p=>{e.logger.error("ImageCacheManager",`Failed to preload image: ${t}`,`Reason: ${p}`),a.forEach(d=>d(p))}),controller:i};this.preloadTasks.set(t,l);let f={abort:()=>{i.abort(),this.preloadTasks.delete(t)},onFinished:p=>(l.promise.then(p),f),onErrored:p=>(a.push(p),f)};return f}abortAll(){this.preloadTasks.forEach(e=>{e.controller.abort()}),this.preloadTasks.clear()}abort(e){let t=this.preloadTasks.get(e);t&&(t.controller.abort(),this.preloadTasks.delete(e))}preloadedSrc(){return Array.from(this.src.values())}filter(e){for(let t of this.src.keys())e.includes(t)||this.src.delete(t);return this}};var pi=da(null);function vr({children:s}){let e=w(),[t]=Ar(()=>new Le),[n]=Ar(()=>new xo(e));return ui.createElement(ui.Fragment,null,ui.createElement(pi,{value:{preloaded:t,cacheManager:n}},s))}function $t(){if(!pi)throw new Error("usePreloaded must be used within a PreloadedProvider");return ma(pi)}function Cr({state:s}){let{preloaded:e,cacheManager:t}=$t(),n=w(),o=fa(new Set),[i]=B(),r="Preload",a=s.getLastScene()||s.getPreloadingScene(),c=n.getLiveGame().stackModel?.getTopSync()?.node?.action||null,l=n.getLiveGame().story;function f(){s.logger.debug(r,"Preload unmounted"),e.events.emit(Le.EventTypes["event:preloaded.unmount"])}return wo(()=>s.events.on(K.EventTypes["event:state:flushPreloadedScenes"],()=>{i()}).cancel,[]),wo(()=>{if(typeof fetch>"u")return e.events.emit(Le.EventTypes["event:preloaded.ready"]),s.logger.warn(r,"Fetch is not supported in this environment, skipping preload"),f;if(!n.config.preloadAllImages)return e.events.emit(Le.EventTypes["event:preloaded.ready"]),s.logger.debug(r,"Preload all images is disabled, skipping preload"),f;if(n.config.forceClearCache&&(t.clear(),s.logger.weakWarn(r,"Cache cleared")),!l||!a)return s.logger.weakWarn(r,"Story/Scene not found, skipping preload"),f;let p=performance.now(),d=ge.catSrc([...a.srcManager?.src||[],...a.srcManager?.getFutureSrc()||[]]),g=new Yt(n.config.preloadConcurrency,n.config.preloadDelay),u=[],C=s.logger.group(r,!0),T=[];s.logger.debug(r,"preloading:",d,a);for(let P of d.image){let m=ge.getSrc(P);if(m){if(u.push(m),t.has(m)||t.isPreloading(m)||T.includes(m)){s.logger.debug(r,`Image already loaded (${d.image.indexOf(P)+1}/${d.image.length})`,m),T.push(m);continue}T.push(m),g.addTask(()=>new Promise(y=>{t.preload(s,m).onFinished(()=>{s.logger.debug(r,`Image loaded (${d.image.indexOf(P)+1}/${d.image.length})`,m),y()}).onErrored(()=>{s.logger.weakError(r,`Failed to preload image (${d.image.indexOf(P)+1}/${d.image.length})`,m),y()})}))}}return C.end(),g.start().then(()=>{s.logger.info(r,"Image preload",`loaded ${t.size()} images in ${performance.now()-p}ms`),n.config.waitForPreload&&e.events.emit(Le.EventTypes["event:preloaded.ready"]),t.filter(u)}),n.config.waitForPreload||e.events.emit(Le.EventTypes["event:preloaded.ready"]),e.events.emit(Le.EventTypes["event:preloaded.mount"]),f},[a,l]),wo(()=>{o.current.clear()},[a]),wo(()=>{if(typeof fetch>"u"||n.config.preloadAllImages)return;if(!l){s.logger.weakWarn(r,"Story not found, skipping preload");return}let p=performance.now(),d=n.getLiveGame().getAllPredictableActions(l,c,n.config.maxPreloadActions).map(m=>ge.getPreloadableSrc(l,m)).filter(function(m){return m!==null});d.filter(function(m){return m?.activeType==="scene"}).forEach(m=>{o.current.has(m)||o.current.add(m)});let u=ge.catSrc([...o.current,...d]),C=new Yt(n.config.preloadConcurrency,n.config.preloadDelay),T=[],P=s.logger.group(r);s.logger.debug(r,"preloading:",u);for(let m of u.image){let y=ge.getSrc(m);if(y){if(T.push(y),t.has(y)||t.isPreloading(y)){s.logger.debug(r,`Image already loaded (${u.image.indexOf(m)+1}/${u.image.length})`,y);continue}C.addTask(()=>new Promise(N=>{t.preload(s,y).onFinished(()=>{s.logger.debug(r,`Image loaded (${u.image.indexOf(m)+1}/${u.image.length})`,y),N()}).onErrored(()=>{s.logger.weakError(r,`Failed to preload image (${u.image.indexOf(m)+1}/${u.image.length})`,y),N()})}))}}P.end(),C.start().then(()=>{s.logger.info(r,"Image preload (quick reload)",`loaded ${t.size()} images in ${performance.now()-p}ms`),t.filter(T)})},[c,l]),null}import ga from"clsx";import _e,{useCallback as di,useMemo as ha,useRef as ya}from"react";function mi({prompt:s,choices:e,afterChoose:t,state:n,words:o}){let i=w(),r=ya([]),a=di(g=>(r.current.push(g),r.current.indexOf(g)),[]),c=di(g=>{let u=r.current.indexOf(g);u!==-1&&r.current.splice(u,1)},[]),l=di(g=>r.current.indexOf(g),[]),f=i.config.menu,p=ha(()=>e.map(g=>({...g,words:g.prompt.evaluate(we.getCtx({gameState:n}))})),[]);function d(g){t(g)}return _e.createElement(_e.Fragment,null,_e.createElement(oi,{value:{evaluated:p,choose:d,gameState:n}},_e.createElement(ii,{value:{register:a,unregister:c,getIndex:l}},_e.createElement(Ze,{className:"absolute"},s&&_e.createElement(dn,{gameState:n,action:{sentence:s,words:o,character:null},useTypeEffect:!1})),_e.createElement(Rt.Div,{color:"green",border:"dashed",className:ga("absolute"),style:{width:`${i.config.width}px`,height:`${i.config.height}px`}},_e.createElement(f,{items:p.map((g,u)=>u)})))))}function xr({items:s}){return _e.createElement(uo,{className:"absolute flex flex-col items-center justify-center min-w-full w-full h-full"},s.map(e=>_e.createElement(ho,{key:e,className:"bg-white text-black p-2 mt-2 w-1/2"})))}import Ro from"react";import ko from"react";import fi,{useEffect as wr,useLayoutEffect as kr,useRef as Pr,useState as gi}from"react";function Bt({element:s,state:e,skipTransform:t,skipTransition:n,overwriteDefinition:o,onTransform:i,onTransition:r,transitionsProps:a=[],propOverwrite:c}){let[l,f]=gi(null),[p,d]=gi(null),g=fi.useRef(null),[u]=gi(()=>new Mn("displayable.refGroup")),C=Pr(u.next()),T=Pr(tt()),m=w().getLiveGame().getGameState(),y=typeof a=="function"?a(l):a,[N]=B([p,l,T]);wr(()=>m.events.depends([m.events.on(K.EventTypes["event:state.player.skip"],dt)]).cancel,[p,l,T]),kr(()=>{if(ye(),!l)return;if(T.current.some(([_])=>!_.current))throw new A("Displayable: Trying to access transition groups before they are mounted");let{controller:k,task:V}=l;return k.onUpdate(_=>{T.current.forEach(([Ie],je)=>{let E=V.resolve[je],D=typeof E=="function"?E:E.resolver;if(!D)throw new A(`Displayable: Trying to resolve element props but found no resolver. (reading: transitionTask.task.resolve[${je}])`);let J=D(..._),$=R(y[je]||y[y.length-1]||{},J);Gt(Ie,c?c($):$)})}).cancel},[l]),wr(()=>{if(!g.current)throw new Error(`Scope not ready. Using element: ${s.constructor.name}`)},[]),kr(()=>{let k=e.toStyle(m,o);Object.assign(g.current.style,k),m.logger.debug("Displayable","Initial style applied",g.current,k)},[]);function ye(){let k=typeof a=="function"?a(l):a;if(!T.current||!T.current.length)throw new A("Displayable: Transition group refs are not initialized correctly");if(T.current.some(([V])=>!V.current))throw new A("Displayable: Trying to access transition groups before they are mounted");T.current.forEach(([V],x)=>{if(!V.current)throw new A("Displayable: Trying to assign properties to unmounted element");Gt(V,k[x]||k[k.length-1]||{})})}function et(k){m.logger.debug("Displayable","Transform applied",e.toStyle(m,o),g.current),N(),i?.(k)}function Gt(k,V){if(!k.current)throw new A("Displayable: Trying to assign properties to unmounted element");let x=k.current,_={},Ie={};Object.keys(V).forEach(E=>{let D=E;D==="style"&&V.style?Object.assign(_,V.style):V[D]!==void 0&&D!=="key"&&(Ie[D]=V[D])}),Object.keys(_).length>0&&Object.assign(x.style,_);let je=c?c(Ie):Ie;for(let[E,D]of Object.entries(je))x.getAttribute(E)!==D&&x.setAttribute(E,D)}function Ke(k,V){p&&(p.abort(),d(null));let x=k.animate(e,{gameState:m,ref:g,overwrites:o}),_=new se(x);return m.timelines.attachTimeline(_),x.onSkipControllerRegister(Ie=>{Ie.onAbort(()=>{_.abort(),d(null)})}),d(x),x.then(()=>{d(null),et(k),V()}),_}function At(k,V){l&&l.controller.complete();let x=k.createTask(m),_=k.requestAnimations(x.animations),Ie=new h().registerSkipController(new L(_.cancel)),je=new se(Ie);Ie.skipController.onAbort(()=>{_.cancel()}),_.onCanceled(()=>{je.abort(),f(null),m.logger.debug("Displayable","Transition cancelled",k)}),m.timelines.attachTimeline(je),f({task:x,controller:_,transition:k,resolve:V});let E;if(T.current=x.resolve.map(J=>{let $=fi.createRef(),me=typeof J=="function"?void 0:J.key;if(!me)return[$,u.next()];if(me==="target")return E=u.next(),[$,E];if(me==="current")return[$,C.current];throw new A("Displayable: Invalid key type")}),!E)throw new A("Displayable: No target key found");C.current=E;let D=T.current.map(([J])=>{let $=J.current;return $?.waitForLoad?$.waitForLoad():Promise.resolve()});return Promise.all(D).then(()=>{_.start(),_.onComplete(()=>{oe(),f(null),r?.(k),V(),Ie.resolve()})}),je}function Fe(k){return m.logger.debug("initDisplayable",s),Ke(O.immediate(e.get()),k)}function dt(){t&&p&&(p.abort(),d(null),m.logger.debug("transform skipped")),n&&l&&(l.controller.complete(),m.logger.debug("transition skipped"))}function tt(){return[[fi.createRef(),C.current]]}function oe(){T.current.forEach(([k])=>{k.current=null}),T.current=tt()}return{transformRef:g,transitionRefs:T.current,isTransforming:!!p,transitionTask:l,initDisplayable:Fe,applyTransform:Ke,applyTransition:At,updateStyleSync:ye,deps:[p,l,T]}}import{useEffect as Ta}from"react";function bt(s,e,t=[]){let o=w().getLiveGame().getGameState();return Ta(()=>{let i=typeof e=="function"?e():e;return o.mountState(s,i).unMount},[...t]),[]}function hi({state:s,text:e}){let{ratio:t}=Z(),[n]=B(),{transformRef:o,transitionRefs:i,initDisplayable:r,applyTransform:a,applyTransition:c,updateStyleSync:l,deps:f,isTransforming:p}=Bt({element:e,state:e.transformState,skipTransform:s.game.config.allowSkipTextTransform,skipTransition:s.game.config.allowSkipTextTransition,overwriteDefinition:{overwrite:d=>({width:"fit-content",transform:O.propToCSSTransform(s,d,{translate:[e.config.alignX==="left"?"0%":e.config.alignX==="right"?"-100%":void 0,e.config.alignY==="top"?"100%":e.config.alignY==="bottom"?"0%":void 0]})})},transitionsProps:[{style:{width:"fit-content",whiteSpace:"nowrap",transform:`scale(${t.state.scale})`,transformOrigin:`${e.config.alignX} ${e.config.alignY}`,fontSize:`${e.state.fontSize}px`}}]});return bt(e,{initDisplayable:r,applyTransform:a,applyTransition:c,flush:n,updateStyleSync:l},[...f]),ko.createElement(Rt.Div,{"data-element-type":"text"},ko.createElement(Rt.mDiv,{tag:"text.container",color:"green",border:"dashed",layout:p,ref:o,className:"absolute"},i.map(([d,g])=>ko.createElement("span",{key:g,ref:d,className:e.config.className},ko.createElement("span",null,e.state.text)))))}import jt,{useRef as Rr,useState as Lr}from"react";import Po,{useEffect as yi,useRef as Eo,forwardRef as Sa}from"react";var Er=Sa(({onSizeChanged:s,onLoad:e,autoFit:t=!1},n)=>{let o=Eo(null),{ratio:i}=Z(),[r,a]=Po.useState(()=>i.state.width),[c,l]=Po.useState(()=>i.state.height),f=w(),p=Eo(!1),d=Eo(null),g=Eo(null);Po.useImperativeHandle(n,()=>o.current,[]),yi(()=>{o.current&&Object.defineProperties(o.current,{isLoaded:{value:()=>p.current,configurable:!0},waitForLoad:{value:()=>p.current?Promise.resolve():(d.current||(d.current=new Promise(T=>{g.current=T})),d.current),configurable:!0}})},[]),yi(()=>(u(),i.onUpdate(u)),[s]),yi(()=>{let T=new MutationObserver(P=>{P.forEach(m=>{m.type==="attributes"&&m.attributeName==="src"&&o.current&&u()})});return o.current&&T.observe(o.current,{attributes:!0}),()=>{T.disconnect()}},[s]);function u(){if(o.current&&o.current.naturalWidth)if(o.current.naturalWidth*o.current.naturalHeight===1){let T=i.state.width,P=i.state.height,m=`${T} / ${P}`;a(T),l(P),o.current.style.aspectRatio=m,s&&s(T,P)}else{let T=t?f.config.width/o.current.naturalWidth:1,P=o.current.naturalWidth*i.state.scale*T,m=o.current.naturalHeight*i.state.scale*T;a(P),l(m),o.current.style.aspectRatio="auto",s&&s(P,m)}}function C(){u(),p.current=!0,g.current&&(g.current(),g.current=null,d.current=null),e&&e()}return Po.createElement("img",{ref:o,onLoad:C,width:r,height:c,alt:""})});Er.displayName="AspectScaleImage";var Dr=Er;import Ir from"clsx";import{motion as ba}from"motion/react";function Do({image:s,state:e}){let[t]=Lr(()=>new F),[n,o]=Lr([]),{cacheManager:i}=$t(),r=Rr([]),a=Rr(null),{transformRef:c,transitionRefs:l,isTransforming:f,initDisplayable:p,applyTransition:d,applyTransform:g,updateStyleSync:u,deps:C}=Bt({element:s,state:s.transformState,skipTransform:e.game.config.allowSkipImageTransform,skipTransition:e.game.config.allowSkipImageTransition,transitionsProps:m=>{let y=m?m.transition._getCurrentSrc():s.state.currentSrc;return[{style:{willChange:"filter",position:"absolute",transformOrigin:"center",backgroundColor:b.isColor(y)?b.colorToString(y):void 0,transform:"none",top:"auto",left:"auto",right:"auto",bottom:"auto",filter:`brightness(${1-s.state.darkness})`},src:b.isImageSrc(y)?b.srcToURL(y):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:m=>m.src?(!b.isDataURI(m.src)&&!i.has(m.src)&&!i.isPreloading(m.src)&&!r.current.includes(m.src)&&(e.game.getLiveGame().getGameState()?.logger.warn("Image",`Image not preloaded: "${m.src}".
60
60
  This may be caused by complicated image action behavior that cannot be predicted.
61
- To fix this issue, you can manually register the image using scene.preloadImage(YourImageSrc). `),r.current.push(m.src)),{...m,src:i.get(m.src)||m.src}):m});bt(s,{createWearable:m=>{o(y=>[...y,m])},disposeWearable:m=>{o(y=>y.filter(G=>G.getId()!==m.getId()))},initDisplayable:p,applyTransform:g,applyTransition:d,events:t,updateStyleSync:u},[...C]);function T(m,y){a.current&&(t.emit("event:image.onLoad"),Object.assign(a.current.style,{width:`${m}px`,height:`${y}px`}))}function P(){t.emit("event:image.onLoad")}return jt.createElement(ba.div,{layout:f,ref:c,className:"absolute w-max h-max","data-element-type":"image"},jt.createElement("div",{className:"relative h-full w-full",ref:a,"data-image-id":s.getId()},l.map(([m,y],G)=>jt.createElement(Dr,{key:y,ref:m,autoFit:s.config.autoFit,onSizeChanged:G===0?T:void 0,onLoad:G===0?P:void 0})),jt.createElement("div",{className:Ir("w-full h-full top-0 left-0 absolute")},n.map(m=>jt.createElement("div",{className:Ir("w-full h-full relative"),key:"wearable-"+m.getId()},jt.createElement(Do,{image:m,state:e}))))))}function Ti({state:s,displayable:e}){return Ro.createElement(Ro.Fragment,null,e.map(t=>{if(t instanceof Dt)return Ro.createElement(hi,{state:s,text:t,key:"text-"+t.getId()});if(t instanceof I)return Ro.createElement(Do,{state:s,image:t,key:"image-"+t.getId()});throw new Error("Unsupported displayable type: "+(t?.constructor?.name||t))}))}import Lo,{useEffect as Aa}from"react";import{motion as va}from"motion/react";function Mr({state:s,layer:e,children:t}){let{transformRef:n,transitionRefs:o,initDisplayable:i,applyTransition:r,applyTransform:a,updateStyleSync:c,deps:l}=Bt({element:e,state:e.transformState,skipTransform:s.game.config.allowSkipLayersTransform,skipTransition:!1,transitionsProps:[{style:{width:"100%",height:"100%",transformOrigin:"center"}}]});return bt(e,{initDisplayable:i,applyTransition:r,applyTransform:a,updateStyleSync:c},[...l]),Aa(()=>(s.logger.debug("Layer","Layer mounted",e.getId()),()=>{s.logger.debug("Layer","Layer unmounted",e.getId())}),[]),Lo.createElement(Lo.Fragment,null,Lo.createElement(va.div,{layout:!0,className:"absolute w-full h-full",ref:n,"data-element-type":"layer","data-layer-id":e.getId(),key:`layer-${e.getId()}`},o.map(([f,p])=>Lo.createElement("div",{className:"relative w-full h-full",ref:f,key:p},t))))}import Ca from"clsx";import{useEffect as Gr,useRef as xa}from"react";import qt from"react";function Si({state:s,className:e,elements:t}){let{scene:n,layers:o,texts:i,menus:r}=t,a=xa(!1);return Gr(()=>n.events.depends([n.events.on(Ee.EventTypes["event:scene.preUnmount"],()=>{if(n.state.backgroundMusic)return s.audioManager.stop(n.state.backgroundMusic).then(()=>{n.state.backgroundMusic=null})})]).cancel,[]),Gr(()=>(n.events.emit(Ee.EventTypes["event:scene.mount"]),s.logger.debug("Scene","Scene mounted",n.getId()),()=>{n.events.emit(Ee.EventTypes["event:scene.unmount"]),s.logger.debug("Scene","Scene unmounted",n.getId())}),[]),bt(n,{setBackgroundMusic(c,l){return new Promise(f=>{n.state.backgroundMusic&&async function(){n.state.backgroundMusic&&s.audioManager.isManaged(n.state.backgroundMusic)&&await s.audioManager.stop(n.state.backgroundMusic,l),c?(await s.audioManager.play(c,{end:c.state.volume,duration:l}),n.state.backgroundMusic=c):n.state.backgroundMusic=null,f()}()})}}),qt.createElement("div",{className:Ca(e,"w-full h-full absolute")},[...o.entries()].sort(([c],[l])=>c.state.zIndex-l.state.zIndex).map(([c,l])=>qt.createElement(Mr,{state:s,layer:c,key:c.getId()},qt.createElement(Ti,{state:s,displayable:l}))),i.map(({action:c,onClick:l})=>qt.createElement(dn,{gameState:s,key:"say-"+c.id,action:c,onFinished:f=>{f!==void 0&&(a.current=f),l(),s.stage.next()},useTypeEffect:!a.current})),r.map(({action:c,onClick:l},f)=>qt.createElement("div",{key:"menu-"+f,"data-element-type":"menu"},qt.createElement(mi,{state:s,prompt:c.prompt,choices:c.choices,afterChoose:p=>{a.current=!1,l(p),s.stage.next()},words:c.words}))))}import wa from"react";import{useEffect as bi,useRef as ka}from"react";import{useCallback as Nr}from"react";function Hr(s){let e=Nr(()=>{if(!s.current)return;let n=s.current;n.style.opacity="1",n.style.pointerEvents="auto",n.style.visibility="visible"},[s]),t=Nr(()=>{if(!s.current)return;let n=s.current;n.style.opacity="0",n.style.pointerEvents="none",n.style.visibility="hidden"},[s]);return{show:e,hide:t}}function Ai({gameState:s,video:e}){let t=ka(null),{show:n,hide:o}=Hr(t);bi(()=>s.events.depends([s.events.on(K.EventTypes["event:state.player.skip"],()=>{s.game.config.allowSkipVideo&&(i(),s.logger.log("NarraLeaf-React: Video","Skipped"))})]).cancel,[]),bi(()=>{o(),e.state.display&&n()},[]),bi(()=>{if(!t.current)return;let r=t.current,a=!1,c=()=>new A(`Failed to add event listener, ref is not available
62
- at Video.tsx: useEffect`),l=()=>{a||!r||(a=!0,s.mountState(e,{show:()=>{if(!t.current)throw c();n()},hide:()=>{if(!t.current)throw c();o()},play:()=>{if(!t.current)throw c();let p=t.current;return p.currentTime=0,new Promise(d=>{s.schedule(({retry:g})=>{if(p.readyState<3){let P=()=>{p.removeEventListener("loadeddata",P),g()};p.addEventListener("loadeddata",P);return}let u=()=>{T(),d()},C=()=>{T(),d()},T=()=>{p.removeEventListener("ended",u),p.removeEventListener("stopped",C)};p.addEventListener("ended",u),p.addEventListener("stopped",C),f.push(T),p.play().catch(P=>{s.logger.error("Failed to play video: "+P),T(),d()})},10)})},pause:()=>{if(!t.current)throw c();t.current.pause()},resume:()=>{if(!t.current)throw c();return t.current.play()},stop:()=>{if(!t.current)throw c();t.current.pause(),t.current.dispatchEvent(new Event("stopped"))},seek:p=>{if(!t.current)throw c();t.current.currentTime=p}}))},f=[];return r.addEventListener("canplay",l),()=>{a=!1,r.removeEventListener("canplay",l),f.forEach(p=>p()),r.currentTime>0&&r.pause(),s.isStateMounted(e)&&s.unMountState(e)}},[s,e]);function i(){t.current&&(t.current.pause(),t.current.currentTime=0,t.current.dispatchEvent(new Event("stopped")))}return wa.createElement("video",{ref:t,src:e.config.src,preload:"auto",muted:e.config.muted,playsInline:!0,width:"100%",height:"100%",onContextMenu:r=>r.preventDefault()})}import Pa from"clsx";import Ur,{useEffect as Kr,useState as Ea}from"react";function vi({children:s,className:e,gameState:t}){let[n,o]=Ea({}),{ratio:i}=Z(),r=w(),[a]=B(),c=r.config.minWidth,l=r.config.minHeight;return Kr(()=>{t.logger.debug("AspectRatio","mount, using interval",r.config.ratioUpdateInterval);let f=()=>{if(i.isLocked()){t.logger.weakWarn("Ratio is locked, skipping update");return}let u=document.getElementById(r.config.contentContainerId);if(u){let C=u.clientWidth,T=u.clientHeight,P=r.config.aspectRatio,m,y;C/T>P?(m=T*P,y=T):(m=C,y=C/P),m<c&&(m=c),y<l&&(y=l),o({width:`${m}px`,height:`${y}px`,margin:"auto",position:"absolute",top:"0",bottom:"0",left:"0",right:"0",display:"flex",alignItems:"center",justifyContent:"center"});let G=m/r.config.width;i.update(m,y,G),i.updateMin(c,l),a()}};i.setUpdate(f);let d=Gi(()=>{f()},r.config.ratioUpdateInterval);d(),window.addEventListener("resize",d);let g=i.onRequestedUpdate(d);return()=>{window.removeEventListener("resize",d),g()}},[i,r.config.ratioUpdateInterval]),Kr(()=>t.events.on(K.EventTypes["event:state.player.requestFlush"],a).cancel,[t]),Ur.createElement("div",{id:r.config.contentContainerId,style:{position:"relative",width:"100%",height:"100%",overflow:"hidden"}},Ur.createElement("div",{className:Pa(e),style:n},s))}import Fr,{useEffect as Da,useRef as Ra,useState as Or}from"react";function Ci({src:s,width:e,height:t}){let[n,o]=Or({x:0,y:0}),[i,r]=Or(!1),a=Ra(null),{ratio:c}=Z();return Da(()=>{let l=f=>{if(a.current){let p=a.current.getBoundingClientRect(),d=f.clientX-p.left,g=f.clientY-p.top;o({x:d,y:g}),i||r(!0)}};return window.addEventListener("mousemove",l),()=>{window.removeEventListener("mousemove",l)}},[i]),Fr.createElement(Ze,{ref:a,className:"overflow-hidden absolute"},Fr.createElement("img",{src:s,style:{position:"absolute",left:n.x,top:n.y,width:e,height:t,pointerEvents:"none",zIndex:1001,display:i?"block":"none",cursor:"none",transform:`scale(${c.state.scale})`},alt:""}))}import Wr from"react";import ut from"react";function xi({error:s,errorInfo:e}){return w().config.app.debug?ut.createElement("div",{className:"text-left"},ut.createElement("h1",null,"NarraLeaf-React cannot initialize the player correctly. (development mode)"),ut.createElement("p",{className:"text-red-700"},"Message: ",s.message),ut.createElement("pre",null,"Error Stack: ",s?.stack),ut.createElement("pre",null,"Component Stack: ",e?.componentStack),ut.createElement("pre",null,"Digest: ",e?.digest)):ut.createElement("div",{className:"bg-white w-full h-full"},ut.createElement("h1",null,"NarraLeaf-React crashed due to an unknown error."),ut.createElement("p",null,"Please contact the game developer for further assistance."))}var Io=class extends Wr.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?Wr.createElement(xi,{error:this.state.error,errorInfo:this.state.errorInfo}):this.props.children}};import $r from"clsx";import j,{useEffect as vn,useReducer as Ga,useState as Cn}from"react";import{flushSync as Br}from"react-dom";import{useRef as La}from"react";import{useEffect as Ia}from"react";function Vr({gameState:s}){let e=La(null);return Ia(()=>(e.current=requestAnimationFrame(()=>{setTimeout(()=>{s.events.emit(K.EventTypes["event:state.onRender"])},0)}),()=>{e.current!==null&&cancelAnimationFrame(e.current)}),[s.deps]),null}import An,{useEffect as Ma}from"react";function wi({gameState:s}){let[e]=B(),{ratio:t}=Z(),n=s.notificationMgr;Ma(()=>n.onFlush(()=>{e()}).cancel,[]);let o=s.game.config.notification;return An.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"},An.createElement(o,{notifications:n.toArray()}))}function zr({notifications:s}){return An.createElement(To,{className:"absolute top-0 left-0 w-full h-full"},s.map(({id:e,message:t})=>An.createElement("div",{key:e,className:"absolute top-0 left-0 w-[100px] h-[80px]"},An.createElement("span",{className:"text-white text-2xl font-bold"},t))))}function jr({story:s=cn.empty(),width:e,height:t,className:n,onReady:o,onEnd:i,onError:r,children:a,active:c=!0}){let[l,f]=Ga(oe=>oe+1,0),[p,d]=Cn(0),g=w(),[u]=Cn(()=>new K(g,{update:f,forceUpdate:()=>{u.logger.weakWarn("Player","force update"),Br(()=>{f()})},forceRemount:()=>{u.logger.weakWarn("Player","force remount"),Br(()=>{d(oe=>oe+1),f()})},next:Fe})),C=j.createRef(),T=j.createRef(),[P,m]=Cn(!1),y=j.useRef(!1),G=j.useRef(null),ye=j.useRef(null),{preloaded:et}=$t(),[Gt,Ke]=Cn(!1),[At]=Cn(new Map);function Fe(){let oe=()=>{At.forEach(x=>x.cancel())};if(u.rollLock.isLocked())return;oe();let k=!1,V=0;for(;!k;){if(V++>g.config.maxStackModelLoop)throw new A("Max stack model loop reached");let x=g.getLiveGame().next();if(!x){if(g.getLiveGame().stackModel&&!g.getLiveGame().stackModel.isEmpty())continue;break}if(h.isAwaitable(x)){if(G.current===x)break;G.current=x,x.onSettled(()=>{G.current===x&&(G.current=null),Fe()}),k=!0;break}if(x instanceof Ht){if(ye.current===x)break;ye.current=x,x.nextUnlock().then(()=>{ye.current===x&&(ye.current=null),Fe()}),k=!0;break}if(De.isCalledActionResult(x)&&x.wait&&De.isStackModelsAwaiting(x.wait.type,x.wait.stackModels)){if(G.current===x)break;G.current=x,x.wait&&De.executeStackModelGroup(x.wait.type,x.wait.stackModels).then(()=>{G.current===x&&(G.current=null),Fe()}),k=!0;break}u.handle(x)}u.stage.update()}vn(()=>(g.getLiveGame().setGameState(u),s&&!g.getLiveGame().isPlaying()&&g.getLiveGame().loadStory(s),u.playerCurrent=C.current,u.mainContentNode=T.current,()=>{g.getLiveGame().setGameState(void 0),u.playerCurrent=null}),[g,s]),vn(()=>Me(()=>{m(!0);let oe=u.getLastScene(),k=[];oe?k.push(oe.events.once("event:scene.mount",()=>{u.stage.next()}).cancel):u.stage.next();let V=u.events.on(K.EventTypes["event:state.end"],()=>{i&&i({game:g,gameState:u,liveGame:g.getLiveGame(),storable:g.getLiveGame().getStorable()})});return u.stage.update(),()=>{oe&&k.forEach(x=>x()),V.cancel()}}),[]),vn(()=>Me(()=>{P&&o&&!y.current&&(y.current=!0,u.stage.forceUpdate(),g.hooks.trigger("init",[]),o({game:g,gameState:u,liveGame:g.getLiveGame(),storable:g.getLiveGame().getStorable()}))}),[P]),vn(()=>et.events.depends([et.events.on(Le.EventTypes["event:preloaded.ready"],()=>{Ke(!0),u.stage.update(),s&&Fe()})]).cancel,[]),vn(()=>{u.flushDep=l},[l]);let dt=e||g.config.width,tt=t||g.config.height;return j.createElement(Io,{onError:r},j.createElement("div",{style:{width:typeof dt=="number"?`${dt}px`:dt,height:typeof tt=="number"?`${tt}px`:tt},className:$r(n,"__narraleaf_content-player"),ref:C,tabIndex:0},j.createElement(vi,{className:$r("flex-grow overflow-auto"),gameState:u},j.createElement(li,{ref:C}),j.createElement(ci,{gameState:u}),j.createElement(Vr,{gameState:u}),j.createElement(Ze,{className:"absolute",ref:T,style:{cursor:u.game.config.cursor?"none":"auto",overflow:u.game.config.showOverflow?"visible":"hidden"}},g.config.cursor&&j.createElement(Ci,{src:g.config.cursor,width:g.config.cursorWidth,height:g.config.cursorHeight}),j.createElement(Na,{show:Gt&&c,key:p},j.createElement(br,{state:u}),u.getSceneElements().map(oe=>j.createElement(Si,{key:"scene-"+oe.scene.getId(),state:u,elements:oe})),u.getVideos().map((oe,k)=>j.createElement("div",{className:"w-full h-full absolute",key:"video-"+k,"data-element-type":"video"},j.createElement(Ai,{gameState:u,video:oe})))),j.createElement(Cr,{state:u}),j.createElement(yr,null,a),j.createElement(wi,{gameState:u})))))}function Na({children:s,show:e}){return j.createElement(j.Fragment,null,e?s:null)}import"client-only";import Qt from"react";function qr({children:s,game:e}){return Qt.createElement(Qt.Fragment,null,Qt.createElement(tr,null,Qt.createElement(Yi,{game:e},Qt.createElement(vr,null,Qt.createElement(er,null,s)))))}var Ha=(i=>(i.image="narraleaf:image",i.text="narraleaf:text",i.layer="narraleaf:layer",i.scene="narraleaf:scene",i.video="narraleaf:video",i))(Ha||{});import Ua from"clsx";import Mt,{useEffect as Qr,useRef as Ka}from"react";function Fa({children:s,...e}){let t=w(),n=lt(),{ratio:o}=Z(),[i]=$e(Q.Preferences.showDialog),r=Ka(null),[a]=Tn("nextAction");function c(){n.requestComplete()}return Qr(()=>{if(!window){console.warn(`Failed to add event listener, window is not available
63
- at Say.tsx: onElementClick`);return}let l=p=>{t.keyMap.match("nextAction",p.key)&&n.requestComplete()};window.addEventListener("keyup",l);let f=n.events.on(Re.Events.simulateClick,()=>{r.current&&r.current.click()});return()=>{window.removeEventListener("keyup",l),f.cancel()}},[n,a]),Qr(()=>{let l=t.preference.onPreferenceChange(Q.Preferences.autoForward,f=>{f&&n.isEnded()?n.tryScheduleAutoForward():n.cancelAutoForward()});return()=>{l.cancel()}},[n]),Mt.createElement("div",{"data-element-type":"dialog",className:"w-full h-full"},Mt.createElement("div",{className:Ua("absolute bottom-0 w-full h-full",!i&&"invisible pointer-events-auto"),onClick:c,style:{...Fn(t.config.useAspectScale,{maxWidth:t.config.dialogWidth,maxHeight:t.config.dialogHeight,transform:`scale(${o.state.scale})`,transformOrigin:"bottom left",width:t.config.width,height:t.config.height})},ref:r},Mt.createElement("div",{...e},s)))}function Xr({children:s,...e}){let t=lt();return!t.config.action.sentence||!t.config.action.words?null:Mt.createElement(Fa,{...e},s)}var la=Xr;function Jr(){return Mt.createElement(Xr,null,Mt.createElement(bo,null),Mt.createElement(ni,null))}var Mo={say:Jr,menu:xr,notification:zr};var Go=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 xn=class{constructor(e={}){this.keyMap=e;this.events=new F}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)??[],o=i=>Array.isArray(i)?i:[i];Array.isArray(n)?this.setKeyBinding(e,[...n,...o(t)]):this.setKeyBinding(e,[n,...o(t)])}getKeyBindings(){return this.keyMap}onKeyBindingChange(e,t){return this.events.on("event:keyMap.change",(n,o)=>{n===e&&t(o)})}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(o=>o.toLowerCase()===t.toLowerCase()):n===t||n.toLowerCase()===t.toLowerCase()}};var Yr=(e=>(e.game="game",e))(Yr||{}),pt=class pt{constructor(e){this.hooks=new Nn;this.liveGame=null;this.sideEffect=[];this.freezeFields=[];this.preference=new pn(pt.DefaultPreference);this.keyMap=new xn({skipAction:["Control"],nextAction:[" "]});this.config=R(pt.DefaultConfig,e),this.plugins=new Go(this),this.router=new St(this)}configure(e){let[t,n]=Vi(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=R(this.config,t),this.getLiveGame().getGameState()?.events.emit(K.EventTypes["event:state.player.requestFlush"]),this}configureAndFreeze(e){return this.configure(e),this.freeze(Object.keys(e)),this}freeze(e){return this.freezeFields.push(...e),this}use(e){return this.plugins.has(e)||this.plugins.use(e).register(e),this}getLiveGame(){if(!this.liveGame){let e=this.createLiveGame();return this.liveGame=e,e}return this.liveGame}dispose(){this.plugins.unregisterAll(),this.liveGame?.dispose(),this.sideEffect.forEach(e=>e())}addSideEffect(e){this.sideEffect.push(e)}createLiveGame(){return new Tt(this)}};pt.defaultSettings={volume:1},pt.DefaultPreference={autoForward:!1,skip:!0,showDialog:!0,gameSpeed:1,cps:10,voiceVolume:1,bgmVolume:1,soundVolume:1,globalVolume:1,skipDelay:500,skipInterval:100},pt.Preferences={autoForward:"autoForward",skip:"skip",showDialog:"showDialog",gameSpeed:"gameSpeed",cps:"cps",voiceVolume:"voiceVolume",bgmVolume:"bgmVolume",soundVolume:"soundVolume",globalVolume:"globalVolume",skipDelay:"skipDelay",skipInterval:"skipInterval"},pt.DefaultConfig={app:{debug:!1,logger:{log:!1,info:!1,warn:!0,error:!0,debug:!1,trace:!1,verbose:!1},inspector:!1,guard:{invalidExposedStateUnmounting:!0,unexpectedTimelineStatusChange:!0}},contentContainerId:"__narraleaf_content",aspectRatio:16/9,minWidth:800,minHeight:450,width:1920,height:1080,useWindowListener:!0,ratioUpdateInterval:50,preloadDelay:100,preloadConcurrency:5,waitForPreload:!0,preloadAllImages:!0,forceClearCache:!1,maxPreloadActions:10,cursor:null,cursorHeight:30,cursorWidth:30,showOverflow:!1,maxRouterHistory:10,screenshotQuality:1,useAspectScale:!0,autoForwardDelay:3*1e3,autoForwardDefaultPause:1e3,allowSkipImageTransform:!0,allowSkipImageTransition:!0,allowSkipBackgroundTransform:!0,allowSkipBackgroundTransition:!1,allowSkipTextTransform:!0,allowSkipTextTransition:!0,allowSkipLayersTransform:!0,allowSkipVideo:!1,animationPropagate:!1,dialogWidth:1920,dialogHeight:1080*.2,defaultTextColor:"#000",defaultNametagColor:"#000",notification:Mo.notification,menu:Mo.menu,dialog:Mo.say,onError:e=>{console.error(e)},fontSize:16,fontWeight:400,fontWeightBold:700,fontFamily:"sans-serif",stage:null,defaultMenuChoiceColor:"#000",maxStackModelLoop:1e3,maxActionHistory:100},pt.GameSettingsNamespace=Yr;var Q=pt;var ki=class s extends ot{constructor(t,n){super();this.duration=t;this.easing=n}createTask(){return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(t=>({style:{opacity:1-t}})),this.asTarget(t=>({style:{opacity:t}}))]}}copy(){return new s(this.duration,this.easing)}};var Pi=class s extends ot{constructor(t,n=[0,0],o){super();this.duration=t;this.startPos=n;this.easing=o}createTask(t){return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing},{type:0,start:this.startPos[0],end:0,duration:this.duration,ease:this.easing},{type:0,start:this.startPos[1],end:0,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(()=>({})),this.asTarget((n,o,i)=>({style:{opacity:n,...b.offset(["50%","50%"],[o,i],t.getStory().getInversionConfig()),transform:"translate(-50%, 50%)"}}))]}}copy(){return new s(this.duration,this.startPos,this.easing)}};var Ei=class extends ln{constructor(){super();this.unlocked={};this.setupActions()}serialize(){return{unlocked:this.unlocked}}deserialize(t){this.unlocked=t.unlocked}add(t,n){return this.trigger("add",t,n)}has(t){return new H(()=>this.unlocked[t]!==void 0)}remove(t){return this.trigger("remove",t)}clear(){return this.trigger("clear")}$remove(t){delete this.unlocked[t]}$clear(){this.unlocked={}}$get(t){return this.unlocked[t]}$set(t,n){this.unlocked[t]=n}$getAll(){return this.unlocked}$has(t){return this.unlocked[t]!==void 0}setupActions(){this.on("add",(t,n,o)=>{let i={gameState:t.gameState,game:t.game,liveGame:t.liveGame,storable:t.storable,$:t.$},r=typeof o=="function"?o(i):o;this.unlocked[n]=r}),this.on("remove",(t,n)=>{delete this.unlocked[n]}),this.on("clear",t=>{this.$clear()})}};if(typeof document<"u"){let s=document.createElement("style");s.textContent=`/*! tailwindcss v4.1.8 | MIT License | https://tailwindcss.com */
61
+ To fix this issue, you can manually register the image using scene.preloadImage(YourImageSrc). `),r.current.push(m.src)),{...m,src:i.get(m.src)||m.src}):m});bt(s,{createWearable:m=>{o(y=>[...y,m])},disposeWearable:m=>{o(y=>y.filter(N=>N.getId()!==m.getId()))},initDisplayable:p,applyTransform:g,applyTransition:d,events:t,updateStyleSync:u},[...C]);function T(m,y){a.current&&(t.emit("event:image.onLoad"),Object.assign(a.current.style,{width:`${m}px`,height:`${y}px`}))}function P(){t.emit("event:image.onLoad")}return jt.createElement(ba.div,{layout:f,ref:c,className:"absolute w-max h-max","data-element-type":"image"},jt.createElement("div",{className:"relative h-full w-full",ref:a,"data-image-id":s.getId()},l.map(([m,y],N)=>jt.createElement(Dr,{key:y,ref:m,autoFit:s.config.autoFit,onSizeChanged:N===0?T:void 0,onLoad:N===0?P:void 0})),jt.createElement("div",{className:Ir("w-full h-full top-0 left-0 absolute")},n.map(m=>jt.createElement("div",{className:Ir("w-full h-full relative"),key:"wearable-"+m.getId()},jt.createElement(Do,{image:m,state:e}))))))}function Ti({state:s,displayable:e}){return Ro.createElement(Ro.Fragment,null,e.map(t=>{if(t instanceof Dt)return Ro.createElement(hi,{state:s,text:t,key:"text-"+t.getId()});if(t instanceof I)return Ro.createElement(Do,{state:s,image:t,key:"image-"+t.getId()});throw new Error("Unsupported displayable type: "+(t?.constructor?.name||t))}))}import Lo,{useEffect as Aa}from"react";import{motion as va}from"motion/react";function Mr({state:s,layer:e,children:t}){let{transformRef:n,transitionRefs:o,initDisplayable:i,applyTransition:r,applyTransform:a,updateStyleSync:c,deps:l}=Bt({element:e,state:e.transformState,skipTransform:s.game.config.allowSkipLayersTransform,skipTransition:!1,transitionsProps:[{style:{width:"100%",height:"100%",transformOrigin:"center"}}]});return bt(e,{initDisplayable:i,applyTransition:r,applyTransform:a,updateStyleSync:c},[...l]),Aa(()=>(s.logger.debug("Layer","Layer mounted",e.getId()),()=>{s.logger.debug("Layer","Layer unmounted",e.getId())}),[]),Lo.createElement(Lo.Fragment,null,Lo.createElement(va.div,{layout:!0,className:"absolute w-full h-full",ref:n,"data-element-type":"layer","data-layer-id":e.getId(),key:`layer-${e.getId()}`},o.map(([f,p])=>Lo.createElement("div",{className:"relative w-full h-full",ref:f,key:p},t))))}import Ca from"clsx";import{useEffect as Gr,useRef as xa}from"react";import qt from"react";function Si({state:s,className:e,elements:t}){let{scene:n,layers:o,texts:i,menus:r}=t,a=xa(!1);return Gr(()=>n.events.depends([n.events.on(Ee.EventTypes["event:scene.preUnmount"],()=>{if(n.state.backgroundMusic)return s.audioManager.stop(n.state.backgroundMusic).then(()=>{n.state.backgroundMusic=null})})]).cancel,[]),Gr(()=>(n.events.emit(Ee.EventTypes["event:scene.mount"]),s.logger.debug("Scene","Scene mounted",n.getId()),()=>{n.events.emit(Ee.EventTypes["event:scene.unmount"]),s.logger.debug("Scene","Scene unmounted",n.getId())}),[]),bt(n,{setBackgroundMusic(c,l){return new Promise(f=>{n.state.backgroundMusic&&async function(){n.state.backgroundMusic&&s.audioManager.isManaged(n.state.backgroundMusic)&&await s.audioManager.stop(n.state.backgroundMusic,l),c?(await s.audioManager.play(c,{end:c.state.volume,duration:l}),n.state.backgroundMusic=c):n.state.backgroundMusic=null,f()}()})}}),qt.createElement("div",{className:Ca(e,"w-full h-full absolute")},[...o.entries()].sort(([c],[l])=>c.state.zIndex-l.state.zIndex).map(([c,l])=>qt.createElement(Mr,{state:s,layer:c,key:c.getId()},qt.createElement(Ti,{state:s,displayable:l}))),i.map(({action:c,onClick:l})=>qt.createElement(dn,{gameState:s,key:"say-"+c.id,action:c,onFinished:f=>{f!==void 0&&(a.current=f),l(),s.stage.next()},useTypeEffect:!a.current})),r.map(({action:c,onClick:l},f)=>qt.createElement("div",{key:"menu-"+f,"data-element-type":"menu"},qt.createElement(mi,{state:s,prompt:c.prompt,choices:c.choices,afterChoose:p=>{a.current=!1,l(p),s.stage.next()},words:c.words}))))}import wa from"react";import{useEffect as bi,useRef as ka}from"react";import{useCallback as Nr}from"react";function Hr(s){let e=Nr(()=>{if(!s.current)return;let n=s.current;n.style.opacity="1",n.style.pointerEvents="auto",n.style.visibility="visible"},[s]),t=Nr(()=>{if(!s.current)return;let n=s.current;n.style.opacity="0",n.style.pointerEvents="none",n.style.visibility="hidden"},[s]);return{show:e,hide:t}}function Ai({gameState:s,video:e}){let t=ka(null),{show:n,hide:o}=Hr(t);bi(()=>s.events.depends([s.events.on(K.EventTypes["event:state.player.skip"],()=>{s.game.config.allowSkipVideo&&(i(),s.logger.log("NarraLeaf-React: Video","Skipped"))})]).cancel,[]),bi(()=>{o(),e.state.display&&n()},[]),bi(()=>{if(!t.current)return;let r=t.current,a=!1,c=()=>new A(`Failed to add event listener, ref is not available
62
+ at Video.tsx: useEffect`),l=()=>{a||!r||(a=!0,s.mountState(e,{show:()=>{if(!t.current)throw c();n()},hide:()=>{if(!t.current)throw c();o()},play:()=>{if(!t.current)throw c();let p=t.current;return p.currentTime=0,new Promise(d=>{s.schedule(({retry:g})=>{if(p.readyState<3){let P=()=>{p.removeEventListener("loadeddata",P),g()};p.addEventListener("loadeddata",P);return}let u=()=>{T(),d()},C=()=>{T(),d()},T=()=>{p.removeEventListener("ended",u),p.removeEventListener("stopped",C)};p.addEventListener("ended",u),p.addEventListener("stopped",C),f.push(T),p.play().catch(P=>{s.logger.error("Failed to play video: "+P),T(),d()})},10)})},pause:()=>{if(!t.current)throw c();t.current.pause()},resume:()=>{if(!t.current)throw c();return t.current.play()},stop:()=>{if(!t.current)throw c();t.current.pause(),t.current.dispatchEvent(new Event("stopped"))},seek:p=>{if(!t.current)throw c();t.current.currentTime=p}}))},f=[];return r.addEventListener("canplay",l),()=>{a=!1,r.removeEventListener("canplay",l),f.forEach(p=>p()),r.currentTime>0&&r.pause(),s.isStateMounted(e)&&s.unMountState(e)}},[s,e]);function i(){t.current&&(t.current.pause(),t.current.currentTime=0,t.current.dispatchEvent(new Event("stopped")))}return wa.createElement("video",{ref:t,src:e.config.src,preload:"auto",muted:e.config.muted,playsInline:!0,width:"100%",height:"100%",onContextMenu:r=>r.preventDefault()})}import Pa from"clsx";import Ur,{useEffect as Kr,useState as Ea}from"react";function vi({children:s,className:e,gameState:t}){let[n,o]=Ea({}),{ratio:i}=Z(),r=w(),[a]=B(),c=r.config.minWidth,l=r.config.minHeight;return Kr(()=>{t.logger.debug("AspectRatio","mount, using interval",r.config.ratioUpdateInterval);let f=()=>{if(i.isLocked()){t.logger.weakWarn("Ratio is locked, skipping update");return}let u=document.getElementById(r.config.contentContainerId);if(u){let C=u.clientWidth,T=u.clientHeight,P=r.config.aspectRatio,m,y;C/T>P?(m=T*P,y=T):(m=C,y=C/P),m<c&&(m=c),y<l&&(y=l),o({width:`${m}px`,height:`${y}px`,margin:"auto",position:"absolute",top:"0",bottom:"0",left:"0",right:"0",display:"flex",alignItems:"center",justifyContent:"center"});let N=m/r.config.width;i.update(m,y,N),i.updateMin(c,l),a()}};i.setUpdate(f);let d=Gi(()=>{f()},r.config.ratioUpdateInterval);d(),window.addEventListener("resize",d);let g=i.onRequestedUpdate(d);return()=>{window.removeEventListener("resize",d),g()}},[i,r.config.ratioUpdateInterval]),Kr(()=>t.events.on(K.EventTypes["event:state.player.requestFlush"],a).cancel,[t]),Ur.createElement("div",{id:r.config.contentContainerId,style:{position:"relative",width:"100%",height:"100%",overflow:"hidden"}},Ur.createElement("div",{className:Pa(e),style:n},s))}import Fr,{useEffect as Da,useRef as Ra,useState as Or}from"react";function Ci({src:s,width:e,height:t}){let[n,o]=Or({x:0,y:0}),[i,r]=Or(!1),a=Ra(null),{ratio:c}=Z();return Da(()=>{let l=f=>{if(a.current){let p=a.current.getBoundingClientRect(),d=f.clientX-p.left,g=f.clientY-p.top;o({x:d,y:g}),i||r(!0)}};return window.addEventListener("mousemove",l),()=>{window.removeEventListener("mousemove",l)}},[i]),Fr.createElement(Ze,{ref:a,className:"overflow-hidden absolute"},Fr.createElement("img",{src:s,style:{position:"absolute",left:n.x,top:n.y,width:e,height:t,pointerEvents:"none",zIndex:1001,display:i?"block":"none",cursor:"none",transform:`scale(${c.state.scale})`},alt:""}))}import Wr from"react";import ut from"react";function xi({error:s,errorInfo:e}){return w().config.app.debug?ut.createElement("div",{className:"text-left"},ut.createElement("h1",null,"NarraLeaf-React cannot initialize the player correctly. (development mode)"),ut.createElement("p",{className:"text-red-700"},"Message: ",s.message),ut.createElement("pre",null,"Error Stack: ",s?.stack),ut.createElement("pre",null,"Component Stack: ",e?.componentStack),ut.createElement("pre",null,"Digest: ",e?.digest)):ut.createElement("div",{className:"bg-white w-full h-full"},ut.createElement("h1",null,"NarraLeaf-React crashed due to an unknown error."),ut.createElement("p",null,"Please contact the game developer for further assistance."))}var Io=class extends Wr.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?Wr.createElement(xi,{error:this.state.error,errorInfo:this.state.errorInfo}):this.props.children}};import $r from"clsx";import j,{useEffect as vn,useReducer as Ga,useState as Cn}from"react";import{flushSync as Br}from"react-dom";import{useRef as La}from"react";import{useEffect as Ia}from"react";function Vr({gameState:s}){let e=La(null);return Ia(()=>(e.current=requestAnimationFrame(()=>{setTimeout(()=>{s.events.emit(K.EventTypes["event:state.onRender"])},0)}),()=>{e.current!==null&&cancelAnimationFrame(e.current)}),[s.deps]),null}import An,{useEffect as Ma}from"react";function wi({gameState:s}){let[e]=B(),{ratio:t}=Z(),n=s.notificationMgr;Ma(()=>n.onFlush(()=>{e()}).cancel,[]);let o=s.game.config.notification;return An.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"},An.createElement(o,{notifications:n.toArray()}))}function zr({notifications:s}){return An.createElement(To,{className:"absolute top-0 left-0 w-full h-full"},s.map(({id:e,message:t})=>An.createElement("div",{key:e,className:"absolute top-0 left-0 w-[100px] h-[80px]"},An.createElement("span",{className:"text-white text-2xl font-bold"},t))))}function jr({story:s=cn.empty(),width:e,height:t,className:n,onReady:o,onEnd:i,onError:r,children:a,active:c=!0}){let[l,f]=Ga(oe=>oe+1,0),[p,d]=Cn(0),g=w(),[u]=Cn(()=>new K(g,{update:f,forceUpdate:()=>{u.logger.weakWarn("Player","force update"),Br(()=>{f()})},forceRemount:()=>{u.logger.weakWarn("Player","force remount"),Br(()=>{d(oe=>oe+1),f()})},next:Fe})),C=j.createRef(),T=j.createRef(),[P,m]=Cn(!1),y=j.useRef(!1),N=j.useRef(null),ye=j.useRef(null),{preloaded:et}=$t(),[Gt,Ke]=Cn(!1),[At]=Cn(new Map);function Fe(){let oe=()=>{At.forEach(x=>x.cancel())};if(u.rollLock.isLocked())return;oe();let k=!1,V=0;for(;!k;){if(V++>g.config.maxStackModelLoop)throw new A("Max stack model loop reached");let x=g.getLiveGame().next();if(!x){if(g.getLiveGame().stackModel&&!g.getLiveGame().stackModel.isEmpty())continue;break}if(h.isAwaitable(x)){if(N.current===x)break;N.current=x,x.onSettled(()=>{N.current===x&&(N.current=null),Fe()}),k=!0;break}if(x instanceof Ht){if(ye.current===x)break;ye.current=x,x.nextUnlock().then(()=>{ye.current===x&&(ye.current=null),Fe()}),k=!0;break}if(De.isCalledActionResult(x)&&x.wait&&De.isStackModelsAwaiting(x.wait.type,x.wait.stackModels)){if(N.current===x)break;N.current=x,x.wait&&De.executeStackModelGroup(x.wait.type,x.wait.stackModels).then(()=>{N.current===x&&(N.current=null),Fe()}),k=!0;break}u.handle(x)}u.stage.update()}vn(()=>(g.getLiveGame().setGameState(u),s&&!g.getLiveGame().isPlaying()&&g.getLiveGame().loadStory(s),u.playerCurrent=C.current,u.mainContentNode=T.current,()=>{g.getLiveGame().setGameState(void 0),u.playerCurrent=null}),[g,s]),vn(()=>Me(()=>{m(!0);let oe=u.getLastScene(),k=[];oe?k.push(oe.events.once("event:scene.mount",()=>{u.stage.next()}).cancel):u.stage.next();let V=u.events.on(K.EventTypes["event:state.end"],()=>{i&&i({game:g,gameState:u,liveGame:g.getLiveGame(),storable:g.getLiveGame().getStorable()})});return u.stage.update(),()=>{oe&&k.forEach(x=>x()),V.cancel()}}),[]),vn(()=>Me(()=>{P&&o&&!y.current&&(y.current=!0,u.stage.forceUpdate(),g.hooks.trigger("init",[]),o({game:g,gameState:u,liveGame:g.getLiveGame(),storable:g.getLiveGame().getStorable()}))}),[P]),vn(()=>et.events.depends([et.events.on(Le.EventTypes["event:preloaded.ready"],()=>{Ke(!0),u.stage.update(),s&&Fe()})]).cancel,[]),vn(()=>{u.flushDep=l},[l]);let dt=e||g.config.width,tt=t||g.config.height;return j.createElement(Io,{onError:r},j.createElement("div",{style:{width:typeof dt=="number"?`${dt}px`:dt,height:typeof tt=="number"?`${tt}px`:tt},className:$r(n,"__narraleaf_content-player"),ref:C,tabIndex:0},j.createElement(vi,{className:$r("flex-grow overflow-auto"),gameState:u},j.createElement(li,{ref:C}),j.createElement(ci,{gameState:u}),j.createElement(Vr,{gameState:u}),j.createElement(Ze,{className:"absolute",ref:T,style:{cursor:u.game.config.cursor?"none":"auto",overflow:u.game.config.showOverflow?"visible":"hidden"}},g.config.cursor&&j.createElement(Ci,{src:g.config.cursor,width:g.config.cursorWidth,height:g.config.cursorHeight}),j.createElement(Na,{show:Gt&&c,key:p},j.createElement(br,{state:u}),u.getSceneElements().map(oe=>j.createElement(Si,{key:"scene-"+oe.scene.getId(),state:u,elements:oe})),u.getVideos().map((oe,k)=>j.createElement("div",{className:"w-full h-full absolute",key:"video-"+k,"data-element-type":"video"},j.createElement(Ai,{gameState:u,video:oe})))),j.createElement(Cr,{state:u}),j.createElement(yr,null,a),j.createElement(wi,{gameState:u})))))}function Na({children:s,show:e}){return j.createElement(j.Fragment,null,e?s:null)}import"client-only";import Qt from"react";function qr({children:s,game:e}){return Qt.createElement(Qt.Fragment,null,Qt.createElement(tr,null,Qt.createElement(Yi,{game:e},Qt.createElement(vr,null,Qt.createElement(er,null,s)))))}var Ha=(i=>(i.image="narraleaf:image",i.text="narraleaf:text",i.layer="narraleaf:layer",i.scene="narraleaf:scene",i.video="narraleaf:video",i))(Ha||{});import Ua from"clsx";import Mt,{useEffect as Qr,useRef as Ka}from"react";function Fa({children:s,...e}){let t=w(),n=lt(),{ratio:o}=Z(),[i]=$e(Q.Preferences.showDialog),r=Ka(null),[a]=Tn("nextAction");function c(){n.requestComplete()}return Qr(()=>{if(!window){console.warn(`Failed to add event listener, window is not available
63
+ at Say.tsx: onElementClick`);return}let l=p=>{t.keyMap.match("nextAction",p.key)&&n.requestComplete()};window.addEventListener("keyup",l);let f=n.events.on(Re.Events.simulateClick,()=>{r.current&&r.current.click()});return()=>{window.removeEventListener("keyup",l),f.cancel()}},[n,a]),Qr(()=>{let l=t.preference.onPreferenceChange(Q.Preferences.autoForward,f=>{f&&n.isEnded()?n.tryScheduleAutoForward():n.cancelAutoForward()});return()=>{l.cancel()}},[n]),Mt.createElement("div",{"data-element-type":"dialog",className:"w-full h-full"},Mt.createElement("div",{className:Ua("absolute bottom-0 w-full h-full",!i&&"invisible pointer-events-auto"),onClick:c,style:{...Fn(t.config.useAspectScale,{maxWidth:t.config.dialogWidth,maxHeight:t.config.dialogHeight,transform:`scale(${o.state.scale})`,transformOrigin:"bottom left",width:t.config.width,height:t.config.height})},ref:r},Mt.createElement("div",{...e},s)))}function Xr({children:s,...e}){let t=lt();return!t.config.action.sentence||!t.config.action.words?null:Mt.createElement(Fa,{...e},s)}var la=Xr;function Jr(){return Mt.createElement(Xr,null,Mt.createElement(bo,null),Mt.createElement(ni,null))}var Mo={say:Jr,menu:xr,notification:zr};var Go=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 xn=class{constructor(e={}){this.keyMap=e;this.events=new F}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)??[],o=i=>Array.isArray(i)?i:[i];Array.isArray(n)?this.setKeyBinding(e,[...n,...o(t)]):this.setKeyBinding(e,[n,...o(t)])}getKeyBindings(){return this.keyMap}onKeyBindingChange(e,t){return this.events.on("event:keyMap.change",(n,o)=>{n===e&&t(o)})}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(o=>o.toLowerCase()===t.toLowerCase()):n===t||n.toLowerCase()===t.toLowerCase()}};var Yr=(e=>(e.game="game",e))(Yr||{}),pt=class pt{constructor(e){this.hooks=new Nn;this.liveGame=null;this.sideEffect=[];this.freezeFields=[];this.preference=new pn(pt.DefaultPreference);this.keyMap=new xn({skipAction:["Control"],nextAction:[" "]});this.config=R(pt.DefaultConfig,e),this.plugins=new Go(this),this.router=new St(this)}configure(e){let[t,n]=Vi(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=R(this.config,t),this.getLiveGame().getGameState()?.events.emit(K.EventTypes["event:state.player.requestFlush"]),this}configureAndFreeze(e){return this.configure(e),this.freeze(Object.keys(e)),this}freeze(e){return this.freezeFields.push(...e),this}use(e){return this.plugins.has(e)||this.plugins.use(e).register(e),this}getLiveGame(){if(!this.liveGame){let e=this.createLiveGame();return this.liveGame=e,e}return this.liveGame}dispose(){this.plugins.unregisterAll(),this.liveGame?.dispose(),this.sideEffect.forEach(e=>e())}addSideEffect(e){this.sideEffect.push(e)}createLiveGame(){return new Tt(this)}};pt.defaultSettings={volume:1},pt.DefaultPreference={autoForward:!1,skip:!0,showDialog:!0,gameSpeed:1,cps:10,voiceVolume:1,bgmVolume:1,soundVolume:1,globalVolume:1,skipDelay:500,skipInterval:100},pt.Preferences={autoForward:"autoForward",skip:"skip",showDialog:"showDialog",gameSpeed:"gameSpeed",cps:"cps",voiceVolume:"voiceVolume",bgmVolume:"bgmVolume",soundVolume:"soundVolume",globalVolume:"globalVolume",skipDelay:"skipDelay",skipInterval:"skipInterval"},pt.DefaultConfig={app:{debug:!1,logger:{log:!1,info:!1,warn:!0,error:!0,debug:!1,trace:!1,verbose:!1},inspector:!1,guard:{invalidExposedStateUnmounting:!0,unexpectedTimelineStatusChange:!0}},contentContainerId:"__narraleaf_content",aspectRatio:16/9,minWidth:800,minHeight:450,width:1920,height:1080,useWindowListener:!0,ratioUpdateInterval:50,preloadDelay:100,preloadConcurrency:5,waitForPreload:!0,preloadAllImages:!0,forceClearCache:!1,maxPreloadActions:10,cursor:null,cursorHeight:30,cursorWidth:30,showOverflow:!1,maxRouterHistory:10,screenshotQuality:1,useAspectScale:!0,autoForwardDelay:3*1e3,autoForwardDefaultPause:1e3,allowSkipImageTransform:!0,allowSkipImageTransition:!0,allowSkipBackgroundTransform:!0,allowSkipBackgroundTransition:!1,allowSkipTextTransform:!0,allowSkipTextTransition:!0,allowSkipLayersTransform:!0,allowSkipVideo:!1,animationPropagate:!1,dialogWidth:1920,dialogHeight:1080*.2,defaultTextColor:"#000",defaultNametagColor:"#000",notification:Mo.notification,menu:Mo.menu,dialog:Mo.say,onError:e=>{console.error(e)},fontSize:16,fontWeight:400,fontWeightBold:700,fontFamily:"sans-serif",stage:null,defaultMenuChoiceColor:"#000",maxStackModelLoop:1e3,maxActionHistory:100},pt.GameSettingsNamespace=Yr;var Q=pt;var ki=class s extends ot{constructor(t,n){super();this.duration=t;this.easing=n}createTask(){return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(t=>({style:{opacity:1-t}})),this.asTarget(t=>({style:{opacity:t}}))]}}copy(){return new s(this.duration,this.easing)}};var Pi=class s extends ot{constructor(t,n=[0,0],o){super();this.duration=t;this.startPos=n;this.easing=o}createTask(t){return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing},{type:0,start:this.startPos[0],end:0,duration:this.duration,ease:this.easing},{type:0,start:this.startPos[1],end:0,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(()=>({})),this.asTarget((n,o,i)=>({style:{opacity:n,...b.offset(["50%","50%"],[o,i],t.getStory().getInversionConfig()),transform:"translate(-50%, 50%)"}}))]}}copy(){return new s(this.duration,this.startPos,this.easing)}};var Ei=class extends ln{constructor(){super();this.unlocked={};this.setupActions()}serialize(){return{unlocked:this.unlocked}}deserialize(t){this.unlocked=t.unlocked}add(t,n){return this.trigger("add",t,n)}has(t){return new G(()=>this.unlocked[t]!==void 0)}remove(t){return this.trigger("remove",t)}clear(){return this.trigger("clear")}$remove(t){delete this.unlocked[t]}$clear(){this.unlocked={}}$get(t){return this.unlocked[t]}$set(t,n){this.unlocked[t]=n}$getAll(){return this.unlocked}$has(t){return this.unlocked[t]!==void 0}setupActions(){this.on("add",(t,n,o)=>{let i={gameState:t.gameState,game:t.game,liveGame:t.liveGame,storable:t.storable,$:t.$},r=typeof o=="function"?o(i):o;this.unlocked[n]=r}),this.on("remove",(t,n)=>{delete this.unlocked[n]}),this.on("clear",t=>{this.$clear()})}};if(typeof document<"u"){let s=document.createElement("style");s.textContent=`/*! tailwindcss v4.1.8 | MIT License | https://tailwindcss.com */
64
64
  @layer properties{@supports ((-webkit-hyphens:none) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial}}}.invisible{visibility:hidden}.visible{visibility:visible}.absolute{position:absolute}.relative{position:relative}.static{position:static}.z-20{z-index:20}.container{width:100%}.\\!hidden{display:none!important}.block{display:block}.contents{display:contents}.flex{display:flex}.hidden{display:none}.inline-block{display:inline-block}.h-\\[80px\\]{height:80px}.h-full{height:100%}.h-max{height:-moz-max-content;height:max-content}.w-1\\/2{width:50%}.w-\\[100px\\]{width:100px}.w-full{width:100%}.w-max{width:-moz-max-content;width:max-content}.min-w-full{min-width:100%}.flex-grow{flex-grow:1}.transform{transform:var(--tw-rotate-x,)var(--tw-rotate-y,)var(--tw-rotate-z,)var(--tw-skew-x,)var(--tw-skew-y,)}.resize{resize:both}.flex-col{flex-direction:column}.items-center{align-items:center}.justify-center{justify-content:center}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.border{border-style:var(--tw-border-style);border-width:1px}.border-2{border-style:var(--tw-border-style);border-width:2px}.text-center{text-align:center}.text-left{text-align:left}.align-bottom{vertical-align:bottom}.break-all{word-break:break-all}.whitespace-pre-wrap{white-space:pre-wrap}.italic{font-style:italic}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.invert{--tw-invert:invert(100%);filter:var(--tw-blur,)var(--tw-brightness,)var(--tw-contrast,)var(--tw-grayscale,)var(--tw-hue-rotate,)var(--tw-invert,)var(--tw-saturate,)var(--tw-sepia,)var(--tw-drop-shadow,)}.filter{filter:var(--tw-blur,)var(--tw-brightness,)var(--tw-contrast,)var(--tw-grayscale,)var(--tw-hue-rotate,)var(--tw-invert,)var(--tw-saturate,)var(--tw-sepia,)var(--tw-drop-shadow,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,visibility,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,ease);transition-duration:var(--tw-duration,0s)}.__narraleaf_content-player *{-webkit-user-select:none;-moz-user-select:none;user-select:none}.__narraleaf_content-player img{pointer-events:none;-webkit-user-drag:none;-webkit-user-select:none}.__narraleaf_content-player .pointer-disabled{pointer-events:none}.__narraleaf_content-player .pointer-disabled>:not(.pointer-disabled){pointer-events:auto}.__narraleaf_content-player img:before,.__narraleaf_content-player img:after{content:none!important;border:none!important}.pointer-events-auto{pointer-events:auto}.pointer-events-none{pointer-events:none}.bottom-0{bottom:0}.left-0{left:0}.right-0{right:0}.top-0{top:0}.bg-cover{background-size:cover}.bg-center{background-position:50%}.pointer-events-auto-rest *{pointer-events:auto}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}\r
65
- `,document.head.appendChild(s)}export{xt as Align,jn as Character,Ne as CommonPosition,_t as CommonPositionType,$o as Condition,Ve as Control,Ae as Coord2D,la as Dialog,ki as Dissolve,Ha as ExposedStateType,Pi as FadeIn,Ei as Gallery,Q as Game,uo as GameMenu,qr as GameProviders,K as GameState,I as Image,ot as ImageTransition,Ze as Isolated,ho as Item,Sn as KeyBindingType,xn as KeyMap,H as Lambda,Wt as Layer,ea as Layout,yn as LayoutRouterProvider,Tt as LiveGame,Bo as Menu,rt as Namespace,bo as Nametag,To as Notifications,ra as Page,si as PageInjectContext,Se as Pause,Ft as Persistent,jr as Player,pn as Preference,_i as RootPath,Ee as Scene,we as Script,ne as Sentence,ln as Service,ve as Sound,As as Stage,an as Storable,cn as Story,Dt as Text,rn as TextTransition,Hs as Texts,O as Transform,Qe as Transition,Qo as Video,U as Word,rs as b,is as c,ss as i,zs as useDialog,w as useGame,Tn as useKeyBinding,ca as useLiveGame,Qs as useParams,qs as usePathname,$e as usePreference,Xs as useQueryParams,Ye as useRouter};
65
+ `,document.head.appendChild(s)}export{xt as Align,jn as Character,Ne as CommonPosition,_t as CommonPositionType,$o as Condition,Ve as Control,Ae as Coord2D,la as Dialog,ki as Dissolve,Ha as ExposedStateType,Pi as FadeIn,Ei as Gallery,Q as Game,uo as GameMenu,qr as GameProviders,K as GameState,I as Image,ot as ImageTransition,Ze as Isolated,ho as Item,Sn as KeyBindingType,xn as KeyMap,G as Lambda,Wt as Layer,ea as Layout,yn as LayoutRouterProvider,Tt as LiveGame,Bo as Menu,rt as Namespace,bo as Nametag,To as Notifications,ra as Page,si as PageInjectContext,Se as Pause,Ft as Persistent,jr as Player,pn as Preference,_i as RootPath,Ee as Scene,we as Script,ne as Sentence,ln as Service,ve as Sound,As as Stage,an as Storable,cn as Story,Dt as Text,rn as TextTransition,Hs as Texts,O as Transform,Qe as Transition,Qo as Video,U as Word,rs as b,is as c,ss as i,zs as useDialog,w as useGame,Tn as useKeyBinding,ca as useLiveGame,Qs as useParams,qs as usePathname,$e as usePreference,Xs as useQueryParams,Ye as useRouter};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "narraleaf-react",
3
- "version": "0.8.5",
3
+ "version": "0.8.6",
4
4
  "description": "A React visual novel player framework",
5
5
  "main": "./dist/main.js",
6
6
  "types": "./dist/index.d.ts",