@cyberart-io/engine 0.0.2 → 0.0.3
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.
- package/README.md +137 -7
- package/dist/headless.d.ts +637 -0
- package/dist/headless.js +8 -0
- package/dist/index.d.ts +467 -64
- package/dist/index.js +1 -1
- package/docs/asset-resolver.md +155 -0
- package/docs/deterministic-mode.md +1 -1
- package/docs/events.md +79 -10
- package/docs/headless-harness.md +58 -16
- package/docs/presentation-adapter.md +150 -0
- package/docs/presentation-cue.md +82 -0
- package/package.json +13 -2
package/dist/index.js
CHANGED
|
@@ -5,4 +5,4 @@
|
|
|
5
5
|
* Not an OSI open-source license.
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
-
var Vt=(t,e)=>()=>(t&&(e=t(t=0)),e);var Xt={};function Yt(t,e){let n=t.indexOf(at);if(n===-1)return null;let r=n+at.length,a=`const __cyberSkip=new Set(${JSON.stringify(e)});const __cyberOrig=registerProcessor;registerProcessor=(n,p)=>__cyberSkip.has(n)?undefined:__cyberOrig(n,p);`;return t.slice(0,r)+a+t.slice(r)}var Ee,pe,Jt,ee,at,st=Vt(()=>{"use strict";Ee=/AudioWorkletProcessor with name:\s*["'`][^"'`]+["'`]\s+is already registered/i,pe="__cyberartWorkletPatchApplied";typeof window<"u"&&!window[pe]&&(window.addEventListener("error",t=>{let e=t?.message??"";Ee.test(e)&&(t.preventDefault(),t.stopImmediatePropagation())},!0),window.addEventListener("unhandledrejection",t=>{let e=t?.reason,n=typeof e=="string"?e:e?.message??"";Ee.test(n)&&t.preventDefault()}),window[pe]=!0);Jt=!1,ee=(...t)=>{Jt&&console.log("[workletPatch]",...t)},at="((AudioWorkletProcessor,registerProcessor)=>{";if(typeof AudioWorklet<"u"&&!AudioWorklet.prototype[pe]){let t=new WeakMap,e=/registerProcessor\s*\(\s*['"`]([^'"`]+)['"`]/g,n=AudioWorklet.prototype.addModule,r=0;AudioWorklet.prototype.addModule=async function(a,o){let c=++r,l=t.get(this);l||(l=new Set,t.set(this,l)),ee(`#${c} addModule`,{url:a.slice(0,64),isBlob:a.startsWith("blob:"),knownBefore:[...l]});let y=a,m=null;if(a.startsWith("blob:")){let h=null;try{h=await(await fetch(a)).text()}catch(b){ee(`#${c} blob fetch failed`,b)}if(h!==null){let b=new Set;for(let w of h.matchAll(e))b.add(w[1]);if(b.size>0){let w=[...b].filter(E=>l.has(E)),d=[...b].filter(E=>!l.has(E));if(w.length>0&&d.length===0){ee(`#${c} short-circuit \u2014 all processors already registered`,w);return}if(w.length>0&&d.length>0){let E=Yt(h,w);if(E!==null){let R=new Blob([E],{type:"application/javascript"});m=URL.createObjectURL(R),y=m,ee(`#${c} rewrote blob; skipping`,w,"allowing",d)}else ee(`#${c} blob rewrite failed; passing original through`)}d.forEach(E=>l.add(E))}}}return n.call(this,y,o).then(()=>{m&&URL.revokeObjectURL(m)},h=>{m&&URL.revokeObjectURL(m);let b=(h&&h.message)??"";if(!(Ee.test(b)||/already registered/i.test(b)))throw h})},AudioWorklet.prototype[pe]=!0}});var qe=()=>{let t=["ms","moz","webkit","o"];for(let e=0;e<t.length&&!window.requestAnimationFrame;++e)window.requestAnimationFrame=window[t[e]+"RequestAnimationFrame"],window.cancelAnimationFrame=window[t[e]+"CancelAnimationFrame"]||window[t[e]+"CancelRequestAnimationFrame"]},T=window.devicePixelRatio||1,K=/Headless/i.test(navigator.userAgent),qn=/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)||/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.platform);function Ge(){return Math.min(window.innerWidth,window.innerHeight)}var ie="data-cyberart-canvas",V=class{constructor(e,n,r=1,i={}){this.width=e,this.height=n;let a=i.container,o=i.adoptFromDocument??!a,c=a?a.querySelector(`canvas[${ie}]`)??a.querySelector("canvas"):null;if(c)this.canvas=c,this.adopted=!0;else if(o){let l=document.getElementById("canvas")??document.querySelector("canvas");l?(this.canvas=l,this.adopted=!0):(this.canvas=document.createElement("canvas"),this.canvas.setAttribute("id","canvas"),this.adopted=!1)}else this.canvas=document.createElement("canvas"),this.adopted=!1;this.canvas.hasAttribute(ie)||this.canvas.setAttribute(ie,""),this.canvas.style.display="block",this.canvas.style.margin="auto",this.ctx=this.canvas.getContext("2d",{colorSpace:"display-p3",alpha:!1}),this.ctx.globalAlpha=r,this.ctx.imageSmoothingEnabled=!1,this.setSize(e,n)}setSize(e,n){this.width=e,this.height=n,this.canvas.width=e,this.canvas.height=n,this.canvas.style.width=`${e/T}px`,this.canvas.style.height=`${n/T}px`,this.imageData=this.ctx.createImageData(e,n),this.ctx.putImageData(this.imageData,0,0)}_blank(e=1){let n=e?Math.max(e,.03):1;this.ctx.fillStyle=`rgba(0,0,0,${n})`,this.ctx.fillRect(0,0,this.width,this.height)}clearAll(){this.ctx.save(),this.ctx.globalAlpha=1,this._blank(),this.ctx.restore()}};function Je(t,e){let n=t/e,r,i;return n>1?(r=t,i=~~(t/n)):(i=e,r=~~(e*n)),{width:r,height:i,iWidth:1/r,iHeight:1/i,area:r*i,largeDim:Math.max(r,i),smallDim:Math.min(r,i),aspectRatio:n}}function Ye(t,e=window.innerWidth,n=window.innerHeight){let r=Ge(),i,a;return n<e?t>1?e>=r*t?(i=r*t,a=r):(i=e,a=i/t):(i=r*t,a=r):t>1?(i=r,a=r/t):n<r/t?(a=n,i=a*t):(i=r,a=r/t),[i,a]}var ae=class{constructor(e=!1,n=!0){this.debugMode=e,this.actionMap={},this.listening=n,this.checkKeypress=this.checkKeypress.bind(this),this.registerAction=this.registerAction.bind(this),this.listening&&window.addEventListener("keydown",this.checkKeypress,!1)}checkKeypress({key:e}){this.debugMode&&console.log(`Pressed ${e}`),e in this.actionMap&&this.actionMap[e]()}inject(e){this.checkKeypress({key:e})}registerAction(e,n,r=!1){if(e.length!==1)throw new Error(`Only single-character actions may be registered. Cannot register: ${e}`);if(e in this.actionMap&&!r)throw new Error(`Action already exists for code: ${e}`);this.actionMap[e]=n}destroy(){this.listening&&window.removeEventListener("keydown",this.checkKeypress,!1),this.actionMap={}}},Xe=ae;var se=class{constructor(e,n={}){this.x=-1;this.y=-1;this.isDown=!1;this.clicks=[];this.canvas=e,this.listening=n.listen!==!1,this.onPointerDown=this.onPointerDown.bind(this),this.onPointerMove=this.onPointerMove.bind(this),this.onPointerUp=this.onPointerUp.bind(this),this.listening&&(e.addEventListener("pointerdown",this.onPointerDown),e.addEventListener("pointermove",this.onPointerMove),e.addEventListener("pointerup",this.onPointerUp))}toCanvasCoords(e){let n=this.canvas.getBoundingClientRect();return{x:(e.clientX-n.left)*(this.canvas.width/n.width),y:(e.clientY-n.top)*(this.canvas.height/n.height)}}onPointerDown(e){let{x:n,y:r}=this.toCanvasCoords(e);this.x=n,this.y=r,this.isDown=!0,this.clicks.push({x:n,y:r})}onPointerMove(e){let{x:n,y:r}=this.toCanvasCoords(e);this.x=n,this.y=r}onPointerUp(e){let{x:n,y:r}=this.toCanvasCoords(e);this.x=n,this.y=r,this.isDown=!1}hasClick(){return this.clicks.length>0}consumeClick(){return this.clicks.shift()??null}inject(e,n,r){this.x=n,this.y=r,e==="down"?(this.isDown=!0,this.clicks.push({x:n,y:r})):e==="up"&&(this.isDown=!1)}destroy(){this.listening&&(this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp))}},Qe=se;function W(){return{now:()=>performance.now()}}function oe(t=0){let e=t;return{now:()=>e,set(n){e=n},advance(n){e+=n}}}var Ze=(t,e,n,r)=>({now:t,startTime:e,elapsedSinceStart:t-e,deltaSinceLastUpdate:n===null?0:t-n,deltaSinceLastRender:r===null?0:t-r}),de=class{constructor(e,n,r,i,a,o={}){this.startTime=0;this.lastUpdateAt=null;this.lastRenderAt=null;this.clockOffsetMs=0;this.pauseStartedAt=null;this.renderAnimation=this.renderAnimation.bind(this),this.dimensionContext=Je(e,n),this.R=r,this.gameManager=o.gameManager,this.hostChannel=o.hostChannel,this.clock=o.clock??W(),this.canvas=new V(this.dimensionContext.width,this.dimensionContext.height,1,o.canvasMount),this.drawingContext=this.canvas.ctx,this.keyboardManager=new Xe(!1,o.captureKeyboard??!0),this.pointerManager=new Qe(this.canvas.canvas,{listen:o.listenToPointer!==!1}),this.animationCart=a;let c=o.customState;this.featureState=a.getDefaultFeatureState?.(this.R,this.dimensionContext,i,this.keyboardManager,c,this.pointerManager,this.gameManager,this.hostChannel),this.cartState=a.getDefaultState(this.R,this.dimensionContext,i,this.keyboardManager,c,this.pointerManager,this.gameManager,this.featureState,this.hostChannel),this.startTime=this.clock.now(),this.canvas.clearAll()}captureFramebuffer(){let e=this.canvas.imageData,n=new ImageData(e.width,e.height);return n.data.set(e.data),n}restoreFramebuffer(e){let n=this.canvas.imageData;return n.width!==e.width||n.height!==e.height||n.data.length!==e.data.length?!1:(n.data.set(e.data),this.drawingContext.putImageData(n,0,0),!0)}setPaused(e){let n=this.clock.now();if(e){this.pauseStartedAt===null&&(this.pauseStartedAt=n);return}this.pauseStartedAt!==null&&(this.clockOffsetMs+=n-this.pauseStartedAt,this.pauseStartedAt=null)}resolveNow(e){let n=this.pauseStartedAt!==null?e-this.pauseStartedAt:0;return e-this.clockOffsetMs-n}getElapsedSinceStart(e=this.clock.now()){return Math.max(0,this.resolveNow(e)-this.startTime)}restoreClock(e,n){this.pauseStartedAt=null,this.lastUpdateAt=null,this.lastRenderAt=null;let r=Math.max(0,e);if(typeof n=="number"&&Number.isFinite(n)){this.startTime=n,this.clockOffsetMs=this.clock.now()-n-r;return}this.clockOffsetMs=0,this.startTime=this.clock.now()-r}getRandomState(){return this.R.getState()}injectKey(e){this.keyboardManager.inject(e)}injectPointer(e,n,r){this.pointerManager.inject(e,n,r)}async updateAnimationState(e,n,r=this.clock.now()){let i=this.resolveNow(r),a=Ze(i,this.startTime,this.lastUpdateAt,this.lastRenderAt);this.cartState=this.animationCart.update(this.R,e,n,this.dimensionContext,this.cartState,this.keyboardManager,this.pointerManager,this.gameManager,a,this.featureState,this.hostChannel),this.lastUpdateAt=i}async renderAnimation(e,n,r=this.clock.now()){let i=this.resolveNow(r),a=Ze(i,this.startTime,this.lastUpdateAt,this.lastRenderAt);this.animationCart.render(this.R,e,n,this.dimensionContext,this.cartState,this.drawingContext,this.canvas.imageData,this.pointerManager,this.gameManager,a,this.featureState,this.hostChannel),this.lastRenderAt=i}getCanvas(){return this.canvas.canvas}getDrawDetails(){return[this.canvas.canvas,0,0,this.dimensionContext.width,this.dimensionContext.height]}teardown(){try{this.animationCart.teardown?.(this.cartState,this.featureState)}catch(e){console.error("Error during cart teardown",e)}this.keyboardManager.destroy(),this.pointerManager.destroy()}};var ue=class extends V{constructor(e,n,r=1,i=!0,a={}){if(super(e,n,r,a),this.adopted)return;let o=a.container;if(o){this.canvas.parentNode!==o&&o.appendChild(this.canvas);return}if(i){let c=document.getElementById("canvas");c&&c!==this.canvas&&c.parentNode===document.body&&document.body.removeChild(c),document.body.appendChild(this.canvas)}}};function et(t){let e=parseInt(t.substring(0,8),16),n=parseInt(t.substring(8,8),16),r=parseInt(t.substring(16,8),16),i=parseInt(t.substring(24,8),16);return{next:()=>{e|=0,n|=0,r|=0,i|=0;let o=(e+n|0)+i|0;return i=i+1|0,e=n^n>>>9,n=r+(r<<3)|0,r=r<<21|r>>>11,r=r+o|0,(o>>>0)/4294967296},getRegs:()=>({a:e,b:n,c:r,d:i}),setRegs:o=>{e=o.a,n=o.b,r=o.c,i=o.d}}}var Q=class{constructor(e){this.seed=e.hash,this.useA=!1,this.genA=et(e.hash.substring(2,32)),this.genB=et(e.hash.substring(34,32)),this.prngA=this.genA.next,this.prngB=this.genB.next;for(let n=0;n<1e6;n+=2)this.prngA(),this.prngB()}getState(){let e=this.genA.getRegs(),n=this.genB.getRegs();return{seed:this.seed,useA:this.useA,prngA:{a:e.a,b:e.b,c:e.c,d:e.d},prngB:{a:n.a,b:n.b,c:n.c,d:n.d}}}setState(e){if(e.seed!==this.seed)throw new Error(`Random.setState: seed ${e.seed} does not match ${this.seed}`);this.useA=e.useA,this.genA.setRegs(e.prngA),this.genB.setRegs(e.prngB)}r_zero_one(){return this.useA=!this.useA,this.useA?this.prngA():this.prngB()}dec(e,n){return e===void 0?this.r_zero_one():n===void 0?e*this.r_zero_one():e+(n-e)*this.r_zero_one()}int(e,n){return n===void 0&&(n=e,e=0),Math.floor(this.dec(e,n))}bool(e=.5){return this.r_zero_one()<e}sign(){return this.bool()?1:-1}choose(e){return e[this.int(e.length)]}};var nt="bafybeicjwcq5lxxtfnyj4p2ugcr7ctyb5wl62cbcechj6tsabdq5whcs7u",tt="https://ipfs.io/ipfs/";function Wt(t){return t.endsWith("/")?t:`${t}/`}var Z=null;function $t(t){return[...Array(t)].map(()=>Math.floor(Math.random()*16).toString(16)).join("")}function jt(t){return t&&t.length>0?t:[{cid:nt}]}function zt(t){return t.startsWith("0x")?t:`0x${t}`}var rt=/^(0[xX])?[0-9a-fA-F]{64}$/;function qt(t){let e="",n=2166136261,r=522970236;for(let i=0;e.length<64;i++){for(let a=0;a<t.length;a++)n^=t.charCodeAt(a)+i,n=Math.imul(n,16777619),r^=t.charCodeAt(a)+i*17,r=Math.imul(r,16777619);e+=(n>>>0).toString(16).padStart(8,"0"),e+=(r>>>0).toString(16).padStart(8,"0")}return`0x${e.slice(0,64)}`}function ce(t){let e=typeof t=="number"?String(t):t;return rt.test(e)?`0x${(e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e).toLowerCase()}`:qt(e)}function le(t,e){if(typeof t=="number"||e==="deterministic")return ce(t);let n=String(t);return rt.test(n)?ce(n):n.startsWith("0x")||n.startsWith("0X")?n:`0x${n}`}function Gt(t){if(!t&&typeof tokenData<"u"&&tokenData?.hash)return{hash:tokenData.hash,tokenId:String(tokenData.tokenId),externalAssetDependencies:jt(tokenData.externalAssetDependencies),preferredIPFSGateway:Wt(tokenData.preferredIPFSGateway||tt),preferredArweaveGateway:tokenData.preferredArweaveGateway};let e=typeof window<"u"?new URLSearchParams(window.location.search):new URLSearchParams;return{hash:t?zt(t):e.get("hash")||`0x${$t(64)}`,tokenId:"18009999",externalAssetDependencies:[{cid:nt}],preferredIPFSGateway:tt}}function we(t){let e=t?.useCache!==!1;if(e&&Z&&!t?.hash)return Z;let n=Gt(t?.hash);return e?Z=n:Z||(Z=n),n}function it(t){return new Array(32).fill(null).map((e,n)=>parseInt(t.hash.slice(2+n*2,4+n*2),16))}async function Se(){let t=await import("tone");if(typeof t.start=="function")return t;let e=t.default;return e&&typeof e.start=="function"?e:t}var ot={id:"tone",async load(){await Promise.resolve().then(()=>(st(),Xt))},async unlock(){await ot.load(),await(await Se()).start()},async resumeIfSuspended(){let t=await Se();t.context.state==="suspended"&&await t.context.resume()},async suspendIfRunning(){let e=(await Se()).context.rawContext;"suspend"in e&&e.state==="running"&&await e.suspend()}},dt={tone:ot};function Ae(t){if(!t)return[];let e=Array.isArray(t)?t:[t],n=[];for(let r of e){if(!(r in dt)){console.warn(`Unknown audio library "${r}"`);continue}let i=r;n.includes(i)||n.push(i)}return n}function Ce(t){return t.map(e=>dt[e])}var he="$cyberartTa",k=class extends Error{constructor(e){super(e),this.name="IncompatibleCartStateError"}},ke={Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array};function Qt(t){for(let e of Object.keys(ke))if(t instanceof ke[e])return e}function ct(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function I(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function xe(t){return I(t)?typeof t[he]=="string"&&Array.isArray(t.d):!1}function Zt(t){return t==null?!1:typeof t=="function"?!0:!(typeof t!="object"||Array.isArray(t)||ct(t)||I(t))}var en=new Set(["audioContextStarted","midiSynths","keepRatioPrimed","audioInitStarted","musicSeekApplied"]);function ut(t){return t===null?"null":xe(t)?String(t[he]):Array.isArray(t)?"array":I(t)?"object":typeof t}function tn(t,e){return t===e||t==="null"||e==="null"}function _(t){return t.trim().toLowerCase().replace(/^0x/,"")}function lt(t,e,n,r){if(!(!n&&!r)&&_(t)!==_(e))throw new k(`Generative cart state is for seed "${e}", but the live token is "${t}"`)}function $(t){return typeof t=="number"&&Number.isFinite(t)&&t>0}function pt(t,e){let n=t.dimensions;if(n&&$(n.width)&&$(n.height))return n;if(e&&$(e.width)&&$(e.height))return{width:e.width,height:e.height};if(I(t.state)){let r=t.state.containerWidth,i=t.state.containerHeight;if($(r)&&$(i))return{width:r,height:i}}return null}function j(t,e=new WeakSet){if(t===null||typeof t=="string"||typeof t=="boolean")return t;if(typeof t=="number")return Number.isFinite(t)?t:null;if(!(typeof t=="function"||typeof t>"u"||typeof t=="bigint"||typeof t=="symbol")){if(ct(t)){let n=Qt(t);return n?{[he]:n,d:Array.from(t)}:void 0}if(typeof t=="object"&&!e.has(t)){e.add(t);try{if(Array.isArray(t)){let i=[],a=0;for(let o of t){let c=j(o,e);c!==void 0&&(i.push(c),a++)}return t.length>0&&a===0?void 0:i}if(!I(t)||Zt(t))return;let n=Object.keys(t),r={};for(let i of n){if(en.has(i))continue;let a=j(t[i],e);a!==void 0&&(r[i]=a)}return n.length>0&&Object.keys(r).length===0?void 0:r}finally{e.delete(t)}}}}function te(t){if(xe(t)){let e=ke[t[he]];return e?new e(t.d.map(n=>Number(n))):t}if(Array.isArray(t))return t.map(e=>te(e));if(I(t)){let e={};for(let n of Object.keys(t))e[n]=te(t[n]);return e}return t}function Te(t,e,n,r,i=!0){if(i&&n&&r&&n!==r)throw new k(`Cart state is for "${r}", but the live cart is "${n}"`);if(!I(e)){if(i)throw new k("Cart state snapshot is empty");return}let a=Object.keys(e);if(a.length===0){if(i)throw new k("Cart state snapshot is empty");return}let o=j(t);if(!I(o)||Object.keys(o).length===0){if(i)throw new k("Live cart has no serializable state");return}let c=a.filter(l=>l in o);if(c.length===0){if(i)throw new k("Cart state snapshot does not overlap the live cart shape");return}for(let l of c){let y=ut(o[l]),m=ut(e[l]);if(!tn(y,m))throw new k(`Cart state field "${l}" has type ${m}, live cart expects ${y}`);if(y==="object"){let h=e[l],b=t[l];I(h)&&!xe(h)&&Te(b,h,void 0,void 0,!1)}}}function ht(t,e){if(!I(t)||!I(e))return;let n=j(t);if(I(n))for(let r of Object.keys(e))r in n&&(t[r]=te(e[r]))}function mt(t){let e=typeof t=="string"?JSON.parse(t):t;if(!e||typeof e!="object")throw new k("Cart state bundle is not an object");if(e.version!==1)throw new k(`Unsupported cart state version ${String(e.version)}`);if(typeof e.seed!="string"||typeof e.framesElapsed!="number")throw new k("Cart state bundle is missing seed or framesElapsed");return e}var Pe="cyberart.asset.ready",De="cyberart.asset.failed";function L(t){try{return JSON.parse(JSON.stringify(t))}catch{return t}}function M(t){try{return JSON.stringify(t)}catch{return String(t)}}function Re(t,e,n){let r=e??[],i=n??[],a=Math.max(r.length,i.length);for(let o=0;o<a;o++)if(M(r[o])!==M(i[o]))return`${t}[${o}]: ${M(r[o])} vs ${M(i[o])}`}function ft(t,e){let n=[];t.seed!==e.seed&&n.push(`seed: ${t.seed} vs ${e.seed}`),t.clock.framesElapsed!==e.clock.framesElapsed&&n.push(`framesElapsed: ${t.clock.framesElapsed} vs ${e.clock.framesElapsed}`),t.clock.now!==e.clock.now&&n.push(`now: ${t.clock.now} vs ${e.clock.now}`),t.clock.frameRate!==e.clock.frameRate&&n.push(`frameRate: ${t.clock.frameRate} vs ${e.clock.frameRate}`),M(t.rng)!==M(e.rng)&&n.push(`rng: ${M(t.rng)} vs ${M(e.rng)}`);let r=Re("actions",t.actions,e.actions);r&&n.push(r);let i=Re("applied",t.applied,e.applied);i&&n.push(i);let a=Re("events",t.events,e.events);return a&&n.push(a),M(t.state)!==M(e.state)&&n.push(`state: ${M(t.state)} vs ${M(e.state)}`),n}function gt(t){return{type:t.status==="ready"?Pe:De,kind:"state",payload:t.detail===void 0?{id:t.id}:{id:t.id,detail:t.detail}}}function rn(t){if(!t||typeof t!="object")return 0;let e=t;return typeof e.startTime=="number"&&typeof e.lastSimulationUpdateAt=="number"?Math.max(0,e.lastSimulationUpdateAt-e.startTime):0}function an(t,e){if(typeof window.resizeTo!="function")return!1;try{if(window.top!==window)return!1}catch{return!1}let n=Math.max(1,Math.round(t)),r=Math.max(1,Math.round(e)),i=Math.max(0,window.outerWidth-window.innerWidth),a=Math.max(0,window.outerHeight-window.innerHeight);try{window.resizeTo(n+i,r+a)}catch{return!1}return Math.abs(window.innerWidth-n)<=8&&Math.abs(window.innerHeight-r)<=8}var sn=[[0,0],[16,9],[9,16],[4,3],[3,4],[2,1],[1,2],[3,1],[1,3],[1,1]],Me=sn[0],on=Me[0]/Me[1],Ie=30,dn=120,un=3840/2160,cn=2160/3840,me=class{constructor(e=Ie,n=!1,r=window.innerWidth,i=window.innerHeight,a=!0,o,c={}){this.framesElapsed=0;this.frameRate=Ie;this._paused=!1;this.savedToken=!1;this.prepared=!1;this.loopRunning=!1;this.fallbackAudio=[];this.audioLibrariesInternal=[];this.virtualClock=null;this.scriptedActions=[];this.initialScriptedActions=[];this.appliedActions=[];this.consumedActionIndexes=new Set;this.outboundEvents=[];this.consecutiveErrorCount=0;this.lastErrorLogAt=0;this.reinitStayPaused=!1;this.reinitPending=!1;this.lastExportedFramebuffer=null;this.pinnedOutput=null;this.pinViewportAtImport=null;this.importing=!1;this.drawLoop=this.drawLoop.bind(this),this.loadCart=this.loadCart.bind(this),this.prepareCart=this.prepareCart.bind(this),this.beginPlayback=this.beginPlayback.bind(this),this.reinit=this.reinit.bind(this),this.tuneFramerate=this.tuneFramerate.bind(this),this.container=c.container,this.seed=c.seed,this.captureKeyboard=c.captureKeyboard??!0,this.customState=c.customState,this.hostChannel=c.hostChannel,this.fallbackAudio=Ae(c.audio),this.audioLibrariesInternal=this.fallbackAudio;let l=c.deterministic;this.deterministic=!!l;let y=l&&typeof l=="object"?l:{};if(this.deterministic){if(c.clock){let m=c.clock;if(typeof m.advance!="function")throw new Error("deterministic mode requires a virtual clock with advance()");this.virtualClock=m,this.clock=m}else this.virtualClock=oe(y.origin??0),this.clock=this.virtualClock;this.initialScriptedActions=L(y.actions??[]),this.scriptedActions=L(this.initialScriptedActions)}else this.clock=c.clock??W();this.isBodyCanvas=this.container?!1:a,this.autoMode=n,this.aspectRatio=on,this.selectedAsp=Me,this.isFullscreen=!!document.fullscreenElement,this.updateFrameRate(e),this.tempUnpause=!1,this.synchronous=K,this.containerWidth=r,this.containerHeight=i,this.gameManager=o,this.init(!0)}setGameManager(e){this.gameManager=e}reinit(e){if(!this.importing){if(this.shouldKeepPinnedOutput()){this.fitPinnedCanvas();return}this.reinitPending||(this.reinitStayPaused=this._paused,this.reinitPending=!0),this.paused=!0,clearTimeout(this.reinitTimeout),this.reinitTimeout=setTimeout(()=>{if(this.importing){this.paused=this.reinitStayPaused,this.reinitPending=!1;return}this.updateInProgress?this.reinit(e):(this.requestedAnimationFrame&&cancelAnimationFrame(this.requestedAnimationFrame),this.clearPinnedOutput(),this.init(),this.reloadCart(),this.paused=this.reinitStayPaused,this.reinitPending=!1)},150)}}initSeed(){this.tokenData=this.seed?we({hash:this.seed,useCache:!1}):we(),this.rawParams=it(this.tokenData),this.mintNo=parseInt(this.tokenData.tokenId)%1e6,console.log("token",this.mintNo,this.tokenData.hash)}init(e=!1){e&&this.initSeed(),this.pureAspectUpdate(this.selectedAsp);let n=this.aspectRatio,[r,i]=Ye(n,this.containerWidth,this.containerHeight);r*=T,i*=T,this.width=~~r,this.height=~~i,this.atCenterX=this.width/2,this.atCenterY=this.height/2,this.mainCanvas?this.mainCanvas.setSize(this.width,this.height):this.mainCanvas=new ue(this.width,this.height,1,this.isBodyCanvas,this.canvasMountOptions())}loadCart(e){this.prepareCart(e)&&this.beginPlayback()}prepareCart(e){if(this.prepared)return!0;try{let n=~~(this.width/1),r=~~(this.height/this.width*n),i=new Q(this.tokenData),a=new de(n,r,i,this.rawParams,e,{gameManager:this.gameManager,canvasMount:this.canvasMountOptions(),customState:this.customState,captureKeyboard:this.deterministic?!1:this.captureKeyboard,hostChannel:this.hostChannel,clock:this.clock,listenToPointer:!this.deterministic});return this.animation=a,this.animationCart=e,this.paused=!1,this.framesElapsed=0,this.outboundEvents=[],this.scriptedActions=L(this.initialScriptedActions),this.appliedActions=[],this.consumedActionIndexes=new Set,this.outboundUnsubscribe?.(),this.outboundUnsubscribe=void 0,this.deterministic&&this.hostChannel&&(this.outboundUnsubscribe=this.hostChannel.onEvent(o=>{this.outboundEvents.push(o)})),this.R=i,this.applyCartFrameRate(e,a),this.resolveAudioLibraries(e),this.prepared=!0,!0}catch(n){return console.error(n),!1}}applyCartFrameRate(e,n){let r=e.metadata,i=r?.frameRate??Ie,a=n.cartState?.visualMode??n.featureState?.visualMode,o=a&&r?.frameRateByVisualMode?r.frameRateByVisualMode[a]:void 0;this.updateFrameRate(typeof o=="number"&&o>0?o:i)}get audioLibraries(){return this.audioLibrariesInternal}get needsAudio(){return this.audioLibrariesInternal.length>0}resolveAudioLibraries(e){this.audioLibrariesInternal=Ae(e.metadata?.audio)}async unlockAudio(){if(this.audioLibrariesInternal.length===0)return;let e=Ce(this.audioLibrariesInternal);if(K){for(let n of e)await n.load();return}for(let n of e)await n.unlock()}async resumeAudioLibraries(){if(!(this.paused||K))for(let e of Ce(this.audioLibrariesInternal))try{await e.resumeIfSuspended()}catch(n){console.error(`Failed to resume audio library "${e.id}" after reload`,n)}}beginPlayback(){!this.prepared||this.loopRunning||(this.prepared=!1,this.loopRunning=!0,this.consecutiveErrorCount=0,!this.deterministic&&(this.requestedAnimationFrame=requestAnimationFrame(this.drawLoop)))}get isPrepared(){return this.prepared}get isLoopRunning(){return this.loopRunning}get isDeterministic(){return this.deterministic}getClock(){return{now:this.clock.now(),framesElapsed:this.framesElapsed,frameRate:this.frameRate}}getRandomState(){return this.requirePreparedAnimation().getRandomState()}schedule(e){this.scriptedActions.push(L(e))}async getReplayMetadata(){let e=await this.exportState();return{seed:this.tokenData.hash,clock:this.getClock(),rng:this.getRandomState(),actions:L(this.scriptedActions),applied:L(this.appliedActions),events:L(this.outboundEvents),state:e.state}}async step(e=1){if(!this.deterministic)throw new Error("step() requires createRuntime({ deterministic: true })");this.requirePreparedAnimation(),this.prepared&&!this.loopRunning&&this.beginPlayback(),this.paused=!1;let n=Math.max(0,Math.floor(e));for(let r=0;r<n&&this.animation;r++){let i=this.framesElapsed;if(this.applyScheduledActions(i),await this.processFrame(this.clock.now(),{ignorePause:!0,scheduleNext:!1}),this.framesElapsed===i||(this.virtualClock?.advance(this.targetDrawTime),!this.loopRunning))break}}async advance(e){let n=Math.max(0,Math.round(e/this.targetDrawTime));await this.step(n)}applyScheduledActions(e){let n=this.animation;n&&this.scriptedActions.forEach((r,i)=>{r.atFrame===e&&(this.consumedActionIndexes.has(i)||(this.consumedActionIndexes.add(i),r.type==="pointer"?n.injectPointer(r.pointer.kind,r.pointer.x,r.pointer.y):r.type==="key"?n.injectKey(r.key):r.type==="event"?this.hostChannel?.dispatch(r.event):r.type==="asset"&&this.hostChannel?.dispatch(gt(r)),this.appliedActions.push({frame:e,action:r})))})}get paused(){return this._paused}set paused(e){this._paused!==e&&(this._paused=e,this.animation?.setPaused(e))}async waitUntilUpdateIdle(){for(;this.updateInProgress;)await new Promise(e=>{this.deterministic?queueMicrotask(e):typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>e()):setTimeout(e,0)})}requirePreparedAnimation(){if(!this.animation)throw new Error("No prepared cart");return this.animation}async exportState(){let e=this.requirePreparedAnimation(),n=this._paused;this.paused=!0,await this.waitUntilUpdateIdle();try{this.lastExportedFramebuffer=e.captureFramebuffer();let r=e.getCanvas();return{version:1,cartId:this.animationCart?.metadata?.id,generative:this.animationCart?.metadata?.generative,seed:this.tokenData.hash,framesElapsed:this.framesElapsed,elapsedSinceStart:e.getElapsedSinceStart(),dimensions:{width:r.width,height:r.height,cssWidth:this.containerWidth,cssHeight:this.containerHeight,dpr:T},state:j(e.cartState)}}finally{this.paused=n}}async exportStateJSON(){return JSON.stringify(await this.exportState())}peekExportedFramebuffer(){return this.lastExportedFramebuffer}peekSeed(){return this.tokenData?.hash}isGenerative(){return this.animationCart?.metadata?.generative===!0}async importState(e,n){let r=this.requirePreparedAnimation(),i=mt(e),a=this._paused,o=this.loopRunning;this.paused=!0,await this.waitUntilUpdateIdle(),Te(r.cartState,i.state,this.animationCart?.metadata?.id,i.cartId),lt(this.tokenData.hash,i.seed,this.animationCart?.metadata?.generative,i.generative),clearTimeout(this.reinitTimeout),this.reinitPending=!1,this.importing=!0;let c=pt(i,n?.framebuffer??this.lastExportedFramebuffer);if(c){this.pinOutputSize(c);let m=c.cssWidth??c.width/T,h=c.cssHeight??c.height/T;an(m,h),this.syncContainerFromDom(),this.pinViewportAtImport={w:this.containerWidth,h:this.containerHeight}}let l=this.customState,y=!1;try{if(this.customState=te(i.state),this.unloadCart(),!this.prepareCart(this.animationCart))throw new Error("Failed to prepare cart while loading state");this.animation.cartState!==this.customState&&ht(this.animation.cartState,i.state),this.framesElapsed=i.framesElapsed;let m=this.animation,h=m.cartState,b=typeof i.elapsedSinceStart=="number"?i.elapsedSinceStart:rn(h);m.restoreClock(b,typeof h?.startTime=="number"?h.startTime:void 0),a&&m.setPaused(!0);let w=n?.framebuffer??this.lastExportedFramebuffer;w&&m.restoreFramebuffer(w)?h.keepRatioPrimed=!0:await m.renderAnimation(this.framesElapsed,this.rawParams),this.fitPinnedCanvas(),y=!0}catch(m){throw this.clearPinnedOutput(),this.customState=l,this.paused=a,this.animationCart&&(this.syncContainerFromDom(),this.init(),this.reloadCart()),m}finally{this.importing=!1,y&&(this.customState=l,this.paused=a,o&&this.beginPlayback())}}unloadCart(){this.loopRunning=!1,this.requestedAnimationFrame&&cancelAnimationFrame(this.requestedAnimationFrame),this.drawLoopTimeout&&clearTimeout(this.drawLoopTimeout),this.animation?.teardown(),this.animation=void 0,this.prepared=!1,this.audioLibrariesInternal=this.fallbackAudio,this.mainCanvas?.clearAll()}reloadCart(e=!1){let n=this.animationCart;if(!n)return;this.pinnedOutput&&(this.clearPinnedOutput(),this.syncContainerFromDom(),this.init());let r=this.reinitPending?this.reinitStayPaused:this._paused;this.unloadCart(),e&&this.initSeed(),this.loadCart(n),this.paused=r,!this.paused&&!K&&this.resumeAudioLibraries()}getFrameRate(){return this.frameRate}updateFrameRate(e){if(this.frameRate=e,e>=1)this.targetDrawTime=1e3/e;else{let r=1/(2-e);this.targetDrawTime=1e3/r}this.drawTime=this.targetDrawTime}canvasMountOptions(){return{container:this.container,adoptFromDocument:!this.container}}syncContainerFromDom(){if(this.container){this.containerWidth=this.container.clientWidth||this.containerWidth,this.containerHeight=this.container.clientHeight||this.containerHeight;return}this.containerWidth=window.innerWidth,this.containerHeight=window.innerHeight}pinOutputSize(e){this.pinnedOutput=e,this.width=~~e.width,this.height=~~e.height,this.atCenterX=this.width/2,this.atCenterY=this.height/2,this.aspectRatio=this.width/this.height,this.mainCanvas&&this.mainCanvas.setSize(this.width,this.height)}shouldKeepPinnedOutput(){return this.pinnedOutput?(this.syncContainerFromDom(),this.viewportMatches(this.pinnedCssSize())?!0:!!(this.pinViewportAtImport&&this.viewportMatches(this.pinViewportAtImport))):!1}pinnedCssSize(){let e=this.pinnedOutput;return{w:e.cssWidth??e.width/T,h:e.cssHeight??e.height/T}}viewportMatches(e){return Math.abs(this.containerWidth-e.w)<8&&Math.abs(this.containerHeight-e.h)<8}fitPinnedCanvas(){let e=this.pinnedOutput,n=this.canvas;if(!e||!n)return;this.container&&!this.container.style.position&&(this.container.style.position="relative");let r=this.containerWidth||window.innerWidth,i=this.containerHeight||window.innerHeight,a=e.width/T,o=e.height/T;if(a<1||o<1||r<1||i<1)return;let c=Math.min(r/a,i/o),l=a*c,y=o*c;n.style.position="absolute",n.style.left="50%",n.style.top="50%",n.style.transform="translate(-50%, -50%)",n.style.margin="0",n.style.width=`${l}px`,n.style.height=`${y}px`,n.style.imageRendering=Math.abs(c-1)<.01?"auto":"pixelated"}clearPinnedOutput(){let e=this.canvas;this.pinnedOutput=null,this.pinViewportAtImport=null,e&&(e.style.position="",e.style.left="",e.style.top="",e.style.transform="",e.style.imageRendering="",e.style.width="",e.style.height="",e.style.margin="auto")}get canvas(){return this.animation?.getCanvas()??this.mainCanvas?.canvas}destroy(){this.outboundUnsubscribe?.(),this.outboundUnsubscribe=void 0,this.clearPinnedOutput(),this.unloadCart(),clearTimeout(this.reinitTimeout),this.mainCanvas&&!this.mainCanvas.adopted&&this.mainCanvas.canvas.remove()}drawIt(){}tuneFramerate(e){let n=this.lastCall||e;this.lastCall=e,this.drawTime=Math.max(0,this.drawTime+this.targetDrawTime-this.lastCall+n)}async processFrame(e,n={}){let r=n.ignorePause===!0,i=n.scheduleNext!==!1;if(!this.loopRunning&&!r)return;let a=!1,o,c="update";try{if(r||!this.paused||this.tempUnpause){if(!K&&!r&&this.tuneFramerate(e),!this.animation)return;if(c="update",this.updateInProgress=!0,await this.animation.updateAnimationState(this.framesElapsed,this.rawParams,e),this.updateInProgress=!1,c="render",await this.animation.renderAnimation(this.framesElapsed,this.rawParams,e),this.autoMode&&this.animation.cartState.saveToken&&!this.savedToken&&!new URLSearchParams(window.location.search).get("hash")){let m=localStorage.getItem("goodones"),h=JSON.stringify(m?[...JSON.parse(m),this.tokenData.hash]:[this.tokenData.hash]);localStorage.setItem("goodones",h),this.savedToken=!0,localStorage.setItem(this.tokenData.hash,this.mainCanvas.canvas.toDataURL("image/png")),window.location.reload(),this.loopRunning=!1;return}this.framesElapsed++,this.tempUnpause&&(this.tempUnpause=!1)}c="draw",this.drawIt()}catch(l){a=!0,o=l,this.handleFrameError(l,c)}finally{this.updateInProgress=!1}a?(this.consecutiveErrorCount++,this.consecutiveErrorCount>=dn&&(this.loopRunning=!1,this.onError?.(o,{phase:c,consecutive:this.consecutiveErrorCount,stopped:!0}))):this.consecutiveErrorCount=0,!(!this.loopRunning||!i)&&(this.drawLoopTimeout=setTimeout(()=>{this.requestedAnimationFrame=requestAnimationFrame(this.drawLoop)},this.drawTime))}async drawLoop(e){await this.processFrame(e,{scheduleNext:!0})}handleFrameError(e,n){let r=performance.now();r-this.lastErrorLogAt>=1e3&&(this.lastErrorLogAt=r,console.error(`Animation ${n} error:`,e)),this.consecutiveErrorCount===0&&this.onError?.(e,{phase:n,consecutive:1,stopped:!1})}pureAspectUpdate(e){if(e[0]===0&&e[1]===0){let r=this.containerWidth||window.innerWidth,i=this.containerHeight||window.innerHeight,a=r/i;this.aspectRatio=Math.min(un,Math.max(cn,a))}else this.aspectRatio=e[0]/e[1]}};var z=class{constructor(){this.inbound=[];this.listeners=[]}dispatch(e){this.inbound.push(e),this.inbound.length>32&&this.inbound.splice(0,this.inbound.length-32)}consume(){if(this.inbound.length===0)return[];let e=this.inbound;return this.inbound=[],e}emit(e){for(let n of this.listeners)n(e)}onEvent(e){return this.listeners.push(e),()=>{this.listeners=this.listeners.filter(n=>n!==e)}}clear(){this.inbound=[],this.listeners=[]}};function He(t){qe();let{container:e,seed:n,captureKeyboard:r=!1,audio:i,deterministic:a}=t,o=n===void 0?void 0:le(n,a?"deterministic":"live"),c=new z,l=!1,y=null,m,h=!1,b=e.clientWidth||window.innerWidth,w=e.clientHeight||window.innerHeight,d=new me(30,!1,b,w,!1,void 0,{container:e,seed:o,captureKeyboard:r,hostChannel:c,audio:i,deterministic:a}),E=()=>{let C=e.clientWidth||window.innerWidth,P=e.clientHeight||window.innerHeight;return C===d.containerWidth&&P===d.containerHeight?!1:(d.containerWidth=C,d.containerHeight=P,!0)},R=null;return!d.isDeterministic&&typeof ResizeObserver<"u"&&(R=new ResizeObserver(()=>{if(l||!y)return;E()&&h&&d.reinit()}),R.observe(e)),d.onError=(C,P)=>{m?.(C,P)},{get tokenData(){return d.tokenData},get onError(){return m},set onError(C){m=C},mount(C,P={}){if(l)throw new Error("createRuntime: cannot mount on a destroyed runtime");y?.destroy(),h=!1,d.customState=P.initialState,d.setGameManager(P.gameManager);let N=P.onEvent?c.onEvent(P.onEvent):()=>{};if(!d.prepareCart(C))throw N(),new Error("createRuntime: failed to prepare cart");let v=!1,B={async start(){if(!v){if(E()&&d.isPrepared&&(d.init(),d.unloadCart(),!d.prepareCart(C)))throw new Error("createRuntime: failed to prepare cart");d.needsAudio&&(await d.unlockAudio(),v)||(h=!0,d.beginPlayback())}},pause(){v||(d.paused=!0)},resume(){v||(d.paused=!1)},dispatch(S){v||c.dispatch(S)},snapshot(){if(v)return{seed:"",pngDataUrl:""};let S=d.canvas;return{seed:d.tokenData.hash,metadata:C.metadata,pngDataUrl:S?S.toDataURL("image/png"):""}},destroy(){v||(v=!0,h=!1,N(),c.clear(),d.unloadCart(),y===B&&(y=null))},reload(){if(!v){if(!h){if(d.isPrepared&&(d.unloadCart(),!d.prepareCart(C)))throw new Error("createRuntime: failed to prepare cart");return}d.reloadCart()}},reinit(S){if(!v){if(!h){E();return}d.reinit(S)}},getCartState(){return d.animation?.cartState},exportState(){return v?Promise.reject(new Error("Cart handle has been destroyed")):d.exportState()},exportStateJSON(){return v?Promise.reject(new Error("Cart handle has been destroyed")):d.exportStateJSON()},async importState(S,re){if(v)throw new Error("Cart handle has been destroyed");await d.importState(S,re)},peekExportedFramebuffer(){return v?null:d.peekExportedFramebuffer()},peekSeed(){if(!v)return d.peekSeed()},isGenerative(){return v?!1:d.isGenerative()},async step(S=1){if(v)throw new Error("Cart handle has been destroyed");await d.step(S)},async advance(S){if(v)throw new Error("Cart handle has been destroyed");await d.advance(S)},schedule(S){v||d.schedule(S)},getClock(){if(v)throw new Error("Cart handle has been destroyed");return d.getClock()},getRandomState(){if(v)throw new Error("Cart handle has been destroyed");return d.getRandomState()},getReplayMetadata(){return v?Promise.reject(new Error("Cart handle has been destroyed")):d.getReplayMetadata()},get canvas(){return d.canvas},get paused(){return d.paused},set paused(S){v||(d.paused=S)},get tokenData(){return d.tokenData},get isPrepared(){return d.isPrepared},get isLoopRunning(){return d.isLoopRunning},get needsAudio(){return d.needsAudio},get audioLibraries(){return d.audioLibraries}};return y=B,B},async unlockAudio(){await d.unlockAudio()},destroy(){l||(l=!0,y?.destroy(),y=null,R?.disconnect(),R=null,c.clear(),d.destroy())}}}var yt="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==",bt=320,vt=180,ln="Headless harness has been destroyed",wt=!1;function Et(){if(typeof globalThis.ImageData>"u"){class e{constructor(r,i){this.colorSpace="srgb";this.width=r,this.height=i,this.data=new Uint8ClampedArray(r*i*4)}}globalThis.ImageData=e}let t=HTMLCanvasElement.prototype;t.getContext=function(){return{globalAlpha:1,imageSmoothingEnabled:!1,fillStyle:"",save(){},restore(){},fillRect(){},putImageData(){},createImageData(r,i){return{data:new Uint8ClampedArray(r*i*4),width:r,height:i}}}},t.toDataURL=()=>yt,wt=!0}function pn(t,e){let n=document.createElement("div");return Object.defineProperty(n,"clientWidth",{value:t,configurable:!0}),Object.defineProperty(n,"clientHeight",{value:e,configurable:!0}),document.body.appendChild(n),n}function hn(t){let e=t.indexOf(","),n=e>=0?t.slice(e+1):t,r=globalThis.atob(n),i=new Uint8Array(r.length);for(let a=0;a<r.length;a++)i[a]=r.charCodeAt(a);return i}function mn(){return typeof process<"u"&&!!process.versions?.node}async function fn(t,e){if(!mn())throw new Error("captureFrame(path) requires Node.js; omit the path to get the snapshot only");let n;try{({writeFile:n}=await import("node:fs/promises"))}catch(r){let i=r instanceof Error?r.message:String(r);throw new Error(`captureFrame(path) could not load node:fs/promises (${i}). Omit the path, or run under Node.`)}try{await n(t,hn(e))}catch(r){let i=r instanceof Error?r.message:String(r);throw new Error(`captureFrame could not write ${t}: ${i}`)}}function gn(t){wt||Et();let e=t.width??bt,n=t.height??vt,r=pn(e,n),i=[],a=[],o=!1,c=t.onEvent,l=t.onError,y=He({container:r,seed:t.seed,deterministic:{origin:t.origin,actions:t.actions??[]}});y.onError=(d,E)=>{a.push({error:d,info:E}),l?.(d,E)},Object.defineProperty(y,"onError",{configurable:!0,enumerable:!0,get(){return l},set(d){l=d}});let m=d=>{i.push(d),c?.(d)},h=y.mount(t.cart,{initialState:t.initialState,gameManager:t.gameManager,onEvent:m}),b=()=>{if(o)throw new Error(ln)};return{runtime:y,container:r,get events(){return i.slice()},get errors(){return a.slice()},get cart(){return h},async step(d=1){b(),await h.step(d)},async advance(d){b(),await h.advance(d)},schedule(d){b(),h.schedule(d)},dispatch(d){b(),h.dispatch(d)},key(d){b(),h.schedule({type:"key",atFrame:h.getClock().framesElapsed,key:d})},click(d,E){b(),h.schedule({type:"pointer",atFrame:h.getClock().framesElapsed,pointer:{kind:"down",x:d,y:E}})},async inspect(){b();let d=await h.getReplayMetadata();return{state:d.state,events:i.slice(),errors:a.slice(),replay:d,clock:h.getClock()}},async captureFrame(d){b();let E=h.snapshot();return d&&await fn(d,E.pngDataUrl),E},remount(d={}){return b(),i.length=0,a.length=0,"onEvent"in d&&(c=d.onEvent),h=y.mount(t.cart,{initialState:d.initialState??t.initialState,gameManager:d.gameManager??t.gameManager,onEvent:m}),h},destroy(){if(!o){o=!0;try{h.destroy()}finally{try{y.destroy()}finally{r.remove()}}}}}}var q="cyberart.state.save",G="cyberart.state.load";function yn(t,e,n={}){let r=n.persist,i=r?{persist:r}:void 0,a=()=>{e.emit({type:q,payload:i})},o=()=>{e.emit({type:G,payload:i})};t.registerAction("w",a,!0),t.registerAction("W",a,!0),t.registerAction("e",o,!0),t.registerAction("E",o,!0)}function St(t){if(t.type!==q&&t.type!==G)return;let e=t.payload?.persist;return e==="localStorage"?e:void 0}var bn="cyberart-io",vn=1,O="framebuffers";function _e(t,e){return`${t||"unknown"}:${e?_(e):"none"}`}function Ct(t,e){return`${t||"unknown"}:${e||"none"}`}function Le(){return new Promise((t,e)=>{let n=indexedDB.open(bn,vn);n.onupgradeneeded=()=>{let r=n.result;r.objectStoreNames.contains(O)||r.createObjectStore(O)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error??new Error("indexedDB open failed"))})}function wn(t){let e=t.data;return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}function At(t,e){return new Promise((n,r)=>{let a=t.transaction(O,"readonly").objectStore(O).get(e);a.onsuccess=()=>n(a.result),a.onerror=()=>r(a.error??new Error("indexedDB read failed"))})}async function kt(t,e,n){if(typeof indexedDB>"u")return;let r=await Le(),i={width:n.width,height:n.height,data:wn(n)};try{await new Promise((a,o)=>{let c=r.transaction(O,"readwrite");c.oncomplete=()=>a(),c.onerror=()=>o(c.error??new Error("indexedDB write failed")),c.objectStore(O).put(i,_e(t,e))})}finally{r.close()}}async function xt(t,e){if(typeof indexedDB>"u")return null;let n=await Le();try{let r=_e(t,e),i=Ct(t,e),a=await At(n,r)??(r===i?void 0:await At(n,i));if(!a||!a.data||a.width<1||a.height<1)return null;let o=new ImageData(a.width,a.height);return o.data.set(new Uint8ClampedArray(a.data)),o}finally{n.close()}}async function Tt(t,e){if(typeof indexedDB>"u")return;let n=await Le();try{await new Promise((r,i)=>{let a=n.transaction(O,"readwrite");a.oncomplete=()=>r(),a.onerror=()=>i(a.error??new Error("indexedDB delete failed"));let o=a.objectStore(O);o.delete(_e(t,e)),o.delete(Ct(t,e))})}finally{n.close()}}var Oe="cyberart.state.",En="Saved state",Sn="Loaded state",An="Failed to save state",Cn="Failed to load state",kn="No saved state";function F(t,e){let n=t||"unknown";return e?Oe+n+"."+_(e):Oe+n}function xn(t,e,n){return r=>{if(St(r)==="localStorage"){if(r.type===q){Tn(t,e,n);return}r.type===G&&Rn(t,e,n)}}}function J(t){try{let e=JSON.parse(t);if(!e||typeof e!="object")return null;let n=e;if(typeof n.savedAt=="number"&&n.bundle&&typeof n.bundle=="object")return{savedAt:n.savedAt,bundle:n.bundle};let r=e;return typeof r.seed=="string"&&typeof r.version=="number"?{savedAt:0,bundle:r}:null}catch{return null}}async function Tn(t,e,n){let r=t();if(r)try{let i=await r.exportState(),a=i.cartId??e?.();i.generative===!0?(Ln(a),fe(F(a,i.seed),i)):fe(F(a),i);let o=r.peekExportedFramebuffer?.();if(o)try{await kt(a,i.seed,o)}catch(c){console.warn("Failed to save cart framebuffer",c)}n?.(En,"transient")}catch(i){console.error("Failed to save cart state",i),n?.(An,"transient")}}async function Rn(t,e,n){let r=t();if(!r)return;let i=e?.(),a=r.peekSeed?.(),o=r.isGenerative?.()===!0,c=Hn(i,o,a);if(!c){console.warn("No saved cart state for",i||"unknown",o&&a?`(hash ${a})`:""),n?.(kn,"transient");return}try{let l=await xt(i,c.bundle.seed).catch(()=>null);await r.importState(c.bundle,{framebuffer:l}),n?.(Sn,"transient")}catch(l){console.error("Failed to load cart state",l),n?.(Cn,"transient")}}function fe(t,e){let n=JSON.stringify({savedAt:Date.now(),bundle:e});Pn(t,n)}function Pn(t,e){for(;;)try{localStorage.setItem(t,e);return}catch(n){if(!Dn(n)||!In(t))throw n}}function Dn(t){if(!t||typeof t!="object")return!1;let e=t.name,n=t.code;return e==="QuotaExceededError"||e==="NS_ERROR_DOM_QUOTA_REACHED"||n===22||n===1014}function In(t){let e=null,n=1/0;for(let a of Mn()){if(a===t)continue;let o=localStorage.getItem(a);if(!o)continue;let l=J(o)?.savedAt??0;l<n&&(n=l,e=a)}if(!e)return!1;let r=localStorage.getItem(e),i=r?J(r):null;return localStorage.removeItem(e),i?.bundle&&Tt(i.bundle.cartId,i.bundle.seed).catch(()=>{}),!0}function Mn(){let t=[];for(let e=0;e<localStorage.length;e++){let n=localStorage.key(e);n&&n.startsWith(Oe)&&t.push(n)}return t}function Hn(t,e,n){if(e&&n){let i=localStorage.getItem(F(t,n));if(i)return J(i);let a=localStorage.getItem(F(t));if(!a)return null;let o=J(a);if(!o||!_n(o.bundle,n))return null;try{fe(F(t,n),o.bundle)}catch{}return o}let r=localStorage.getItem(F(t));return r?J(r):null}function _n(t,e){return typeof t.seed=="string"&&_(t.seed)===_(e)}function Ln(t){let e=F(t),n=localStorage.getItem(e);if(!n)return;let r=J(n);if(r&&typeof r.bundle.seed=="string"){let i=F(t,r.bundle.seed);if(!localStorage.getItem(i))try{fe(i,r.bundle)}catch{return}}localStorage.removeItem(e)}var ne=1,Fe="cyberart.diagnostic.rejected",ge=8,On=new Set(["intent","state","diagnostic"]),Fn=new Set([q,G]);function Rt(t){return typeof t=="string"&&On.has(t)}function Pt(t){if(t.kind!==void 0)return Rt(t.kind)?t.kind:void 0;if(typeof t.type!="string"||t.type.length===0)return;if(Fn.has(t.type))return"intent";let e=t.type.split(".");if(e.length<2)return;let n=e[1];return Rt(n)?n:void 0}function Dt(t,e){let n=t.split("."),r=e.split(".");if(n.length!==r.length)return!1;for(let i=0;i<n.length;i++)if(n[i]!=="*"&&n[i]!==r[i])return!1;return!0}function Y(t,e){for(let n of t)if(Dt(n,e))return!0;return!1}function Nn(t){if(t===void 0)return{ok:!0,value:void 0};try{return{ok:!0,value:JSON.parse(JSON.stringify(t))}}catch{return{ok:!1}}}function ye(t,e){if(!t||typeof t.type!="string"||t.type.length===0)return{ok:!1,reason:"malformed",detail:"type is required"};if(t.schemaVersion!==void 0&&t.schemaVersion!==ne)return{ok:!1,reason:"malformed",detail:`unsupported schemaVersion ${String(t.schemaVersion)}`};let n=Pt(t);if(!n)return{ok:!1,reason:"malformed",detail:`cannot infer kind from type "${t.type}"`};let r=Nn(t.payload);if(!r.ok)return{ok:!1,reason:"malformed",detail:"payload is not JSON-serializable"};let i=e.createId(),a=typeof t.correlationId=="string"&&t.correlationId.length>0?t.correlationId:i,o=typeof t.causationId=="string"&&t.causationId.length>0?t.causationId:e.causationId,c=typeof t.target=="string"&&t.target.length>0?t.target:void 0,l=e.maxHops??ge,y=e.parentHops===void 0?l:Math.max(0,e.parentHops-1),m=typeof t.idempotencyKey=="string"&&t.idempotencyKey.length>0?t.idempotencyKey:void 0,h={schemaVersion:ne,type:t.type,kind:n,source:e.source,id:i,correlationId:a,seq:e.seq,hops:y};return c&&(h.target=c),o&&(h.causationId=o),m&&(h.idempotencyKey=m),r.value!==void 0&&(h.payload=r.value),{ok:!0,envelope:h}}var Bn=new Set(["rate-limited","storm-detected","hop-limit","loop-detected","not-subscribed"]),Un=8,Kn=8,Vn=16,Wn=256,$n=["*.intent.*"];function jn(t={}){let e=t.hostSource??"host",n="router",r=t.maxPerTurn??Un,i=t.maxCausationDepth??Kn,a=t.maxHops??ge,o=t.maxCorrelationPerTurn??Vn,c=t.maxIndex??Wn,l=t.maxPerWindow,y=t.windowMs??1e3,m=t.now??Date.now,h=0,b=t.createId??(()=>`evt-${++h}`),w=new Map,d=[],E=new Map,R=new Map,be=new Map,C=0,P=0,N=[],v=!1;function B(s,u,f){for(s.set(u,f);s.size>c;){let g=s.keys().next().value;if(g===void 0)break;s.delete(g)}}function S(s){B(E,s.id,{type:s.type,source:s.source,causationId:s.causationId,hops:s.hops,correlationId:s.correlationId,idempotencyKey:s.idempotencyKey})}function re(s,u){u&&(s.correlationId||(s.correlationId=u.correlationId),s.causationId||(s.causationId=u.id),!s.idempotencyKey&&u.idempotencyKey&&(s.idempotencyKey=`${u.idempotencyKey}::${s.type}`))}function Ne(s,u){if(s){let f=E.get(s);return f?f.hops:a}return u}function Be(s,u){return`${s}\0${u}`}function Ue(s,u){s.idempotencyKey&&B(be,Be(s.source,s.idempotencyKey),u)}function ve(s,u){if(u)return be.get(Be(s,u))}function It(s){return ve(s.source,s.idempotencyKey)}function Mt(s){return s.seq+=1,s.seq}function Ht(s,u){if(!(typeof u.causationId=="string"&&u.causationId.length>0))return s.lastDelivered}function Ke(s){let u=new Set,f=new Set([`${s.type}\0${s.source}`]),g=s.causationId,p=0;for(;g;){if(p+=1,p>i||u.has(g))return!0;u.add(g);let A=E.get(g);if(!A)break;let D=`${A.type}\0${A.source}`;if(f.has(D))return!0;f.add(D),g=A.causationId}return!1}function _t(s){let u=(R.get(s)??0)+1;return R.set(s,u),u}function Ve(s,u){l!==void 0&&(s.emitTimestamps=s.emitTimestamps.filter(f=>u-f<y))}function Lt(s,u){return(u.kind==="state"||u.kind==="diagnostic")&&!s.authoritative?!1:Y(s.emit,u.type)}function We(s){for(let u of d)if(Y(u.patterns,s.type))try{u.listener(s)}catch{}}function Ot(s){if(s.target){let u=w.get(s.target);if(!u||!Y(u.subscribe,s.type))return;u.channel.dispatch(s),u.lastDelivered={id:s.id,hops:s.hops,correlationId:s.correlationId,idempotencyKey:s.idempotencyKey};return}for(let u of w.values())Y(u.subscribe,s.type)&&(u.channel.dispatch(s),u.lastDelivered={id:s.id,hops:s.hops,correlationId:s.correlationId,idempotencyKey:s.idempotencyKey})}function Ft(s,u,f,g,p,A,D){let H={reason:g,eventType:u,source:f};p&&(H.detail=p),P+=1;let X=b(),U={schemaVersion:ne,type:Fe,kind:"diagnostic",source:n,id:X,correlationId:A??X,seq:P,hops:0,payload:H};D&&(U.causationId=D),S(U);let ze=w.get(s);ze&&ze.channel.dispatch(U),We(U)}function x(s,u,f,g,p){Ft(s,p?.type??(typeof u.type=="string"?u.type:""),p?.source??s,f,g,p?.correlationId,p?.id),p?.idempotencyKey&&!Bn.has(f)&&Ue(p,{status:"rejected"})}function Nt(s){S(s),Ue(s,{status:"accepted",envelope:s}),_t(s.correlationId),We(s),Ot(s)}function $e(s,u,f,g){if(!f.ok){x(s,u,"malformed",f.detail);return}let p=f.envelope,A=It(p);if(A)return A.status==="accepted"?A.envelope:void 0;if(p.hops<1){x(s,u,"hop-limit","no hops remaining",p);return}if(p.target&&p.target!==e){let D=w.get(p.target);if(!D){x(s,u,"unknown-target",`unknown target "${p.target}"`,p);return}if(!Y(D.subscribe,p.type)){x(s,u,"not-subscribed",`target "${p.target}" does not subscribe to ${p.type}`,p);return}}if(g){if(!Lt(g,p)){x(s,u,"unauthorized","source may not emit this event",p);return}if(g.emitsThisTurn+=1,g.emitsThisTurn>r){x(s,u,"rate-limited","maxPerTurn exceeded",p);return}if(l!==void 0){let H=m();if(Ve(g,H),g.emitTimestamps.push(H),g.emitTimestamps.length>l){x(s,u,"rate-limited","maxPerWindow exceeded",p);return}}if(Ke(p)){x(s,u,"loop-detected","causation chain cycle or depth exceeded",p);return}if((R.get(p.correlationId)??0)+1>o){x(s,u,"storm-detected","correlationId storm",p);return}if(t.validate){let H;try{H=t.validate(p)}catch(X){let U=X instanceof Error?X.message:"validate threw";x(s,u,"host-rejected",U,p);return}if(H!==!0){x(s,u,"host-rejected",H.detail,p);return}}}else{if(Ke(p)){x(s,u,"loop-detected","causation chain cycle or depth exceeded",p);return}if((R.get(p.correlationId)??0)+1>o){x(s,u,"storm-detected","correlationId storm",p);return}}return Nt(p),p}function Bt(s,u){let f=w.get(s);if(!f)return;let g={...u},p=Ht(f,g);if(re(g,p),ve(f.id,g.idempotencyKey))return;let D=Mt(f),H=ye(g,{source:f.id,createId:b,seq:D,causationId:p?.id,maxHops:a,parentHops:Ne(g.causationId??p?.id,p?.hops)});$e(s,g,H,f)}function Ut(s,u){let f=u?.cause,g={...s};re(g,f);let p=ve(e,g.idempotencyKey);if(p)return p.status==="accepted"?p.envelope:void 0;C+=1;let A=ye(g,{source:e,createId:b,seq:C,causationId:g.causationId,maxHops:a,parentHops:Ne(g.causationId,f?.hops)});return $e(e,g,A,void 0)}function Kt(){if(!v){v=!0;try{for(;N.length>0;){let s=N.shift();s&&(s.kind==="cart"?Bt(s.participantId,s.event):s.result=Ut(s.event,s.extras))}}finally{v=!1}}}function je(s){N.push(s),Kt()}return{attach(s,u,f={}){if(s===e||s===n)throw new Error(`createEventRouter: "${s}" is a reserved participant id`);for(let A of w.values())if(A.channel===u&&A.id!==s)throw new Error(`createEventRouter: channel already attached as "${A.id}"`);w.get(s)?.unsubscribe();let p={id:s,channel:u,emit:f.emit??$n,subscribe:f.subscribe??[],authoritative:f.authoritative===!0,seq:0,emitsThisTurn:0,emitTimestamps:[],unsubscribe:()=>{}};p.unsubscribe=u.onEvent(A=>{je({kind:"cart",participantId:s,event:A})}),w.set(s,p)},detach(s){let u=w.get(s);u&&(u.unsubscribe(),w.delete(s))},publish(s,u){let f={kind:"publish",event:s,extras:u};return je(f),f.result},subscribe(s,u){let f={patterns:s,listener:u};return d.push(f),()=>{let g=d.indexOf(f);g>=0&&d.splice(g,1)}},turn(){R.clear();for(let s of w.values())s.emitsThisTurn=0,s.lastDelivered=void 0,l!==void 0&&Ve(s,m())}}}export{De as ASSET_FAILED_EVENT,Pe as ASSET_READY_EVENT,ie as CYBERART_CANVAS_ATTR,vt as DEFAULT_HEADLESS_HEIGHT,bt as DEFAULT_HEADLESS_WIDTH,ge as DEFAULT_MAX_HOPS,ne as EVENT_ENVELOPE_VERSION,yt as HEADLESS_PNG_DATA_URL,z as HostChannel,k as IncompatibleCartStateError,ae as KeyboardManager,se as PointerManager,Fe as REJECTED_EVENT_TYPE,Q as Random,xn as attachCartStatePersistence,ce as canonicalizeSeed,jn as createEventRouter,gn as createHeadlessHarness,He as createRuntime,oe as createVirtualClock,W as createWallClock,ft as describeReplayMismatch,Pt as inferEventKind,Et as installHeadlessCanvas,Dt as matchEventPattern,ye as normalizeEvent,yn as registerCartStateHotkeys,le as resolveRuntimeSeed};
|
|
8
|
+
var Mn=(e,t)=>()=>(e&&(t=e(e=0)),t);var $n={};function Kn(e,t){let n=e.indexOf(Kt);if(n===-1)return null;let r=n+Kt.length,a=`const __cyberSkip=new Set(${JSON.stringify(t)});const __cyberOrig=registerProcessor;registerProcessor=(n,p)=>__cyberSkip.has(n)?undefined:__cyberOrig(n,p);`;return e.slice(0,r)+a+e.slice(r)}var nt,je,Hn,ke,Kt,$t=Mn(()=>{"use strict";nt=/AudioWorkletProcessor with name:\s*["'`][^"'`]+["'`]\s+is already registered/i,je="__cyberartWorkletPatchApplied";typeof window<"u"&&!window[je]&&(window.addEventListener("error",e=>{let t=e?.message??"";nt.test(t)&&(e.preventDefault(),e.stopImmediatePropagation())},!0),window.addEventListener("unhandledrejection",e=>{let t=e?.reason,n=typeof t=="string"?t:t?.message??"";nt.test(n)&&e.preventDefault()}),window[je]=!0);Hn=!1,ke=(...e)=>{Hn&&console.log("[workletPatch]",...e)},Kt="((AudioWorkletProcessor,registerProcessor)=>{";if(typeof AudioWorklet<"u"&&!AudioWorklet.prototype[je]){let e=new WeakMap,t=/registerProcessor\s*\(\s*['"`]([^'"`]+)['"`]/g,n=AudioWorklet.prototype.addModule,r=0;AudioWorklet.prototype.addModule=async function(a,s){let u=++r,f=e.get(this);f||(f=new Set,e.set(this,f)),ke(`#${u} addModule`,{url:a.slice(0,64),isBlob:a.startsWith("blob:"),knownBefore:[...f]});let v=a,m=null;if(a.startsWith("blob:")){let h=null;try{h=await(await fetch(a)).text()}catch(S){ke(`#${u} blob fetch failed`,S)}if(h!==null){let S=new Set;for(let E of h.matchAll(t))S.add(E[1]);if(S.size>0){let E=[...S].filter(l=>f.has(l)),N=[...S].filter(l=>!f.has(l));if(E.length>0&&N.length===0){ke(`#${u} short-circuit \u2014 all processors already registered`,E);return}if(E.length>0&&N.length>0){let l=Kn(h,E);if(l!==null){let c=new Blob([l],{type:"application/javascript"});m=URL.createObjectURL(c),v=m,ke(`#${u} rewrote blob; skipping`,E,"allowing",N)}else ke(`#${u} blob rewrite failed; passing original through`)}N.forEach(l=>f.add(l))}}}return n.call(this,v,s).then(()=>{m&&URL.revokeObjectURL(m)},h=>{m&&URL.revokeObjectURL(m);let S=(h&&h.message)??"";if(!(nt.test(S)||/already registered/i.test(S)))throw h})},AudioWorklet.prototype[je]=!0}});var xt=()=>{let e=["ms","moz","webkit","o"];for(let t=0;t<e.length&&!window.requestAnimationFrame;++t)window.requestAnimationFrame=window[e[t]+"RequestAnimationFrame"],window.cancelAnimationFrame=window[e[t]+"CancelAnimationFrame"]||window[e[t]+"CancelRequestAnimationFrame"]},j=window.devicePixelRatio||1,de=/Headless/i.test(navigator.userAgent),pi=/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)||/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.platform);function Rt(){return Math.min(window.innerWidth,window.innerHeight)}var _e="data-cyberart-canvas",ue=class{constructor(t,n,r=1,i={}){this.width=t,this.height=n;let a=i.container,s=i.adoptFromDocument??!a,u=a?a.querySelector(`canvas[${_e}]`)??a.querySelector("canvas"):null;if(u)this.canvas=u,this.adopted=!0;else if(s){let f=document.getElementById("canvas")??document.querySelector("canvas");f?(this.canvas=f,this.adopted=!0):(this.canvas=document.createElement("canvas"),this.canvas.setAttribute("id","canvas"),this.adopted=!1)}else this.canvas=document.createElement("canvas"),this.adopted=!1;this.canvas.hasAttribute(_e)||this.canvas.setAttribute(_e,""),this.canvas.style.display="block",this.canvas.style.margin="auto",this.ctx=this.canvas.getContext("2d",{colorSpace:"display-p3",alpha:!1}),this.ctx.globalAlpha=r,this.ctx.imageSmoothingEnabled=!1,this.setSize(t,n)}setSize(t,n){this.width=t,this.height=n,this.canvas.width=t,this.canvas.height=n,this.canvas.style.width=`${t/j}px`,this.canvas.style.height=`${n/j}px`,this.imageData=this.ctx.createImageData(t,n),this.ctx.putImageData(this.imageData,0,0)}_blank(t=1){let n=t?Math.max(t,.03):1;this.ctx.fillStyle=`rgba(0,0,0,${n})`,this.ctx.fillRect(0,0,this.width,this.height)}clearAll(){this.ctx.save(),this.ctx.globalAlpha=1,this._blank(),this.ctx.restore()}};function Dt(e,t){let n=e/t,r,i;return n>1?(r=e,i=~~(e/n)):(i=t,r=~~(t*n)),{width:r,height:i,iWidth:1/r,iHeight:1/i,area:r*i,largeDim:Math.max(r,i),smallDim:Math.min(r,i),aspectRatio:n}}function It(e,t=window.innerWidth,n=window.innerHeight){let r=Rt(),i,a;return n<t?e>1?t>=r*e?(i=r*e,a=r):(i=t,a=i/e):(i=r*e,a=r):e>1?(i=r,a=r/e):n<r/e?(a=n,i=a*e):(i=r,a=r/e),[i,a]}var Oe=class{constructor(t=!1,n=!0){this.debugMode=t,this.actionMap={},this.listening=n,this.checkKeypress=this.checkKeypress.bind(this),this.registerAction=this.registerAction.bind(this),this.listening&&window.addEventListener("keydown",this.checkKeypress,!1)}checkKeypress({key:t}){this.debugMode&&console.log(`Pressed ${t}`),t in this.actionMap&&this.actionMap[t]()}inject(t){this.checkKeypress({key:t})}registerAction(t,n,r=!1){if(t.length!==1)throw new Error(`Only single-character actions may be registered. Cannot register: ${t}`);if(t in this.actionMap&&!r)throw new Error(`Action already exists for code: ${t}`);this.actionMap[t]=n}destroy(){this.listening&&window.removeEventListener("keydown",this.checkKeypress,!1),this.actionMap={}}},Mt=Oe;var Le=class{constructor(t,n={}){this.x=-1;this.y=-1;this.isDown=!1;this.clicks=[];this.canvas=t,this.listening=n.listen!==!1,this.onPointerDown=this.onPointerDown.bind(this),this.onPointerMove=this.onPointerMove.bind(this),this.onPointerUp=this.onPointerUp.bind(this),this.listening&&(t.addEventListener("pointerdown",this.onPointerDown),t.addEventListener("pointermove",this.onPointerMove),t.addEventListener("pointerup",this.onPointerUp))}toCanvasCoords(t){let n=this.canvas.getBoundingClientRect();return{x:(t.clientX-n.left)*(this.canvas.width/n.width),y:(t.clientY-n.top)*(this.canvas.height/n.height)}}onPointerDown(t){let{x:n,y:r}=this.toCanvasCoords(t);this.x=n,this.y=r,this.isDown=!0,this.clicks.push({x:n,y:r})}onPointerMove(t){let{x:n,y:r}=this.toCanvasCoords(t);this.x=n,this.y=r}onPointerUp(t){let{x:n,y:r}=this.toCanvasCoords(t);this.x=n,this.y=r,this.isDown=!1}hasClick(){return this.clicks.length>0}consumeClick(){return this.clicks.shift()??null}inject(t,n,r){this.x=n,this.y=r,t==="down"?(this.isDown=!0,this.clicks.push({x:n,y:r})):t==="up"&&(this.isDown=!1)}destroy(){this.listening&&(this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp))}},Ft=Le;function ce(){return{now:()=>performance.now()}}function Ve(e=0){let t=e;return{now:()=>t,set(n){t=n},advance(n){t+=n}}}var _t=(e,t,n,r)=>({now:e,startTime:t,elapsedSinceStart:e-t,deltaSinceLastUpdate:n===null?0:e-n,deltaSinceLastRender:r===null?0:e-r}),Ne=class{constructor(t,n,r,i,a,s={}){this.startTime=0;this.lastUpdateAt=null;this.lastRenderAt=null;this.clockOffsetMs=0;this.pauseStartedAt=null;this.renderAnimation=this.renderAnimation.bind(this),this.dimensionContext=Dt(t,n),this.R=r,this.gameManager=s.gameManager,this.hostChannel=s.hostChannel,this.clock=s.clock??ce(),this.canvas=new ue(this.dimensionContext.width,this.dimensionContext.height,1,s.canvasMount),this.drawingContext=this.canvas.ctx,this.keyboardManager=new Mt(!1,s.captureKeyboard??!0),this.pointerManager=new Ft(this.canvas.canvas,{listen:s.listenToPointer!==!1}),this.animationCart=a;let u=s.customState;this.featureState=a.getDefaultFeatureState?.(this.R,this.dimensionContext,i,this.keyboardManager,u,this.pointerManager,this.gameManager,this.hostChannel),this.cartState=a.getDefaultState(this.R,this.dimensionContext,i,this.keyboardManager,u,this.pointerManager,this.gameManager,this.featureState,this.hostChannel),this.startTime=this.clock.now(),this.canvas.clearAll()}captureFramebuffer(){let t=this.canvas.imageData,n=new ImageData(t.width,t.height);return n.data.set(t.data),n}restoreFramebuffer(t){let n=this.canvas.imageData;return n.width!==t.width||n.height!==t.height||n.data.length!==t.data.length?!1:(n.data.set(t.data),this.drawingContext.putImageData(n,0,0),!0)}setPaused(t){let n=this.clock.now();if(t){this.pauseStartedAt===null&&(this.pauseStartedAt=n);return}this.pauseStartedAt!==null&&(this.clockOffsetMs+=n-this.pauseStartedAt,this.pauseStartedAt=null)}resolveNow(t){let n=this.pauseStartedAt!==null?t-this.pauseStartedAt:0;return t-this.clockOffsetMs-n}getElapsedSinceStart(t=this.clock.now()){return Math.max(0,this.resolveNow(t)-this.startTime)}restoreClock(t,n){this.pauseStartedAt=null,this.lastUpdateAt=null,this.lastRenderAt=null;let r=Math.max(0,t);if(typeof n=="number"&&Number.isFinite(n)){this.startTime=n,this.clockOffsetMs=this.clock.now()-n-r;return}this.clockOffsetMs=0,this.startTime=this.clock.now()-r}getRandomState(){return this.R.getState()}injectKey(t){this.keyboardManager.inject(t)}injectPointer(t,n,r){this.pointerManager.inject(t,n,r)}async updateAnimationState(t,n,r=this.clock.now()){let i=this.resolveNow(r),a=_t(i,this.startTime,this.lastUpdateAt,this.lastRenderAt);this.cartState=this.animationCart.update(this.R,t,n,this.dimensionContext,this.cartState,this.keyboardManager,this.pointerManager,this.gameManager,a,this.featureState,this.hostChannel),this.lastUpdateAt=i}async renderAnimation(t,n,r=this.clock.now()){let i=this.resolveNow(r),a=_t(i,this.startTime,this.lastUpdateAt,this.lastRenderAt);this.animationCart.render(this.R,t,n,this.dimensionContext,this.cartState,this.drawingContext,this.canvas.imageData,this.pointerManager,this.gameManager,a,this.featureState,this.hostChannel),this.lastRenderAt=i}getCanvas(){return this.canvas.canvas}getDrawDetails(){return[this.canvas.canvas,0,0,this.dimensionContext.width,this.dimensionContext.height]}teardown(){try{this.animationCart.teardown?.(this.cartState,this.featureState)}catch(t){console.error("Error during cart teardown",t)}this.keyboardManager.destroy(),this.pointerManager.destroy()}};var He=class extends ue{constructor(t,n,r=1,i=!0,a={}){if(super(t,n,r,a),this.adopted)return;let s=a.container;if(s){this.canvas.parentNode!==s&&s.appendChild(this.canvas);return}if(i){let u=document.getElementById("canvas");u&&u!==this.canvas&&u.parentNode===document.body&&document.body.removeChild(u),document.body.appendChild(this.canvas)}}};function Ot(e){let t=parseInt(e.substring(0,8),16),n=parseInt(e.substring(8,8),16),r=parseInt(e.substring(16,8),16),i=parseInt(e.substring(24,8),16);return{next:()=>{t|=0,n|=0,r|=0,i|=0;let s=(t+n|0)+i|0;return i=i+1|0,t=n^n>>>9,n=r+(r<<3)|0,r=r<<21|r>>>11,r=r+s|0,(s>>>0)/4294967296},getRegs:()=>({a:t,b:n,c:r,d:i}),setRegs:s=>{t=s.a,n=s.b,r=s.c,i=s.d}}}var Se=class{constructor(t){this.seed=t.hash,this.useA=!1,this.genA=Ot(t.hash.substring(2,32)),this.genB=Ot(t.hash.substring(34,32)),this.prngA=this.genA.next,this.prngB=this.genB.next;for(let n=0;n<1e6;n+=2)this.prngA(),this.prngB()}getState(){let t=this.genA.getRegs(),n=this.genB.getRegs();return{seed:this.seed,useA:this.useA,prngA:{a:t.a,b:t.b,c:t.c,d:t.d},prngB:{a:n.a,b:n.b,c:n.c,d:n.d}}}setState(t){if(t.seed!==this.seed)throw new Error(`Random.setState: seed ${t.seed} does not match ${this.seed}`);this.useA=t.useA,this.genA.setRegs(t.prngA),this.genB.setRegs(t.prngB)}r_zero_one(){return this.useA=!this.useA,this.useA?this.prngA():this.prngB()}dec(t,n){return t===void 0?this.r_zero_one():n===void 0?t*this.r_zero_one():t+(n-t)*this.r_zero_one()}int(t,n){return n===void 0&&(n=t,t=0),Math.floor(this.dec(t,n))}bool(t=.5){return this.r_zero_one()<t}sign(){return this.bool()?1:-1}choose(t){return t[this.int(t.length)]}};var Vt="bafybeicjwcq5lxxtfnyj4p2ugcr7ctyb5wl62cbcechj6tsabdq5whcs7u",Lt="https://ipfs.io/ipfs/";function Fn(e){return e.endsWith("/")?e:`${e}/`}var Ce=null;function _n(e){return[...Array(e)].map(()=>Math.floor(Math.random()*16).toString(16)).join("")}function On(e){return e&&e.length>0?e:[{cid:Vt}]}function Ln(e){return e.startsWith("0x")?e:`0x${e}`}var Nt=/^(0[xX])?[0-9a-fA-F]{64}$/;function Vn(e){let t="",n=2166136261,r=522970236;for(let i=0;t.length<64;i++){for(let a=0;a<e.length;a++)n^=e.charCodeAt(a)+i,n=Math.imul(n,16777619),r^=e.charCodeAt(a)+i*17,r=Math.imul(r,16777619);t+=(n>>>0).toString(16).padStart(8,"0"),t+=(r>>>0).toString(16).padStart(8,"0")}return`0x${t.slice(0,64)}`}function Ke(e){let t=typeof e=="number"?String(e):e;return Nt.test(t)?`0x${(t.startsWith("0x")||t.startsWith("0X")?t.slice(2):t).toLowerCase()}`:Vn(t)}function $e(e,t){if(typeof e=="number"||t==="deterministic")return Ke(e);let n=String(e);return Nt.test(n)?Ke(n):n.startsWith("0x")||n.startsWith("0X")?n:`0x${n}`}function Nn(e){if(!e&&typeof tokenData<"u"&&tokenData?.hash)return{hash:tokenData.hash,tokenId:String(tokenData.tokenId),externalAssetDependencies:On(tokenData.externalAssetDependencies),preferredIPFSGateway:Fn(tokenData.preferredIPFSGateway||Lt),preferredArweaveGateway:tokenData.preferredArweaveGateway};let t=typeof window<"u"?new URLSearchParams(window.location.search):new URLSearchParams;return{hash:e?Ln(e):t.get("hash")||`0x${_n(64)}`,tokenId:"18009999",externalAssetDependencies:[{cid:Vt}],preferredIPFSGateway:Lt}}function tt(e){let t=e?.useCache!==!1;if(t&&Ce&&!e?.hash)return Ce;let n=Nn(e?.hash);return t?Ce=n:Ce||(Ce=n),n}function Ht(e){return new Array(32).fill(null).map((t,n)=>parseInt(e.hash.slice(2+n*2,4+n*2),16))}async function rt(){let e=await import("tone");if(typeof e.start=="function")return e;let t=e.default;return t&&typeof t.start=="function"?t:e}var jt={id:"tone",async load(){await Promise.resolve().then(()=>($t(),$n))},async unlock(){await jt.load(),await(await rt()).start()},async resumeIfSuspended(){let e=await rt();e.context.state==="suspended"&&await e.context.resume()},async suspendIfRunning(){let t=(await rt()).context.rawContext;"suspend"in t&&t.state==="running"&&await t.suspend()}},Ut={tone:jt};function it(e){if(!e)return[];let t=Array.isArray(e)?e:[e],n=[];for(let r of t){if(!(r in Ut)){console.warn(`Unknown audio library "${r}"`);continue}let i=r;n.includes(i)||n.push(i)}return n}function at(e){return e.map(t=>Ut[t])}var Ue="$cyberartTa",$=class extends Error{constructor(t){super(t),this.name="IncompatibleCartStateError"}},ot={Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array};function jn(e){for(let t of Object.keys(ot))if(e instanceof ot[t])return t}function Wt(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function B(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function st(e){return B(e)?typeof e[Ue]=="string"&&Array.isArray(e.d):!1}function Un(e){return e==null?!1:typeof e=="function"?!0:!(typeof e!="object"||Array.isArray(e)||Wt(e)||B(e))}var Bn=new Set(["audioContextStarted","midiSynths","keepRatioPrimed","audioInitStarted","musicSeekApplied"]);function Bt(e){return e===null?"null":st(e)?String(e[Ue]):Array.isArray(e)?"array":B(e)?"object":typeof e}function Wn(e,t){return e===t||e==="null"||t==="null"}function ee(e){return e.trim().toLowerCase().replace(/^0x/,"")}function zt(e,t,n,r){if(!(!n&&!r)&&ee(e)!==ee(t))throw new $(`Generative cart state is for seed "${t}", but the live token is "${e}"`)}function le(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function qt(e,t){let n=e.dimensions;if(n&&le(n.width)&&le(n.height))return n;if(t&&le(t.width)&&le(t.height))return{width:t.width,height:t.height};if(B(e.state)){let r=e.state.containerWidth,i=e.state.containerHeight;if(le(r)&&le(i))return{width:r,height:i}}return null}function pe(e,t=new WeakSet){if(e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)?e:null;if(!(typeof e=="function"||typeof e>"u"||typeof e=="bigint"||typeof e=="symbol")){if(Wt(e)){let n=jn(e);return n?{[Ue]:n,d:Array.from(e)}:void 0}if(typeof e=="object"&&!t.has(e)){t.add(e);try{if(Array.isArray(e)){let i=[],a=0;for(let s of e){let u=pe(s,t);u!==void 0&&(i.push(u),a++)}return e.length>0&&a===0?void 0:i}if(!B(e)||Un(e))return;let n=Object.keys(e),r={};for(let i of n){if(Bn.has(i))continue;let a=pe(e[i],t);a!==void 0&&(r[i]=a)}return n.length>0&&Object.keys(r).length===0?void 0:r}finally{t.delete(e)}}}}function Pe(e){if(st(e)){let t=ot[e[Ue]];return t?new t(e.d.map(n=>Number(n))):e}if(Array.isArray(e))return e.map(t=>Pe(t));if(B(e)){let t={};for(let n of Object.keys(e))t[n]=Pe(e[n]);return t}return e}function dt(e,t,n,r,i=!0){if(i&&n&&r&&n!==r)throw new $(`Cart state is for "${r}", but the live cart is "${n}"`);if(!B(t)){if(i)throw new $("Cart state snapshot is empty");return}let a=Object.keys(t);if(a.length===0){if(i)throw new $("Cart state snapshot is empty");return}let s=pe(e);if(!B(s)||Object.keys(s).length===0){if(i)throw new $("Live cart has no serializable state");return}let u=a.filter(f=>f in s);if(u.length===0){if(i)throw new $("Cart state snapshot does not overlap the live cart shape");return}for(let f of u){let v=Bt(s[f]),m=Bt(t[f]);if(!Wn(v,m))throw new $(`Cart state field "${f}" has type ${m}, live cart expects ${v}`);if(v==="object"){let h=t[f],S=e[f];B(h)&&!st(h)&&dt(S,h,void 0,void 0,!1)}}}function Gt(e,t){if(!B(e)||!B(t))return;let n=pe(e);if(B(n))for(let r of Object.keys(t))r in n&&(e[r]=Pe(t[r]))}function Yt(e){let t=typeof e=="string"?JSON.parse(e):e;if(!t||typeof t!="object")throw new $("Cart state bundle is not an object");if(t.version!==1)throw new $(`Unsupported cart state version ${String(t.version)}`);if(typeof t.seed!="string"||typeof t.framesElapsed!="number")throw new $("Cart state bundle is missing seed or framesElapsed");return t}var Te="cyberart.asset.ready",xe="cyberart.asset.failed";function te(e){try{return JSON.parse(JSON.stringify(e))}catch{return e}}function W(e){try{return JSON.stringify(e)}catch{return String(e)}}function ut(e,t,n){let r=t??[],i=n??[],a=Math.max(r.length,i.length);for(let s=0;s<a;s++)if(W(r[s])!==W(i[s]))return`${e}[${s}]: ${W(r[s])} vs ${W(i[s])}`}function Jt(e,t){let n=[];e.seed!==t.seed&&n.push(`seed: ${e.seed} vs ${t.seed}`),e.clock.framesElapsed!==t.clock.framesElapsed&&n.push(`framesElapsed: ${e.clock.framesElapsed} vs ${t.clock.framesElapsed}`),e.clock.now!==t.clock.now&&n.push(`now: ${e.clock.now} vs ${t.clock.now}`),e.clock.frameRate!==t.clock.frameRate&&n.push(`frameRate: ${e.clock.frameRate} vs ${t.clock.frameRate}`),W(e.rng)!==W(t.rng)&&n.push(`rng: ${W(e.rng)} vs ${W(t.rng)}`);let r=ut("actions",e.actions,t.actions);r&&n.push(r);let i=ut("applied",e.applied,t.applied);i&&n.push(i);let a=ut("events",e.events,t.events);return a&&n.push(a),W(e.state)!==W(t.state)&&n.push(`state: ${W(e.state)} vs ${W(t.state)}`),n}function Xt(e){return{type:e.status==="ready"?Te:xe,kind:"state",payload:e.detail===void 0?{id:e.id}:{id:e.id,detail:e.detail}}}function qn(e){if(!e||typeof e!="object")return 0;let t=e;return typeof t.startTime=="number"&&typeof t.lastSimulationUpdateAt=="number"?Math.max(0,t.lastSimulationUpdateAt-t.startTime):0}function Gn(e,t){if(typeof window.resizeTo!="function")return!1;try{if(window.top!==window)return!1}catch{return!1}let n=Math.max(1,Math.round(e)),r=Math.max(1,Math.round(t)),i=Math.max(0,window.outerWidth-window.innerWidth),a=Math.max(0,window.outerHeight-window.innerHeight);try{window.resizeTo(n+i,r+a)}catch{return!1}return Math.abs(window.innerWidth-n)<=8&&Math.abs(window.innerHeight-r)<=8}var Yn=[[0,0],[16,9],[9,16],[4,3],[3,4],[2,1],[1,2],[3,1],[1,3],[1,1]],lt=Yn[0],Jn=lt[0]/lt[1],ct=30,Xn=120,Qn=3840/2160,Zn=2160/3840,Be=class{constructor(t=ct,n=!1,r=window.innerWidth,i=window.innerHeight,a=!0,s,u={}){this.framesElapsed=0;this.frameRate=ct;this._paused=!1;this.savedToken=!1;this.prepared=!1;this.loopRunning=!1;this.fallbackAudio=[];this.audioLibrariesInternal=[];this.virtualClock=null;this.scriptedActions=[];this.initialScriptedActions=[];this.appliedActions=[];this.consumedActionIndexes=new Set;this.outboundEvents=[];this.consecutiveErrorCount=0;this.lastErrorLogAt=0;this.reinitStayPaused=!1;this.reinitPending=!1;this.lastExportedFramebuffer=null;this.pinnedOutput=null;this.pinViewportAtImport=null;this.importing=!1;this.drawLoop=this.drawLoop.bind(this),this.loadCart=this.loadCart.bind(this),this.prepareCart=this.prepareCart.bind(this),this.beginPlayback=this.beginPlayback.bind(this),this.reinit=this.reinit.bind(this),this.tuneFramerate=this.tuneFramerate.bind(this),this.container=u.container,this.seed=u.seed,this.captureKeyboard=u.captureKeyboard??!0,this.customState=u.customState,this.hostChannel=u.hostChannel,this.fallbackAudio=it(u.audio),this.audioLibrariesInternal=this.fallbackAudio;let f=u.deterministic;this.deterministic=!!f;let v=f&&typeof f=="object"?f:{};if(this.deterministic){if(u.clock){let m=u.clock;if(typeof m.advance!="function")throw new Error("deterministic mode requires a virtual clock with advance()");this.virtualClock=m,this.clock=m}else this.virtualClock=Ve(v.origin??0),this.clock=this.virtualClock;this.initialScriptedActions=te(v.actions??[]),this.scriptedActions=te(this.initialScriptedActions)}else this.clock=u.clock??ce();this.isBodyCanvas=this.container?!1:a,this.autoMode=n,this.aspectRatio=Jn,this.selectedAsp=lt,this.isFullscreen=!!document.fullscreenElement,this.updateFrameRate(t),this.tempUnpause=!1,this.synchronous=de,this.containerWidth=r,this.containerHeight=i,this.gameManager=s,this.init(!0)}setGameManager(t){this.gameManager=t}reinit(t){if(!this.importing){if(this.shouldKeepPinnedOutput()){this.fitPinnedCanvas();return}this.reinitPending||(this.reinitStayPaused=this._paused,this.reinitPending=!0),this.paused=!0,clearTimeout(this.reinitTimeout),this.reinitTimeout=setTimeout(()=>{if(this.importing){this.paused=this.reinitStayPaused,this.reinitPending=!1;return}this.updateInProgress?this.reinit(t):(this.requestedAnimationFrame&&cancelAnimationFrame(this.requestedAnimationFrame),this.clearPinnedOutput(),this.init(),this.reloadCart(),this.paused=this.reinitStayPaused,this.reinitPending=!1)},150)}}initSeed(){this.tokenData=this.seed?tt({hash:this.seed,useCache:!1}):tt(),this.rawParams=Ht(this.tokenData),this.mintNo=parseInt(this.tokenData.tokenId)%1e6,console.log("token",this.mintNo,this.tokenData.hash)}init(t=!1){t&&this.initSeed(),this.pureAspectUpdate(this.selectedAsp);let n=this.aspectRatio,[r,i]=It(n,this.containerWidth,this.containerHeight);r*=j,i*=j,this.width=~~r,this.height=~~i,this.atCenterX=this.width/2,this.atCenterY=this.height/2,this.mainCanvas?this.mainCanvas.setSize(this.width,this.height):this.mainCanvas=new He(this.width,this.height,1,this.isBodyCanvas,this.canvasMountOptions())}loadCart(t){this.prepareCart(t)&&this.beginPlayback()}prepareCart(t){if(this.prepared)return!0;try{let n=~~(this.width/1),r=~~(this.height/this.width*n),i=new Se(this.tokenData),a=new Ne(n,r,i,this.rawParams,t,{gameManager:this.gameManager,canvasMount:this.canvasMountOptions(),customState:this.customState,captureKeyboard:this.deterministic?!1:this.captureKeyboard,hostChannel:this.hostChannel,clock:this.clock,listenToPointer:!this.deterministic});return this.animation=a,this.animationCart=t,this.paused=!1,this.framesElapsed=0,this.outboundEvents=[],this.scriptedActions=te(this.initialScriptedActions),this.appliedActions=[],this.consumedActionIndexes=new Set,this.outboundUnsubscribe?.(),this.outboundUnsubscribe=void 0,this.deterministic&&this.hostChannel&&(this.outboundUnsubscribe=this.hostChannel.onEvent(s=>{this.outboundEvents.push(s)})),this.R=i,this.applyCartFrameRate(t,a),this.resolveAudioLibraries(t),this.prepared=!0,!0}catch(n){return console.error(n),!1}}applyCartFrameRate(t,n){let r=t.metadata,i=r?.frameRate??ct,a=n.cartState?.visualMode??n.featureState?.visualMode,s=a&&r?.frameRateByVisualMode?r.frameRateByVisualMode[a]:void 0;this.updateFrameRate(typeof s=="number"&&s>0?s:i)}get audioLibraries(){return this.audioLibrariesInternal}get needsAudio(){return this.audioLibrariesInternal.length>0}resolveAudioLibraries(t){this.audioLibrariesInternal=it(t.metadata?.audio)}async unlockAudio(){if(this.audioLibrariesInternal.length===0)return;let t=at(this.audioLibrariesInternal);if(de){for(let n of t)await n.load();return}for(let n of t)await n.unlock()}async resumeAudioLibraries(){if(!(this.paused||de))for(let t of at(this.audioLibrariesInternal))try{await t.resumeIfSuspended()}catch(n){console.error(`Failed to resume audio library "${t.id}" after reload`,n)}}beginPlayback(){!this.prepared||this.loopRunning||(this.prepared=!1,this.loopRunning=!0,this.consecutiveErrorCount=0,!this.deterministic&&(this.requestedAnimationFrame=requestAnimationFrame(this.drawLoop)))}get isPrepared(){return this.prepared}get isLoopRunning(){return this.loopRunning}get isDeterministic(){return this.deterministic}getClock(){return{now:this.clock.now(),framesElapsed:this.framesElapsed,frameRate:this.frameRate}}getRandomState(){return this.requirePreparedAnimation().getRandomState()}schedule(t){this.scriptedActions.push(te(t))}async getReplayMetadata(){let t=await this.exportState();return{seed:this.tokenData.hash,clock:this.getClock(),rng:this.getRandomState(),actions:te(this.scriptedActions),applied:te(this.appliedActions),events:te(this.outboundEvents),state:t.state}}async step(t=1){if(!this.deterministic)throw new Error("step() requires createRuntime({ deterministic: true })");this.requirePreparedAnimation(),this.prepared&&!this.loopRunning&&this.beginPlayback(),this.paused=!1;let n=Math.max(0,Math.floor(t));for(let r=0;r<n&&this.animation;r++){let i=this.framesElapsed;if(this.applyScheduledActions(i),await this.processFrame(this.clock.now(),{ignorePause:!0,scheduleNext:!1}),this.framesElapsed===i||(this.virtualClock?.advance(this.targetDrawTime),!this.loopRunning))break}}async advance(t){let n=Math.max(0,Math.round(t/this.targetDrawTime));await this.step(n)}applyScheduledActions(t){let n=this.animation;n&&this.scriptedActions.forEach((r,i)=>{r.atFrame===t&&(this.consumedActionIndexes.has(i)||(this.consumedActionIndexes.add(i),r.type==="pointer"?n.injectPointer(r.pointer.kind,r.pointer.x,r.pointer.y):r.type==="key"?n.injectKey(r.key):r.type==="event"?this.hostChannel?.dispatch(r.event):r.type==="asset"&&this.hostChannel?.dispatch(Xt(r)),this.appliedActions.push({frame:t,action:r})))})}get paused(){return this._paused}set paused(t){this._paused!==t&&(this._paused=t,this.animation?.setPaused(t))}async waitUntilUpdateIdle(){for(;this.updateInProgress;)await new Promise(t=>{this.deterministic?queueMicrotask(t):typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>t()):setTimeout(t,0)})}requirePreparedAnimation(){if(!this.animation)throw new Error("No prepared cart");return this.animation}async exportState(){let t=this.requirePreparedAnimation(),n=this._paused;this.paused=!0,await this.waitUntilUpdateIdle();try{this.lastExportedFramebuffer=t.captureFramebuffer();let r=t.getCanvas();return{version:1,cartId:this.animationCart?.metadata?.id,generative:this.animationCart?.metadata?.generative,seed:this.tokenData.hash,framesElapsed:this.framesElapsed,elapsedSinceStart:t.getElapsedSinceStart(),dimensions:{width:r.width,height:r.height,cssWidth:this.containerWidth,cssHeight:this.containerHeight,dpr:j},state:pe(t.cartState)}}finally{this.paused=n}}async exportStateJSON(){return JSON.stringify(await this.exportState())}peekExportedFramebuffer(){return this.lastExportedFramebuffer}peekSeed(){return this.tokenData?.hash}isGenerative(){return this.animationCart?.metadata?.generative===!0}async importState(t,n){let r=this.requirePreparedAnimation(),i=Yt(t),a=this._paused,s=this.loopRunning;this.paused=!0,await this.waitUntilUpdateIdle(),dt(r.cartState,i.state,this.animationCart?.metadata?.id,i.cartId),zt(this.tokenData.hash,i.seed,this.animationCart?.metadata?.generative,i.generative),clearTimeout(this.reinitTimeout),this.reinitPending=!1,this.importing=!0;let u=qt(i,n?.framebuffer??this.lastExportedFramebuffer);if(u){this.pinOutputSize(u);let m=u.cssWidth??u.width/j,h=u.cssHeight??u.height/j;Gn(m,h),this.syncContainerFromDom(),this.pinViewportAtImport={w:this.containerWidth,h:this.containerHeight}}let f=this.customState,v=!1;try{if(this.customState=Pe(i.state),this.unloadCart(),!this.prepareCart(this.animationCart))throw new Error("Failed to prepare cart while loading state");this.animation.cartState!==this.customState&&Gt(this.animation.cartState,i.state),this.framesElapsed=i.framesElapsed;let m=this.animation,h=m.cartState,S=typeof i.elapsedSinceStart=="number"?i.elapsedSinceStart:qn(h);m.restoreClock(S,typeof h?.startTime=="number"?h.startTime:void 0),a&&m.setPaused(!0);let E=n?.framebuffer??this.lastExportedFramebuffer;E&&m.restoreFramebuffer(E)?h.keepRatioPrimed=!0:await m.renderAnimation(this.framesElapsed,this.rawParams),this.fitPinnedCanvas(),v=!0}catch(m){throw this.clearPinnedOutput(),this.customState=f,this.paused=a,this.animationCart&&(this.syncContainerFromDom(),this.init(),this.reloadCart()),m}finally{this.importing=!1,v&&(this.customState=f,this.paused=a,s&&this.beginPlayback())}}unloadCart(){this.loopRunning=!1,this.requestedAnimationFrame&&cancelAnimationFrame(this.requestedAnimationFrame),this.drawLoopTimeout&&clearTimeout(this.drawLoopTimeout),this.animation?.teardown(),this.animation=void 0,this.prepared=!1,this.audioLibrariesInternal=this.fallbackAudio,this.mainCanvas?.clearAll()}reloadCart(t=!1){let n=this.animationCart;if(!n)return;this.pinnedOutput&&(this.clearPinnedOutput(),this.syncContainerFromDom(),this.init());let r=this.reinitPending?this.reinitStayPaused:this._paused;this.unloadCart(),t&&this.initSeed(),this.loadCart(n),this.paused=r,!this.paused&&!de&&this.resumeAudioLibraries()}getFrameRate(){return this.frameRate}updateFrameRate(t){if(this.frameRate=t,t>=1)this.targetDrawTime=1e3/t;else{let r=1/(2-t);this.targetDrawTime=1e3/r}this.drawTime=this.targetDrawTime}canvasMountOptions(){return{container:this.container,adoptFromDocument:!this.container}}syncContainerFromDom(){if(this.container){this.containerWidth=this.container.clientWidth||this.containerWidth,this.containerHeight=this.container.clientHeight||this.containerHeight;return}this.containerWidth=window.innerWidth,this.containerHeight=window.innerHeight}pinOutputSize(t){this.pinnedOutput=t,this.width=~~t.width,this.height=~~t.height,this.atCenterX=this.width/2,this.atCenterY=this.height/2,this.aspectRatio=this.width/this.height,this.mainCanvas&&this.mainCanvas.setSize(this.width,this.height)}shouldKeepPinnedOutput(){return this.pinnedOutput?(this.syncContainerFromDom(),this.viewportMatches(this.pinnedCssSize())?!0:!!(this.pinViewportAtImport&&this.viewportMatches(this.pinViewportAtImport))):!1}pinnedCssSize(){let t=this.pinnedOutput;return{w:t.cssWidth??t.width/j,h:t.cssHeight??t.height/j}}viewportMatches(t){return Math.abs(this.containerWidth-t.w)<8&&Math.abs(this.containerHeight-t.h)<8}fitPinnedCanvas(){let t=this.pinnedOutput,n=this.canvas;if(!t||!n)return;this.container&&!this.container.style.position&&(this.container.style.position="relative");let r=this.containerWidth||window.innerWidth,i=this.containerHeight||window.innerHeight,a=t.width/j,s=t.height/j;if(a<1||s<1||r<1||i<1)return;let u=Math.min(r/a,i/s),f=a*u,v=s*u;n.style.position="absolute",n.style.left="50%",n.style.top="50%",n.style.transform="translate(-50%, -50%)",n.style.margin="0",n.style.width=`${f}px`,n.style.height=`${v}px`,n.style.imageRendering=Math.abs(u-1)<.01?"auto":"pixelated"}clearPinnedOutput(){let t=this.canvas;this.pinnedOutput=null,this.pinViewportAtImport=null,t&&(t.style.position="",t.style.left="",t.style.top="",t.style.transform="",t.style.imageRendering="",t.style.width="",t.style.height="",t.style.margin="auto")}get canvas(){return this.animation?.getCanvas()??this.mainCanvas?.canvas}destroy(){this.outboundUnsubscribe?.(),this.outboundUnsubscribe=void 0,this.clearPinnedOutput(),this.unloadCart(),clearTimeout(this.reinitTimeout),this.mainCanvas&&!this.mainCanvas.adopted&&this.mainCanvas.canvas.remove()}drawIt(){}tuneFramerate(t){let n=this.lastCall||t;this.lastCall=t,this.drawTime=Math.max(0,this.drawTime+this.targetDrawTime-this.lastCall+n)}async processFrame(t,n={}){let r=n.ignorePause===!0,i=n.scheduleNext!==!1;if(!this.loopRunning&&!r)return;let a=!1,s,u="update";try{if(r||!this.paused||this.tempUnpause){if(!de&&!r&&this.tuneFramerate(t),!this.animation)return;if(u="update",this.updateInProgress=!0,await this.animation.updateAnimationState(this.framesElapsed,this.rawParams,t),this.updateInProgress=!1,u="render",await this.animation.renderAnimation(this.framesElapsed,this.rawParams,t),this.autoMode&&this.animation.cartState.saveToken&&!this.savedToken&&!new URLSearchParams(window.location.search).get("hash")){let m=localStorage.getItem("goodones"),h=JSON.stringify(m?[...JSON.parse(m),this.tokenData.hash]:[this.tokenData.hash]);localStorage.setItem("goodones",h),this.savedToken=!0,localStorage.setItem(this.tokenData.hash,this.mainCanvas.canvas.toDataURL("image/png")),window.location.reload(),this.loopRunning=!1;return}this.framesElapsed++,this.tempUnpause&&(this.tempUnpause=!1)}u="draw",this.drawIt()}catch(f){a=!0,s=f,this.handleFrameError(f,u)}finally{this.updateInProgress=!1}a?(this.consecutiveErrorCount++,this.consecutiveErrorCount>=Xn&&(this.loopRunning=!1,this.onError?.(s,{phase:u,consecutive:this.consecutiveErrorCount,stopped:!0}))):this.consecutiveErrorCount=0,!(!this.loopRunning||!i)&&(this.drawLoopTimeout=setTimeout(()=>{this.requestedAnimationFrame=requestAnimationFrame(this.drawLoop)},this.drawTime))}async drawLoop(t){await this.processFrame(t,{scheduleNext:!0})}handleFrameError(t,n){let r=performance.now();r-this.lastErrorLogAt>=1e3&&(this.lastErrorLogAt=r,console.error(`Animation ${n} error:`,t)),this.consecutiveErrorCount===0&&this.onError?.(t,{phase:n,consecutive:1,stopped:!1})}pureAspectUpdate(t){if(t[0]===0&&t[1]===0){let r=this.containerWidth||window.innerWidth,i=this.containerHeight||window.innerHeight,a=r/i;this.aspectRatio=Math.min(Qn,Math.max(Zn,a))}else this.aspectRatio=t[0]/t[1]}};var er="HostChannel has been destroyed",fe=class{constructor(){this.inbound=[];this.listeners=[];this.closed=!1}dispatch(t){this.requireOpen(),this.inbound.push(t),this.inbound.length>32&&this.inbound.splice(0,this.inbound.length-32)}consume(){if(this.requireOpen(),this.inbound.length===0)return[];let t=this.inbound;return this.inbound=[],t}emit(t){this.requireOpen();for(let n of this.listeners)n(t)}onEvent(t){return this.requireOpen(),this.listeners.push(t),()=>{this.listeners=this.listeners.filter(n=>n!==t)}}clearInbound(){this.requireOpen(),this.inbound=[]}clear(){this.inbound=[],this.listeners=[]}close(){this.closed=!0,this.clear()}requireOpen(){if(this.closed)throw new Error(er)}};var nn=["image","audio","font","spritesheet"],rn=["timeout","cors","not-found","invalid","aborted","resolver"],me="cyberart:fallback/silent",Qt="Asset preloader has been destroyed",tr=4,nr=new Set(nn),rr=new Set(rn),ir={timeout:"asset load timed out",cors:"CORS blocked this asset","not-found":"asset was not found",invalid:"asset declaration or resource is invalid",aborted:"asset load was aborted",resolver:"asset resolver failed"};function an(e){return typeof e=="string"&&nr.has(e)}function on(e){return typeof e=="string"&&rr.has(e)}function We(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.id=="string"&&typeof t.ref=="string"&&on(t.code)&&typeof t.message=="string"}function F(e){return{id:e.id,ref:e.ref,code:e.code,message:e.message&&e.message.length>0?e.message:ir[e.code]}}function ae(e,t){return{type:e==="ready"?Te:xe,kind:"state",payload:t}}function sn(e){if(!e?.aborted)return;let t=new Error("aborted");throw t.name="AbortError",t}function ar(e){return e instanceof Error&&e.name==="AbortError"||typeof DOMException<"u"&&e instanceof DOMException&&e.name==="AbortError"}function pt(e){return e?{...e}:void 0}function X(e){let t={id:e.id,ref:e.ref,type:e.type,url:e.url};return e.integrity!==void 0&&(t.integrity=e.integrity),e.provenance&&(t.provenance=pt(e.provenance)),e.cors!==void 0&&(t.cors=e.cors),e.usedFallback&&(t.usedFallback=!0),e.managed&&(t.managed=!0),t}function Re(e){return{id:e.id,ref:e.ref,code:e.code,message:e.message}}function or(e){if(e.state==="ready"){let t={state:"ready",resource:X(e.resource)};return e.failure&&(t.failure=Re(e.failure)),t}return e.state==="failed"?{state:"failed",failure:Re(e.failure)}:{state:e.state}}function sr(e){return/^https?:/i.test(e)}function dn(e){return e.endsWith("/")?e:`${e}/`}function un(e,t){let n=dn(t);if(/^(https?:|data:|blob:)/i.test(e))return e;let r=/^moltazine:post\/([^#]+)#(.+)$/.exec(e);if(r)return`${n}moltazine/${encodeURIComponent(r[1])}/${r[2]}`;let i=/^world:asset\/(.+)$/.exec(e);if(i)return`${n}world/${i[1]}`;let a=/^library:(.+)$/.exec(e);return a?`${n}library/${a[1]}`:`${n}${e.replace(/^\//,"")}`}function dr(e){return{async resolve(t,n){sn(n);let r=e[t.ref];if(!r)throw F({id:t.id,ref:t.ref,code:"not-found",message:`no fixture for ${t.ref}`});if("error"in r)throw F({id:t.id,ref:t.ref,code:r.error,message:r.message});return{id:t.id,ref:t.ref,type:t.type,url:r.url,integrity:r.integrity??t.integrity,cors:r.cors??"omit",provenance:r.provenance??t.provenance}}}}function ur(e){let t=dn(e.cdnBase);return{async resolve(n,r){sn(r);let i=e.failures?.[n.ref];if(i){let s=typeof i=="string"?i:i.code,u=typeof i=="string"?void 0:i.message;throw F({id:n.id,ref:n.ref,code:s,message:u})}let a=un(n.ref,t);return{id:n.id,ref:n.ref,type:n.type,url:a,integrity:n.integrity,cors:sr(a)?"anonymous":"omit",provenance:n.provenance}}}}function cr(e){if(!e||typeof e!="object")return F({id:"",ref:"",code:"invalid",message:"declaration is required"});if(typeof e.id!="string"||e.id.length===0)return F({id:typeof e.id=="string"?e.id:"",ref:typeof e.ref=="string"?e.ref:"",code:"invalid",message:"id is required"});if(typeof e.ref!="string"||e.ref.length===0)return F({id:e.id,ref:"",code:"invalid",message:"ref is required"});if(!an(e.type))return F({id:e.id,ref:e.ref,code:"invalid",message:`unsupported type ${String(e.type)}`});if(e.integrity!==void 0&&typeof e.integrity!="string")return F({id:e.id,ref:e.ref,code:"invalid",message:"integrity must be a string"});if(e.timeoutMs!==void 0&&(typeof e.timeoutMs!="number"||!Number.isFinite(e.timeoutMs)||e.timeoutMs<0))return F({id:e.id,ref:e.ref,code:"invalid",message:"timeoutMs must be a non-negative finite number"})}function Zt(e){return{id:e.id,ref:me,type:e.type,url:me,usedFallback:!0,cors:"omit"}}function en(e,t){return We(t)?{id:e.id,ref:e.ref,code:t.code,message:t.message}:ar(t)?F({id:e.id,ref:e.ref,code:"aborted"}):F({id:e.id,ref:e.ref,code:"resolver",message:t instanceof Error?t.message:String(t)})}function tn(e,t){if(!t||typeof t.url!="string"||t.url.length===0)throw F({id:e.id,ref:e.ref,code:"invalid",message:"resolver returned no url"});if(t.integrity&&e.integrity&&t.integrity!==e.integrity)throw F({id:e.id,ref:e.ref,code:"invalid",message:"integrity mismatch"});let n=X(t);return n.id=e.id,n.ref=t.ref||e.ref,n.type=e.type,!n.integrity&&e.integrity&&(n.integrity=e.integrity),!n.provenance&&e.provenance&&(n.provenance=pt(e.provenance)),n}function ft(e){if(typeof e?.resolver?.resolve!="function")throw new Error("createAssetPreloader: resolver is required");let t=e.emitEvents!==!1,n=e.wallClockTimeout!==!1,r=new Map,i=[],a=new Map,s=new Map,u=new Map,f=new Map,v=new Map,m=new Set,h=!1;function S(o){return o.code==="aborted"||o.code==="timeout"}function E(o,g,b){let k=en(o,b);return k.code==="timeout"?k:g.aborted?F({id:o.id,ref:o.ref,code:"aborted"}):k}function N(o,g){let b=v.get(o);b||(b=new Set,v.set(o,b)),b.add(g)}function l(o){if(o?.state==="ready")return`${o.resource.type}\0${o.resource.ref}`}function c(o,g){for(let[b,k]of v)if(b!==g&&k.has(o))return!0;for(let[b,k]of r)if(b!==g&&l(k)===o)return!0;return!1}function D(o,g){let b=new Set(v.get(o)),k=l(g);k&&b.add(k),v.delete(o);for(let H of b)c(H,o)||u.delete(H)}function x(){let o=0,g=0,b=0,k=0,H={};for(let[R,T]of r)H[R]=or(T),T.state==="pending"||T.state==="loading"?o+=1:T.state==="failed"?b+=1:(g+=1,(T.resource.usedFallback||T.failure)&&(k+=1));return{total:r.size,pending:o,ready:g,failed:b,fallbacks:k,items:H,failures:i.map(Re)}}function q(){if(m.size===0)return;let o=x();for(let g of m)g(o)}function I(o){i.push(Re(o))}function L(o){h||!t||!e.dispatch||e.dispatch(o)}function G(o){if(o?.managed&&o.url.startsWith("blob:")&&!(typeof URL>"u"||typeof URL.revokeObjectURL!="function"))try{URL.revokeObjectURL(o.url)}catch{}}function P(o,g){if(h)return;let b=r.get(o);b?.state==="ready"&&G(b.resource),r.set(o,g),q()}function Q(o){if(o.fallback!==void 0)return o.fallback==="silent"?{id:`${o.id}::fallback`,ref:me,type:o.type}:typeof o.fallback=="string"?{id:`${o.id}::fallback`,ref:o.fallback,type:o.type}:{...o.fallback,id:typeof o.fallback.id=="string"&&o.fallback.id.length>0?o.fallback.id:`${o.id}::fallback`}}function _(o,g,b){let k=`${o.type}\0${o.ref}`,H=u.get(k);if(H)return g.aborted?Promise.reject(F({id:o.id,ref:o.ref,code:"aborted"})):(N(b,k),Promise.resolve(X(H.resource)));if(g.aborted)return Promise.reject(F({id:o.id,ref:o.ref,code:"aborted"}));let R=f.get(k);if(!R){let C=new AbortController,M={id:o.id,ref:o.ref,type:o.type};o.integrity!==void 0&&(M.integrity=o.integrity),o.provenance&&(M.provenance=pt(o.provenance)),R={promise:Promise.resolve().then(()=>e.resolver.resolve(M,C.signal)).then(O=>{let J=tn(o,O);if(C.signal.aborted)throw F({id:o.id,ref:o.ref,code:"aborted"});return u.set(k,{resource:X(J)}),J}).catch(O=>{throw en(o,O)}).finally(()=>{f.delete(k)}),controller:C,waiters:0},f.set(k,R)}let T=R;return T.waiters+=1,new Promise((C,M)=>{let Y=!1,O=(Z,et)=>{Y||(Y=!0,g.removeEventListener("abort",J),T.waiters-=1,et&&T.waiters<=0&&T.controller.abort(),Z())},J=()=>{O(()=>M(F({id:o.id,ref:o.ref,code:"aborted"})),!0)};if(g.aborted){J();return}g.addEventListener("abort",J,{once:!0}),T.promise.then(Z=>{if(!Y){if(g.aborted){J();return}N(b,k),O(()=>C(X(Z)),!1)}},Z=>{if(!Y){if(g.aborted){J();return}O(()=>M(Z),!1)}})})}function oe(o,g,b){if(g.aborted)return Promise.reject(F({id:o.id,ref:o.ref,code:"aborted"}));if(o.ref===me)return Promise.resolve(Zt(o));let k=new AbortController,H=()=>k.abort();g.addEventListener("abort",H,{once:!0});let R=o.timeoutMs??e.timeoutMs,T,C=!1;return n&&R!==void 0&&R>0&&Number.isFinite(R)&&(T=setTimeout(()=>{C=!0,k.abort()},R)),_(o,k.signal,b).then(M=>{let Y=tn(o,M);return Y.id=o.id,Y}).catch(M=>{throw C?F({id:o.id,ref:o.ref,code:"timeout"}):M}).finally(()=>{T!==void 0&&clearTimeout(T),g.removeEventListener("abort",H)})}async function Ee(o,g,b,k){try{return{resource:await oe(o,g,k)}}catch(H){let R=E(o,g,H);if(S(R)||g.aborted||b>=tr)throw R;let T=Q(o);if(!T)throw R;if(g.aborted)throw F({id:o.id,ref:o.ref,code:"aborted"});if(o.fallback==="silent"||T.ref===me)return{resource:Zt(o),failure:R};try{let C=await Ee(T,g,b+1,k);return{resource:{...X(C.resource),id:o.id,usedFallback:!0},failure:R}}catch(C){let M=We(C)&&!S(C)&&!g.aborted?C:E(o,g,C);throw!S(M)&&!g.aborted&&I(R),M}}}async function Ae(o,g){if(h)throw new Error(Qt);let b=r.get(o.id);if(b?.state==="ready"||b?.state==="failed")return;let k=a.get(o.id);if(k){await k;return}let H=(async()=>{let R=cr(o);if(R){P(o.id,{state:"failed",failure:R}),I(R),L(ae("failed",{id:o.id,ref:o.ref,failure:R}));return}P(o.id,{state:"loading"});let T=s.get(o.id)??new AbortController;s.has(o.id)||s.set(o.id,T);try{let C=await Ee(o,T.signal,g,o.id);if(h)return;if(T.signal.aborted){let M=F({id:o.id,ref:o.ref,code:"aborted"});P(o.id,{state:"failed",failure:M}),I(M),L(ae("failed",{id:o.id,ref:o.ref,failure:M}));return}if(C.resource.id=o.id,C.failure){P(o.id,{state:"ready",resource:C.resource,failure:C.failure}),I(C.failure),L(ae("failed",{id:o.id,ref:o.ref,failure:C.failure,resource:X(C.resource)})),L(ae("ready",{id:o.id,ref:C.resource.ref,resource:X(C.resource),failure:C.failure}));return}P(o.id,{state:"ready",resource:C.resource}),L(ae("ready",{id:o.id,ref:o.ref,resource:X(C.resource)}))}catch(C){if(h)return;let M=We(C)&&!S(C)&&!T.signal.aborted?{...Re(C),id:o.id}:E(o,T.signal,C);P(o.id,{state:"failed",failure:M}),I(M),L(ae("failed",{id:o.id,ref:o.ref,failure:M}))}finally{s.get(o.id)===T&&s.delete(o.id)}})();a.set(o.id,H);try{await H}finally{a.delete(o.id)}}return{async preload(o){if(h)throw new Error(Qt);let g=Array.isArray(o)?o:[];for(let b of g)b&&typeof b.id=="string"&&b.id.length>0&&(r.has(b.id)||r.set(b.id,{state:"pending"}),s.has(b.id)||s.set(b.id,new AbortController));return q(),await Promise.all(g.map(b=>Ae(b,0))),x()},get(o){let g=r.get(o);if(g?.state==="ready")return X(g.resource)},getProgress(){return x()},onProgress(o){return m.add(o),()=>{m.delete(o)}},abort(o){if(!h){if(o!==void 0){s.get(o)?.abort();return}for(let g of s.values())g.abort()}},forget(o){if(h)return;if(o===void 0){for(let b of r.values())b.state==="ready"&&G(b.resource);r.clear(),i.length=0,u.clear(),v.clear(),q();return}let g=r.get(o);g?.state==="ready"&&G(g.resource),D(o,g),r.delete(o);for(let b=i.length-1;b>=0;b--)i[b].id===o&&i.splice(b,1);q()},dispose(){if(!h){h=!0;for(let o of s.values())o.abort();s.clear();for(let o of r.values())o.state==="ready"&&G(o.resource);r.clear(),i.length=0,a.clear();for(let o of f.values())o.controller.abort();u.clear(),f.clear(),v.clear(),m.clear()}}}}function lr(e){xt();let{container:t,seed:n,captureKeyboard:r=!1,audio:i,deterministic:a,assets:s}=e,u=n===void 0?void 0:$e(n,a?"deterministic":"live"),f=new fe;if(s&&typeof s.resolver?.resolve!="function")throw new Error("createRuntime: assets.resolver is required");let v=s?ft({resolver:s.resolver,timeoutMs:s.timeoutMs,emitEvents:s.emitEvents??!a,wallClockTimeout:!a,dispatch:I=>f.dispatch(I)}):void 0,m=!1,h=null,S,E=!1,N=t.clientWidth||window.innerWidth,l=t.clientHeight||window.innerHeight,c=new Be(30,!1,N,l,!1,void 0,{container:t,seed:u,captureKeyboard:r,hostChannel:f,audio:i,deterministic:a}),D=()=>{let I=t.clientWidth||window.innerWidth,L=t.clientHeight||window.innerHeight;return I===c.containerWidth&&L===c.containerHeight?!1:(c.containerWidth=I,c.containerHeight=L,!0)},x=null;return!c.isDeterministic&&typeof ResizeObserver<"u"&&(x=new ResizeObserver(()=>{if(m||!h)return;D()&&E&&c.reinit()}),x.observe(t)),c.onError=(I,L)=>{S?.(I,L)},{get tokenData(){return c.tokenData},get hostChannel(){return f},get assets(){return v},get onError(){return S},set onError(I){S=I},mount(I,L={}){if(m)throw new Error("createRuntime: cannot mount on a destroyed runtime");h?.destroy(),E=!1,c.customState=L.initialState,c.setGameManager(L.gameManager);let G=L.onEvent?f.onEvent(L.onEvent):()=>{};if(!c.prepareCart(I))throw G(),new Error("createRuntime: failed to prepare cart");let P=!1,Q={async start(){if(!P){if(D()&&c.isPrepared&&(c.init(),c.unloadCart(),!c.prepareCart(I)))throw new Error("createRuntime: failed to prepare cart");c.needsAudio&&(await c.unlockAudio(),P)||(E=!0,c.beginPlayback())}},pause(){P||(c.paused=!0)},resume(){P||(c.paused=!1)},dispatch(_){P||f.dispatch(_)},snapshot(){if(P)return{seed:"",pngDataUrl:""};let _=c.canvas;return{seed:c.tokenData.hash,metadata:I.metadata,pngDataUrl:_?_.toDataURL("image/png"):""}},destroy(){P||(P=!0,E=!1,G(),f.clearInbound(),c.unloadCart(),h===Q&&(h=null))},reload(){if(!P){if(!E){if(c.isPrepared&&(c.unloadCart(),!c.prepareCart(I)))throw new Error("createRuntime: failed to prepare cart");return}c.reloadCart()}},reinit(_){if(!P){if(!E){D();return}c.reinit(_)}},getCartState(){return c.animation?.cartState},exportState(){return P?Promise.reject(new Error("Cart handle has been destroyed")):c.exportState()},exportStateJSON(){return P?Promise.reject(new Error("Cart handle has been destroyed")):c.exportStateJSON()},async importState(_,oe){if(P)throw new Error("Cart handle has been destroyed");await c.importState(_,oe)},peekExportedFramebuffer(){return P?null:c.peekExportedFramebuffer()},peekSeed(){if(!P)return c.peekSeed()},isGenerative(){return P?!1:c.isGenerative()},async step(_=1){if(P)throw new Error("Cart handle has been destroyed");await c.step(_)},async advance(_){if(P)throw new Error("Cart handle has been destroyed");await c.advance(_)},schedule(_){P||c.schedule(_)},getClock(){if(P)throw new Error("Cart handle has been destroyed");return c.getClock()},getRandomState(){if(P)throw new Error("Cart handle has been destroyed");return c.getRandomState()},getReplayMetadata(){return P?Promise.reject(new Error("Cart handle has been destroyed")):c.getReplayMetadata()},get canvas(){return c.canvas},get paused(){return c.paused},set paused(_){P||(c.paused=_)},get tokenData(){return c.tokenData},get isPrepared(){return c.isPrepared},get isLoopRunning(){return c.isLoopRunning},get needsAudio(){return c.needsAudio},get audioLibraries(){return c.audioLibraries}};return h=Q,Q},async unlockAudio(){await c.unlockAudio()},destroy(){m||(m=!0,h?.destroy(),h=null,x?.disconnect(),x=null,v?.dispose(),f.close(),c.destroy())}}}var he="cyberart.state.save",ye="cyberart.state.load";function pr(e,t,n={}){let r=n.persist,i=r?{persist:r}:void 0,a=()=>{t.emit({type:he,payload:i})},s=()=>{t.emit({type:ye,payload:i})};e.registerAction("w",a,!0),e.registerAction("W",a,!0),e.registerAction("e",s,!0),e.registerAction("E",s,!0)}function cn(e){if(e.type!==he&&e.type!==ye)return;let t=e.payload?.persist;return t==="localStorage"?t:void 0}var fr="cyberart-io",mr=1,ne="framebuffers";function mt(e,t){return`${e||"unknown"}:${t?ee(t):"none"}`}function pn(e,t){return`${e||"unknown"}:${t||"none"}`}function ht(){return new Promise((e,t)=>{let n=indexedDB.open(fr,mr);n.onupgradeneeded=()=>{let r=n.result;r.objectStoreNames.contains(ne)||r.createObjectStore(ne)},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error??new Error("indexedDB open failed"))})}function hr(e){let t=e.data;return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}function ln(e,t){return new Promise((n,r)=>{let a=e.transaction(ne,"readonly").objectStore(ne).get(t);a.onsuccess=()=>n(a.result),a.onerror=()=>r(a.error??new Error("indexedDB read failed"))})}async function fn(e,t,n){if(typeof indexedDB>"u")return;let r=await ht(),i={width:n.width,height:n.height,data:hr(n)};try{await new Promise((a,s)=>{let u=r.transaction(ne,"readwrite");u.oncomplete=()=>a(),u.onerror=()=>s(u.error??new Error("indexedDB write failed")),u.objectStore(ne).put(i,mt(e,t))})}finally{r.close()}}async function mn(e,t){if(typeof indexedDB>"u")return null;let n=await ht();try{let r=mt(e,t),i=pn(e,t),a=await ln(n,r)??(r===i?void 0:await ln(n,i));if(!a||!a.data||a.width<1||a.height<1)return null;let s=new ImageData(a.width,a.height);return s.data.set(new Uint8ClampedArray(a.data)),s}finally{n.close()}}async function hn(e,t){if(typeof indexedDB>"u")return;let n=await ht();try{await new Promise((r,i)=>{let a=n.transaction(ne,"readwrite");a.oncomplete=()=>r(),a.onerror=()=>i(a.error??new Error("indexedDB delete failed"));let s=a.objectStore(ne);s.delete(mt(e,t)),s.delete(pn(e,t))})}finally{n.close()}}var yt="cyberart.state.",yr="Saved state",gr="Loaded state",br="Failed to save state",vr="Failed to load state",Er="No saved state";function re(e,t){let n=e||"unknown";return t?yt+n+"."+ee(t):yt+n}function Ar(e,t,n){return r=>{if(cn(r)==="localStorage"){if(r.type===he){wr(e,t,n);return}r.type===ye&&Sr(e,t,n)}}}function ge(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t;if(typeof n.savedAt=="number"&&n.bundle&&typeof n.bundle=="object")return{savedAt:n.savedAt,bundle:n.bundle};let r=t;return typeof r.seed=="string"&&typeof r.version=="number"?{savedAt:0,bundle:r}:null}catch{return null}}async function wr(e,t,n){let r=e();if(r)try{let i=await r.exportState(),a=i.cartId??t?.();i.generative===!0?(Dr(a),ze(re(a,i.seed),i)):ze(re(a),i);let s=r.peekExportedFramebuffer?.();if(s)try{await fn(a,i.seed,s)}catch(u){console.warn("Failed to save cart framebuffer",u)}n?.(yr,"transient")}catch(i){console.error("Failed to save cart state",i),n?.(br,"transient")}}async function Sr(e,t,n){let r=e();if(!r)return;let i=t?.(),a=r.peekSeed?.(),s=r.isGenerative?.()===!0,u=xr(i,s,a);if(!u){console.warn("No saved cart state for",i||"unknown",s&&a?`(hash ${a})`:""),n?.(Er,"transient");return}try{let f=await mn(i,u.bundle.seed).catch(()=>null);await r.importState(u.bundle,{framebuffer:f}),n?.(gr,"transient")}catch(f){console.error("Failed to load cart state",f),n?.(vr,"transient")}}function ze(e,t){let n=JSON.stringify({savedAt:Date.now(),bundle:t});Cr(e,n)}function Cr(e,t){for(;;)try{localStorage.setItem(e,t);return}catch(n){if(!kr(n)||!Pr(e))throw n}}function kr(e){if(!e||typeof e!="object")return!1;let t=e.name,n=e.code;return t==="QuotaExceededError"||t==="NS_ERROR_DOM_QUOTA_REACHED"||n===22||n===1014}function Pr(e){let t=null,n=1/0;for(let a of Tr()){if(a===e)continue;let s=localStorage.getItem(a);if(!s)continue;let f=ge(s)?.savedAt??0;f<n&&(n=f,t=a)}if(!t)return!1;let r=localStorage.getItem(t),i=r?ge(r):null;return localStorage.removeItem(t),i?.bundle&&hn(i.bundle.cartId,i.bundle.seed).catch(()=>{}),!0}function Tr(){let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n&&n.startsWith(yt)&&e.push(n)}return e}function xr(e,t,n){if(t&&n){let i=localStorage.getItem(re(e,n));if(i)return ge(i);let a=localStorage.getItem(re(e));if(!a)return null;let s=ge(a);if(!s||!Rr(s.bundle,n))return null;try{ze(re(e,n),s.bundle)}catch{}return s}let r=localStorage.getItem(re(e));return r?ge(r):null}function Rr(e,t){return typeof e.seed=="string"&&ee(e.seed)===ee(t)}function Dr(e){let t=re(e),n=localStorage.getItem(t);if(!n)return;let r=ge(n);if(r&&typeof r.bundle.seed=="string"){let i=re(e,r.bundle.seed);if(!localStorage.getItem(i))try{ze(i,r.bundle)}catch{return}}localStorage.removeItem(t)}var De=1,Ie="cyberart.diagnostic.rejected",Ge=8,Ir=new Set(["intent","state","diagnostic"]),Mr=new Set([he,ye]);function qe(e){return typeof e=="string"&&Ir.has(e)}function yn(e){if(e.kind!==void 0)return qe(e.kind)?e.kind:void 0;if(!(typeof e.type!="string"||e.type.length===0)){if(Mr.has(e.type))return"intent";for(let t of e.type.split("."))if(qe(t))return t}}function gn(e,t){let n=e.split("."),r=t.split(".");if(n.length!==r.length)return!1;for(let i=0;i<n.length;i++)if(n[i]!=="*"&&n[i]!==r[i])return!1;return!0}function ie(e,t){for(let n of e)if(gn(n,t))return!0;return!1}function be(e){if(e===void 0)return{ok:!0,value:void 0};try{return{ok:!0,value:JSON.parse(JSON.stringify(e))}}catch{return{ok:!1}}}function Ye(e,t){if(!e||typeof e.type!="string"||e.type.length===0)return{ok:!1,reason:"malformed",detail:"type is required"};if(e.schemaVersion!==void 0&&e.schemaVersion!==De)return{ok:!1,reason:"malformed",detail:`unsupported schemaVersion ${String(e.schemaVersion)}`};let n=yn(e);if(!n)return{ok:!1,reason:"malformed",detail:`cannot infer kind from type "${e.type}"`};let r=be(e.payload);if(!r.ok)return{ok:!1,reason:"malformed",detail:"payload is not JSON-serializable"};let i=t.createId(),a=typeof e.correlationId=="string"&&e.correlationId.length>0?e.correlationId:i,s=typeof e.causationId=="string"&&e.causationId.length>0?e.causationId:t.causationId,u=typeof e.target=="string"&&e.target.length>0?e.target:void 0,f=t.maxHops??Ge,v=t.parentHops===void 0?f:Math.max(0,t.parentHops-1),m=typeof e.idempotencyKey=="string"&&e.idempotencyKey.length>0?e.idempotencyKey:void 0,h={schemaVersion:De,type:e.type,kind:n,source:t.source,id:i,correlationId:a,seq:t.seq,hops:v};return u&&(h.target=u),s&&(h.causationId=s),m&&(h.idempotencyKey=m),r.value!==void 0&&(h.payload=r.value),{ok:!0,envelope:h}}var Fr=new Set(["rate-limited","storm-detected","hop-limit","loop-detected","not-subscribed"]),_r=8,Or=8,Lr=16,Vr=256,Nr=["*.intent.*"];function Hr(e={}){let t=e.hostSource??"host",n="router",r=e.maxPerTurn??_r,i=e.maxCausationDepth??Or,a=e.maxHops??Ge,s=e.maxCorrelationPerTurn??Lr,u=e.maxIndex??Vr,f=e.maxPerWindow,v=e.windowMs??1e3,m=e.now??Date.now,h=0,S=e.createId??(()=>`evt-${++h}`),E=new Map,N=[],l=new Map,c=new Map,D=new Map,x=0,q=0,I=[],L=!1;function G(d,p,A){for(d.set(p,A);d.size>u;){let w=d.keys().next().value;if(w===void 0)break;d.delete(w)}}function P(d){G(l,d.id,{type:d.type,source:d.source,causationId:d.causationId,hops:d.hops,correlationId:d.correlationId,idempotencyKey:d.idempotencyKey})}function Q(d,p){p&&(d.correlationId||(d.correlationId=p.correlationId),d.causationId||(d.causationId=p.id),!d.idempotencyKey&&p.idempotencyKey&&(d.idempotencyKey=`${p.idempotencyKey}::${d.type}`))}function _(d,p){if(d){let A=l.get(d);return A?A.hops:a}return p}function oe(d,p){return`${d}\0${p}`}function Ee(d,p){d.idempotencyKey&&G(D,oe(d.source,d.idempotencyKey),p)}function Ae(d,p){if(p)return D.get(oe(d,p))}function o(d){return Ae(d.source,d.idempotencyKey)}function g(d){return d.seq+=1,d.seq}function b(d,p){if(!(typeof p.causationId=="string"&&p.causationId.length>0))return d.lastDelivered}function k(d){let p=new Set,A=new Set([`${d.type}\0${d.source}`]),w=d.causationId,y=0;for(;w;){if(y+=1,y>i||p.has(w))return!0;p.add(w);let V=l.get(w);if(!V)break;let U=`${V.type}\0${V.source}`;if(A.has(U))return!0;A.add(U),w=V.causationId}return!1}function H(d){let p=(c.get(d)??0)+1;return c.set(d,p),p}function R(d,p){f!==void 0&&(d.emitTimestamps=d.emitTimestamps.filter(A=>p-A<v))}function T(d,p){return(p.kind==="state"||p.kind==="diagnostic")&&!d.authoritative?!1:ie(d.emit,p.type)}function C(d){for(let p of N)if(ie(p.patterns,d.type))try{p.listener(d)}catch{}}function M(d){if(d.target){let p=E.get(d.target);if(!p||!ie(p.subscribe,d.type))return;p.channel.dispatch(d),p.lastDelivered={id:d.id,hops:d.hops,correlationId:d.correlationId,idempotencyKey:d.idempotencyKey};return}for(let p of E.values())ie(p.subscribe,d.type)&&(p.channel.dispatch(d),p.lastDelivered={id:d.id,hops:d.hops,correlationId:d.correlationId,idempotencyKey:d.idempotencyKey})}function Y(d,p,A,w,y,V,U){let z={reason:w,eventType:p,source:A};y&&(z.detail=y),q+=1;let we=S(),se={schemaVersion:De,type:Ie,kind:"diagnostic",source:n,id:we,correlationId:V??we,seq:q,hops:0,payload:z};U&&(se.causationId=U),P(se);let Tt=E.get(d);Tt&&Tt.channel.dispatch(se),C(se)}function O(d,p,A,w,y){Y(d,y?.type??(typeof p.type=="string"?p.type:""),y?.source??d,A,w,y?.correlationId,y?.id),y?.idempotencyKey&&!Fr.has(A)&&Ee(y,{status:"rejected"})}function J(d){P(d),Ee(d,{status:"accepted",envelope:d}),H(d.correlationId),C(d),M(d)}function Z(d,p,A,w){if(!A.ok){O(d,p,"malformed",A.detail);return}let y=A.envelope,V=o(y);if(V)return V.status==="accepted"?V.envelope:void 0;if(y.hops<1){O(d,p,"hop-limit","no hops remaining",y);return}if(y.target&&y.target!==t){let U=E.get(y.target);if(!U){O(d,p,"unknown-target",`unknown target "${y.target}"`,y);return}if(!ie(U.subscribe,y.type)){O(d,p,"not-subscribed",`target "${y.target}" does not subscribe to ${y.type}`,y);return}}if(w){if(!T(w,y)){O(d,p,"unauthorized","source may not emit this event",y);return}if(w.emitsThisTurn+=1,w.emitsThisTurn>r){O(d,p,"rate-limited","maxPerTurn exceeded",y);return}if(f!==void 0){let z=m();if(R(w,z),w.emitTimestamps.push(z),w.emitTimestamps.length>f){O(d,p,"rate-limited","maxPerWindow exceeded",y);return}}if(k(y)){O(d,p,"loop-detected","causation chain cycle or depth exceeded",y);return}if((c.get(y.correlationId)??0)+1>s){O(d,p,"storm-detected","correlationId storm",y);return}if(e.validate){let z;try{z=e.validate(y)}catch(we){let se=we instanceof Error?we.message:"validate threw";O(d,p,"host-rejected",se,y);return}if(z!==!0){O(d,p,"host-rejected",z.detail,y);return}}}else{if(k(y)){O(d,p,"loop-detected","causation chain cycle or depth exceeded",y);return}if((c.get(y.correlationId)??0)+1>s){O(d,p,"storm-detected","correlationId storm",y);return}}return J(y),y}function et(d,p){let A=E.get(d);if(!A)return;let w={...p},y=b(A,w);if(Q(w,y),Ae(A.id,w.idempotencyKey))return;let U=g(A),z=Ye(w,{source:A.id,createId:S,seq:U,causationId:y?.id,maxHops:a,parentHops:_(w.causationId??y?.id,y?.hops)});Z(d,w,z,A)}function Dn(d,p){let A=p?.cause,w={...d};Q(w,A);let y=Ae(t,w.idempotencyKey);if(y)return y.status==="accepted"?y.envelope:void 0;x+=1;let V=Ye(w,{source:t,createId:S,seq:x,causationId:w.causationId,maxHops:a,parentHops:_(w.causationId,A?.hops)});return Z(t,w,V,void 0)}function In(){if(!L){L=!0;try{for(;I.length>0;){let d=I.shift();d&&(d.kind==="cart"?et(d.participantId,d.event):d.result=Dn(d.event,d.extras))}}finally{L=!1}}}function Pt(d){I.push(d),In()}return{attach(d,p,A={}){if(d===t||d===n)throw new Error(`createEventRouter: "${d}" is a reserved participant id`);for(let V of E.values())if(V.channel===p&&V.id!==d)throw new Error(`createEventRouter: channel already attached as "${V.id}"`);E.get(d)?.unsubscribe();let y={id:d,channel:p,emit:A.emit??Nr,subscribe:A.subscribe??[],authoritative:A.authoritative===!0,seq:0,emitsThisTurn:0,emitTimestamps:[],unsubscribe:()=>{}};y.unsubscribe=p.onEvent(V=>{Pt({kind:"cart",participantId:d,event:V})}),E.set(d,y)},detach(d){let p=E.get(d);p&&(p.unsubscribe(),E.delete(d))},publish(d,p){let A={kind:"publish",event:d,extras:p};return Pt(A),A.result},subscribe(d,p){let A={patterns:d,listener:p};return N.push(A),()=>{let w=N.indexOf(A);w>=0&&N.splice(w,1)}},turn(){c.clear();for(let d of E.values())d.emitsThisTurn=0,d.lastDelivered=void 0,f!==void 0&&R(d,m())}}}var Kr=new Set(["string","number","boolean","object","array"]);function K(e,t,n){return n?{code:e,detail:t,path:n}:{code:e,detail:t}}function bn(e){if(!(typeof e!="string"||e.length===0)){for(let t of e.split("."))if(qe(t))return t}}function vn(e){let t=e.split(".");return t.length===0?"*":(t[t.length-1]="*",t.join("."))}function gt(e){let t=[];if(!e||typeof e!="object")return[K("invalid-schema","payload schema is required")];if((typeof e.version!="number"||!Number.isInteger(e.version)||e.version<1)&&t.push(K("invalid-version","payload schema version must be an integer >= 1")),!e.fields||typeof e.fields!="object"||Array.isArray(e.fields))return t.push(K("invalid-fields","payload schema fields must be an object")),t;for(let[n,r]of Object.entries(e.fields)){if(!n){t.push(K("invalid-field","field name is required",n));continue}(!r||typeof r!="object"||!Kr.has(r.type))&&t.push(K("invalid-field-type",`field "${n}" type must be string | number | boolean | object | array`,n))}return t}function $r(e){return e===null?"null":e===void 0?"undefined":Array.isArray(e)?"array":typeof e=="string"?"string":typeof e=="number"&&Number.isFinite(e)?"number":typeof e=="boolean"?"boolean":typeof e=="object"?"object":"other"}function jr(e,t){if(t===void 0){let i=Object.entries(e.fields).filter(([,a])=>a.optional!==!0);return i.length===0?{ok:!0,payload:void 0}:{ok:!1,errors:i.map(([a])=>K("missing-field",`payload is missing required field "${a}"`,a))}}if(t===null||typeof t!="object"||Array.isArray(t))return{ok:!1,errors:[K("invalid-payload","payload must be a JSON object")]};let n=t,r=[];for(let[i,a]of Object.entries(e.fields)){if(!(i in n)||n[i]===void 0){a.optional!==!0&&r.push(K("missing-field",`payload is missing required field "${i}"`,i));continue}let s=$r(n[i]);s!==a.type&&r.push(K("field-type",`payload.${i} expected ${a.type}, got ${s}`,i))}return r.length>0?{ok:!1,errors:r}:{ok:!0,payload:t}}function Ur(e,t,n){let r=vn(e);return{type:e,kind:t,payloadSchema:{version:n.version,fields:{...n.fields}},emitPattern:r,subscribePattern:r,toManifest(){let i={};for(let[a,s]of Object.entries(this.payloadSchema.fields))i[a]={type:s.type,optional:s.optional===!0};return{type:this.type,kind:this.kind,version:this.payloadSchema.version,fields:i,emitPattern:this.emitPattern,subscribePattern:this.subscribePattern}},validatePayload(i){return jr(this.payloadSchema,i)}}}function bt(e,t,n){let r=[];if(typeof t!="string"||t.length===0)r.push(K("invalid-type","event type is required"));else if(t.split(".").some(i=>i.length===0))r.push(K("invalid-type",`event type "${t}" has empty dotted segments`));else{let i=bn(t);i?i!==e&&r.push(K("kind-mismatch",`type "${t}" infers kind "${i}" but this helper defines "${e}"`)):r.push(K("kind-mismatch",`type "${t}" has no "${e}" segment; Adventure-style names like adventure.presentation.* need e.g. adventure.presentation.${e}.cue-started`))}return r.push(...gt(n)),r.length>0?{ok:!1,errors:r}:{ok:!0,contract:Ur(t,e,n)}}function Br(e,t){return bt("intent",e,t)}function Wr(e,t){return bt("state",e,t)}function zr(e,t){return bt("diagnostic",e,t)}function qr(e,t){let n=gt(e),r=gt(t);if(n.length>0||r.length>0||t.version<e.version)return"breaking";let i=Object.keys(e.fields),a=Object.keys(t.fields),s=new Set(i),u=new Set(a);for(let m of i){if(!u.has(m))return"breaking";let h=e.fields[m],S=t.fields[m];if(h.type!==S.type)return"breaking";let E=h.optional!==!0,N=S.optional===!0;if(E&&N||!E&&S.optional!==!0&&h.optional===!0)return"breaking"}let f=!1;for(let m of a)if(!s.has(m)){if(t.fields[m].optional!==!0)return"breaking";f=!0}let v=i.length===a.length&&i.every(m=>t.fields[m].type===e.fields[m].type&&t.fields[m].optional===!0==(e.fields[m].optional===!0));return v&&t.version===e.version?"identical":t.version>e.version&&(f||v)?"backward-compatible":t.version===e.version&&f?"breaking":v?"identical":"breaking"}function Gr(e,t){let n=[],r=[],i=new Set,a=new Set;for(let s of e)(t==="authoritative"||s.kind==="intent")&&!i.has(s.emitPattern)&&(i.add(s.emitPattern),n.push(s.emitPattern)),s.kind!=="intent"&&!a.has(s.subscribePattern)&&(a.add(s.subscribePattern),r.push(s.subscribePattern));return{emit:n,subscribe:r,authoritative:t==="authoritative"}}function Yr(e,t){let n=e.emit??["*.intent.*"],r=e.authoritative===!0,i=[];for(let a of t)ie(n,a.type)&&(a.kind==="state"||a.kind==="diagnostic")&&!r&&i.push(K("unauthorized-emit",`emit pattern allows ${a.kind} "${a.type}" but attach is not authoritative`,a.type));return i.length>0?{ok:!1,errors:i}:{ok:!0}}function Jr(e){let t=new Map;for(let i of e)t.set(i.type,i);let n=i=>{let a=t.get(i.type);return a?a.kind!==i.kind?{ok:!1,errors:[K("kind-mismatch",`envelope kind "${i.kind}" does not match contract "${a.kind}"`,i.type)]}:a.validatePayload(i.payload):{ok:!1,errors:[K("unknown-type",`no contract registered for "${i.type}"`,i.type)]}};return{get(i){return t.get(i)},manifest(){return[...t.values()].sort((i,a)=>i.type.localeCompare(a.type)).map(i=>i.toManifest())},validateEnvelope:n,asRouterValidate:i=>{let a=n(i);return a.ok?!0:{reason:"host-rejected",detail:a.errors.map(s=>s.detail).join("; ")}}}}var ve=1,Et="presentation.state.model",An="presentation.intent.unsupported",wn=["loading","ready","error","unsupported"],Xr=["presentation.state.*",Ie],Qr="Presentation adapter has been destroyed",Sn="Presentation adapter: model is invalid or not JSON-serializable",Zr=new Set(wn);function Cn(e){return typeof e=="string"&&Zr.has(e)}function At(e){if(e===null||typeof e!="object")return!1;let t=e;return!(t.contractVersion!==ve||!Cn(t.phase)||t.reason!==void 0&&typeof t.reason!="string"||t.view!==void 0&&(t.view===null||typeof t.view!="object"))}function vt(e,t){let n={type:Et,kind:"state",payload:e};return t?.correlationId&&(n.correlationId=t.correlationId),t?.causationId&&(n.causationId=t.causationId),t?.idempotencyKey&&(n.idempotencyKey=t.idempotencyKey),n}function wt(){return{contractVersion:ve,phase:"loading"}}function St(e){return{contractVersion:ve,phase:"unsupported",reason:e}}function Ct(e){let t=be(e);return t.ok?At(t.value)?{ok:!0,model:t.value}:t.value!==null&&typeof t.value=="object"&&"contractVersion"in t.value&&t.value.contractVersion!==ve?{ok:!1,reason:"unknown-contract-version",contractVersion:t.value.contractVersion}:{ok:!1,reason:"invalid-model"}:{ok:!1,reason:"model-not-serializable"}}function Je(e){let t=Ct(e);if(!t.ok)throw new Error(Sn);return t.model}function ei(e){let t=be(e);return t.ok&&At(t.value)?t.value:St("model-not-serializable")}function ti(e,t){if(e.type!==Et)return{model:t};let n=Ct(e.payload);return n.ok?{model:n.model}:{model:St(n.reason),rejected:{reason:n.reason,contractVersion:n.contractVersion}}}function ni(e){if(e===null||typeof e!="object"||!("regions"in e))return[];let t=e.regions;return Array.isArray(t)?t:[]}function ri(e,t,n){return e>=n.x&&e<n.x+n.width&&t>=n.y&&t<n.y+n.height}function ii(e,t){let n=t.intent;if(!n||typeof n.type!="string"||n.type.length===0)return;let r={type:n.type,kind:"intent"};if(n.payload!==void 0){let i=be(n.payload);if(!i.ok)return;r.payload=i.value}n.target&&(r.target=n.target),n.correlationId&&(r.correlationId=n.correlationId),n.idempotencyKey&&(r.idempotencyKey=n.idempotencyKey),e.emit(r)}function kn(e,t,n){let r={reason:t};if(n!==void 0){let i=be(n);i.ok&&(r.contractVersion=i.value)}e.emit({type:An,kind:"intent",payload:r})}function En(e,t,n){let r=t;for(let i of e){let a=ti(i,r);a.rejected&&n&&kn(n,a.rejected.reason,a.rejected.contractVersion),r=a.model}return r}function Pn(){return{metadata:{id:"cyberart.presentation.reference",name:"Reference presentation",frameRate:30},getDefaultState:(e,t,n,r,i,a,s,u,f)=>{let v=i?.model;if(v===void 0)return{model:wt()};let m=Ct(v);return m.ok?{model:m.model}:(f&&kn(f,m.reason,m.contractVersion),{model:St(m.reason)})},update:(e,t,n,r,i,a,s,u,f,v,m)=>{let h=En(m?.consume()??[],i.model,m);for(;s?.hasClick();){let S=s.consumeClick();if(!(!S||h.phase!=="ready"||!m)){for(let E of ni(h.view))if(ri(S.x,S.y,E)){ii(m,E);break}}}return m&&(h=En(m.consume(),h,m)),h===i.model?i:{...i,model:h}},render:(e,t,n,r,i,a)=>{let s=i.model.view?.background;a.fillStyle=s??"#111",a.fillRect(0,0,r.width,r.height)}}}function Tn(e,t={}){let n=e,r=t.model?Je(t.model):wt(),i=!1,a=t.present??t.model!==void 0,s=()=>{if(i)throw new Error(Qr)},u=f=>{s(),r=Je(f),n.dispatch(vt(r))};return a&&n.dispatch(vt(r)),{version:ve,get target(){return n},get model(){return ei(r)},get phase(){return r.phase},get paused(){return n.paused===!0},present:u,async start(){return s(),n.start()},pause(){s(),n.pause()},resume(){s(),n.resume()},retarget(f){s(),n=f},destroy(){i||(i=!0,n.destroy())}}}function ai(e,t={}){let n=t.model?Je(t.model):t.initialState?.model!==void 0?Je(t.initialState.model):wt(),r=t.cart??Pn(),i=e.mount(r,{initialState:{...t.initialState,model:n},onEvent:t.onEvent});return Tn(i,{model:n,present:!1})}var Me="cue.started",Qe="cue.completed",Fe="cue.cancelled",Ze="cue.replaced",oi=[Me,Qe,Fe,Ze];function si(e){return e===Me||e===Qe||e===Fe||e===Ze}function Rn(e,t){let n=e<0?0:e>1?1:e;return t==="ease-out"?1-(1-n)*(1-n):n}function xn(e){return{type:e.type,atFrame:e.atFrame,name:e.name,idempotencyKey:e.idempotencyKey,progress:e.progress}}function Xe(e){return{name:e.name,idempotencyKey:e.idempotencyKey,phase:e.phase,startFrame:e.startFrame,durationFrames:e.durationFrames,delayFrames:e.delayFrames,easing:e.easing,progress:e.progress,repeatIndex:e.repeatIndex}}function kt(e){return e.startFrame+e.delayFrames}function di(e,t){if(!e||typeof e!="object")return{ok:!1,reason:"invalid",detail:"spec is required"};if(typeof e.name!="string"||e.name.length===0)return{ok:!1,reason:"invalid",detail:"name is required"};if(typeof e.idempotencyKey!="string"||e.idempotencyKey.length===0)return{ok:!1,reason:"invalid",detail:"idempotencyKey is required"};if(typeof e.durationFrames!="number"||!Number.isFinite(e.durationFrames)||e.durationFrames<0)return{ok:!1,reason:"invalid",detail:"durationFrames must be a non-negative finite number"};let n=e.startFrame===void 0?t:e.startFrame;if(typeof n!="number"||!Number.isFinite(n))return{ok:!1,reason:"invalid",detail:"startFrame must be finite"};let r=e.delayFrames??0;if(typeof r!="number"||!Number.isFinite(r)||r<0)return{ok:!1,reason:"invalid",detail:"delayFrames must be a non-negative finite number"};let i=e.easing??"linear";if(i!=="linear"&&i!=="ease-out")return{ok:!1,reason:"invalid",detail:"unsupported easing"};let a=e.onDuplicate??"replace";if(a!=="ignore"&&a!=="replace"&&a!=="reject")return{ok:!1,reason:"invalid",detail:"unsupported onDuplicate"};let s=0;if(e.repeat)if("forever"in e.repeat&&e.repeat.forever)s="forever";else if("count"in e.repeat){if(typeof e.repeat.count!="number"||!Number.isFinite(e.repeat.count)||e.repeat.count<0)return{ok:!1,reason:"invalid",detail:"repeat.count must be >= 0"};s=Math.floor(e.repeat.count)}else return{ok:!1,reason:"invalid",detail:"unsupported repeat"};let u=e.reducedMotion??"complete";return u!=="skip"&&u!=="complete"&&(typeof u!="object"||typeof u.durationFrames!="number"||!Number.isFinite(u.durationFrames)||u.durationFrames<0)?{ok:!1,reason:"invalid",detail:"unsupported reducedMotion"}:{name:e.name,idempotencyKey:e.idempotencyKey,startFrame:n,durationFrames:e.durationFrames,delayFrames:r,easing:i,repeatRemaining:s,repeatIndex:0,reducedMotion:u,onDuplicate:a,phase:"scheduled",progress:0}}function ui(e,t){if(!t)return e;let n=e.reducedMotion;return n==="skip"||n==="complete"?{...e,durationFrames:0,delayFrames:0,startFrame:e.startFrame}:{...e,durationFrames:n.durationFrames}}function ci(e={}){let t=!!e.reducedMotion,n=e.originFrame??0,r=new Map,i=[];function a(l){i.push(l)}function s(l,c){let D=kt(l)-kt(c);return D!==0?D:l.name<c.name?-1:l.name>c.name?1:l.idempotencyKey<c.idempotencyKey?-1:l.idempotencyKey>c.idempotencyKey?1:0}function u(l,c){a({type:c,atFrame:n,name:l.name,idempotencyKey:l.idempotencyKey,progress:l.progress})}function f(l){if(l.phase="completed",l.progress=1,u(l,Qe),l.repeatRemaining==="forever"||l.repeatRemaining>0){if(typeof l.repeatRemaining=="number"&&(l.repeatRemaining-=1),l.repeatIndex+=1,l.phase="scheduled",l.progress=0,l.startFrame=n,l.delayFrames=0,l.durationFrames===0){r.delete(l.idempotencyKey);return}l.phase="active",u(l,Me)}else r.delete(l.idempotencyKey)}function v(l){if(l.phase==="cancelled"||l.phase==="completed")return;let c=kt(l);if(!(n<c)){if(l.phase==="scheduled"&&(l.phase="active",l.progress=l.durationFrames===0?1:0,u(l,Me),l.durationFrames===0)){f(l);return}if(l.phase==="active"){let D=n-c;D>=l.durationFrames?(l.progress=1,f(l)):l.progress=Rn(l.durationFrames===0?1:D/l.durationFrames,l.easing)}}}function m(){let l=[...r.values()].sort(s);for(let c of l)v(c)}function h(l){let c=di(l,n);if("ok"in c&&c.ok===!1)return c;let D=ui(c,t),x=r.get(D.idempotencyKey);if(x&&(x.phase==="scheduled"||x.phase==="active")){if(x.onDuplicate==="reject"||D.onDuplicate==="reject")return{ok:!1,reason:"duplicate",detail:`cue ${D.idempotencyKey} is already ${x.phase}`};if(x.onDuplicate==="ignore"||D.onDuplicate==="ignore")return{ok:!0,cue:Xe(x)};x.phase="cancelled",x.progress=x.progress,u(x,Ze),r.delete(x.idempotencyKey)}r.set(D.idempotencyKey,D),v(D);let q=r.get(D.idempotencyKey)??D;return{ok:!0,cue:Xe(q)}}function S(l){let c=r.get(l);return!c||c.phase==="completed"||c.phase==="cancelled"?!1:(c.phase="cancelled",u(c,Fe),r.delete(l),!0)}function E(){for(let l of[...r.values()].sort(s))(l.phase==="scheduled"||l.phase==="active")&&(l.phase="cancelled",u(l,Fe));r.clear(),i.length=0,n=e.originFrame??0}function N(l=1){let c=Number.isFinite(l)?Math.max(0,Math.floor(l)):0,D=i.length;for(let x=0;x<c;x++)n+=1,m();return i.slice(D).map(xn)}return{play:h,step:N,cancel:S,reset:E,snapshot(){return{frame:n,reducedMotion:t,cues:[...r.values()].sort(s).map(Xe),events:i.map(xn)}},get(l){let c=r.get(l);return c?Xe(c):void 0},get frame(){return n},get reducedMotion(){return t}}}export{xe as ASSET_FAILED_EVENT,rn as ASSET_FAILURE_CODES,nn as ASSET_KINDS,Te as ASSET_READY_EVENT,Fe as CUE_CANCELLED_EVENT,Qe as CUE_COMPLETED_EVENT,oi as CUE_LIFECYCLE_EVENTS,Ze as CUE_REPLACED_EVENT,Me as CUE_STARTED_EVENT,_e as CYBERART_CANVAS_ATTR,Ge as DEFAULT_MAX_HOPS,De as EVENT_ENVELOPE_VERSION,fe as HostChannel,Sn as INVALID_PRESENTATION_MODEL_MESSAGE,$ as IncompatibleCartStateError,Oe as KeyboardManager,ve as PRESENTATION_ADAPTER_VERSION,Et as PRESENTATION_MODEL_EVENT,wn as PRESENTATION_PHASES,Xr as PRESENTATION_SUBSCRIBE_PATTERNS,An as PRESENTATION_UNSUPPORTED_EVENT,Le as PointerManager,Ie as REJECTED_EVENT_TYPE,Se as Random,me as SILENT_ASSET_FALLBACK_REF,Rn as applyCueEasing,ae as assetStatusEvent,Ar as attachCartStatePersistence,Tn as attachPresentationAdapter,Ke as canonicalizeSeed,qr as comparePayloadSchemas,F as createAssetFailure,ft as createAssetPreloader,Jr as createContractRegistry,Hr as createEventRouter,dr as createFixtureAssetResolver,ur as createHostedAssetResolver,vt as createPresentationModelEvent,ci as createPresentationTimeline,Pn as createReferencePresentationCart,lr as createRuntime,Ve as createVirtualClock,ce as createWallClock,zr as defineDiagnostic,Br as defineIntent,Wr as defineStateEvent,Gr as deriveAttachOptions,Jt as describeReplayMismatch,vn as familyPatternForType,yn as inferEventKind,We as isAssetFailure,on as isAssetFailureCode,an as isAssetKind,si as isCueLifecycleType,At as isPresentationModel,Cn as isPresentationPhase,bn as kindSegmentInType,gn as matchEventPattern,ai as mountPresentationAdapter,Ye as normalizeEvent,pr as registerCartStateHotkeys,$e as resolveRuntimeSeed,un as rewriteHostedAssetRef,Yr as verifyAttachOptions};
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
# Asset resolver / preloader
|
|
2
|
+
|
|
3
|
+
Host-owned URL policy. The engine caches, dedupes, tracks progress, applies timeouts and fallbacks, and (in live mode) dispatches `ASSET_READY_EVENT` / `ASSET_FAILED_EVENT`. Authored carts keep logical refs (`moltazine:post/<id>#primary-image`, `world:asset/…`, `library:…`, or ordinary URLs). Adventure Kit, Cyberart, and a local preview each supply a different `AssetResolver`.
|
|
4
|
+
|
|
5
|
+
Deterministic timing: [deterministic mode](deterministic-mode.md). CI: [headless harness](headless-harness.md). Event mailbox: [events](events.md).
|
|
6
|
+
|
|
7
|
+
Back to the [package README](../README.md).
|
|
8
|
+
|
|
9
|
+
## One-command reproduce (this repo)
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
pnpm exec vitest run packages/engine/src/canvas/cyb-26-asset-resolver.repro.spec.ts
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Why this exists
|
|
16
|
+
|
|
17
|
+
The same room must load through two resolvers without changing cart or world content:
|
|
18
|
+
|
|
19
|
+
| Host | Resolver | Example URL |
|
|
20
|
+
|---|---|---|
|
|
21
|
+
| Local fixtures | `createFixtureAssetResolver` | `fixture://images/porch.png` |
|
|
22
|
+
| Hosted / Library | `createHostedAssetResolver({ cdnBase })` | `https://cdn.example/moltazine/porch-1/primary-image` |
|
|
23
|
+
|
|
24
|
+
Resolution policy stays in the host. The engine never fetches over the network.
|
|
25
|
+
|
|
26
|
+
## `createRuntime({ assets })`
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
import {
|
|
30
|
+
createRuntime,
|
|
31
|
+
createFixtureAssetResolver,
|
|
32
|
+
createHostedAssetResolver,
|
|
33
|
+
} from '@cyberart-io/engine';
|
|
34
|
+
|
|
35
|
+
const runtime = createRuntime({
|
|
36
|
+
container,
|
|
37
|
+
assets: {
|
|
38
|
+
resolver: createHostedAssetResolver({
|
|
39
|
+
cdnBase: 'https://cdn.example/library/',
|
|
40
|
+
failures: { 'world:asset/stream-loop': 'cors' },
|
|
41
|
+
}),
|
|
42
|
+
},
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
await runtime.assets!.preload([
|
|
46
|
+
{ id: 'room-bg', ref: 'moltazine:post/porch-1#primary-image', type: 'image' },
|
|
47
|
+
{
|
|
48
|
+
id: 'ambience',
|
|
49
|
+
ref: 'world:asset/stream-loop',
|
|
50
|
+
type: 'audio',
|
|
51
|
+
fallback: 'silent',
|
|
52
|
+
},
|
|
53
|
+
]);
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
`runtime.assets` is undefined when `assets` is omitted. It survives cart remount. `runtime.destroy()` disposes it (aborts in-flight work, revokes `managed` blob URLs).
|
|
57
|
+
|
|
58
|
+
| Option | Default | Meaning |
|
|
59
|
+
|---|---|---|
|
|
60
|
+
| `resolver` | required | Host `resolve(request, signal?)`. |
|
|
61
|
+
| `timeoutMs` | none | Default per-asset timeout. Ignored under `deterministic` (no wall-clock). |
|
|
62
|
+
| `emitEvents` | `!deterministic` | When true, preload dispatches `ASSET_READY_EVENT` / `ASSET_FAILED_EVENT`. |
|
|
63
|
+
|
|
64
|
+
Under `deterministic`, emit and wall-clock timeout are off so scripted `{ type: 'asset', atFrame, id, status }` own when the cart `consume()`s ready/failed. Preload still fills the cache and progress snapshot immediately.
|
|
65
|
+
|
|
66
|
+
## Declarations
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
import type { AssetDeclaration } from '@cyberart-io/engine';
|
|
70
|
+
|
|
71
|
+
const roomBg: AssetDeclaration = {
|
|
72
|
+
id: 'room-bg',
|
|
73
|
+
ref: 'moltazine:post/porch-1#primary-image',
|
|
74
|
+
type: 'image', // 'image' | 'audio' | 'font' | 'spritesheet'
|
|
75
|
+
integrity: 'sha256-…', // optional; mismatch → `invalid`
|
|
76
|
+
provenance: { source: 'moltazine', postId: 'porch-1' },
|
|
77
|
+
timeoutMs: 8_000,
|
|
78
|
+
fallback: 'silent', // or another ref string, or a nested declaration
|
|
79
|
+
};
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
`fallback: 'silent'` synthesizes `SILENT_ASSET_FALLBACK_REF` (`cyberart:fallback/silent`) so a failed audio load does not hang on a black screen. A string is another logical ref of the same type. A nested `AssetDeclaration` may itself declare `fallback` (up to four levels). The host still sees the typed failure on `getProgress().failures`. `abort` and live `timeout` skip fallbacks and terminate as `aborted` / `timeout`.
|
|
83
|
+
|
|
84
|
+
## Resolvers (built-in)
|
|
85
|
+
|
|
86
|
+
```ts
|
|
87
|
+
createFixtureAssetResolver({
|
|
88
|
+
'moltazine:post/porch-1#primary-image': { url: 'fixture://images/porch.png' },
|
|
89
|
+
'world:asset/stream-loop': { error: 'cors' },
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
createHostedAssetResolver({
|
|
93
|
+
cdnBase: 'https://cdn.example/library/',
|
|
94
|
+
failures: { 'world:asset/stream-loop': { code: 'timeout', message: 'cdn stalled' } },
|
|
95
|
+
});
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
`rewriteHostedAssetRef(ref, cdnBase)`:
|
|
99
|
+
|
|
100
|
+
| Authored ref | Rewritten |
|
|
101
|
+
|---|---|
|
|
102
|
+
| `https://…` / `data:` / `blob:` | unchanged |
|
|
103
|
+
| `moltazine:post/<id>#fragment` | `{cdnBase}moltazine/<id>/<fragment>` |
|
|
104
|
+
| `world:asset/<name>` | `{cdnBase}world/<name>` |
|
|
105
|
+
| `library:<path>` | `{cdnBase}library/<path>` |
|
|
106
|
+
| other | `{cdnBase}{ref}` |
|
|
107
|
+
|
|
108
|
+
Hosted HTTP(S) results use `cors: 'anonymous'`. CORS / timeout / not-found are **structured failures the resolver emits** — do not `fetch` in tests or CI. Custom hosts implement `AssetResolver`.
|
|
109
|
+
|
|
110
|
+
`createAssetFailure({ id, ref, code, message? })` builds a typed error. Codes: `timeout` | `cors` | `not-found` | `invalid` | `aborted` | `resolver`.
|
|
111
|
+
|
|
112
|
+
## Preloader
|
|
113
|
+
|
|
114
|
+
`createAssetPreloader({ resolver, timeoutMs, emitEvents, wallClockTimeout, dispatch })` is the same object `createRuntime` stores on `runtime.assets`.
|
|
115
|
+
|
|
116
|
+
| Member | Meaning |
|
|
117
|
+
|---|---|
|
|
118
|
+
| `preload(declarations)` | Validate, resolve, cache, fallback. Returns a snapshot. |
|
|
119
|
+
| `get(id)` | Copy of the ready resource, including silent fallback. |
|
|
120
|
+
| `getProgress()` | Copy: `total` / `pending` / `ready` / `failed` / `fallbacks` / `items` / `failures`. |
|
|
121
|
+
| `onProgress(listener)` | Fires after each item state change. Unsubscribe by calling the return. |
|
|
122
|
+
| `abort(id?)` | Cancel that id (or all), including in-flight fallback work. Terminates as `aborted`, or `timeout` if a live timer already fired. Does not apply silent, string, or nested fallbacks. A sibling that shares type+ref is not aborted. |
|
|
123
|
+
| `forget(id?)` | Drop item(s) and revoke `managed` blob URLs. If no other id still uses those type+ref keys (including fallback refs), drop the resolver cache so the next preload re-resolves. |
|
|
124
|
+
| `dispose()` | Idempotent teardown. Further `preload` throws. |
|
|
125
|
+
|
|
126
|
+
Repeated `preload` of the same `id` joins the in-flight promise or returns the cached terminal state. The same `type`+`ref` under two ids shares one `resolver.resolve` call.
|
|
127
|
+
|
|
128
|
+
Live `dispatch` uses the existing envelope: `{ type: ASSET_READY_EVENT \| ASSET_FAILED_EVENT, kind: 'state', payload: { id, ref?, resource?, failure? } }`. Payload still always has `id`. Do not `await fetch` inside cart `update` / `render`.
|
|
129
|
+
|
|
130
|
+
## Deterministic tests
|
|
131
|
+
|
|
132
|
+
```ts
|
|
133
|
+
const runtime = createRuntime({
|
|
134
|
+
container,
|
|
135
|
+
seed: 42,
|
|
136
|
+
deterministic: {
|
|
137
|
+
actions: [
|
|
138
|
+
{ type: 'asset', atFrame: 2, id: 'room-bg', status: 'ready' },
|
|
139
|
+
{
|
|
140
|
+
type: 'asset',
|
|
141
|
+
atFrame: 3,
|
|
142
|
+
id: 'ambience',
|
|
143
|
+
status: 'failed',
|
|
144
|
+
detail: { code: 'cors' },
|
|
145
|
+
},
|
|
146
|
+
],
|
|
147
|
+
},
|
|
148
|
+
assets: { resolver: fixtureResolver },
|
|
149
|
+
});
|
|
150
|
+
await runtime.assets!.preload(ROOM_ASSETS);
|
|
151
|
+
// progress is already terminal; the cart has not seen events yet
|
|
152
|
+
await cart.step(4);
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
A resolver used under `deterministic` must not be what tests wait on for ready/failed. Scripted actions remain the clock.
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Host-controlled time, input, and asset completion so two runs with the same seed, actions, and `step` count match. Production kaleidoscope / Art Blocks **leave `deterministic` unset** (rAF, `performance.now()`, token hash).
|
|
4
4
|
|
|
5
|
-
CI should use the [headless harness](headless-harness.md) on this path, not a mock engine. Router hosts: [events](events.md).
|
|
5
|
+
CI should use the [headless harness](headless-harness.md) on this path, not a mock engine. Router hosts: [events](events.md). Frame-local effects: [presentation cue](presentation-cue.md) (`timeline.step` beside `cart.step`).
|
|
6
6
|
|
|
7
7
|
Back to the [package README](../README.md).
|
|
8
8
|
|