UNPKG

narraleaf-react

Version:

A React visual novel player framework

6 lines 229 kB
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"},Eo={action:"condition:action"},Do={action:"script:action"},Ro={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"},Ve={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"},Yt={action:"persistent:action",set:"persistent:set",assign:"persistent:assign"},Ct={action:"layer:action",setZIndex:"layer:setZIndex"},Ht={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 Lo=(p=>(p[p.string=0]="string",p[p.number=1]="number",p[p.boolean=2]="boolean",p[p.object=3]="object",p[p.array=4]="array",p[p.function=5]="function",p[p.symbol=6]="symbol",p[p.undefined=7]="undefined",p[p.null=8]="null",p[p.date=9]="date",p[p.regexp=10]="regexp",p[p.other=11]="other",p))(Lo||{}),Ni=function(o){return typeof o=="string"?0:typeof o=="number"?1:typeof o=="boolean"?2:typeof o=="object"?Array.isArray(o)?4:o===null?8:o instanceof Date?9:o instanceof RegExp?10:3:typeof o=="function"?5:typeof o=="symbol"?6:typeof o>"u"?7:11};Ni.DataTypes=Lo;function R(o,e,...t){let n=(s,a)=>Object.prototype.hasOwnProperty.call(s,a),i={},r=(s,a,c)=>Ni(a)===3&&Ni(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 s in o)n(o,s)&&(i[s]=r(s,o[s],e[s]));for(let s in e)n(e,s)&&!n(i,s)&&(typeof e[s]=="object"&&e[s]!==null?e[s].constructor===Object?i[s]=R({},e[s]):Array.isArray(e[s])?i[s]=[...e[s]]:i[s]=e[s]:i[s]=e[s]);if(t.length){let[s,...a]=t;return R(i,s,...a)}return i}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=Gi()}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(i=>{e.forEach(r=>{r!==n&&r.skipController?.abort()}),t.resolve(i)})}),t.registerSkipController(new I(()=>{e.forEach(n=>n.skipController?.abort())})),t)}static forward(e,t,n){let i=new Te().registerSkipController(n||new I(()=>t));e.then(()=>i.resolve(t));let r=e.skipController?.onAbort(()=>{i.skipController?.abort(),r?.cancel(),s?.cancel()}),s=i.skipController?.onAbort(()=>{e.skipController?.abort(),r?.cancel(),s?.cancel()});return i}static toPromise(e){return new Promise(t=>{e.then(t)})}static toPromiseForce(e){return new Promise(t=>{e.onSettled(t)})}static any(...e){let t=new Te;return e.forEach(n=>{n.onSettled(()=>t.resolve())}),t}static all(...e){let t=new Te,n=0;return e.forEach(i=>{i.onSettled(()=>{n++,n===e.length&&t.resolve()})}),t}registerSkipController(e){this.skipController=e;for(let t of this.onRegisterSkipController)t(e);return this}resolve(e){if(!this.solved){this.result=this.receiver(e),this.solved=!0,this.skipController&&this.skipController.cancel();for(let t of this.listeners)t(this.result)}}then(e){return this.solved?e(this.result):this.pushListener(e),this}onSettled(e){if(this.solved)e();else{this.pushListener(e);let t=[];return t.push(this.onSkipControllerRegister(n=>{t.push(n.onAbort(()=>{e()}))})),{cancel:()=>{t.forEach(n=>n.cancel()),this.offListener(e)}}}return{cancel:()=>{}}}onSkipControllerRegister(e){return this.skipController?e(this.skipController):this.onRegisterSkipController.push(e),{cancel:()=>{this.offSkipControllerRegister(e)}}}offSkipControllerRegister(e){let t=this.onRegisterSkipController.indexOf(e);return t!==-1&&this.onRegisterSkipController.splice(t,1),this}abort(){return this.aborted=!0,this.skipController?this.skipController.abort():this.result}isSolved(){return this.solved&&!this.aborted}isAborted(){return this.aborted}isSettled(){return this.solved||this.aborted}pushListener(e){return this.listeners.length>=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 g=Te;function Io(o){let e=new WeakSet;function t(n){if(n===null||typeof n!="object")return n;if(e.has(n))return;if(e.add(n),Array.isArray(n)){let r=[];for(let s of n)r.push(t(s));return r}let i={};for(let r in n)Object.prototype.hasOwnProperty.call(n,r)&&(i[r]=t(n[r]));return i}return t(o)}function xt(o){return typeof o=="string"?o:`#${(o.r||0).toString(16).padStart(2,"0")}${(o.g||0).toString(16).padStart(2,"0")}${(o.b||0).toString(16).padStart(2,"0")}${o.a===void 0?"":o.a.toString(16).padStart(2,"0")}`}var 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(i=>{i(...t)}),n}once(e,t){let n=(...i)=>{t(...i),this.off(e,n)};return this.on(e,n)}async any(e,...t){if(this.events[e]||(this.events[e]=[]),this.events[e].length>0){await Promise.all(this.events[e].map(n=>n(...t)));return}return new Promise(n=>{let i="event:EventDispatcher.register",r=this.on(i,(s,a)=>{if(s===e){this.off(i,r);let c=a?.(...t);c!==null&&typeof c=="object"&&c.then?c.then(n):n(c)}}).listener})}setMaxListeners(e){return this.maxListeners=e,this}hasListeners(e){return this.events[e]?.length>0}clear(){this.events={}}};function Gi(o=1){let e=new Error().stack;return e?e.split(` `).slice(o+1).join(` `).trim():""}function Kn(o){return new Promise(e=>setTimeout(e,o))}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 I=Un;var Zt=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}},Ut=class{constructor(){this.locks=[]}unlock(e){return e.unlock(),this.off(e),e}register(e){let t=e||new Zt;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(o,e,t={}){return o?e:t}function Mo(o,e){if(e<=0)return o;let t=null;return function(...n){t&&clearTimeout(t),t=setTimeout(()=>{o(...n)},e)}}var In=class{constructor(){this.taskToken=null}scheduleTask(e,t){this.taskToken&&this.taskToken.cancel();let n=!1,i=setTimeout(()=>{n||e()},t);return this.taskToken={cancel:()=>{clearTimeout(i),n=!0},isCancelled:()=>n},this.taskToken}cancelTask(){return this.taskToken&&(this.taskToken.cancel(),this.taskToken=null),this}};function No(o,e){let t=[];for(let n=0;n<Math.max(o.length,e.length);n++)n<o.length&&t.push(o[n]),n<e.length&&t.push(e[n]);return t}async function Go(o,e){return new Promise((t,n)=>{fetch(o,e).then(i=>i.blob()).then(i=>{let r=new FileReader;r.onload=()=>{t(r.result)},r.readAsDataURL(i)}).catch(n)})}var _t=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(o){let e,t=Promise.resolve().then(()=>{e=o()});return()=>{t.then(()=>{e&&e()})}}function Ho(o,e){let t={};for(let n in o)e.includes(n)||(t[n]=o[n]);return t}var be=class o{constructor(e={},t={}){this.serializer=e;this.deserializer=t}serialize(e){let t={};for(let n of Object.keys(e))n in this.serializer&&e[n]!==void 0?t[n]=this.serializer[n]?.(e[n]):t[n]=e[n];return t}deserialize(e){let t={};for(let n of Object.keys(e))typeof this.deserializer[n]=="function"&&e[n]!==void 0?t[n]=this.deserializer[n](e[n]):t[n]=e[n];return t}extend(e,t){let n={...this.serializer,...e},i={...this.deserializer,...t};return new o(n,i)}};function Uo(o){return["aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkgrey","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkslategrey","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dimgrey","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","green","greenyellow","grey","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightgrey","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightslategrey","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","slategrey","snow","springgreen","steelblue","tan","teal","thistle","tomato","transparent","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen"].includes(o)}function Ko(o){return o.constructor.name==="AsyncFunction"||Object.prototype.toString.call(o)==="[object AsyncFunction]"}function Hi(o){let e={};for(let t in o)o[t]!==void 0&&(e[t]=o[t]);return e}function Ui(o,e=new WeakSet){if(o===null||typeof o!="object"||Array.isArray(o)||o instanceof Date||o instanceof RegExp||Object.getPrototypeOf(o)!==Object.prototype||e.has(o))return!1;e.add(o);for(let t in o)if(Object.prototype.hasOwnProperty.call(o,t)){let n=o[t];if(n!==null&&typeof n=="object"&&!Ui(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 Fo(o=16){let e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=t.length;for(let i=0;i<o;i++)e+=t.charAt(Math.floor(Math.random()*n));return e}function Vo(o=16){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",t="";for(let n=0;n<o;n++)t+=e[Math.floor(Math.random()*e.length)];return t}var Nn=class{constructor(e=""){this.prefix=e;this.counter=0}generateId(){return`${this.prefix?this.prefix+"-":""}${this.counter++}`}},Gn=class{constructor(){this.hooks={}}hook(e,t){return this.hooks[e]=this.hooks[e]||[],this.hooks[e].push(t),{cancel:()=>this.unhook(e,t)}}unhook(e,t){this.hooks[e]=this.hooks[e]?.filter(n=>n!==t)||[]}trigger(e,t){let n=this.hooks[e];if(!n)return()=>{};let i=n.map(r=>r(...t));return()=>{i.forEach(r=>r&&r())}}rawTrigger(e,t){let n=this.hooks[e];if(!n)return()=>{};let i=n.map(r=>r(...t()));return()=>{i.forEach(r=>r&&r())}}};var 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 Oo(o,e){let t={},n=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&(e.includes(i)?n.push(i):t[i]=o[i]);return[t,n]}function Wo(o){let e=3421674724,t=2216829733;for(let n=0;n<o.length;n++){let i=o.charCodeAt(n);e^=i;let r=e>>>0,s=t>>>0,a=435,c=16777216,l=r*a>>>0,f=r*c+s*a>>>0,d=s*c+(f>>>0)>>>0;e=l,t=d}return("00000000"+t.toString(16)).slice(-8)+("00000000"+e.toString(16)).slice(-8)}var en=class{constructor(e,t,n){this.callee=e,this.type=t,this.contentNode=n,this.__stack=Gi(),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]:[]}};en.ActionTypes={action:"action"};var M=class extends en{constructor(e,t,n){super(e,t,n),this.callee=e.getSelf(),this.contentNode.action=this}unknownTypeError(){throw new Error("Unknown action type: "+this.type)}resolveAwaitable(e,t){let n=t||new g(i=>i);return(async()=>await e(n.resolve.bind(n),n))(),n}is(e,t){return this instanceof e&&this.type===t}stringify(e,t,n){return this.stringifyWithName("Action")}stringifyWithName(e){return`${e}#${this._id}(${this.type})`}stringifyWithContent(e,t){return`${e}#${this._id}(${this.type}){${t}}`}};var Ki=class{constructor(e){this.type=e,this.content=void 0}setContent(e){return this.content=e,this}getContent(){return this.content}},T=class o extends Ki{static create(e){return new o().setContent(e)}static forEachParent(e,t){let n=new Set,i=e;for(;i&&!n.has(i);)n.add(i),t(i),i=i.getParent()}static forEachChild(e,t){let n=new Set,i=e;for(;i&&!n.has(i);)n.add(i),t(i),i=i.getChild()}constructor(e,t,n){super("ContentNode"),this.child=n||null,this.parent=t||null,this.action=e||null}setParent(e){if(e===this)throw new Error("Cannot set parent to itself");return this.parent&&this.parent.setChild(null),this.parent=e,this}setChild(e){if(e===this)throw new Error("Cannot set child to itself");return this.child&&(this.child.parent=null),this.child=e,e&&e.parent!==this&&(e.remove(),e.parent=this),this}getChild(){return this.child||null}getParent(){return this.parent||null}addChild(e){return this.setChild(e),this}removeChild(e){return e&&this.child===e?(this.child=null,e.setParent(null)):e||(this.child=null),this}remove(){return this.parent&&this.parent.removeChild(this),this.child&&this.child.setParent(null),this}hasChild(){return!!this.child}};var Vn={center:"center",left:"left",right:"right"};import{animate as os}from"motion/react";var tn=(n=>(n.Left="left",n.Center="center",n.Right="right",n))(tn||{}),zo={left:"33.33%",center:"50%",right:"66.66%"},Ne=class Ne{static isUnknown(e){return e===Ne.Unknown}static D2PositionToCSS(e,t=!1,n=!1){let i=this.calc(e.y,e.yoffset),r=this.calc(e.x,e.xoffset),s=n?{bottom:i}:{top:i},a=t?{right:r}:{left:r};return this.wrap({...s,...a})}static calc(e,t){return!e||Ne.isUnknown(e)?"auto":t===void 0||Ne.isUnknown(t)?`calc(${e} + 0px)`:`calc(${typeof e=="number"?`${e}px`:e} + ${t}px)`}static toCoord2D(e){if(Ge.isCommonPositionType(e))return ve.fromCommonPosition(e);if(ve.isCoord2DPosition(e))return e;if(wt.isAlignPosition(e))return ve.fromAlignPosition(e);if(typeof e=="object"&&["x","y","xoffset","yoffset"].some(t=>t in e)){let t=e;return new ve(t)}else throw new Error("Invalid position type")}static orUnknown(e){return Ne.isUnknown(e)||e===void 0?Ne.Unknown:e}static mergePosition(e,t){let n=this.toCoord2D(e),i=this.toCoord2D(t);return ve.merge(n,i)}static serializePosition(e){let t=this.toCoord2D(e);return{x:Ne.isUnknown(t.x)?0:t.x,y:Ne.isUnknown(t.y)?0:t.y,xoffset:Ne.isUnknown(t.xoffset)?0:t.xoffset,yoffset:Ne.isUnknown(t.yoffset)?0:t.yoffset}}static isRawCommonPositionType(e){return Object.values(tn).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 Ge||e instanceof ve||e instanceof wt}static rawPositionToCoord2D(e){if(this.isRawCommonPositionType(e))return ve.fromCommonPosition(new Ge(e));if(this.isRawCoord2DPosition(e))return new ve(e);if(this.isRawAlignPosition(e))return ve.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}}};Ne.Unknown=Symbol("Unknown");var A=Ne,On=class On{static isCommonPositionType(e){return e instanceof On}constructor(e){this.position=e}toCSS(){return{x:zo[this.position],y:"50%",xoffset:0,yoffset:0}}};On.Positions=tn;var Ge=On,ve=class o{static isCoord2DPosition(e){return e instanceof o}static fromCommonPosition(e){return new o({x:zo[e.position],y:"50%"})}static fromAlignPosition(e){let t=n=>!n||A.isUnknown(n)?A.Unknown:`${n*100}%`;return new o({x:t(e.xalign),y:t(e.yalign),xoffset:e.xoffset,yoffset:e.yoffset})}static merge(e,t){return new o({x:A.isUnknown(t.x)?e.x:t.x,y:A.isUnknown(t.y)?e.y:t.y,xoffset:A.isUnknown(t.xoffset)?e.xoffset:t.xoffset,yoffset:A.isUnknown(t.yoffset)?e.yoffset:t.yoffset})}constructor(e,t){typeof e=="object"?(this.x=A.orUnknown(e.x),this.y=A.orUnknown(e.y),this.xoffset=A.orUnknown(e.xoffset),this.yoffset=A.orUnknown(e.yoffset)):(this.x=A.orUnknown(e),this.y=A.orUnknown(t),this.xoffset=A.Unknown,this.yoffset=A.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}}},wt=class o{static isAlignPosition(e){return e instanceof o}constructor(e,t){typeof e=="object"?(this.xalign=A.orUnknown(e.xalign),this.yalign=A.orUnknown(e.yalign),this.xoffset=A.orUnknown(e.xoffset),this.yoffset=A.orUnknown(e.yoffset)):(this.xalign=A.orUnknown(e),this.yalign=A.orUnknown(t),this.xoffset=A.Unknown,this.yoffset=A.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:A.isUnknown(this.xalign)?this.xalign:`${this.xalign*100}%`,y:A.isUnknown(this.yalign)?this.yalign:`${this.yalign*100}%`,xoffset:this.xoffset,yoffset:this.yoffset}}};var H=class o{constructor(e,t){this.defaultConfig=e;this.handlers=t||{}}create(e={}){return new Fi(this.mergeWithDefaultConfig(e))}copy(){return new o(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}},Fi=class o{constructor(e){this.config=e}get(){return this.config}copy(){return new o(R({},this.config))}join(e){let t=Ho(this.config,Object.keys(e));return new o(Object.assign(t,e instanceof o?e.get():e))}extract(e){let t={},n={};for(let i of e)t[i]=this.config[i];for(let i in this.config)e.includes(i)||(n[i]=this.config[i]);return[new o(t),new o(n)]}assign(e){return new o(Object.assign({},this.config,e))}};var rs={[Vn.left]:"25.33%",[Vn.center]:"50%",[Vn.right]:"75.66%"},Oe=class Oe{constructor(e={}){this.state={};this.locked=null;this.frozen=!1;this.state=e}static deserialize(e){return new Oe(Oe.TransformStateSerializer.deserialize(e))}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?A.toCoord2D(A.tryParsePosition(e||t)):A.mergePosition(A.tryParsePosition(e),A.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=Oe.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 Hi(V.constructStyle(e,this.state,t))}toStyle(e,t){return Hi(V.constructStyle(e,this.state,t))}serialize(){return Oe.TransformStateSerializer.serialize(this.state)}clone(){return new Oe(Oe.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=Oe.mergeState(this.state,t),this}forceOverwrite(e){return this.state=e,this}};Oe.DefaultTransformState=new H({scaleX:1,scaleY:1,zoom:1,rotation:0,position:new Ge("center"),opacity:0,alt:""}),Oe.TransformStateSerializer=new be({position:e=>A.serializePosition(A.tryParsePosition(e))},{position:e=>A.toCoord2D(e)});var re=Oe,oe=class oe{constructor(e,t){this.sequences=[];this.stagedChanges=[];if(Array.isArray(e))this.sequences.push(...e),this.config=Object.assign({},oe.defaultConfig,t||{});else{let[n,i]=[e,t||oe.defaultOptions];this.sequences.push({props:n,options:i||oe.defaultOptions}),this.config=Object.assign({},oe.defaultConfig)}}static isPosition(e){return Ge.isCommonPositionType(e)||ve.isCoord2DPosition(e)||wt.isAlignPosition(e)}static immediate(e){return new oe(e,{duration:0,ease:"linear"})}static left(e,t){return new oe({position:Ge.Positions.Left},{duration:e,ease:t})}static right(e,t){return new oe({position:Ge.Positions.Right},{duration:e,ease:t})}static center(e,t){return new oe({position:Ge.Positions.Center},{duration:e,ease:t})}static create(e){return new oe([],e)}static positionToCSS(e,t,n){return e?A.isRawPosition(e)?A.D2PositionToCSS(A.rawPositionToCoord2D(e),n,t):A.D2PositionToCSS(e.toCSS(),n,t):{}}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?A.toCoord2D(A.tryParsePosition(e||t)):A.mergePosition(A.tryParsePosition(e),A.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:i,invertX:r}=e.getStory().getInversionConfig(),{translate:s=[]}=n||{},a=t.zoom??1,c=function(p,h,u){return typeof p>"u"?typeof u<"u"?h(u):"":h(p)},l=s[0]||(r?"":"-")+"50%",f=s[1]||(i?"":"-")+"50%";return[`translate(${l}, ${f})`,c(t.rotation,p=>`rotate(${p}deg)`,0),c(t.scaleX,p=>`scaleX(${p*a})`,1),c(t.scaleY,p=>`scaleY(${p*a})`,1)].filter(Boolean).join(" ")}static constructStyle(e,t,n){let{invertY:i,invertX:r}=e.getStory().getInversionConfig(),{overwrite:s}=n||{};return{...oe.positionToCSS(t.position,i,r),opacity:t.opacity,color:"fontColor"in t&&t.fontColor?xt(t.fontColor):void 0,transform:oe.propToCSSTransform(e,t),...s?s(t):{}}}animate(e,{gameState:t,ref:n,overwrites:i}){if(!n.current)throw new Error("No ref found when animating.");this.commit();let{finalState:r,sequences:s,options:a}=this.constructAnimation({gameState:t,transformState:e,overwrites:i,current:n.current});s.length||t.logger.warn("Transform","No sequences to animate.");let c=!1,l=e.lock(),f=os(s,a),d=()=>{e.overwrite(l,r.get()).unlock(l),f.complete(),c=!0},p=new g().registerSkipController(new I(d)),h=()=>{c||e.overwrite(l,r.get()).unlock(l),c=!0,t.logger.debug("Transform","Transform Completed",e.toStyle(t,i)),p.resolve()};return f.then(h,u=>{t.logger.error("Failed to animate transform. "+(u?.toString?.()||""))}),f.play(),t.logger.debug("Transform","Ready to animate transform.",{finalState:r,sequences:s,options:a},this),p}repeat(e){let t=this.copy();return t.config.repeat||(t.config.repeat=1),t.config.repeat*=e,t}getOptions(e){if(!e)return{...oe.defaultOptions};let{duration:t,ease:n,delay:i,at:r}=e;return{duration:this.toSeconds(t,void 0),ease:n,delay:this.toSeconds(i,void 0),at:this.atToSeconds(r)}}constructAnimation({gameState:e,transformState:t,overwrites:n={},current:i}){let r=t.clone(),s=r.lock(),a=this.sequences.map(({props:c,options:l})=>{let f=r.assign(s,c).toFramesDefinition(e,n);return[i,f,this.getOptions(l)]});return{finalState:r.unlock(s).freeze(),sequences:a,options:this.getSequenceOptions()}}getSequenceOptions(){let{repeat:e,repeatDelay:t}=this.config;return{repeat:e,repeatDelay:this.toSeconds(t,void 0)}}copy(){return new oe(this.sequences,this.config)}commit(e){if(!this.stagedChanges.length)return this;let t=this.constructCommit(this.stagedChanges,this.getSequenceOptions());return this.sequences.push({props:t.props,options:{...this.getSequenceOptions(),...e}}),this.stagedChanges=[],this}zoom(e){return this.pushChange({key:"zoom",props:e})}scaleX(e){return this.pushChange({key:"scaleX",props:e})}scaleY(e){return this.pushChange({key:"scaleY",props:e})}scale(e,t){return this.pushChange({key:"scaleX",props:e}).pushChange({key:"scaleY",props:t})}rotation(e){return this.pushChange({key:"rotation",props:e})}position(e){return this.pushChange({key:"position",props:e})}opacity(e){return this.pushChange({key:"opacity",props:e})}fontColor(e){return this.pushChange({key:"fontColor",props:e})}constructCommit(e,t){let n={props:{},options:t};for(let i of e)n.props[i.key]=i.props;return n}pushChange(e){return this.stagedChanges.push(e),this}toSeconds(e,t){return typeof e>"u"?t:e/1e3}atToSeconds(e){if(typeof e>"u")return e;if(typeof e=="number")return e/1e3;let n=/^([+-])(\d+)$/.exec(e);if(!n)throw new X("Invalid at definition. At definition must be a number or a string in the format of `+n` or `-n`.");let[i,r,s]=n,a=Number(s);if(isNaN(a))throw new X("Invalid number in at definition.");let c=a/1e3;return r==="+"?`+${c}`:`-${c}`}};oe.defaultConfig={sync:!0},oe.defaultOptions={duration:0,ease:"linear"},oe.CommonImagePositionMap=rs;var V=oe;var jC={};var Wn=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 o{constructor(e,t){this.awaitable=e;this.guard=t;this.children=[];this._onResolved=[];this._onCancelled=[];this._onTimelineRegistered=[];this._ableToAttach=!0;this._status="pending";e.onSettled(()=>{this.resolveStatus()}),Me(()=>{this.preventAttach()})}static proxy(e){let t=new g,n=new g,i=new o(n);return i.onTimelineRegistered(()=>{n.resolve()}).onSettled(()=>{let[r,s]=i.catSettled();e(r,s)}),t.onSkipControllerRegister(r=>{r.onAbort(()=>{i.abort()})}),[t,i]}static any(e){if(e.length===0)throw new v("Cannot create an 'any' timeline with no awaitables.");let t=new g,n=new g,i=new o(n),r=!1;for(let s of e)i.attachChild(s),s.then(a=>{r||(r=!0,t.resolve(a))});return t.onSkipControllerRegister(s=>{s.onAbort(()=>{i.abort()})}),[t,i]}static all(e){if(e.length===0)throw new v("Cannot create an 'all' timeline with no awaitables.");let t=new g,n=new g,i=new o(n),r=new Array(e.length),s=0;for(let a=0;a<e.length;a++){let c=e[a];i.attachChild(c),c.then(l=>{r[a]=l,s++,s===e.length&&t.resolve(r)})}return t.onSkipControllerRegister(a=>{a.onAbort(()=>{i.abort()})}),[t,i]}static sequence(e,t){let n=t,i=null,r=new g,s=()=>{if(i){let a;i.onSkipControllerRegister(c=>{a=c.onAbort(()=>{r.abort()})}),i.then(c=>{a?.cancel(),n=c,i=e(c),i?Me(()=>s()):r.resolve(n)})}else r.resolve(n)};return r.registerSkipController(new I(()=>(i&&i.abort(),t))),i=e(t),i?Me(()=>s()):Me(()=>r.resolve(n)),r}get status(){return this._status}isSettled(){return this._status!=="pending"}isResolved(){return this._status==="resolved"}isCancelled(){return this._status==="cancelled"}onResolved(e){this._onResolved.push(e)}onCancelled(e){this._onCancelled.push(e)}onSettled(e){this.isSettled()?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 v(`Attaching to this timeline violates the timeline's state. Timeline attaching is only allowed synchronously after the timeline is created. Current _ableToAttach: `+this._ableToAttach);let t=g.isAwaitable(e)?new o(e,this.guard):e;return this.children.push(t),this.guard&&t.setGuard(this.guard),t.onSettled(()=>{this.resolveStatus()}),this}setGuard(e){return this.guard=e,this}catSettled(){return this.children.reduce(([e,t],n)=>(n.isResolved()?e.push(n):n.isCancelled()&&t.push(n),[e,t]),[[],[]])}onTimelineRegistered(e){return this._onTimelineRegistered.push(e),this}resolveStatus(){this.awaitable.solved&&this.children.every(e=>e.isSettled())?this.setStatus("resolved",this.emitEvents.bind(this)):this.awaitable.skipController?.isAborted()&&this.setStatus("cancelled",this.emitEvents.bind(this))}emitEvents(){this.isResolved()?this._onResolved.forEach(e=>e()):this.isCancelled()&&this._onCancelled.forEach(e=>e()),this._onResolved=[],this._onCancelled=[]}setStatus(e,t){if(this.isSettled()){this.guard&&this.guard.warn("unexpectedTimelineStatusChange",`Trying to resolve a settled timeline: ${this._status} -> ${e}`);return}e!==this._status&&t?(this._status=e,t()):this._status=e}preventAttach(){this._ableToAttach=!1,this._onTimelineRegistered.forEach(e=>e())}},Bn=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 nn=class nn 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,[i]=n.getContent();if(this.type===Ve.do)return[{type:this.type,node:this.contentNode.getChild()},{type:this.type,node:i[0].contentNode}];if(this.type===Ve.doAsync){let r=nn.executeActionsAsync(e,i[0]);return e.timelines.attachTimeline(r),super.executeAction(e,t)}else if(this.type===Ve.any){if(i.length===0)return{type:this.type,node:this.contentNode.getChild()};let r=this.checkActionChain(i).map(s=>e.game.getLiveGame().requestAsyncStackModel([{type:s.type,node:s.contentNode}]));return{type:this.type,node:this.contentNode.getChild(),wait:{type:"any",stackModels:r}}}else if(this.type===Ve.all){if(i.length===0)return{type:this.type,node:this.contentNode.getChild()};let r=this.checkActionChain(i).map(s=>e.game.getLiveGame().requestAsyncStackModel([{type:s.type,node:s.contentNode}]));return{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:r}}}else if(this.type===Ve.allAsync){if(i.length===0)return{type:this.type,node:this.contentNode.getChild()};let r=this.checkActionChain(i).map(s=>e.game.getLiveGame().requestAsyncStackModel([{type:s.type,node:s.contentNode}]));return e.timelines.attachTimeline(g.all(...r.map(s=>s.execute()))),super.executeAction(e,t)}else if(this.type===Ve.repeat){let[r,s]=this.contentNode.getContent();if(s<=0)return super.executeAction(e,t);let a=se.sequence(c=>{if(c>=s)return null;let l=nn.executeActionsAsync(e,r[0]);return e.timelines.attachTimeline(l),g.forward(l,c+1)},0);return e.logger.debug("ControlAction","repeat",r,s),g.forward(a,{type:this.type,node:this.contentNode.getChild()})}else if(this.type===Ve.sleep){let[,r]=this.contentNode.getContent(),s;typeof r=="number"?s=g.delay(r):g.isAwaitable(r)?s=r:s=g.fromPromise(r);let a=new g,c=new se(s);return e.timelines.attachTimeline(c),s.then(()=>{a.resolve({type:this.type,node:this.contentNode.getChild()})}),a.onSkipControllerRegister(l=>{l.onAbort(()=>{c.abort()})}),a}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],i=super.getFutureActions(e,t);return[...n,...i]}stringify(e,t,n){let i=this.contentNode,[r]=i.getContent();return super.stringifyWithContent("Control",r.map(s=>s.stringify(e,t,n)).join(";"))}};nn.ActionTypes=Ve;var te=nn;var $o=Symbol("_Chained"),jo;jo=$o;var Vi=class Vi{constructor(e){this[jo]=!0;this.__actions=[];this.__self=e}static isChained(e){return e&&e[$o]}static toActions(e){return e.flat(2).map(t=>Vi.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=Vi,Kt=class extends Wn{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(i,r){if(r in t)return t[r];let s=i[r];return typeof s=="function"?s.bind(n):s},set:function(i,r,s){return i[r]=s,!0}});return n}combineActions(e,t){let n=t(this.chain().newChain()),i=new te(e.chain(),te.ActionTypes.do,new T().setContent([this.construct(fe.toActions([n]))]));return this.chain(i)}};var q=class extends Kt{constructor(){super()}toData(){return null}fromChained(e){return e.getActions()}};var Se=class o{static from(e){return o.isPauseConstructor(e)?new o:e}static wait(e){return new o({duration:e})}static isPause(e){return this.isPauseConstructor(e)||e instanceof o}static isPauseConstructor(e){return e===o}constructor(e={}){this.config=e}};var 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[i]=this.contentNode.getContent(),r=this.callee.toData(),s=g.forward(e.audioManager.play(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===mt.stop){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=g.forward(e.audioManager.stop(this.callee,i.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===mt.setVolume){let[i,r]=this.contentNode.getContent(),s=this.callee.toData(),a=g.forward(e.audioManager.setVolume(this.callee,i,r),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(a),e.actionHistory.push(n,c=>{c&&this.callee.fromData(c)},[s]),a}else if(this.type===mt.setRate){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=g.forward(e.audioManager.setRate(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===mt.pause){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=g.forward(e.audioManager.pause(this.callee,i.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===mt.resume){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=g.forward(e.audioManager.resume(this.callee,i.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("SoundAction")}};Pe.ActionTypes=mt;var ft=(n=>(n.Voice="voice",n.Bgm="bgm",n.Sound="sound",n))(ft||{}),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),[i]=n.extract(Y.DefaultConfig.keys());this.config=i.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. 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 T().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 Ae=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:Ae.toSound(t.voice)}),this.state=Io(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 i=this.text[n].evaluate(e);t.push(...Ce.formatStaticWord(i))}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 $n=class $n 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:i,voice:r}=t.config;return!i&&!r?null:Ae.toSound(n.getVoice(i)||r)}executeAction(e,t){if(this.type===Rn.say){let n=new g(f=>f).registerSkipController(new I(()=>{c.cancel()})),i=new se(n),r=this.contentNode.getContent(),s=$n.getVoice(e,r);if(s){let f=e.audioManager.play(s);i.attachChild(f)}let a=e.idManager.generateId(),c=e.createDialog(a,r,()=>{if(s){let f=e.audioManager.stop(s);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(i);let{id:l}=e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:i},()=>{if(s&&e.audioManager.isPlaying(s)){let f=e.audioManager.stop(s);i.attachChild(f)}c.cancel()});return e.gameHistory.push({token:l,action:this,element:{type:"say",text:c.text,voice:s?s.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},i=>{this.callee.state.name=i},[n]),super.executeAction(e,t)}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("CharacterAction")}};$n.ActionTypes=Rn;var nt=$n;var on=class on extends q{constructor(e,t={}){super(),this.config=R(on.defaultConfig,t),this.state={name:e||""};let n=this,i=function(r,s,...a){return n.call(r,s,...a)};return new Proxy(i,{get(r,s){return n[s]},set(r,s,a){return n[s]=a,!0},has(r,s){return s in n}})}say(e,t,...n){if(Array.isArray(e)&&e.every(c=>typeof c=="string")&&[t,...n].length>0&&[t,...n].every(c=>ne.isSingleWord(c))){let c=e,l=ne.format([t,...n]),f=new ne(No(c,l),{character:this}),d=new nt(this.chain(),nt.ActionTypes.say,new T().setContent(f));return this.chain(d)}let i=t||{},r=e,s=Array.isArray(r)?new ne(r,{...i,character:this}):(ne.isSentence(r)?r:new ne(r,{...i,character:this})).copy();s.setCharacter(this);let a=new nt(this.chain(),nt.ActionTypes.say,new T().setContent(s));return this.chain(a)}setName(e){let t=new nt(this.chain(),nt.ActionTypes.setName,new T().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)}};on.defaultCharacterColor="#000",on.defaultConfig={};var jn=on,ht=new jn(null);var We=class o extends q{constructor(t={}){super();this.config=t}static do(t){return new o().do(t)}static doAsync(t){return new o().doAsync(t)}static any(t){return new o().any(t)}static all(t){return new o().all(t)}static allAsync(t){return new o().allAsync(t)}static repeat(t,n){return new o().repeat(t,n)}static sleep(t){return new o().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,...i){let r=this.narrativeToActions(n),s=new te(this.chain(),t,new T().setContent([this.construct(r),...i]));return this.chain(s)}pushUnchained(t,n,...i){let r=this.narrativeToActions(n),s=new te(this.chain(),t,new T().setContent([r,...i]));return this.chain(s)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?ht.say(n).getActions():fe.toActions([n]))}};var pe=class extends M{executeAction(e,t){if(this.type===ce.applyTransform){let[n]=this.contentNode.getContent(),i=this.callee;return this.applyTransform(e,i,n,t)}else if(this.type===ce.applyTransition){let[n,i]=this.contentNode.getContent(),r=this.callee,s=i?i(n):n;return this.applyTransition(e,r,s,t)}else if(this.type===ce.init){let[n,i,r]=this.contentNode.getContent(),s=this.callee;return this.initDisplayable(e,n,s,i||null,r,t)}throw this.unknownTypeError()}applyTransform(e,t,n,i,r){let s=new g().registerSkipController(new I(()=>(e.logger.info("Displayable Transition","Skipped"),super.executeAction(e,i)))),a=e.getExposedStateForce(t),c=t.transformState.clone(),l=a.applyTransform(n,()=>{r?.(),s.resolve(super.executeAction(e,i))}),f=e.timelines.attachTimeline(s).attachChild(l);return e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:f},d=>{s.isSettled()||s.abort(),l.abort(),t.transformState.forceOverwrite(d.state)},[c]),s}applyTransition(e,t,n,i,r){let s=new g().registerSkipController(new I(()=>(e.logger.info("Displayable Transition","Skipped"),super.executeAction(e,i)))),c=e.getExposedStateForce(t).applyTransition(n,()=>{r?.(),s.resolve(super.executeAction(e,i))}),l=e.timelines.attachTimeline(s).attachChild(c);return e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:l},()=>{s.isSettled()||s.abort(),c.abort()}),s}initDisplayable(e,t,n,i,r=!0,s){if(r!==!1){let l=e.findElementByDisplayable(this.callee,i);l&&e.disposeDisplayable(n,l.scene,i),e.createDisplayable(n,t,i)}e.flush();let a=new g().registerSkipController(new I(()=>super.executeAction(e,s)));e.getExposedStateAsync(n,l=>{l.initDisplayable(()=>{a.resolve(super.executeAction(e,s))})});let c=e.timelines.attachTimeline(a);return e.actionHistory.push({action:this,stackModel:s.stackModel,timeline:c},()=>{r!==!1&&e.findElementByDisplayable(n,i)&&e.disposeDisplayable(n,t,i)}),a}stringify(e,t,n){return super.stringifyWithName("DisplayableAction")}};pe.ActionTypes=ce;var kt=class kt{constructor(){this.src=[];this.future=[]}static catSrc(e){let t=new Set,n=new Set,i=new Set;return e.forEach(({type:r,src:s})=>{r===kt.SrcTypes.image?t.add(s):r===kt.SrcTypes.video?n.add(s):i.add(s)}),{image:Array.from(t),video:Array.from(n),audio:Array.from(i)}}static getSrc(e){return typeof e=="string"?e:e instanceof L?L.getSrcURL(e):e.type==="image"?L.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],r=e.getScene(n,!0).state.backgroundImage;if(b.isImageURL(r.config.src))return{type:"image",src:r.config.src,activeType:"once"}}else if(t instanceof z){let n=t;if(t.is(z,ke.setSrc)){let i=t.contentNode.getContent()[0];if(b.isImageSrc(i))return{type:"image",src:b.srcToURL(i),activeType:"scene"}}else{if(t.type===ke.initWearable)return{type:"image",src:t.contentNode.getContent()[0],activeType:"scene"};if(t.type=