@cyberart-io/engine 0.0.4 → 0.0.5
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 +41 -18
- package/dist/headless.d.ts +497 -67
- package/dist/headless.js +1 -1
- package/dist/index.d.ts +470 -7
- package/dist/index.js +1 -1
- package/docs/asset-resolver.md +4 -4
- package/docs/browser-harness.md +126 -0
- package/docs/capability-manifest.md +18 -7
- package/docs/compositor.md +103 -0
- package/docs/deterministic-mode.md +1 -1
- package/docs/events.md +75 -13
- package/docs/headless-harness.md +44 -14
- package/docs/presentation-adapter.md +8 -8
- package/docs/presentation-cue.md +2 -2
- package/docs/replay-inspector.md +88 -0
- package/docs/runtime-group.md +9 -7
- package/package.json +1 -1
package/dist/headless.js
CHANGED
|
@@ -5,4 +5,4 @@
|
|
|
5
5
|
* Not an OSI open-source license.
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
-
var Kt=(e,t)=>()=>(e&&(t=e(e=0)),t);var Jt={};function qt(e,t){let n=e.indexOf(ct);if(n===-1)return null;let r=n+ct.length,o=`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)+o+e.slice(r)}var Ie,we,zt,le,ct,lt=Kt(()=>{"use strict";Ie=/AudioWorkletProcessor with name:\s*["'`][^"'`]+["'`]\s+is already registered/i,we="__cyberartWorkletPatchApplied";typeof window<"u"&&!window[we]&&(window.addEventListener("error",e=>{let t=e?.message??"";Ie.test(t)&&(e.preventDefault(),e.stopImmediatePropagation())},!0),window.addEventListener("unhandledrejection",e=>{let t=e?.reason,n=typeof t=="string"?t:t?.message??"";Ie.test(n)&&e.preventDefault()}),window[we]=!0);zt=!1,le=(...e)=>{zt&&console.log("[workletPatch]",...e)},ct="((AudioWorkletProcessor,registerProcessor)=>{";if(typeof AudioWorklet<"u"&&!AudioWorklet.prototype[we]){let e=new WeakMap,t=/registerProcessor\s*\(\s*['"`]([^'"`]+)['"`]/g,n=AudioWorklet.prototype.addModule,r=0;AudioWorklet.prototype.addModule=async function(o,u){let p=++r,m=e.get(this);m||(m=new Set,e.set(this,m)),le(`#${p} addModule`,{url:o.slice(0,64),isBlob:o.startsWith("blob:"),knownBefore:[...m]});let C=o,v=null;if(o.startsWith("blob:")){let l=null;try{l=await(await fetch(o)).text()}catch(w){le(`#${p} blob fetch failed`,w)}if(l!==null){let w=new Set;for(let E of l.matchAll(t))w.add(E[1]);if(w.size>0){let E=[...w].filter(M=>m.has(M)),b=[...w].filter(M=>!m.has(M));if(E.length>0&&b.length===0){le(`#${p} short-circuit \u2014 all processors already registered`,E);return}if(E.length>0&&b.length>0){let M=qt(l,E);if(M!==null){let h=new Blob([M],{type:"application/javascript"});v=URL.createObjectURL(h),C=v,le(`#${p} rewrote blob; skipping`,E,"allowing",b)}else le(`#${p} blob rewrite failed; passing original through`)}b.forEach(M=>m.add(M))}}}return n.call(this,C,u).then(()=>{v&&URL.revokeObjectURL(v)},l=>{v&&URL.revokeObjectURL(v);let w=(l&&l.message)??"";if(!(Ie.test(w)||/already registered/i.test(w)))throw l})},AudioWorklet.prototype[we]=!0}});var Je=()=>{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"]},G=window.devicePixelRatio||1,re=/Headless/i.test(navigator.userAgent),jn=/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)||/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.platform);function Ye(){return Math.min(window.innerWidth,window.innerHeight)}var Te="data-cyberart-canvas",ie=class{constructor(t,n,r=1,a={}){this.width=t,this.height=n;let o=a.container,u=a.adoptFromDocument??!o,p=o?o.querySelector(`canvas[${Te}]`)??o.querySelector("canvas"):null;if(p)this.canvas=p,this.adopted=!0;else if(u){let m=document.getElementById("canvas")??document.querySelector("canvas");m?(this.canvas=m,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(Te)||this.canvas.setAttribute(Te,""),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/G}px`,this.canvas.style.height=`${n/G}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 Xe(e,t){let n=e/t,r,a;return n>1?(r=e,a=~~(e/n)):(a=t,r=~~(t*n)),{width:r,height:a,iWidth:1/r,iHeight:1/a,area:r*a,largeDim:Math.max(r,a),smallDim:Math.min(r,a),aspectRatio:n}}function Qe(e,t=window.innerWidth,n=window.innerHeight){let r=Ye(),a,o;return n<t?e>1?t>=r*e?(a=r*e,o=r):(a=t,o=a/e):(a=r*e,o=r):e>1?(a=r,o=r/e):n<r/e?(o=n,a=o*e):(a=r,o=r/e),[a,o]}var Pe=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={}}},Ze=Pe;var Me=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))}},et=Me;function ge(){return{now:()=>performance.now()}}function tt(e=0){let t=e;return{now:()=>t,set(n){t=n},advance(n){t+=n}}}var nt=(e,t,n,r)=>({now:e,startTime:t,elapsedSinceStart:e-t,deltaSinceLastUpdate:n===null?0:e-n,deltaSinceLastRender:r===null?0:e-r}),ye=class{constructor(t,n,r,a,o,u={}){this.startTime=0;this.lastUpdateAt=null;this.lastRenderAt=null;this.clockOffsetMs=0;this.pauseStartedAt=null;this.renderAnimation=this.renderAnimation.bind(this),this.dimensionContext=Xe(t,n),this.R=r,this.gameManager=u.gameManager,this.hostChannel=u.hostChannel,this.clock=u.clock??ge(),this.canvas=new ie(this.dimensionContext.width,this.dimensionContext.height,1,u.canvasMount),this.drawingContext=this.canvas.ctx,this.keyboardManager=new Ze(!1,u.captureKeyboard??!0),this.pointerManager=new et(this.canvas.canvas,{listen:u.listenToPointer!==!1}),this.animationCart=o;let p=u.customState;this.featureState=o.getDefaultFeatureState?.(this.R,this.dimensionContext,a,this.keyboardManager,p,this.pointerManager,this.gameManager,this.hostChannel),this.cartState=o.getDefaultState(this.R,this.dimensionContext,a,this.keyboardManager,p,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 a=this.resolveNow(r),o=nt(a,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,o,this.featureState,this.hostChannel),this.lastUpdateAt=a}async renderAnimation(t,n,r=this.clock.now()){let a=this.resolveNow(r),o=nt(a,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,o,this.featureState,this.hostChannel),this.lastRenderAt=a}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 be=class extends ie{constructor(t,n,r=1,a=!0,o={}){if(super(t,n,r,o),this.adopted)return;let u=o.container;if(u){this.canvas.parentNode!==u&&u.appendChild(this.canvas);return}if(a){let p=document.getElementById("canvas");p&&p!==this.canvas&&p.parentNode===document.body&&document.body.removeChild(p),document.body.appendChild(this.canvas)}}};function rt(e){let t=parseInt(e.substring(0,8),16),n=parseInt(e.substring(8,8),16),r=parseInt(e.substring(16,8),16),a=parseInt(e.substring(24,8),16);return{next:()=>{t|=0,n|=0,r|=0,a|=0;let u=(t+n|0)+a|0;return a=a+1|0,t=n^n>>>9,n=r+(r<<3)|0,r=r<<21|r>>>11,r=r+u|0,(u>>>0)/4294967296},getRegs:()=>({a:t,b:n,c:r,d:a}),setRegs:u=>{t=u.a,n=u.b,r=u.c,a=u.d}}}var ve=class{constructor(t){this.seed=t.hash,this.useA=!1,this.genA=rt(t.hash.substring(2,32)),this.genB=rt(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 st="bafybeicjwcq5lxxtfnyj4p2ugcr7ctyb5wl62cbcechj6tsabdq5whcs7u",it="https://ipfs.io/ipfs/";function $t(e){return e.endsWith("/")?e:`${e}/`}var ce=null;function Wt(e){return[...Array(e)].map(()=>Math.floor(Math.random()*16).toString(16)).join("")}function Gt(e){return e&&e.length>0?e:[{cid:st}]}function Bt(e){return e.startsWith("0x")?e:`0x${e}`}var ot=/^(0[xX])?[0-9a-fA-F]{64}$/;function Vt(e){let t="",n=2166136261,r=522970236;for(let a=0;t.length<64;a++){for(let o=0;o<e.length;o++)n^=e.charCodeAt(o)+a,n=Math.imul(n,16777619),r^=e.charCodeAt(o)+a*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 at(e){let t=typeof e=="number"?String(e):e;return ot.test(t)?`0x${(t.startsWith("0x")||t.startsWith("0X")?t.slice(2):t).toLowerCase()}`:Vt(t)}function dt(e,t){if(typeof e=="number"||t==="deterministic")return at(e);let n=String(e);return ot.test(n)?at(n):n.startsWith("0x")||n.startsWith("0X")?n:`0x${n}`}function jt(e){if(!e&&typeof tokenData<"u"&&tokenData?.hash)return{hash:tokenData.hash,tokenId:String(tokenData.tokenId),externalAssetDependencies:Gt(tokenData.externalAssetDependencies),preferredIPFSGateway:$t(tokenData.preferredIPFSGateway||it),preferredArweaveGateway:tokenData.preferredArweaveGateway};let t=typeof window<"u"?new URLSearchParams(window.location.search):new URLSearchParams;return{hash:e?Bt(e):t.get("hash")||`0x${Wt(64)}`,tokenId:"18009999",externalAssetDependencies:[{cid:st}],preferredIPFSGateway:it}}function De(e){let t=e?.useCache!==!1;if(t&&ce&&!e?.hash)return ce;let n=jt(e?.hash);return t?ce=n:ce||(ce=n),n}function ut(e){return new Array(32).fill(null).map((t,n)=>parseInt(e.hash.slice(2+n*2,4+n*2),16))}async function He(){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 pt={id:"tone",async load(){await Promise.resolve().then(()=>(lt(),Jt))},async unlock(){await pt.load(),await(await He()).start()},async resumeIfSuspended(){let e=await He();e.context.state==="suspended"&&await e.context.resume()},async suspendIfRunning(){let t=(await He()).context.rawContext;"suspend"in t&&t.state==="running"&&await t.suspend()}},ht={tone:pt};function Fe(e){if(!e)return[];let t=Array.isArray(e)?e:[e],n=[];for(let r of t){if(!(r in ht)){console.warn(`Unknown audio library "${r}"`);continue}let a=r;n.includes(a)||n.push(a)}return n}function Le(e){return e.map(t=>ht[t])}var Ae="$cyberartTa",j=class extends Error{constructor(t){super(t),this.name="IncompatibleCartStateError"}},Oe={Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array};function Yt(e){for(let t of Object.keys(Oe))if(e instanceof Oe[t])return t}function gt(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function z(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function _e(e){return z(e)?typeof e[Ae]=="string"&&Array.isArray(e.d):!1}function Xt(e){return e==null?!1:typeof e=="function"?!0:!(typeof e!="object"||Array.isArray(e)||gt(e)||z(e))}var Qt=new Set(["audioContextStarted","midiSynths","keepRatioPrimed","audioInitStarted","musicSeekApplied"]);function mt(e){return e===null?"null":_e(e)?String(e[Ae]):Array.isArray(e)?"array":z(e)?"object":typeof e}function Zt(e,t){return e===t||e==="null"||t==="null"}function ft(e){return e.trim().toLowerCase().replace(/^0x/,"")}function yt(e,t,n,r){if(!(!n&&!r)&&ft(e)!==ft(t))throw new j(`Generative cart state is for seed "${t}", but the live token is "${e}"`)}function ae(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function bt(e,t){let n=e.dimensions;if(n&&ae(n.width)&&ae(n.height))return n;if(t&&ae(t.width)&&ae(t.height))return{width:t.width,height:t.height};if(z(e.state)){let r=e.state.containerWidth,a=e.state.containerHeight;if(ae(r)&&ae(a))return{width:r,height:a}}return null}function se(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(gt(e)){let n=Yt(e);return n?{[Ae]:n,d:Array.from(e)}:void 0}if(typeof e=="object"&&!t.has(e)){t.add(e);try{if(Array.isArray(e)){let a=[],o=0;for(let u of e){let p=se(u,t);p!==void 0&&(a.push(p),o++)}return e.length>0&&o===0?void 0:a}if(!z(e)||Xt(e))return;let n=Object.keys(e),r={};for(let a of n){if(Qt.has(a))continue;let o=se(e[a],t);o!==void 0&&(r[a]=o)}return n.length>0&&Object.keys(r).length===0?void 0:r}finally{t.delete(e)}}}}function pe(e){if(_e(e)){let t=Oe[e[Ae]];return t?new t(e.d.map(n=>Number(n))):e}if(Array.isArray(e))return e.map(t=>pe(t));if(z(e)){let t={};for(let n of Object.keys(e))t[n]=pe(e[n]);return t}return e}function Ne(e,t,n,r,a=!0){if(a&&n&&r&&n!==r)throw new j(`Cart state is for "${r}", but the live cart is "${n}"`);if(!z(t)){if(a)throw new j("Cart state snapshot is empty");return}let o=Object.keys(t);if(o.length===0){if(a)throw new j("Cart state snapshot is empty");return}let u=se(e);if(!z(u)||Object.keys(u).length===0){if(a)throw new j("Live cart has no serializable state");return}let p=o.filter(m=>m in u);if(p.length===0){if(a)throw new j("Cart state snapshot does not overlap the live cart shape");return}for(let m of p){let C=mt(u[m]),v=mt(t[m]);if(!Zt(C,v))throw new j(`Cart state field "${m}" has type ${v}, live cart expects ${C}`);if(C==="object"){let l=t[m],w=e[m];z(l)&&!_e(l)&&Ne(w,l,void 0,void 0,!1)}}}function vt(e,t){if(!z(e)||!z(t))return;let n=se(e);if(z(n))for(let r of Object.keys(t))r in n&&(e[r]=pe(t[r]))}function wt(e){let t=typeof e=="string"?JSON.parse(e):e;if(!t||typeof t!="object")throw new j("Cart state bundle is not an object");if(t.version!==1)throw new j(`Unsupported cart state version ${String(t.version)}`);if(typeof t.seed!="string"||typeof t.framesElapsed!="number")throw new j("Cart state bundle is missing seed or framesElapsed");return t}var Ue="cyberart.asset.ready",Ke="cyberart.asset.failed";function ee(e){try{return JSON.parse(JSON.stringify(e))}catch{return e}}function At(e){return{type:e.status==="ready"?Ue:Ke,kind:"state",payload:e.detail===void 0?{id:e.id}:{id:e.id,detail:e.detail}}}function tn(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 nn(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)),a=Math.max(0,window.outerWidth-window.innerWidth),o=Math.max(0,window.outerHeight-window.innerHeight);try{window.resizeTo(n+a,r+o)}catch{return!1}return Math.abs(window.innerWidth-n)<=8&&Math.abs(window.innerHeight-r)<=8}var rn=[[0,0],[16,9],[9,16],[4,3],[3,4],[2,1],[1,2],[3,1],[1,3],[1,1]],We=rn[0],an=We[0]/We[1],$e=30,sn=120,on=3840/2160,dn=2160/3840,Ee=class{constructor(t=$e,n=!1,r=window.innerWidth,a=window.innerHeight,o=!0,u,p={}){this.framesElapsed=0;this.frameRate=$e;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=p.container,this.seed=p.seed,this.captureKeyboard=p.captureKeyboard??!0,this.customState=p.customState,this.hostChannel=p.hostChannel,this.fallbackAudio=Fe(p.audio),this.audioLibrariesInternal=this.fallbackAudio;let m=p.deterministic;this.deterministic=!!m;let C=m&&typeof m=="object"?m:{};if(this.deterministic){if(p.clock){let v=p.clock;if(typeof v.advance!="function")throw new Error("deterministic mode requires a virtual clock with advance()");this.virtualClock=v,this.clock=v}else this.virtualClock=tt(C.origin??0),this.clock=this.virtualClock;this.initialScriptedActions=ee(C.actions??[]),this.scriptedActions=ee(this.initialScriptedActions)}else this.clock=p.clock??ge();this.isBodyCanvas=this.container?!1:o,this.autoMode=n,this.aspectRatio=an,this.selectedAsp=We,this.isFullscreen=!!document.fullscreenElement,this.updateFrameRate(t),this.tempUnpause=!1,this.synchronous=re,this.containerWidth=r,this.containerHeight=a,this.gameManager=u,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?De({hash:this.seed,useCache:!1}):De(),this.rawParams=ut(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,a]=Qe(n,this.containerWidth,this.containerHeight);r*=G,a*=G,this.width=~~r,this.height=~~a,this.atCenterX=this.width/2,this.atCenterY=this.height/2,this.mainCanvas?this.mainCanvas.setSize(this.width,this.height):this.mainCanvas=new be(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),a=new ve(this.tokenData),o=new ye(n,r,a,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=o,this.animationCart=t,this.paused=!1,this.framesElapsed=0,this.outboundEvents=[],this.scriptedActions=ee(this.initialScriptedActions),this.appliedActions=[],this.consumedActionIndexes=new Set,this.outboundUnsubscribe?.(),this.outboundUnsubscribe=void 0,this.deterministic&&this.hostChannel&&(this.outboundUnsubscribe=this.hostChannel.onEvent(u=>{this.outboundEvents.push(u)})),this.R=a,this.applyCartFrameRate(t,o),this.resolveAudioLibraries(t),this.prepared=!0,!0}catch(n){return console.error(n),!1}}applyCartFrameRate(t,n){let r=t.metadata,a=r?.frameRate??$e,o=n.cartState?.visualMode??n.featureState?.visualMode,u=o&&r?.frameRateByVisualMode?r.frameRateByVisualMode[o]:void 0;this.updateFrameRate(typeof u=="number"&&u>0?u:a)}get audioLibraries(){return this.audioLibrariesInternal}get needsAudio(){return this.audioLibrariesInternal.length>0}resolveAudioLibraries(t){this.audioLibrariesInternal=Fe(t.metadata?.audio)}async unlockAudio(){if(this.audioLibrariesInternal.length===0)return;let t=Le(this.audioLibrariesInternal);if(re){for(let n of t)await n.load();return}for(let n of t)await n.unlock()}async resumeAudioLibraries(){if(!(this.paused||re))for(let t of Le(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(ee(t))}async getReplayMetadata(){let t=await this.exportState();return{seed:this.tokenData.hash,clock:this.getClock(),rng:this.getRandomState(),actions:ee(this.scriptedActions),applied:ee(this.appliedActions),events:ee(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 a=this.framesElapsed;if(this.applyScheduledActions(a),await this.processFrame(this.clock.now(),{ignorePause:!0,scheduleNext:!1}),this.framesElapsed===a||(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,a)=>{r.atFrame===t&&(this.consumedActionIndexes.has(a)||(this.consumedActionIndexes.add(a),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(At(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:G},state:se(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(),a=wt(t),o=this._paused,u=this.loopRunning;this.paused=!0,await this.waitUntilUpdateIdle(),Ne(r.cartState,a.state,this.animationCart?.metadata?.id,a.cartId),yt(this.tokenData.hash,a.seed,this.animationCart?.metadata?.generative,a.generative),clearTimeout(this.reinitTimeout),this.reinitPending=!1,this.importing=!0;let p=bt(a,n?.framebuffer??this.lastExportedFramebuffer);if(p){this.pinOutputSize(p);let v=p.cssWidth??p.width/G,l=p.cssHeight??p.height/G;nn(v,l),this.syncContainerFromDom(),this.pinViewportAtImport={w:this.containerWidth,h:this.containerHeight}}let m=this.customState,C=!1;try{if(this.customState=pe(a.state),this.unloadCart(),!this.prepareCart(this.animationCart))throw new Error("Failed to prepare cart while loading state");this.animation.cartState!==this.customState&&vt(this.animation.cartState,a.state),this.framesElapsed=a.framesElapsed;let v=this.animation,l=v.cartState,w=typeof a.elapsedSinceStart=="number"?a.elapsedSinceStart:tn(l);v.restoreClock(w,typeof l?.startTime=="number"?l.startTime:void 0),o&&v.setPaused(!0);let E=n?.framebuffer??this.lastExportedFramebuffer;E&&v.restoreFramebuffer(E)?l.keepRatioPrimed=!0:await v.renderAnimation(this.framesElapsed,this.rawParams),this.fitPinnedCanvas(),C=!0}catch(v){throw this.clearPinnedOutput(),this.customState=m,this.paused=o,this.animationCart&&(this.syncContainerFromDom(),this.init(),this.reloadCart()),v}finally{this.importing=!1,C&&(this.customState=m,this.paused=o,u&&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&&!re&&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/G,h:t.cssHeight??t.height/G}}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,a=this.containerHeight||window.innerHeight,o=t.width/G,u=t.height/G;if(o<1||u<1||r<1||a<1)return;let p=Math.min(r/o,a/u),m=o*p,C=u*p;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=`${m}px`,n.style.height=`${C}px`,n.style.imageRendering=Math.abs(p-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,a=n.scheduleNext!==!1;if(!this.loopRunning&&!r)return;let o=!1,u,p="update";try{if(r||!this.paused||this.tempUnpause){if(!re&&!r&&this.tuneFramerate(t),!this.animation)return;if(p="update",this.updateInProgress=!0,await this.animation.updateAnimationState(this.framesElapsed,this.rawParams,t),this.updateInProgress=!1,p="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 v=localStorage.getItem("goodones"),l=JSON.stringify(v?[...JSON.parse(v),this.tokenData.hash]:[this.tokenData.hash]);localStorage.setItem("goodones",l),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)}p="draw",this.drawIt()}catch(m){o=!0,u=m,this.handleFrameError(m,p)}finally{this.updateInProgress=!1}o?(this.consecutiveErrorCount++,this.consecutiveErrorCount>=sn&&(this.loopRunning=!1,this.onError?.(u,{phase:p,consecutive:this.consecutiveErrorCount,stopped:!0}))):this.consecutiveErrorCount=0,!(!this.loopRunning||!a)&&(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,a=this.containerHeight||window.innerHeight,o=r/a;this.aspectRatio=Math.min(on,Math.max(dn,o))}else this.aspectRatio=t[0]/t[1]}};var un="HostChannel has been destroyed",Ce=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(un)}};var cn=["image","audio","font","spritesheet"],ln=["timeout","cors","not-found","invalid","aborted","resolver"],he="cyberart:fallback/silent",Et="Asset preloader has been destroyed",pn=4,hn=new Set(cn),mn=new Set(ln),fn={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 gn(e){return typeof e=="string"&&hn.has(e)}function yn(e){return typeof e=="string"&&mn.has(e)}function Ge(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.id=="string"&&typeof t.ref=="string"&&yn(t.code)&&typeof t.message=="string"}function N(e){return{id:e.id,ref:e.ref,code:e.code,message:e.message&&e.message.length>0?e.message:fn[e.code]}}function oe(e,t){return{type:e==="ready"?Ue:Ke,kind:"state",payload:t}}function bn(e){return e instanceof Error&&e.name==="AbortError"||typeof DOMException<"u"&&e instanceof DOMException&&e.name==="AbortError"}function Be(e){return e?{...e}:void 0}function Q(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=Be(e.provenance)),e.cors!==void 0&&(t.cors=e.cors),e.usedFallback&&(t.usedFallback=!0),e.managed&&(t.managed=!0),t}function me(e){return{id:e.id,ref:e.ref,code:e.code,message:e.message}}function vn(e){if(e.state==="ready"){let t={state:"ready",resource:Q(e.resource)};return e.failure&&(t.failure=me(e.failure)),t}return e.state==="failed"?{state:"failed",failure:me(e.failure)}:{state:e.state}}function wn(e){if(!e||typeof e!="object")return N({id:"",ref:"",code:"invalid",message:"declaration is required"});if(typeof e.id!="string"||e.id.length===0)return N({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 N({id:e.id,ref:"",code:"invalid",message:"ref is required"});if(!gn(e.type))return N({id:e.id,ref:e.ref,code:"invalid",message:`unsupported type ${String(e.type)}`});if(e.integrity!==void 0&&typeof e.integrity!="string")return N({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 N({id:e.id,ref:e.ref,code:"invalid",message:"timeoutMs must be a non-negative finite number"})}function Ct(e){return{id:e.id,ref:he,type:e.type,url:he,usedFallback:!0,cors:"omit"}}function St(e,t){return Ge(t)?{id:e.id,ref:e.ref,code:t.code,message:t.message}:bn(t)?N({id:e.id,ref:e.ref,code:"aborted"}):N({id:e.id,ref:e.ref,code:"resolver",message:t instanceof Error?t.message:String(t)})}function kt(e,t){if(!t||typeof t.url!="string"||t.url.length===0)throw N({id:e.id,ref:e.ref,code:"invalid",message:"resolver returned no url"});if(t.integrity&&e.integrity&&t.integrity!==e.integrity)throw N({id:e.id,ref:e.ref,code:"invalid",message:"integrity mismatch"});let n=Q(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=Be(e.provenance)),n}function Rt(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,a=[],o=new Map,u=new Map,p=new Map,m=new Map,C=new Map,v=new Set,l=!1;function w(i){return i.code==="aborted"||i.code==="timeout"}function E(i,g,y){let x=St(i,y);return x.code==="timeout"?x:g.aborted?N({id:i.id,ref:i.ref,code:"aborted"}):x}function b(i,g){let y=C.get(i);y||(y=new Set,C.set(i,y)),y.add(g)}function M(i){if(i?.state==="ready")return`${i.resource.type}\0${i.resource.ref}`}function h(i,g){for(let[y,x]of C)if(y!==g&&x.has(i))return!0;for(let[y,x]of r)if(y!==g&&M(x)===i)return!0;return!1}function K(i,g){let y=new Set(C.get(i)),x=M(g);x&&y.add(x),C.delete(i);for(let U of y)h(U,i)||p.delete(U)}function $(){let i=0,g=0,y=0,x=0,U={};for(let[I,P]of r)U[I]=vn(P),P.state==="pending"||P.state==="loading"?i+=1:P.state==="failed"?y+=1:(g+=1,(P.resource.usedFallback||P.failure)&&(x+=1));return{total:r.size,pending:i,ready:g,failed:y,fallbacks:x,items:U,failures:a.map(me)}}function J(){if(v.size===0)return;let i=$();for(let g of v)g(i)}function F(i){a.push(me(i))}function d(i){l||!t||!e.dispatch||e.dispatch(i)}function T(i){if(i?.managed&&i.url.startsWith("blob:")&&!(typeof URL>"u"||typeof URL.revokeObjectURL!="function"))try{URL.revokeObjectURL(i.url)}catch{}}function A(i,g){if(l)return;let y=r.get(i);y?.state==="ready"&&T(y.resource),r.set(i,g),J()}function D(i){if(i.fallback!==void 0)return i.fallback==="silent"?{id:`${i.id}::fallback`,ref:he,type:i.type}:typeof i.fallback=="string"?{id:`${i.id}::fallback`,ref:i.fallback,type:i.type}:{...i.fallback,id:typeof i.fallback.id=="string"&&i.fallback.id.length>0?i.fallback.id:`${i.id}::fallback`}}function H(i,g,y){let x=`${i.type}\0${i.ref}`,U=p.get(x);if(U)return g.aborted?Promise.reject(N({id:i.id,ref:i.ref,code:"aborted"})):(b(y,x),Promise.resolve(Q(U.resource)));if(g.aborted)return Promise.reject(N({id:i.id,ref:i.ref,code:"aborted"}));let I=m.get(x);if(!I){let R=new AbortController,L={id:i.id,ref:i.ref,type:i.type};i.integrity!==void 0&&(L.integrity=i.integrity),i.provenance&&(L.provenance=Be(i.provenance)),I={promise:Promise.resolve().then(()=>e.resolver.resolve(L,R.signal)).then(O=>{let X=kt(i,O);if(R.signal.aborted)throw N({id:i.id,ref:i.ref,code:"aborted"});return p.set(x,{resource:Q(X)}),X}).catch(O=>{throw St(i,O)}).finally(()=>{m.delete(x)}),controller:R,waiters:0},m.set(x,I)}let P=I;return P.waiters+=1,new Promise((R,L)=>{let Y=!1,O=(Z,xe)=>{Y||(Y=!0,g.removeEventListener("abort",X),P.waiters-=1,xe&&P.waiters<=0&&P.controller.abort(),Z())},X=()=>{O(()=>L(N({id:i.id,ref:i.ref,code:"aborted"})),!0)};if(g.aborted){X();return}g.addEventListener("abort",X,{once:!0}),P.promise.then(Z=>{if(!Y){if(g.aborted){X();return}b(y,x),O(()=>R(Q(Z)),!1)}},Z=>{if(!Y){if(g.aborted){X();return}O(()=>L(Z),!1)}})})}function W(i,g,y){if(g.aborted)return Promise.reject(N({id:i.id,ref:i.ref,code:"aborted"}));if(i.ref===he)return Promise.resolve(Ct(i));let x=new AbortController,U=()=>x.abort();g.addEventListener("abort",U,{once:!0});let I=i.timeoutMs??e.timeoutMs,P,R=!1;return n&&I!==void 0&&I>0&&Number.isFinite(I)&&(P=setTimeout(()=>{R=!0,x.abort()},I)),H(i,x.signal,y).then(L=>{let Y=kt(i,L);return Y.id=i.id,Y}).catch(L=>{throw R?N({id:i.id,ref:i.ref,code:"timeout"}):L}).finally(()=>{P!==void 0&&clearTimeout(P),g.removeEventListener("abort",U)})}async function B(i,g,y,x){try{return{resource:await W(i,g,x)}}catch(U){let I=E(i,g,U);if(w(I)||g.aborted||y>=pn)throw I;let P=D(i);if(!P)throw I;if(g.aborted)throw N({id:i.id,ref:i.ref,code:"aborted"});if(i.fallback==="silent"||P.ref===he)return{resource:Ct(i),failure:I};try{let R=await B(P,g,y+1,x);return{resource:{...Q(R.resource),id:i.id,usedFallback:!0},failure:I}}catch(R){let L=Ge(R)&&!w(R)&&!g.aborted?R:E(i,g,R);throw!w(L)&&!g.aborted&&F(I),L}}}async function te(i,g){if(l)throw new Error(Et);let y=r.get(i.id);if(y?.state==="ready"||y?.state==="failed")return;let x=o.get(i.id);if(x){await x;return}let U=(async()=>{let I=wn(i);if(I){A(i.id,{state:"failed",failure:I}),F(I),d(oe("failed",{id:i.id,ref:i.ref,failure:I}));return}A(i.id,{state:"loading"});let P=u.get(i.id)??new AbortController;u.has(i.id)||u.set(i.id,P);try{let R=await B(i,P.signal,g,i.id);if(l)return;if(P.signal.aborted){let L=N({id:i.id,ref:i.ref,code:"aborted"});A(i.id,{state:"failed",failure:L}),F(L),d(oe("failed",{id:i.id,ref:i.ref,failure:L}));return}if(R.resource.id=i.id,R.failure){A(i.id,{state:"ready",resource:R.resource,failure:R.failure}),F(R.failure),d(oe("failed",{id:i.id,ref:i.ref,failure:R.failure,resource:Q(R.resource)})),d(oe("ready",{id:i.id,ref:R.resource.ref,resource:Q(R.resource),failure:R.failure}));return}A(i.id,{state:"ready",resource:R.resource}),d(oe("ready",{id:i.id,ref:i.ref,resource:Q(R.resource)}))}catch(R){if(l)return;let L=Ge(R)&&!w(R)&&!P.signal.aborted?{...me(R),id:i.id}:E(i,P.signal,R);A(i.id,{state:"failed",failure:L}),F(L),d(oe("failed",{id:i.id,ref:i.ref,failure:L}))}finally{u.get(i.id)===P&&u.delete(i.id)}})();o.set(i.id,U);try{await U}finally{o.delete(i.id)}}return{async preload(i){if(l)throw new Error(Et);let g=Array.isArray(i)?i:[];for(let y of g)y&&typeof y.id=="string"&&y.id.length>0&&(r.has(y.id)||r.set(y.id,{state:"pending"}),u.has(y.id)||u.set(y.id,new AbortController));return J(),await Promise.all(g.map(y=>te(y,0))),$()},get(i){let g=r.get(i);if(g?.state==="ready")return Q(g.resource)},getProgress(){return $()},onProgress(i){return v.add(i),()=>{v.delete(i)}},abort(i){if(!l){if(i!==void 0){u.get(i)?.abort();return}for(let g of u.values())g.abort()}},forget(i){if(l)return;if(i===void 0){for(let y of r.values())y.state==="ready"&&T(y.resource);r.clear(),a.length=0,p.clear(),C.clear(),J();return}let g=r.get(i);g?.state==="ready"&&T(g.resource),K(i,g),r.delete(i);for(let y=a.length-1;y>=0;y--)a[y].id===i&&a.splice(y,1);J()},dispose(){if(!l){l=!0;for(let i of u.values())i.abort();u.clear();for(let i of r.values())i.state==="ready"&&T(i.resource);r.clear(),a.length=0,o.clear();for(let i of m.values())i.controller.abort();p.clear(),m.clear(),C.clear(),v.clear()}}}}function Se(e){Je();let{container:t,seed:n,captureKeyboard:r=!1,audio:a,deterministic:o,assets:u}=e,p=n===void 0?void 0:dt(n,o?"deterministic":"live"),m=new Ce;if(u&&typeof u.resolver?.resolve!="function")throw new Error("createRuntime: assets.resolver is required");let C=u?Rt({resolver:u.resolver,timeoutMs:u.timeoutMs,emitEvents:u.emitEvents??!o,wallClockTimeout:!o,dispatch:F=>m.dispatch(F)}):void 0,v=!1,l=null,w,E=!1,b=t.clientWidth||window.innerWidth,M=t.clientHeight||window.innerHeight,h=new Ee(30,!1,b,M,!1,void 0,{container:t,seed:p,captureKeyboard:r,hostChannel:m,audio:a,deterministic:o}),K=()=>{let F=t.clientWidth||window.innerWidth,d=t.clientHeight||window.innerHeight;return F===h.containerWidth&&d===h.containerHeight?!1:(h.containerWidth=F,h.containerHeight=d,!0)},$=null;return!h.isDeterministic&&typeof ResizeObserver<"u"&&($=new ResizeObserver(()=>{if(v||!l)return;K()&&E&&h.reinit()}),$.observe(t)),h.onError=(F,d)=>{w?.(F,d)},{get tokenData(){return h.tokenData},get hostChannel(){return m},get assets(){return C},get onError(){return w},set onError(F){w=F},mount(F,d={}){if(v)throw new Error("createRuntime: cannot mount on a destroyed runtime");l?.destroy(),E=!1,h.customState=d.initialState,h.setGameManager(d.gameManager);let T=d.onEvent?m.onEvent(d.onEvent):()=>{};if(!h.prepareCart(F))throw T(),new Error("createRuntime: failed to prepare cart");let A=!1,D={async start(){if(!A){if(K()&&h.isPrepared&&(h.init(),h.unloadCart(),!h.prepareCart(F)))throw new Error("createRuntime: failed to prepare cart");h.needsAudio&&(await h.unlockAudio(),A)||(E=!0,h.beginPlayback())}},pause(){A||(h.paused=!0)},resume(){A||(h.paused=!1)},dispatch(H){A||m.dispatch(H)},snapshot(){if(A)return{seed:"",pngDataUrl:""};let H=h.canvas;return{seed:h.tokenData.hash,metadata:F.metadata,pngDataUrl:H?H.toDataURL("image/png"):""}},destroy(){A||(A=!0,E=!1,T(),m.clearInbound(),h.unloadCart(),l===D&&(l=null))},reload(){if(!A){if(!E){if(h.isPrepared&&(h.unloadCart(),!h.prepareCart(F)))throw new Error("createRuntime: failed to prepare cart");return}h.reloadCart()}},reinit(H){if(!A){if(!E){K();return}h.reinit(H)}},getCartState(){return h.animation?.cartState},exportState(){return A?Promise.reject(new Error("Cart handle has been destroyed")):h.exportState()},exportStateJSON(){return A?Promise.reject(new Error("Cart handle has been destroyed")):h.exportStateJSON()},async importState(H,W){if(A)throw new Error("Cart handle has been destroyed");await h.importState(H,W)},peekExportedFramebuffer(){return A?null:h.peekExportedFramebuffer()},peekSeed(){if(!A)return h.peekSeed()},isGenerative(){return A?!1:h.isGenerative()},async step(H=1){if(A)throw new Error("Cart handle has been destroyed");await h.step(H)},async advance(H){if(A)throw new Error("Cart handle has been destroyed");await h.advance(H)},schedule(H){A||h.schedule(H)},getClock(){if(A)throw new Error("Cart handle has been destroyed");return h.getClock()},getRandomState(){if(A)throw new Error("Cart handle has been destroyed");return h.getRandomState()},getReplayMetadata(){return A?Promise.reject(new Error("Cart handle has been destroyed")):h.getReplayMetadata()},get canvas(){return h.canvas},get paused(){return h.paused},set paused(H){A||(h.paused=H)},get tokenData(){return h.tokenData},get isPrepared(){return h.isPrepared},get isLoopRunning(){return h.isLoopRunning},get needsAudio(){return h.needsAudio},get audioLibraries(){return h.audioLibraries}};return l=D,D},async unlockAudio(){await h.unlockAudio()},destroy(){v||(v=!0,l?.destroy(),l=null,$?.disconnect(),$=null,C?.dispose(),m.close(),h.destroy())}}}var xt="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==",Tt=320,Pt=180,An="Headless harness has been destroyed",Mt=!1;function ke(){if(typeof globalThis.ImageData>"u"){class t{constructor(r,a){this.colorSpace="srgb";this.width=r,this.height=a,this.data=new Uint8ClampedArray(r*a*4)}}globalThis.ImageData=t}let e=HTMLCanvasElement.prototype;e.getContext=function(){return{globalAlpha:1,imageSmoothingEnabled:!1,fillStyle:"",save(){},restore(){},fillRect(){},putImageData(){},createImageData(r,a){return{data:new Uint8ClampedArray(r*a*4),width:r,height:a}}}},e.toDataURL=()=>xt,Mt=!0}function En(e,t){let n=document.createElement("div");return Object.defineProperty(n,"clientWidth",{value:e,configurable:!0}),Object.defineProperty(n,"clientHeight",{value:t,configurable:!0}),document.body.appendChild(n),n}function Cn(e){let t=e.indexOf(","),n=t>=0?e.slice(t+1):e,r=globalThis.atob(n),a=new Uint8Array(r.length);for(let o=0;o<r.length;o++)a[o]=r.charCodeAt(o);return a}function Sn(){return typeof process<"u"&&!!process.versions?.node}async function kn(e,t){if(!Sn())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 a=r instanceof Error?r.message:String(r);throw new Error(`captureFrame(path) could not load node:fs/promises (${a}). Omit the path, or run under Node.`)}try{await n(e,Cn(t))}catch(r){let a=r instanceof Error?r.message:String(r);throw new Error(`captureFrame could not write ${e}: ${a}`)}}function Rn(e){Mt||ke();let t=e.width??Tt,n=e.height??Pt,r=En(t,n),a=[],o=[],u=!1,p=e.onEvent,m=e.onError,C=Se({container:r,seed:e.seed,deterministic:{origin:e.origin,actions:e.actions??[]}});C.onError=(b,M)=>{o.push({error:b,info:M}),m?.(b,M)},Object.defineProperty(C,"onError",{configurable:!0,enumerable:!0,get(){return m},set(b){m=b}});let v=b=>{a.push(b),p?.(b)},l=C.mount(e.cart,{initialState:e.initialState,gameManager:e.gameManager,onEvent:v}),w=()=>{if(u)throw new Error(An)};return{runtime:C,container:r,get events(){return a.slice()},get errors(){return o.slice()},get cart(){return l},async step(b=1){w(),await l.step(b)},async advance(b){w(),await l.advance(b)},schedule(b){w(),l.schedule(b)},dispatch(b){w(),l.dispatch(b)},start(){return w(),l.start()},pause(){w(),l.pause()},resume(){w(),l.resume()},get paused(){return l.paused},key(b){w(),l.schedule({type:"key",atFrame:l.getClock().framesElapsed,key:b})},click(b,M){w(),l.schedule({type:"pointer",atFrame:l.getClock().framesElapsed,pointer:{kind:"down",x:b,y:M}})},async inspect(){w();let b=await l.getReplayMetadata();return{state:b.state,events:a.slice(),errors:o.slice(),replay:b,clock:l.getClock()}},async captureFrame(b){w();let M=l.snapshot();return b&&await kn(b,M.pngDataUrl),M},remount(b={}){return w(),a.length=0,o.length=0,"onEvent"in b&&(p=b.onEvent),l=C.mount(e.cart,{initialState:b.initialState??e.initialState,gameManager:b.gameManager??e.gameManager,onEvent:v}),l},destroy(){if(!u){u=!0;try{l.destroy()}finally{try{C.destroy()}finally{r.remove()}}}}}}var Dt="cyberart.state.save",It="cyberart.state.load";var Re=1,fe="cyberart.diagnostic.rejected",Ve=8,xn=new Set(["intent","state","diagnostic"]),Tn=new Set([Dt,It]);function Ht(e){return typeof e=="string"&&xn.has(e)}function Pn(e){if(e.kind!==void 0)return Ht(e.kind)?e.kind:void 0;if(!(typeof e.type!="string"||e.type.length===0)){if(Tn.has(e.type))return"intent";for(let t of e.type.split("."))if(Ht(t))return t}}function Mn(e,t){let n=e.split("."),r=t.split(".");if(n.length!==r.length)return!1;for(let a=0;a<n.length;a++)if(n[a]!=="*"&&n[a]!==r[a])return!1;return!0}function de(e,t){for(let n of e)if(Mn(n,t))return!0;return!1}function Dn(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 je(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!==Re)return{ok:!1,reason:"malformed",detail:`unsupported schemaVersion ${String(e.schemaVersion)}`};let n=Pn(e);if(!n)return{ok:!1,reason:"malformed",detail:`cannot infer kind from type "${e.type}"`};let r=Dn(e.payload);if(!r.ok)return{ok:!1,reason:"malformed",detail:"payload is not JSON-serializable"};let a=t.createId(),o=typeof e.correlationId=="string"&&e.correlationId.length>0?e.correlationId:a,u=typeof e.causationId=="string"&&e.causationId.length>0?e.causationId:t.causationId,p=typeof e.target=="string"&&e.target.length>0?e.target:void 0,m=t.maxHops??Ve,C=t.parentHops===void 0?m:Math.max(0,t.parentHops-1),v=typeof e.idempotencyKey=="string"&&e.idempotencyKey.length>0?e.idempotencyKey:void 0,l={schemaVersion:Re,type:e.type,kind:n,source:t.source,id:a,correlationId:o,seq:t.seq,hops:C};return p&&(l.target=p),u&&(l.causationId=u),v&&(l.idempotencyKey=v),r.value!==void 0&&(l.payload=r.value),{ok:!0,envelope:l}}var In=new Set(["rate-limited","storm-detected","hop-limit","loop-detected","not-subscribed"]),Hn=8,Fn=8,Ln=16,On=256,_n=["*.intent.*"];function Ft(e={}){let t=e.hostSource??"host",n="router",r=e.maxPerTurn??Hn,a=e.maxCausationDepth??Fn,o=e.maxHops??Ve,u=e.maxCorrelationPerTurn??Ln,p=e.maxIndex??On,m=e.maxPerWindow,C=e.windowMs??1e3,v=e.now??Date.now,l=0,w=e.createId??(()=>`evt-${++l}`),E=new Map,b=[],M=new Map,h=new Map,K=new Map,$=0,J=0,F=[],d=!1;function T(s,c,S){for(s.set(c,S);s.size>p;){let k=s.keys().next().value;if(k===void 0)break;s.delete(k)}}function A(s){T(M,s.id,{type:s.type,source:s.source,causationId:s.causationId,hops:s.hops,correlationId:s.correlationId,idempotencyKey:s.idempotencyKey})}function D(s,c){c&&(s.correlationId||(s.correlationId=c.correlationId),s.causationId||(s.causationId=c.id),!s.idempotencyKey&&c.idempotencyKey&&(s.idempotencyKey=`${c.idempotencyKey}::${s.type}`))}function H(s,c){if(s){let S=M.get(s);return S?S.hops:o}return c}function W(s,c){return`${s}\0${c}`}function B(s,c){s.idempotencyKey&&T(K,W(s.source,s.idempotencyKey),c)}function te(s,c){if(c)return K.get(W(s,c))}function i(s){return te(s.source,s.idempotencyKey)}function g(s){return s.seq+=1,s.seq}function y(s,c){if(!(typeof c.causationId=="string"&&c.causationId.length>0))return s.lastDelivered}function x(s){let c=new Set,S=new Set([`${s.type}\0${s.source}`]),k=s.causationId,f=0;for(;k;){if(f+=1,f>a||c.has(k))return!0;c.add(k);let _=M.get(k);if(!_)break;let V=`${_.type}\0${_.source}`;if(S.has(V))return!0;S.add(V),k=_.causationId}return!1}function U(s){let c=(h.get(s)??0)+1;return h.set(s,c),c}function I(s,c){m!==void 0&&(s.emitTimestamps=s.emitTimestamps.filter(S=>c-S<C))}function P(s,c){return(c.kind==="state"||c.kind==="diagnostic")&&!s.authoritative?!1:de(s.emit,c.type)}function R(s){for(let c of b)if(de(c.patterns,s.type))try{c.listener(s)}catch{}}function L(s){if(s.target){let c=E.get(s.target);if(!c||!de(c.subscribe,s.type))return;c.channel.dispatch(s),c.lastDelivered={id:s.id,hops:s.hops,correlationId:s.correlationId,idempotencyKey:s.idempotencyKey};return}for(let c of E.values())de(c.subscribe,s.type)&&(c.channel.dispatch(s),c.lastDelivered={id:s.id,hops:s.hops,correlationId:s.correlationId,idempotencyKey:s.idempotencyKey})}function Y(s,c,S,k,f,_,V){let q={reason:k,eventType:c,source:S};f&&(q.detail=f),J+=1;let ue=w(),ne={schemaVersion:Re,type:fe,kind:"diagnostic",source:n,id:ue,correlationId:_??ue,seq:J,hops:0,payload:q};V&&(ne.causationId=V),A(ne);let qe=E.get(s);qe&&qe.channel.dispatch(ne),R(ne)}function O(s,c,S,k,f){Y(s,f?.type??(typeof c.type=="string"?c.type:""),f?.source??s,S,k,f?.correlationId,f?.id),f?.idempotencyKey&&!In.has(S)&&B(f,{status:"rejected"})}function X(s){A(s),B(s,{status:"accepted",envelope:s}),U(s.correlationId),R(s),L(s)}function Z(s,c,S,k){if(!S.ok){O(s,c,"malformed",S.detail);return}let f=S.envelope,_=i(f);if(_)return _.status==="accepted"?_.envelope:void 0;if(f.hops<1){O(s,c,"hop-limit","no hops remaining",f);return}if(f.target&&f.target!==t){let V=E.get(f.target);if(!V){O(s,c,"unknown-target",`unknown target "${f.target}"`,f);return}if(!de(V.subscribe,f.type)){O(s,c,"not-subscribed",`target "${f.target}" does not subscribe to ${f.type}`,f);return}}if(k){if(!P(k,f)){O(s,c,"unauthorized","source may not emit this event",f);return}if(k.emitsThisTurn+=1,k.emitsThisTurn>r){O(s,c,"rate-limited","maxPerTurn exceeded",f);return}if(m!==void 0){let q=v();if(I(k,q),k.emitTimestamps.push(q),k.emitTimestamps.length>m){O(s,c,"rate-limited","maxPerWindow exceeded",f);return}}if(x(f)){O(s,c,"loop-detected","causation chain cycle or depth exceeded",f);return}if((h.get(f.correlationId)??0)+1>u){O(s,c,"storm-detected","correlationId storm",f);return}if(e.validate){let q;try{q=e.validate(f)}catch(ue){let ne=ue instanceof Error?ue.message:"validate threw";O(s,c,"host-rejected",ne,f);return}if(q!==!0){O(s,c,"host-rejected",q.detail,f);return}}}else{if(x(f)){O(s,c,"loop-detected","causation chain cycle or depth exceeded",f);return}if((h.get(f.correlationId)??0)+1>u){O(s,c,"storm-detected","correlationId storm",f);return}}return X(f),f}function xe(s,c){let S=E.get(s);if(!S)return;let k={...c},f=y(S,k);if(D(k,f),te(S.id,k.idempotencyKey))return;let V=g(S),q=je(k,{source:S.id,createId:w,seq:V,causationId:f?.id,maxHops:o,parentHops:H(k.causationId??f?.id,f?.hops)});Z(s,k,q,S)}function Nt(s,c){let S=c?.cause,k={...s};D(k,S);let f=te(t,k.idempotencyKey);if(f)return f.status==="accepted"?f.envelope:void 0;$+=1;let _=je(k,{source:t,createId:w,seq:$,causationId:k.causationId,maxHops:o,parentHops:H(k.causationId,S?.hops)});return Z(t,k,_,void 0)}function Ut(){if(!d){d=!0;try{for(;F.length>0;){let s=F.shift();s&&(s.kind==="cart"?xe(s.participantId,s.event):s.result=Nt(s.event,s.extras))}}finally{d=!1}}}function ze(s){F.push(s),Ut()}return{attach(s,c,S={}){if(s===t||s===n)throw new Error(`createEventRouter: "${s}" is a reserved participant id`);for(let _ of E.values())if(_.channel===c&&_.id!==s)throw new Error(`createEventRouter: channel already attached as "${_.id}"`);E.get(s)?.unsubscribe();let f={id:s,channel:c,emit:S.emit??_n,subscribe:S.subscribe??[],authoritative:S.authoritative===!0,seq:0,emitsThisTurn:0,emitTimestamps:[],unsubscribe:()=>{}};f.unsubscribe=c.onEvent(_=>{ze({kind:"cart",participantId:s,event:_})}),E.set(s,f)},detach(s){let c=E.get(s);c&&(c.unsubscribe(),E.delete(s))},publish(s,c){let S={kind:"publish",event:s,extras:c};return ze(S),S.result},subscribe(s,c){let S={patterns:s,listener:c};return b.push(S),()=>{let k=b.indexOf(S);k>=0&&b.splice(k,1)}},turn(){h.clear();for(let s of E.values())s.emitsThisTurn=0,s.lastDelivered=void 0,m!==void 0&&I(s,v())}}}var Nn=320,Un=180,Kn="Runtime group has been destroyed";function $n(e){let t="";for(let n=0;n<32;n++){let r=e.charCodeAt(n%Math.max(e.length,1))+n*17&255;t+=r.toString(16).padStart(2,"0")}return`0x${t}`}function Wn(e,t){let n=document.createElement("div");return Object.defineProperty(n,"clientWidth",{value:e,configurable:!0}),Object.defineProperty(n,"clientHeight",{value:t,configurable:!0}),document.body.appendChild(n),n}function Ot(e){let t=e.capability,n={},r=e.emit??t?.emit,a=e.subscribe??t?.subscribe,o=e.authoritative??t?.authoritative;return r&&(n.emit=r),a&&(n.subscribe=a),o!==void 0&&(n.authoritative=o),n}function Lt(e){try{return JSON.parse(JSON.stringify(e))}catch{return e}}function Gn(e){let t=new Set([fe,"*.*","*.*.*","*.*.*.*","*.*.*.*.*"]);for(let n of e){let r=Ot(n);for(let a of r.emit??[])t.add(a);for(let a of r.subscribe??[])t.add(a)}return[...t]}function _t(e){if(!e.participants.length)throw new Error("createRuntimeGroup: at least one participant is required");let t=new Set;for(let d of e.participants){if(!d.id)throw new Error("createRuntimeGroup: participant id is required");if(t.has(d.id))throw new Error(`createRuntimeGroup: duplicate participant id "${d.id}"`);t.add(d.id)}let n=e.origin??0,r=e.width??Nn,a=e.height??Un,o=[...e.participants].sort((d,T)=>d.id.localeCompare(T.id)),u=[],p=new Map,m=0,C=e.createId??e.router?.createId??(()=>`evt-${++m}`),v=e.now??e.router?.now??(()=>{let d=u[0];if(!d)return n;try{return d.cart.getClock().now}catch{return n}}),l=Ft({...e.router,createId:C,now:v,validate:e.validate??e.router?.validate}),w=[],E=!1,b=!1,M=()=>{},h=d=>T=>{d.events.push(T),d.userOnEvent?.(T)},K=()=>{if(b)throw new Error(Kn)},$=()=>{M();for(let d of u){try{l.detach(d.id)}catch{}try{d.runtime.destroy()}catch{}d.ownsContainer&&d.container.remove()}u.length=0,p.clear()};try{for(let d of o){let T=d.width??r,A=d.height??a,D=!d.container,H=d.container??Wn(T,A),W=Se({container:H,seed:d.seed??$n(d.id),deterministic:{origin:n}}),B={id:d.id,kind:d.kind??"render",cartDef:d.cart,initialState:d.initialState,gameManager:d.gameManager,userOnEvent:d.onEvent,runtime:W,container:H,ownsContainer:D,cart:void 0,events:[],errors:[]};W.onError=(te,i)=>{B.errors.push({error:te,info:i})},l.attach(d.id,W.hostChannel,Ot(d)),B.cart=W.mount(d.cart,{initialState:d.initialState,gameManager:d.gameManager,onEvent:h(B)}),u.push(B),p.set(B.id,B)}M=l.subscribe(Gn(o),d=>{w.push(Lt(d))})}catch(d){throw $(),d}let J=d=>({id:d.id,kind:d.kind,runtime:d.runtime,container:d.container,get events(){return d.events.slice()},get errors(){return d.errors.slice()},get cart(){return d.cart}});return{router:l,origin:n,get paused(){return E},participant(d){K();let T=p.get(d);if(!T)throw new Error(`createRuntimeGroup: unknown participant "${d}"`);return J(T)},async step(d=1){if(K(),E)return;let T=Math.max(0,Math.floor(d));for(let A=0;A<T;A++){l.turn();for(let D of u)await D.cart.step(1)}},pause(){K(),E=!0;for(let d of u)d.cart.pause()},resume(){K(),E=!1;for(let d of u)d.cart.resume()},reset(){K(),w.length=0;for(let d of u)d.events.length=0,d.errors.length=0,d.cart=d.runtime.mount(d.cartDef,{initialState:d.initialState,gameManager:d.gameManager,onEvent:h(d)});l.turn()},dispatch(d,T){K();let A=p.get(d);if(!A)throw new Error(`createRuntimeGroup: unknown participant "${d}"`);A.cart.dispatch(T)},publish(d,T){return K(),l.publish(d,T)},async inspect(){K();let d={},T={};for(let D of u){let H=await D.cart.getReplayMetadata(),W=D.cart.getClock();T[D.id]=W,d[D.id]={state:H.state,events:D.events.slice(),errors:D.errors.slice(),kind:D.kind,clock:W}}let A=w.map(D=>Lt(D));return{participants:d,trace:A,diagnostics:{paused:E,participantIds:u.map(D=>D.id),clocks:T,rejections:A.filter(D=>D.type===fe).map(D=>D.payload)}}},destroy(){if(!b){b=!0,E=!1;try{$()}finally{w.length=0}}}}}function Bn(e){return ke(),_t(e)}export{Pt as DEFAULT_HEADLESS_HEIGHT,Tt as DEFAULT_HEADLESS_WIDTH,xt as HEADLESS_PNG_DATA_URL,Rn as createHeadlessHarness,Bn as createHeadlessMultiCartHarness,ke as installHeadlessCanvas};
|
|
8
|
+
var Nn=(e,t)=>()=>(e&&(t=e(e=0)),t);var dr={};function cr(e,t){let n=e.indexOf(nn);if(n===-1)return null;let r=n+nn.length,s=`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)+s+e.slice(r)}var mt,ze,ur,De,nn,rn=Nn(()=>{"use strict";mt=/AudioWorkletProcessor with name:\s*["'`][^"'`]+["'`]\s+is already registered/i,ze="__cyberartWorkletPatchApplied";typeof window<"u"&&!window[ze]&&(window.addEventListener("error",e=>{let t=e?.message??"";mt.test(t)&&(e.preventDefault(),e.stopImmediatePropagation())},!0),window.addEventListener("unhandledrejection",e=>{let t=e?.reason,n=typeof t=="string"?t:t?.message??"";mt.test(n)&&e.preventDefault()}),window[ze]=!0);ur=!1,De=(...e)=>{ur&&console.log("[workletPatch]",...e)},nn="((AudioWorkletProcessor,registerProcessor)=>{";if(typeof AudioWorklet<"u"&&!AudioWorklet.prototype[ze]){let e=new WeakMap,t=/registerProcessor\s*\(\s*['"`]([^'"`]+)['"`]/g,n=AudioWorklet.prototype.addModule,r=0;AudioWorklet.prototype.addModule=async function(s,a){let c=++r,h=e.get(this);h||(h=new Set,e.set(this,h)),De(`#${c} addModule`,{url:s.slice(0,64),isBlob:s.startsWith("blob:"),knownBefore:[...h]});let g=s,b=null;if(s.startsWith("blob:")){let m=null;try{m=await(await fetch(s)).text()}catch(E){De(`#${c} blob fetch failed`,E)}if(m!==null){let E=new Set;for(let H of m.matchAll(t))E.add(H[1]);if(E.size>0){let H=[...E].filter(O=>h.has(O)),C=[...E].filter(O=>!h.has(O));if(H.length>0&&C.length===0){De(`#${c} short-circuit \u2014 all processors already registered`,H);return}if(H.length>0&&C.length>0){let O=cr(m,H);if(O!==null){let R=new Blob([O],{type:"application/javascript"});b=URL.createObjectURL(R),g=b,De(`#${c} rewrote blob; skipping`,H,"allowing",C)}else De(`#${c} blob rewrite failed; passing original through`)}C.forEach(O=>h.add(O))}}}return n.call(this,g,a).then(()=>{b&&URL.revokeObjectURL(b)},m=>{b&&URL.revokeObjectURL(b);let E=(m&&m.message)??"";if(!(mt.test(E)||/already registered/i.test(E)))throw m})},AudioWorklet.prototype[ze]=!0}});var j=class extends Error{constructor(n,r){super(r?`Headless Canvas2D does not support ${n}: ${r}`:`Headless Canvas2D does not support ${n}`);this.name="HeadlessUnsupportedOperationError";this.operation=n}},ge=class{constructor(t,n,r,i,s,a=0,c=0){this.stops=[];this.kind=t,this.x0=n,this.y0=r,this.x1=i,this.y1=s,this.r0=a,this.r1=c}addColorStop(t,n){if(!Number.isFinite(t)||t<0||t>1)throw new j("addColorStop","offset must be in [0, 1]");this.stops.push({offset:t,color:Ke(n)}),this.stops.sort((r,i)=>r.offset-i.offset)}colorAt(t){let n=t<0?0:t>1?1:t;if(this.stops.length===0)return{r:0,g:0,b:0,a:0};if(this.stops.length===1||n<=this.stops[0].offset)return this.stops[0].color;let r=this.stops[this.stops.length-1];if(n>=r.offset)return r.color;for(let i=1;i<this.stops.length;i++){let s=this.stops[i],a=this.stops[i-1];if(n<=s.offset){let c=s.offset-a.offset,h=c===0?0:(n-a.offset)/c;return jn(a.color,s.color,h)}}return r.color}},tt={a:1,b:0,c:0,d:1,e:0,f:0},Gn={black:"#000000",white:"#ffffff",red:"#ff0000",green:"#008000",blue:"#0000ff",cyan:"#00ffff",magenta:"#ff00ff",yellow:"#ffff00",gold:"#ffd700",orange:"#ffa500",navy:"#000080",gray:"#808080",grey:"#808080",transparent:"#00000000"},we=new WeakMap,Ft,Pt=!1,at=class{constructor(t,n,r,i){this.context=null;this.onDeviceReset=null;this.canvas=t,this.width=Math.max(0,n|0),this.height=Math.max(0,r|0),this.alpha=i.alpha!==!1,this.pixels=new Uint8ClampedArray(this.width*this.height*4),this.glyphAtlas=i.glyphAtlas??Ft??Ut(),this.alpha||this.fillOpaqueBlack()}resize(t,n,r=!1){let i=Math.max(0,t|0),s=Math.max(0,n|0);i!==this.width||s!==this.height?(this.width=i,this.height=s,this.pixels=new Uint8ClampedArray(i*s*4)):r&&this.pixels.fill(0),this.alpha||this.fillOpaqueBlack()}fillOpaqueBlack(){let t=this.pixels;for(let n=3;n<t.length;n+=4)t[n]=255}};function Kn(e,t,n){let r=n??new Uint8ClampedArray(e*t*4);if(r.length!==e*t*4)throw new j("createImageFixture","data length must be width*height*4");return{__headlessImage:!0,width:e,height:t,data:r}}function ot(e){Ft=e}function Vn(e){return we.get(e)}function ut(e,t={}){let n=we.get(e);if(n?.context)return n.context;let r=Math.max(0,Number(e.width)||0),i=Math.max(0,Number(e.height)||0),s=new at(e,r,i,t);we.set(e,s);let a=Wn(s);return s.context=a,a}function Ot(e){let t=we.get(e);if(t)return t.resize(e.width,e.height,!1),Ee(t.width,t.height,t.pixels)}function Wn(e){let t={...tt},n=[],r="#000000",i="#000000",s={r:0,g:0,b:0,a:255},a={r:0,g:0,b:0,a:255},c=1,h="source-over",g=1,b="butt",m="10px sans-serif",E="start",H="alphabetic",C=null,O=!0,R=[],G=null,K=(o,p)=>{G={points:[T(o,p)],closed:!1},R.push(G)},z=(o,p)=>{if(!G){K(o,p);return}G.points.push(T(o,p))},v=()=>{if(!G||G.points.length===0)return;G.closed=!0;let o=G.points[0];G.points.push({x:o.x,y:o.y})},T=(o,p)=>({x:t.a*o+t.c*p+t.e,y:t.b*o+t.d*p+t.f}),l=()=>{if(h!=="source-over"&&h!=="copy")throw new j("globalCompositeOperation",h)},x=()=>{e.resize(e.canvas.width,e.canvas.height,!1)},U=()=>{t={...tt},n.length=0,R.length=0,G=null,C=null,r="#000000",i="#000000",s={r:0,g:0,b:0,a:255},a={r:0,g:0,b:0,a:255},c=1,h="source-over",g=1,b="butt",m="10px sans-serif",E="start",H="alphabetic",O=!0};e.onDeviceReset=U;let V=(o,p,f,A=h)=>{if(o<0||p<0||o>=e.width||p>=e.height||C&&C[p*e.width+o]===0)return;let w=(p*e.width+o)*4,S=e.pixels;if(A==="copy"){S[w]=f.r,S[w+1]=f.g,S[w+2]=f.b,S[w+3]=e.alpha?f.a:255;return}let I=Math.round(f.a/255*c*255);if(I<=0)return;if(I>=255){S[w]=f.r,S[w+1]=f.g,S[w+2]=f.b,S[w+3]=255;return}let M=I/255,_=S[w+3]/255,B=M+_*(1-M);if(B<=0){S[w]=0,S[w+1]=0,S[w+2]=0,S[w+3]=e.alpha?0:255;return}S[w]=Math.round((f.r*M+S[w]*_*(1-M))/B),S[w+1]=Math.round((f.g*M+S[w+1]*_*(1-M))/B),S[w+2]=Math.round((f.b*M+S[w+2]*_*(1-M))/B),S[w+3]=e.alpha?Math.round(B*255):255},W=(o,p,f,A)=>{if(!(o instanceof ge))return p;let w=Ge(t,f+.5,A+.5);return Bn(o,w.x,w.y)},Q=(o,p,f,A,w)=>{l(),x();let S=rt(o,e.width,e.height);if(S)for(let I=S.minY;I<=S.maxY;I++)for(let M=S.minX;M<=S.maxX;M++){let _=M+.5,B=I+.5;Dt(o,_,B,A)&&V(M,I,W(p,f,M,I),w)}},ee=o=>{l(),x();let p=Math.sqrt(Math.abs(t.a*t.d-t.b*t.c)),f=g*(p===0?1:p)/2,A=rt(o,e.width,e.height,f+1);if(A)for(let w=A.minY;w<=A.maxY;w++)for(let S=A.minX;S<=A.maxX;S++)qn(o,S+.5,w+.5,f,b)&&V(S,w,W(i,a,S,w))},d=(o,p)=>{if(o instanceof ge){p==="fillStyle"?(r=o,s={r:0,g:0,b:0,a:255}):(i=o,a={r:0,g:0,b:0,a:255});return}if(typeof o!="string")throw new j(p,String(o));let f=Ke(o);p==="fillStyle"?(r=o,s=f):(i=o,a=f)},F={get canvas(){return e.canvas},get fillStyle(){return r},set fillStyle(o){d(o,"fillStyle")},get strokeStyle(){return i},set strokeStyle(o){d(o,"strokeStyle")},get globalAlpha(){return c},set globalAlpha(o){c=Lt(o)},get globalCompositeOperation(){return h},set globalCompositeOperation(o){if(o!=="source-over"&&o!=="copy")throw new j("globalCompositeOperation",o);h=o},get lineWidth(){return g},set lineWidth(o){g=Number.isFinite(o)&&o>0?o:1},get lineCap(){return b},set lineCap(o){if(o!=="butt"&&o!=="round"&&o!=="square")throw new j("lineCap",String(o));b=o},get font(){return m},set font(o){m=o},get textAlign(){return E},set textAlign(o){if(o!=="start"&&o!=="left"&&o!=="center"&&o!=="right"&&o!=="end")throw new j("textAlign",String(o));E=o},get textBaseline(){return H},set textBaseline(o){H=o},get imageSmoothingEnabled(){return O},set imageSmoothingEnabled(o){O=!!o},imageSmoothingQuality:"low",lineJoin:"miter",miterLimit:10,lineDashOffset:0,shadowBlur:0,shadowColor:"rgba(0, 0, 0, 0)",shadowOffsetX:0,shadowOffsetY:0,setGlyphAtlas(o){e.glyphAtlas=o},save(){n.push({transform:{...t},fillStyle:r,strokeStyle:i,fillStyleRaw:r,strokeStyleRaw:i,globalAlpha:c,globalCompositeOperation:h,lineWidth:g,lineCap:b,font:m,textAlign:E,textBaseline:H,clip:C?C.slice():null,imageSmoothingEnabled:O})},restore(){let o=n.pop();o&&(t=o.transform,r=o.fillStyleRaw,i=o.strokeStyleRaw,r instanceof ge?s={r:0,g:0,b:0,a:255}:s=Ke(r),i instanceof ge?a={r:0,g:0,b:0,a:255}:a=Ke(i),c=o.globalAlpha,h=o.globalCompositeOperation,g=o.lineWidth,b=o.lineCap,m=o.font,E=o.textAlign,H=o.textBaseline,C=o.clip,O=o.imageSmoothingEnabled)},beginPath(){R.length=0,G=null},closePath:v,moveTo:K,lineTo:z,rect(o,p,f,A){K(o,p),z(o+f,p),z(o+f,p+A),z(o,p+A),v()},quadraticCurveTo(o,p,f,A){let w=G?.points[G.points.length-1];if(!w){K(f,A);return}let S=Ge(t,w.x,w.y);Xn(S.x,S.y,o,p,f,A,16,(I,M)=>{G.points.push(T(I,M))})},bezierCurveTo(o,p,f,A,w,S){let I=G?.points[G.points.length-1];if(!I){K(w,S);return}let M=Ge(t,I.x,I.y);Jn(M.x,M.y,o,p,f,A,w,S,24,(_,B)=>{G.points.push(T(_,B))})},arc(o,p,f,A,w,S=!1){if(f<0)throw new j("arc","negative radius");let I=Mt(o,p,f,A,w,S);if(I.length===0)return;let M=I[0];G?G.points.push(T(M.x,M.y)):K(M.x,M.y);for(let _=1;_<I.length;_++)G.points.push(T(I[_].x,I[_].y))},ellipse(o,p,f,A,w,S,I,M=!1){if(f<0||A<0)throw new j("ellipse","negative radius");let _=Mt(0,0,1,S,I,M),B=Math.cos(w),X=Math.sin(w);for(let q=0;q<_.length;q++){let re=_[q].x*f,J=_[q].y*A,ae=o+re*B-J*X,ie=p+re*X+J*B;q===0&&!G?K(ae,ie):z(ae,ie)}},fill(o="nonzero"){Q(nt(R),r,s,o)},stroke(){ee(nt(R))},clip(o="nonzero"){let p=new Uint8Array(e.width*e.height),f=nt(R),A=rt(f,e.width,e.height);if(A)for(let w=A.minY;w<=A.maxY;w++)for(let S=A.minX;S<=A.maxX;S++)Dt(f,S+.5,w+.5,o)&&(p[w*e.width+S]=1);if(!C){C=p;return}for(let w=0;w<C.length;w++)C[w]=C[w]&&p[w]?1:0},fillRect(o,p,f,A){Q(L(o,p,f,A),r,s,"nonzero")},strokeRect(o,p,f,A){ee(L(o,p,f,A))},clearRect(o,p,f,A){let w=e.alpha?{r:0,g:0,b:0,a:0}:{r:0,g:0,b:0,a:255};Q(L(o,p,f,A),"#000000",w,"nonzero","copy")},fillText(o,p,f){$(String(o),p,f,r,s,!0)},strokeText(o,p,f){$(String(o),p,f,i,a,!1)},measureText(o){return{width:Ht(String(o),m,e.glyphAtlas)}},translate(o,p){t=Ne(t,{a:1,b:0,c:0,d:1,e:o,f:p})},rotate(o){let p=Math.cos(o),f=Math.sin(o);t=Ne(t,{a:p,b:f,c:-f,d:p,e:0,f:0})},scale(o,p){t=Ne(t,{a:o,b:0,c:0,d:p,e:0,f:0})},transform(o,p,f,A,w,S){t=Ne(t,{a:o,b:p,c:f,d:A,e:w,f:S})},setTransform(o,p,f,A,w,S){if(o&&typeof o=="object"){t={a:o.a,b:o.b,c:o.c,d:o.d,e:o.e,f:o.f};return}t={a:Number(o)||0,b:Number(p)||0,c:Number(f)||0,d:Number(A)||0,e:Number(w)||0,f:Number(S)||0}},resetTransform(){t={...tt}},getTransform(){return{...t}},createLinearGradient(o,p,f,A){return new ge("linear",o,p,f,A)},createRadialGradient(o,p,f,A,w,S){if(f<0||S<0)throw new j("createRadialGradient","negative radius");return new ge("radial",o,p,A,w,f,S)},createImageData(o,p){return typeof o=="object"?he(new Uint8ClampedArray(o.width*o.height*4),o.width,o.height):he(new Uint8ClampedArray(o*(p??0)*4),o,p??0)},getImageData(o,p,f,A){x();let w=o|0,S=p|0,I=f|0,M=A|0,_=new Uint8ClampedArray(I*M*4);for(let B=0;B<M;B++)for(let X=0;X<I;X++){let q=w+X,re=S+B,J=(B*I+X)*4;if(q<0||re<0||q>=e.width||re>=e.height)continue;let ae=(re*e.width+q)*4;_[J]=e.pixels[ae],_[J+1]=e.pixels[ae+1],_[J+2]=e.pixels[ae+2],_[J+3]=e.pixels[ae+3]}return he(_,I,M)},putImageData(o,p,f){x();let A=p|0,w=f|0,S=o.data;for(let I=0;I<o.height;I++)for(let M=0;M<o.width;M++){let _=A+M,B=w+I;if(_<0||B<0||_>=e.width||B>=e.height)continue;let X=(I*o.width+M)*4,q=(B*e.width+_)*4;e.pixels[q]=S[X],e.pixels[q+1]=S[X+1],e.pixels[q+2]=S[X+2],e.pixels[q+3]=e.alpha?S[X+3]:255}},drawImage(o,...p){let f=$n(o),A=0,w=0,S=f.width,I=f.height,M,_,B,X;if(p.length===2)M=p[0],_=p[1],B=S,X=I;else if(p.length===4)M=p[0],_=p[1],B=p[2],X=p[3];else if(p.length===8)A=p[0],w=p[1],S=p[2],I=p[3],M=p[4],_=p[5],B=p[6],X=p[7];else throw new j("drawImage","invalid argument count");l(),x();let q=[T(M,_),T(M+B,_),T(M+B,_+X),T(M,_+X)],re=Math.max(0,Math.floor(Math.min(...q.map(Y=>Y.x)))),J=Math.min(e.width-1,Math.ceil(Math.max(...q.map(Y=>Y.x)))),ae=Math.max(0,Math.floor(Math.min(...q.map(Y=>Y.y)))),ie=Math.min(e.height-1,Math.ceil(Math.max(...q.map(Y=>Y.y))));for(let Y=ae;Y<=ie;Y++)for(let te=re;te<=J;te++){let ve=Ge(t,te+.5,Y+.5),ye=(ve.x-M)/B,me=(ve.y-_)/X;if(ye<0||me<0||ye>=1||me>=1)continue;let u=Math.floor(A+ye*S),y=Math.floor(w+me*I);if(u<0||y<0||u>=f.width||y>=f.height)continue;let k=(y*f.width+u)*4;V(te,Y,{r:f.data[k],g:f.data[k+1],b:f.data[k+2],a:f.data[k+3]})}},setLineDash(o){if(o.length>0)throw new j("setLineDash","non-empty dash")},getLineDash(){return[]},createPattern(){throw new j("createPattern")}};function L(o,p,f,A){let w=T(o,p),S=T(o+f,p),I=T(o+f,p+A),M=T(o,p+A);return[{closed:!0,points:[w,S,I,M,w]}]}function $(o,p,f,A,w,S){l();let I=e.glyphAtlas,M=_t(m),_=M/I.cellHeight,B=Ht(o,m,I),X=p;E==="center"?X=p-B/2:(E==="right"||E==="end")&&(X=p-B);let q=f;H==="top"||H==="hanging"?q=f:H==="middle"?q=f-M/2:q=f-M;let re=X,J=(I.cellWidth+1)*_;for(let ae of o){let ie=I.glyphs[ae]??I.glyphs[ae.toUpperCase()];if(!ie){re+=J;continue}for(let Y=0;Y<I.cellHeight;Y++)for(let te=0;te<I.cellWidth;te++){if(ie[Y*I.cellWidth+te]===0)continue;if(!S){let ne=te===0||ie[Y*I.cellWidth+te-1]===0,ce=te===I.cellWidth-1||ie[Y*I.cellWidth+te+1]===0,fe=Y===0||ie[(Y-1)*I.cellWidth+te]===0,Ue=Y===I.cellHeight-1||ie[(Y+1)*I.cellWidth+te]===0;if(!ne&&!ce&&!fe&&!Ue)continue}let ve=re+te*_,ye=q+Y*_,me=re+(te+1)*_,u=q+(Y+1)*_,y=T(ve,ye),k=T(me,u),P=Math.max(0,Math.floor(Math.min(y.x,k.x))),D=Math.min(e.width-1,Math.ceil(Math.max(y.x,k.x))-1),N=Math.max(0,Math.floor(Math.min(y.y,k.y))),oe=Math.min(e.height-1,Math.ceil(Math.max(y.y,k.y))-1);for(let ne=N;ne<=oe;ne++)for(let ce=P;ce<=D;ce++)V(ce,ne,W(A,w,ce,ne))}re+=J}}return new Proxy(F,{get(o,p,f){if(Reflect.has(o,p))return Reflect.get(o,p,f);if(typeof p=="symbol")return;let A=String(p);if(!(A==="then"||A==="toJSON"))return(...w)=>{throw new j(A)}},set(o,p,f,A){if(p==="shadowBlur"&&f)throw new j("shadowBlur");if((p==="shadowOffsetX"||p==="shadowOffsetY")&&f)throw new j(String(p));if(p==="filter"&&f&&f!=="none")throw new j("filter",String(f));if(Reflect.has(o,p))return Reflect.set(o,p,f,A);throw new j(String(p))}})}function $n(e){if(e&&typeof e=="object"&&"__headlessImage"in e){let t=e;return{width:t.width,height:t.height,data:t.data}}if(e&&typeof e=="object"&&"data"in e&&"width"in e&&"height"in e){let t=e;if(t.data instanceof Uint8ClampedArray)return{width:t.width,height:t.height,data:t.data}}if(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement){let t=we.get(e);if(!t)throw new j("drawImage","source canvas has no headless surface");return{width:t.width,height:t.height,data:t.pixels}}throw new j("drawImage","source must be ImageData, a headless canvas, or createImageFixture()")}function Bn(e,t,n){if(e.kind==="linear"){let a=e.x1-e.x0,c=e.y1-e.y0,h=a*a+c*c,g=h===0?0:((t-e.x0)*a+(n-e.y0)*c)/h;return e.colorAt(g)}let r=Math.hypot(t-e.x1,n-e.y1),i=e.r1-e.r0,s=i===0?0:(r-e.r0)/i;return e.colorAt(s)}function jn(e,t,n){return{r:Math.round(e.r+(t.r-e.r)*n),g:Math.round(e.g+(t.g-e.g)*n),b:Math.round(e.b+(t.b-e.b)*n),a:Math.round(e.a+(t.a-e.a)*n)}}function Ne(e,t){return{a:e.a*t.a+e.c*t.b,b:e.b*t.a+e.d*t.b,c:e.a*t.c+e.c*t.d,d:e.b*t.c+e.d*t.d,e:e.a*t.e+e.c*t.f+e.e,f:e.b*t.e+e.d*t.f+e.f}}function Ge(e,t,n){let r=e.a*e.d-e.b*e.c;if(r===0)return{x:t,y:n};let i=e.d/r,s=-e.b/r,a=-e.c/r,c=e.a/r,h=(e.c*e.f-e.d*e.e)/r,g=(e.b*e.e-e.a*e.f)/r;return{x:i*t+a*n+h,y:s*t+c*n+g}}function nt(e){return e.map(t=>({closed:t.closed,points:t.points.map(n=>({x:n.x,y:n.y}))}))}function rt(e,t,n,r=0){let i=1/0,s=1/0,a=-1/0,c=-1/0;for(let h of e)for(let g of h.points)i=Math.min(i,g.x),s=Math.min(s,g.y),a=Math.max(a,g.x),c=Math.max(c,g.y);return Number.isFinite(i)?{minX:Math.max(0,Math.floor(i-r)),minY:Math.max(0,Math.floor(s-r)),maxX:Math.min(t-1,Math.ceil(a+r)),maxY:Math.min(n-1,Math.ceil(c+r))}:null}function Dt(e,t,n,r){let i=0,s=0;for(let a of e){let c=a.points;if(!(c.length<2))for(let h=1;h<c.length;h++){let g=c[h-1],b=c[h],m=zn(g.x,g.y,b.x,b.y,t,n);i+=m,m!==0&&(s+=1)}}return r==="evenodd"?s%2===1:i!==0}function zn(e,t,n,r,i,s){if(t<=s==r<=s)return 0;let a=e+(s-t)/(r-t)*(n-e);return i<a?r>t?1:-1:0}function qn(e,t,n,r,i){for(let s of e){let a=s.points;for(let c=1;c<a.length;c++){let h=a[c-1],g=a[c];if(i==="round"){if(Yn(t,n,h.x,h.y,g.x,g.y)<=r)return!0;continue}let b=g.x-h.x,m=g.y-h.y,E=Math.hypot(b,m);if(E===0){if(Math.hypot(t-h.x,n-h.y)<=r)return!0;continue}let H=b/E,C=m/E,O=h.x,R=h.y,G=g.x,K=g.y;i==="square"&&(O-=H*r,R-=C*r,G+=H*r,K+=C*r);let z=G-O,v=K-R,T=z*z+v*v,l=((t-O)*z+(n-R)*v)/T;if(l<0||l>1)continue;let x=O+l*z,U=R+l*v;if(Math.hypot(t-x,n-U)<=r)return!0}}return!1}function Yn(e,t,n,r,i,s){let a=i-n,c=s-r,h=a*a+c*c;if(h===0)return Math.hypot(e-n,t-r);let g=((e-n)*a+(t-r)*c)/h;return g=g<0?0:g>1?1:g,Math.hypot(e-(n+g*a),t-(r+g*c))}function Xn(e,t,n,r,i,s,a,c){for(let h=1;h<=a;h++){let g=h/a,b=1-g;c(b*b*e+2*b*g*n+g*g*i,b*b*t+2*b*g*r+g*g*s)}}function Jn(e,t,n,r,i,s,a,c,h,g){for(let b=1;b<=h;b++){let m=b/h,E=1-m,H=E*E,C=m*m;g(H*E*e+3*H*m*n+3*E*C*i+C*m*a,H*E*t+3*H*m*r+3*E*C*s+C*m*c)}}function Mt(e,t,n,r,i,s){let a=r,c=i;!s&&c<a&&(c+=Math.PI*2),s&&a<c&&(a+=Math.PI*2);let h=c-a,g=Math.max(8,Math.min(360,Math.ceil(Math.abs(h)*Math.max(n,1)))),b=[];for(let m=0;m<=g;m++){let E=a+h*m/g;b.push({x:e+Math.cos(E)*n,y:t+Math.sin(E)*n})}return b}function Lt(e){return Number.isFinite(e)?e<0?0:e>1?1:e:1}function Ke(e){let t=e.trim().toLowerCase(),r=Gn[t]??t;if(r==="transparent")return{r:0,g:0,b:0,a:0};if(r[0]==="#"){let s=r.slice(1);if(s.length===3)return{r:parseInt(s[0]+s[0],16),g:parseInt(s[1]+s[1],16),b:parseInt(s[2]+s[2],16),a:255};if(s.length===6)return{r:parseInt(s.slice(0,2),16),g:parseInt(s.slice(2,4),16),b:parseInt(s.slice(4,6),16),a:255};if(s.length===8)return{r:parseInt(s.slice(0,2),16),g:parseInt(s.slice(2,4),16),b:parseInt(s.slice(4,6),16),a:parseInt(s.slice(6,8),16)}}let i=r.match(/^rgba?\(\s*([0-9.]+)\s*,\s*([0-9.]+)\s*,\s*([0-9.]+)(?:\s*,\s*([0-9.]+))?\s*\)$/);if(i)return{r:it(Number(i[1])),g:it(Number(i[2])),b:it(Number(i[3])),a:i[4]===void 0?255:Math.round(Lt(Number(i[4]))*255)};throw new j("fillStyle",e)}function it(e){return Number.isFinite(e)?e<0?0:e>255?255:Math.round(e):0}function _t(e){let t=e.match(/([0-9]+(?:\.[0-9]+)?)px/);return t?Number(t[1]):10}function Ht(e,t,n){let r=_t(t)/n.cellHeight;return e.length*(n.cellWidth+1)*r}function he(e,t,n){if(typeof ImageData=="function")try{return new ImageData(e,t,n)}catch{try{let r=new ImageData(t,n);return r.data.set(e),r}catch{}}return{data:e,width:t,height:n,colorSpace:"srgb"}}function Ut(){let n={" ":new Uint8Array(35)},r={0:[14,17,19,21,25,17,14],1:[4,12,4,4,4,4,14],2:[14,17,1,2,4,8,31],3:[14,17,1,6,1,17,14],4:[2,6,10,18,31,2,2],5:[31,16,30,1,1,17,14],6:[14,16,30,17,17,17,14],7:[31,1,2,4,8,8,8],8:[14,17,17,14,17,17,14],9:[14,17,17,15,1,1,14],A:[14,17,17,31,17,17,17],B:[30,17,17,30,17,17,30],C:[14,17,16,16,16,17,14],D:[30,17,17,17,17,17,30],E:[31,16,16,30,16,16,31],F:[31,16,16,30,16,16,16],G:[14,17,16,23,17,17,14],H:[17,17,17,31,17,17,17],I:[14,4,4,4,4,4,14],K:[17,18,20,24,20,18,17],L:[16,16,16,16,16,16,31],M:[17,27,21,21,17,17,17],N:[17,25,21,19,17,17,17],O:[14,17,17,17,17,17,14],P:[30,17,17,30,16,16,16],R:[30,17,17,30,20,18,17],S:[15,16,16,14,1,1,30],T:[31,4,4,4,4,4,4],U:[17,17,17,17,17,17,14],V:[17,17,17,17,17,10,4],W:[17,17,17,21,21,21,10],Y:[17,17,10,4,4,4,4],Z:[31,1,2,4,8,16,31],".":[0,0,0,0,0,0,4],"-":[0,0,0,31,0,0,0],"+":[0,4,4,31,4,4,0],"*":[0,21,14,31,14,21,0],"!":[4,4,4,4,4,0,4],"?":[14,17,1,2,4,0,4],"/":[1,2,2,4,8,8,16],":":[0,4,0,0,0,4,0],"\u2713":[1,1,2,2,20,8,0]};for(let[i,s]of Object.entries(r)){let a=new Uint8Array(35);for(let c=0;c<7;c++)for(let h=0;h<5;h++)a[c*5+h]=s[c]&1<<4-h?1:0;n[i]=a,n[i.toLowerCase()]=a}return{cellWidth:5,cellHeight:7,glyphs:n}}var Nt=new Uint32Array(256);for(let e=0;e<256;e++){let t=e;for(let n=0;n<8;n++)t=t&1?3988292384^t>>>1:t>>>1;Nt[e]=t>>>0}function Qn(e){let t=4294967295;for(let n=0;n<e.length;n++)t=Nt[(t^e[n])&255]^t>>>8;return(t^4294967295)>>>0}function Zn(e){let t=1,n=0;for(let r=0;r<e.length;r++)t=(t+e[r])%65521,n=(n+t)%65521;return(n<<16|t)>>>0}function Ie(e){return new Uint8Array([e>>>24&255,e>>>16&255,e>>>8&255,e&255])}function st(e,t){let n=new Uint8Array(8+t.length+4);n.set(Ie(t.length),0),n[4]=e.charCodeAt(0),n[5]=e.charCodeAt(1),n[6]=e.charCodeAt(2),n[7]=e.charCodeAt(3),n.set(t,8);let r=n.subarray(4,8+t.length);return n.set(Ie(Qn(r)),8+t.length),n}function er(e){let t=[];for(let a=0;a<e.length;a+=65535){let c=e.subarray(a,Math.min(a+65535,e.length)),h=a+65535>=e.length,g=new Uint8Array(5+c.length);g[0]=h?1:0,g[1]=c.length&255,g[2]=c.length>>>8&255;let b=~c.length&65535;g[3]=b&255,g[4]=b>>>8&255,g.set(c,5),t.push(g)}t.length===0&&t.push(new Uint8Array([1,0,0,255,255]));let r=t.reduce((a,c)=>a+c.length,0),i=new Uint8Array(2+r+4);i[0]=120,i[1]=1;let s=2;for(let a of t)i.set(a,s),s+=a.length;return i.set(Ie(Zn(e)),s),i}function Ae(e,t,n){let r=e*4,i=new Uint8Array(t*(1+r));for(let m=0;m<t;m++){let E=m*(1+r);i[E]=0,i.set(n.subarray(m*r,(m+1)*r),E+1)}let s=new Uint8Array(13);s.set(Ie(e),0),s.set(Ie(t),4),s[8]=8,s[9]=6;let a=new Uint8Array([137,80,78,71,13,10,26,10]),c=[st("IHDR",s),st("IDAT",er(i)),st("IEND",new Uint8Array(0))],h=a.length+c.reduce((m,E)=>m+E.length,0),g=new Uint8Array(h);g.set(a,0);let b=a.length;for(let m of c)g.set(m,b),b+=m.length;return g}function Ee(e,t,n){let r=Ae(e,t,n),i="";for(let s=0;s<r.length;s++)i+=String.fromCharCode(r[s]);return`data:image/png;base64,${globalThis.btoa(i)}`}function ct(e){let t=[137,80,78,71,13,10,26,10];for(let g=0;g<8;g++)if(e[g]!==t[g])throw new j("decodePng","invalid signature");let n=0,r=0,i=[],s=8;for(;s<e.length;){let g=e[s]<<24|e[s+1]<<16|e[s+2]<<8|e[s+3],b=String.fromCharCode(e[s+4],e[s+5],e[s+6],e[s+7]),m=e.subarray(s+8,s+8+g);if(b==="IHDR"){if(n=m[0]<<24|m[1]<<16|m[2]<<8|m[3],r=m[4]<<24|m[5]<<16|m[6]<<8|m[7],m[8]!==8||m[9]!==6)throw new j("decodePng","only 8-bit RGBA is supported")}else if(b==="IDAT")for(let E=0;E<m.length;E++)i.push(m[E]);else if(b==="IEND")break;s+=12+g}let a=tr(new Uint8Array(i)),c=n*4,h=new Uint8ClampedArray(n*r*4);for(let g=0;g<r;g++){let b=g*(1+c);if(a[b]!==0)throw new j("decodePng",`unsupported scanline filter ${a[b]}`);h.set(a.subarray(b+1,b+1+c),g*c)}return he(h,n,r)}function tr(e){if(e.length<6)throw new j("decodePng","truncated zlib");let t=[],n=2;for(;n<e.length-4;){let a=e[n]&1;if((e[n]>>>1&3)!==0)throw new j("decodePng","only stored deflate blocks are supported");n+=1;let h=e[n]|e[n+1]<<8;if(n+=4,t.push(e.subarray(n,n+h)),n+=h,a)break}let r=t.reduce((a,c)=>a+c.length,0),i=new Uint8Array(r),s=0;for(let a of t)i.set(a,s),s+=a.length;return i}function Ve(e){let t=e.indexOf(","),n=t>=0?e.slice(t+1):e,r=globalThis.atob(n),i=new Uint8Array(r.length);for(let s=0;s<r.length;s++)i[s]=r.charCodeAt(s);return i}function Gt(){if(!Pt){Pt=!0;for(let e of["width","height"]){let t=Object.getOwnPropertyDescriptor(HTMLCanvasElement.prototype,e);if(!t?.set||!t.get)continue;let n=t.set;Object.defineProperty(HTMLCanvasElement.prototype,e,{configurable:!0,enumerable:t.enumerable,get:t.get,set(r){n.call(this,r);let i=we.get(this);i&&(i.resize(this.width,this.height,!0),i.onDeviceReset?.())}})}}}var Kt=()=>{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"]},ue=window.devicePixelRatio||1,Ce=/Headless/i.test(navigator.userAgent),wi=/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)||/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.platform);function Vt(){return Math.min(window.innerWidth,window.innerHeight)}var dt="data-cyberart-canvas",xe=class{constructor(t,n,r=1,i={}){this.width=t,this.height=n;let s=i.container,a=i.adoptFromDocument??!s,c=s?s.querySelector(`canvas[${dt}]`)??s.querySelector("canvas"):null;if(c)this.canvas=c,this.adopted=!0;else if(a){let h=document.getElementById("canvas")??document.querySelector("canvas");h?(this.canvas=h,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(dt)||this.canvas.setAttribute(dt,""),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/ue}px`,this.canvas.style.height=`${n/ue}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 Wt(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 $t(e,t=window.innerWidth,n=window.innerHeight){let r=Vt(),i,s;return n<t?e>1?t>=r*e?(i=r*e,s=r):(i=t,s=i/e):(i=r*e,s=r):e>1?(i=r,s=r/e):n<r/e?(s=n,i=s*e):(i=r,s=r/e),[i,s]}var lt=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={}}},Bt=lt;var pt=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))}},jt=pt;function We(){return{now:()=>performance.now()}}function zt(e=0){let t=e;return{now:()=>t,set(n){t=n},advance(n){t+=n}}}var qt=(e,t,n,r)=>({now:e,startTime:t,elapsedSinceStart:e-t,deltaSinceLastUpdate:n===null?0:e-n,deltaSinceLastRender:r===null?0:e-r}),$e=class{constructor(t,n,r,i,s,a={}){this.startTime=0;this.lastUpdateAt=null;this.lastRenderAt=null;this.clockOffsetMs=0;this.pauseStartedAt=null;this.renderAnimation=this.renderAnimation.bind(this),this.dimensionContext=Wt(t,n),this.R=r,this.gameManager=a.gameManager,this.hostChannel=a.hostChannel,this.clock=a.clock??We(),this.canvas=new xe(this.dimensionContext.width,this.dimensionContext.height,1,a.canvasMount),this.drawingContext=this.canvas.ctx,this.keyboardManager=new Bt(!1,a.captureKeyboard??!0),this.pointerManager=new jt(this.canvas.canvas,{listen:a.listenToPointer!==!1}),this.animationCart=s;let c=a.customState;this.featureState=s.getDefaultFeatureState?.(this.R,this.dimensionContext,i,this.keyboardManager,c,this.pointerManager,this.gameManager,this.hostChannel),this.cartState=s.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 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),s=qt(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,s,this.featureState,this.hostChannel),this.lastUpdateAt=i}async renderAnimation(t,n,r=this.clock.now()){let i=this.resolveNow(r),s=qt(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,s,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 Be=class extends xe{constructor(t,n,r=1,i=!0,s={}){if(super(t,n,r,s),this.adopted)return;let a=s.container;if(a){this.canvas.parentNode!==a&&a.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 Yt(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 a=(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+a|0,(a>>>0)/4294967296},getRegs:()=>({a:t,b:n,c:r,d:i}),setRegs:a=>{t=a.a,n=a.b,r=a.c,i=a.d}}}var je=class{constructor(t){this.seed=t.hash,this.useA=!1,this.genA=Yt(t.hash.substring(2,32)),this.genB=Yt(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 Qt="bafybeicjwcq5lxxtfnyj4p2ugcr7ctyb5wl62cbcechj6tsabdq5whcs7u",Xt="https://ipfs.io/ipfs/";function nr(e){return e.endsWith("/")?e:`${e}/`}var Pe=null;function rr(e){return[...Array(e)].map(()=>Math.floor(Math.random()*16).toString(16)).join("")}function ir(e){return e&&e.length>0?e:[{cid:Qt}]}function sr(e){return e.startsWith("0x")?e:`0x${e}`}var Zt=/^(0[xX])?[0-9a-fA-F]{64}$/;function ar(e){let t="",n=2166136261,r=522970236;for(let i=0;t.length<64;i++){for(let s=0;s<e.length;s++)n^=e.charCodeAt(s)+i,n=Math.imul(n,16777619),r^=e.charCodeAt(s)+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 Jt(e){let t=typeof e=="number"?String(e):e;return Zt.test(t)?`0x${(t.startsWith("0x")||t.startsWith("0X")?t.slice(2):t).toLowerCase()}`:ar(t)}function en(e,t){if(typeof e=="number"||t==="deterministic")return Jt(e);let n=String(e);return Zt.test(n)?Jt(n):n.startsWith("0x")||n.startsWith("0X")?n:`0x${n}`}function or(e){if(!e&&typeof tokenData<"u"&&tokenData?.hash)return{hash:tokenData.hash,tokenId:String(tokenData.tokenId),externalAssetDependencies:ir(tokenData.externalAssetDependencies),preferredIPFSGateway:nr(tokenData.preferredIPFSGateway||Xt),preferredArweaveGateway:tokenData.preferredArweaveGateway};let t=typeof window<"u"?new URLSearchParams(window.location.search):new URLSearchParams;return{hash:e?sr(e):t.get("hash")||`0x${rr(64)}`,tokenId:"18009999",externalAssetDependencies:[{cid:Qt}],preferredIPFSGateway:Xt}}function ht(e){let t=e?.useCache!==!1;if(t&&Pe&&!e?.hash)return Pe;let n=or(e?.hash);return t?Pe=n:Pe||(Pe=n),n}function tn(e){return new Array(32).fill(null).map((t,n)=>parseInt(e.hash.slice(2+n*2,4+n*2),16))}async function ft(){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 sn={id:"tone",async load(){await Promise.resolve().then(()=>(rn(),dr))},async unlock(){await sn.load(),await(await ft()).start()},async resumeIfSuspended(){let e=await ft();e.context.state==="suspended"&&await e.context.resume()},async suspendIfRunning(){let t=(await ft()).context.rawContext;"suspend"in t&&t.state==="running"&&await t.suspend()}},an={tone:sn};function gt(e){if(!e)return[];let t=Array.isArray(e)?e:[e],n=[];for(let r of t){if(!(r in an)){console.warn(`Unknown audio library "${r}"`);continue}let i=r;n.includes(i)||n.push(i)}return n}function bt(e){return e.map(t=>an[t])}var qe="$cyberartTa",de=class extends Error{constructor(t){super(t),this.name="IncompatibleCartStateError"}},yt={Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array};function lr(e){for(let t of Object.keys(yt))if(e instanceof yt[t])return t}function cn(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function le(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function vt(e){return le(e)?typeof e[qe]=="string"&&Array.isArray(e.d):!1}function pr(e){return e==null?!1:typeof e=="function"?!0:!(typeof e!="object"||Array.isArray(e)||cn(e)||le(e))}var hr=new Set(["audioContextStarted","midiSynths","keepRatioPrimed","audioInitStarted","musicSeekApplied"]);function on(e){return e===null?"null":vt(e)?String(e[qe]):Array.isArray(e)?"array":le(e)?"object":typeof e}function mr(e,t){return e===t||e==="null"||t==="null"}function un(e){return e.trim().toLowerCase().replace(/^0x/,"")}function dn(e,t,n,r){if(!(!n&&!r)&&un(e)!==un(t))throw new de(`Generative cart state is for seed "${t}", but the live token is "${e}"`)}function Re(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function ln(e,t){let n=e.dimensions;if(n&&Re(n.width)&&Re(n.height))return n;if(t&&Re(t.width)&&Re(t.height))return{width:t.width,height:t.height};if(le(e.state)){let r=e.state.containerWidth,i=e.state.containerHeight;if(Re(r)&&Re(i))return{width:r,height:i}}return null}function Se(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(cn(e)){let n=lr(e);return n?{[qe]:n,d:Array.from(e)}:void 0}if(typeof e=="object"&&!t.has(e)){t.add(e);try{if(Array.isArray(e)){let i=[],s=0;for(let a of e){let c=Se(a,t);c!==void 0&&(i.push(c),s++)}return e.length>0&&s===0?void 0:i}if(!le(e)||pr(e))return;let n=Object.keys(e),r={};for(let i of n){if(hr.has(i))continue;let s=Se(e[i],t);s!==void 0&&(r[i]=s)}return n.length>0&&Object.keys(r).length===0?void 0:r}finally{t.delete(e)}}}}function Me(e){if(vt(e)){let t=yt[e[qe]];return t?new t(e.d.map(n=>Number(n))):e}if(Array.isArray(e))return e.map(t=>Me(t));if(le(e)){let t={};for(let n of Object.keys(e))t[n]=Me(e[n]);return t}return e}function wt(e,t,n,r,i=!0){if(i&&n&&r&&n!==r)throw new de(`Cart state is for "${r}", but the live cart is "${n}"`);if(!le(t)){if(i)throw new de("Cart state snapshot is empty");return}let s=Object.keys(t);if(s.length===0){if(i)throw new de("Cart state snapshot is empty");return}let a=Se(e);if(!le(a)||Object.keys(a).length===0){if(i)throw new de("Live cart has no serializable state");return}let c=s.filter(h=>h in a);if(c.length===0){if(i)throw new de("Cart state snapshot does not overlap the live cart shape");return}for(let h of c){let g=on(a[h]),b=on(t[h]);if(!mr(g,b))throw new de(`Cart state field "${h}" has type ${b}, live cart expects ${g}`);if(g==="object"){let m=t[h],E=e[h];le(m)&&!vt(m)&&wt(E,m,void 0,void 0,!1)}}}function pn(e,t){if(!le(e)||!le(t))return;let n=Se(e);if(le(n))for(let r of Object.keys(t))r in n&&(e[r]=Me(t[r]))}function hn(e){let t=typeof e=="string"?JSON.parse(e):e;if(!t||typeof t!="object")throw new de("Cart state bundle is not an object");if(t.version!==1)throw new de(`Unsupported cart state version ${String(t.version)}`);if(typeof t.seed!="string"||typeof t.framesElapsed!="number")throw new de("Cart state bundle is missing seed or framesElapsed");return t}var He="cyberart.asset.ready",Fe="cyberart.asset.failed";function be(e){try{return JSON.parse(JSON.stringify(e))}catch{return e}}function mn(e){return{type:e.status==="ready"?He:Fe,kind:"state",payload:e.detail===void 0?{id:e.id}:{id:e.id,detail:e.detail}}}function gr(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 br(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),s=Math.max(0,window.outerHeight-window.innerHeight);try{window.resizeTo(n+i,r+s)}catch{return!1}return Math.abs(window.innerWidth-n)<=8&&Math.abs(window.innerHeight-r)<=8}var yr=[[0,0],[16,9],[9,16],[4,3],[3,4],[2,1],[1,2],[3,1],[1,3],[1,1]],Et=yr[0],vr=Et[0]/Et[1],At=30,wr=120,Ar=3840/2160,Er=2160/3840,Ye=class{constructor(t=At,n=!1,r=window.innerWidth,i=window.innerHeight,s=!0,a,c={}){this.framesElapsed=0;this.frameRate=At;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=gt(c.audio),this.audioLibrariesInternal=this.fallbackAudio;let h=c.deterministic;this.deterministic=!!h;let g=h&&typeof h=="object"?h:{};if(this.deterministic){if(c.clock){let b=c.clock;if(typeof b.advance!="function")throw new Error("deterministic mode requires a virtual clock with advance()");this.virtualClock=b,this.clock=b}else this.virtualClock=zt(g.origin??0),this.clock=this.virtualClock;this.initialScriptedActions=be(g.actions??[]),this.scriptedActions=be(this.initialScriptedActions)}else this.clock=c.clock??We();this.isBodyCanvas=this.container?!1:s,this.autoMode=n,this.aspectRatio=vr,this.selectedAsp=Et,this.isFullscreen=!!document.fullscreenElement,this.updateFrameRate(t),this.tempUnpause=!1,this.synchronous=Ce,this.containerWidth=r,this.containerHeight=i,this.gameManager=a,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?ht({hash:this.seed,useCache:!1}):ht(),this.rawParams=tn(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]=$t(n,this.containerWidth,this.containerHeight);r*=ue,i*=ue,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 Be(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 je(this.tokenData),s=new $e(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=s,this.animationCart=t,this.paused=!1,this.framesElapsed=0,this.outboundEvents=[],this.scriptedActions=be(this.initialScriptedActions),this.appliedActions=[],this.consumedActionIndexes=new Set,this.outboundUnsubscribe?.(),this.outboundUnsubscribe=void 0,this.deterministic&&this.hostChannel&&(this.outboundUnsubscribe=this.hostChannel.onEvent(a=>{this.outboundEvents.push(a)})),this.R=i,this.applyCartFrameRate(t,s),this.resolveAudioLibraries(t),this.prepared=!0,!0}catch(n){return console.error(n),!1}}applyCartFrameRate(t,n){let r=t.metadata,i=r?.frameRate??At,s=n.cartState?.visualMode??n.featureState?.visualMode,a=s&&r?.frameRateByVisualMode?r.frameRateByVisualMode[s]:void 0;this.updateFrameRate(typeof a=="number"&&a>0?a:i)}get audioLibraries(){return this.audioLibrariesInternal}get needsAudio(){return this.audioLibrariesInternal.length>0}resolveAudioLibraries(t){this.audioLibrariesInternal=gt(t.metadata?.audio)}async unlockAudio(){if(this.audioLibrariesInternal.length===0)return;let t=bt(this.audioLibrariesInternal);if(Ce){for(let n of t)await n.load();return}for(let n of t)await n.unlock()}async resumeAudioLibraries(){if(!(this.paused||Ce))for(let t of bt(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(be(t))}async getReplayMetadata(){let t=await this.exportState();return{seed:this.tokenData.hash,clock:this.getClock(),rng:this.getRandomState(),actions:be(this.scriptedActions),applied:be(this.appliedActions),events:be(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(mn(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:ue},state:Se(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=hn(t),s=this._paused,a=this.loopRunning;this.paused=!0,await this.waitUntilUpdateIdle(),wt(r.cartState,i.state,this.animationCart?.metadata?.id,i.cartId),dn(this.tokenData.hash,i.seed,this.animationCart?.metadata?.generative,i.generative),clearTimeout(this.reinitTimeout),this.reinitPending=!1,this.importing=!0;let c=ln(i,n?.framebuffer??this.lastExportedFramebuffer);if(c){this.pinOutputSize(c);let b=c.cssWidth??c.width/ue,m=c.cssHeight??c.height/ue;br(b,m),this.syncContainerFromDom(),this.pinViewportAtImport={w:this.containerWidth,h:this.containerHeight}}let h=this.customState,g=!1;try{if(this.customState=Me(i.state),this.unloadCart(),!this.prepareCart(this.animationCart))throw new Error("Failed to prepare cart while loading state");this.animation.cartState!==this.customState&&pn(this.animation.cartState,i.state),this.framesElapsed=i.framesElapsed;let b=this.animation,m=b.cartState,E=typeof i.elapsedSinceStart=="number"?i.elapsedSinceStart:gr(m);b.restoreClock(E,typeof m?.startTime=="number"?m.startTime:void 0),s&&b.setPaused(!0);let H=n?.framebuffer??this.lastExportedFramebuffer;H&&b.restoreFramebuffer(H)?m.keepRatioPrimed=!0:await b.renderAnimation(this.framesElapsed,this.rawParams),this.fitPinnedCanvas(),g=!0}catch(b){throw this.clearPinnedOutput(),this.customState=h,this.paused=s,this.animationCart&&(this.syncContainerFromDom(),this.init(),this.reloadCart()),b}finally{this.importing=!1,g&&(this.customState=h,this.paused=s,a&&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&&!Ce&&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/ue,h:t.cssHeight??t.height/ue}}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,s=t.width/ue,a=t.height/ue;if(s<1||a<1||r<1||i<1)return;let c=Math.min(r/s,i/a),h=s*c,g=a*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=`${h}px`,n.style.height=`${g}px`,n.style.imageRendering=Math.abs(c-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 s=!1,a,c="update";try{if(r||!this.paused||this.tempUnpause){if(!Ce&&!r&&this.tuneFramerate(t),!this.animation)return;if(c="update",this.updateInProgress=!0,await this.animation.updateAnimationState(this.framesElapsed,this.rawParams,t),this.updateInProgress=!1,c="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 b=localStorage.getItem("goodones"),m=JSON.stringify(b?[...JSON.parse(b),this.tokenData.hash]:[this.tokenData.hash]);localStorage.setItem("goodones",m),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(h){s=!0,a=h,this.handleFrameError(h,c)}finally{this.updateInProgress=!1}s?(this.consecutiveErrorCount++,this.consecutiveErrorCount>=wr&&(this.loopRunning=!1,this.onError?.(a,{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(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,s=r/i;this.aspectRatio=Math.min(Ar,Math.max(Er,s))}else this.aspectRatio=t[0]/t[1]}};var Cr="HostChannel has been destroyed",Xe=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(Cr)}};var xr=["image","audio","font","spritesheet"],Rr=["timeout","cors","not-found","invalid","aborted","resolver"],Oe="cyberart:fallback/silent",fn="Asset preloader has been destroyed",Sr=4,kr=new Set(xr),Tr=new Set(Rr),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 Pr(e){return typeof e=="string"&&kr.has(e)}function Dr(e){return typeof e=="string"&&Tr.has(e)}function Ct(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.id=="string"&&typeof t.ref=="string"&&Dr(t.code)&&typeof t.message=="string"}function Z(e){return{id:e.id,ref:e.ref,code:e.code,message:e.message&&e.message.length>0?e.message:Ir[e.code]}}function ke(e,t){return{type:e==="ready"?He:Fe,kind:"state",payload:t}}function Mr(e){return e instanceof Error&&e.name==="AbortError"||typeof DOMException<"u"&&e instanceof DOMException&&e.name==="AbortError"}function xt(e){return e?{...e}:void 0}function pe(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=xt(e.provenance)),e.cors!==void 0&&(t.cors=e.cors),e.usedFallback&&(t.usedFallback=!0),e.managed&&(t.managed=!0),t}function Le(e){return{id:e.id,ref:e.ref,code:e.code,message:e.message}}function Hr(e){if(e.state==="ready"){let t={state:"ready",resource:pe(e.resource)};return e.failure&&(t.failure=Le(e.failure)),t}return e.state==="failed"?{state:"failed",failure:Le(e.failure)}:{state:e.state}}function Fr(e){if(!e||typeof e!="object")return Z({id:"",ref:"",code:"invalid",message:"declaration is required"});if(typeof e.id!="string"||e.id.length===0)return Z({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 Z({id:e.id,ref:"",code:"invalid",message:"ref is required"});if(!Pr(e.type))return Z({id:e.id,ref:e.ref,code:"invalid",message:`unsupported type ${String(e.type)}`});if(e.integrity!==void 0&&typeof e.integrity!="string")return Z({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 Z({id:e.id,ref:e.ref,code:"invalid",message:"timeoutMs must be a non-negative finite number"})}function gn(e){return{id:e.id,ref:Oe,type:e.type,url:Oe,usedFallback:!0,cors:"omit"}}function bn(e,t){return Ct(t)?{id:e.id,ref:e.ref,code:t.code,message:t.message}:Mr(t)?Z({id:e.id,ref:e.ref,code:"aborted"}):Z({id:e.id,ref:e.ref,code:"resolver",message:t instanceof Error?t.message:String(t)})}function yn(e,t){if(!t||typeof t.url!="string"||t.url.length===0)throw Z({id:e.id,ref:e.ref,code:"invalid",message:"resolver returned no url"});if(t.integrity&&e.integrity&&t.integrity!==e.integrity)throw Z({id:e.id,ref:e.ref,code:"invalid",message:"integrity mismatch"});let n=pe(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=xt(e.provenance)),n}function vn(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=[],s=new Map,a=new Map,c=new Map,h=new Map,g=new Map,b=new Set,m=!1;function E(d){return d.code==="aborted"||d.code==="timeout"}function H(d,F,L){let $=bn(d,L);return $.code==="timeout"?$:F.aborted?Z({id:d.id,ref:d.ref,code:"aborted"}):$}function C(d,F){let L=g.get(d);L||(L=new Set,g.set(d,L)),L.add(F)}function O(d){if(d?.state==="ready")return`${d.resource.type}\0${d.resource.ref}`}function R(d,F){for(let[L,$]of g)if(L!==F&&$.has(d))return!0;for(let[L,$]of r)if(L!==F&&O($)===d)return!0;return!1}function G(d,F){let L=new Set(g.get(d)),$=O(F);$&&L.add($),g.delete(d);for(let o of L)R(o,d)||c.delete(o)}function K(){let d=0,F=0,L=0,$=0,o={};for(let[p,f]of r)o[p]=Hr(f),f.state==="pending"||f.state==="loading"?d+=1:f.state==="failed"?L+=1:(F+=1,(f.resource.usedFallback||f.failure)&&($+=1));return{total:r.size,pending:d,ready:F,failed:L,fallbacks:$,items:o,failures:i.map(Le)}}function z(){if(b.size===0)return;let d=K();for(let F of b)F(d)}function v(d){i.push(Le(d))}function T(d){m||!t||!e.dispatch||e.dispatch(d)}function l(d){if(d?.managed&&d.url.startsWith("blob:")&&!(typeof URL>"u"||typeof URL.revokeObjectURL!="function"))try{URL.revokeObjectURL(d.url)}catch{}}function x(d,F){if(m)return;let L=r.get(d);L?.state==="ready"&&l(L.resource),r.set(d,F),z()}function U(d){if(d.fallback!==void 0)return d.fallback==="silent"?{id:`${d.id}::fallback`,ref:Oe,type:d.type}:typeof d.fallback=="string"?{id:`${d.id}::fallback`,ref:d.fallback,type:d.type}:{...d.fallback,id:typeof d.fallback.id=="string"&&d.fallback.id.length>0?d.fallback.id:`${d.id}::fallback`}}function V(d,F,L){let $=`${d.type}\0${d.ref}`,o=c.get($);if(o)return F.aborted?Promise.reject(Z({id:d.id,ref:d.ref,code:"aborted"})):(C(L,$),Promise.resolve(pe(o.resource)));if(F.aborted)return Promise.reject(Z({id:d.id,ref:d.ref,code:"aborted"}));let p=h.get($);if(!p){let A=new AbortController,w={id:d.id,ref:d.ref,type:d.type};d.integrity!==void 0&&(w.integrity=d.integrity),d.provenance&&(w.provenance=xt(d.provenance)),p={promise:Promise.resolve().then(()=>e.resolver.resolve(w,A.signal)).then(I=>{let M=yn(d,I);if(A.signal.aborted)throw Z({id:d.id,ref:d.ref,code:"aborted"});return c.set($,{resource:pe(M)}),M}).catch(I=>{throw bn(d,I)}).finally(()=>{h.delete($)}),controller:A,waiters:0},h.set($,p)}let f=p;return f.waiters+=1,new Promise((A,w)=>{let S=!1,I=(_,B)=>{S||(S=!0,F.removeEventListener("abort",M),f.waiters-=1,B&&f.waiters<=0&&f.controller.abort(),_())},M=()=>{I(()=>w(Z({id:d.id,ref:d.ref,code:"aborted"})),!0)};if(F.aborted){M();return}F.addEventListener("abort",M,{once:!0}),f.promise.then(_=>{if(!S){if(F.aborted){M();return}C(L,$),I(()=>A(pe(_)),!1)}},_=>{if(!S){if(F.aborted){M();return}I(()=>w(_),!1)}})})}function W(d,F,L){if(F.aborted)return Promise.reject(Z({id:d.id,ref:d.ref,code:"aborted"}));if(d.ref===Oe)return Promise.resolve(gn(d));let $=new AbortController,o=()=>$.abort();F.addEventListener("abort",o,{once:!0});let p=d.timeoutMs??e.timeoutMs,f,A=!1;return n&&p!==void 0&&p>0&&Number.isFinite(p)&&(f=setTimeout(()=>{A=!0,$.abort()},p)),V(d,$.signal,L).then(w=>{let S=yn(d,w);return S.id=d.id,S}).catch(w=>{throw A?Z({id:d.id,ref:d.ref,code:"timeout"}):w}).finally(()=>{f!==void 0&&clearTimeout(f),F.removeEventListener("abort",o)})}async function Q(d,F,L,$){try{return{resource:await W(d,F,$)}}catch(o){let p=H(d,F,o);if(E(p)||F.aborted||L>=Sr)throw p;let f=U(d);if(!f)throw p;if(F.aborted)throw Z({id:d.id,ref:d.ref,code:"aborted"});if(d.fallback==="silent"||f.ref===Oe)return{resource:gn(d),failure:p};try{let A=await Q(f,F,L+1,$);return{resource:{...pe(A.resource),id:d.id,usedFallback:!0},failure:p}}catch(A){let w=Ct(A)&&!E(A)&&!F.aborted?A:H(d,F,A);throw!E(w)&&!F.aborted&&v(p),w}}}async function ee(d,F){if(m)throw new Error(fn);let L=r.get(d.id);if(L?.state==="ready"||L?.state==="failed")return;let $=s.get(d.id);if($){await $;return}let o=(async()=>{let p=Fr(d);if(p){x(d.id,{state:"failed",failure:p}),v(p),T(ke("failed",{id:d.id,ref:d.ref,failure:p}));return}x(d.id,{state:"loading"});let f=a.get(d.id)??new AbortController;a.has(d.id)||a.set(d.id,f);try{let A=await Q(d,f.signal,F,d.id);if(m)return;if(f.signal.aborted){let w=Z({id:d.id,ref:d.ref,code:"aborted"});x(d.id,{state:"failed",failure:w}),v(w),T(ke("failed",{id:d.id,ref:d.ref,failure:w}));return}if(A.resource.id=d.id,A.failure){x(d.id,{state:"ready",resource:A.resource,failure:A.failure}),v(A.failure),T(ke("failed",{id:d.id,ref:d.ref,failure:A.failure,resource:pe(A.resource)})),T(ke("ready",{id:d.id,ref:A.resource.ref,resource:pe(A.resource),failure:A.failure}));return}x(d.id,{state:"ready",resource:A.resource}),T(ke("ready",{id:d.id,ref:d.ref,resource:pe(A.resource)}))}catch(A){if(m)return;let w=Ct(A)&&!E(A)&&!f.signal.aborted?{...Le(A),id:d.id}:H(d,f.signal,A);x(d.id,{state:"failed",failure:w}),v(w),T(ke("failed",{id:d.id,ref:d.ref,failure:w}))}finally{a.get(d.id)===f&&a.delete(d.id)}})();s.set(d.id,o);try{await o}finally{s.delete(d.id)}}return{async preload(d){if(m)throw new Error(fn);let F=Array.isArray(d)?d:[];for(let L of F)L&&typeof L.id=="string"&&L.id.length>0&&(r.has(L.id)||r.set(L.id,{state:"pending"}),a.has(L.id)||a.set(L.id,new AbortController));return z(),await Promise.all(F.map(L=>ee(L,0))),K()},get(d){let F=r.get(d);if(F?.state==="ready")return pe(F.resource)},getProgress(){return K()},onProgress(d){return b.add(d),()=>{b.delete(d)}},abort(d){if(!m){if(d!==void 0){a.get(d)?.abort();return}for(let F of a.values())F.abort()}},forget(d){if(m)return;if(d===void 0){for(let L of r.values())L.state==="ready"&&l(L.resource);r.clear(),i.length=0,c.clear(),g.clear(),z();return}let F=r.get(d);F?.state==="ready"&&l(F.resource),G(d,F),r.delete(d);for(let L=i.length-1;L>=0;L--)i[L].id===d&&i.splice(L,1);z()},dispose(){if(!m){m=!0;for(let d of a.values())d.abort();a.clear();for(let d of r.values())d.state==="ready"&&l(d.resource);r.clear(),i.length=0,s.clear();for(let d of h.values())d.controller.abort();c.clear(),h.clear(),g.clear(),b.clear()}}}}function Je(e){Kt();let{container:t,seed:n,captureKeyboard:r=!1,audio:i,deterministic:s,assets:a}=e,c=n===void 0?void 0:en(n,s?"deterministic":"live"),h=new Xe;if(a&&typeof a.resolver?.resolve!="function")throw new Error("createRuntime: assets.resolver is required");let g=a?vn({resolver:a.resolver,timeoutMs:a.timeoutMs,emitEvents:a.emitEvents??!s,wallClockTimeout:!s,dispatch:v=>h.dispatch(v)}):void 0,b=!1,m=null,E,H=!1,C=t.clientWidth||window.innerWidth,O=t.clientHeight||window.innerHeight,R=new Ye(30,!1,C,O,!1,void 0,{container:t,seed:c,captureKeyboard:r,hostChannel:h,audio:i,deterministic:s}),G=()=>{let v=t.clientWidth||window.innerWidth,T=t.clientHeight||window.innerHeight;return v===R.containerWidth&&T===R.containerHeight?!1:(R.containerWidth=v,R.containerHeight=T,!0)},K=null;return!R.isDeterministic&&typeof ResizeObserver<"u"&&(K=new ResizeObserver(()=>{if(b||!m)return;G()&&H&&R.reinit()}),K.observe(t)),R.onError=(v,T)=>{E?.(v,T)},{get tokenData(){return R.tokenData},get hostChannel(){return h},get assets(){return g},get onError(){return E},set onError(v){E=v},mount(v,T={}){if(b)throw new Error("createRuntime: cannot mount on a destroyed runtime");m?.destroy(),H=!1,R.customState=T.initialState,R.setGameManager(T.gameManager);let l=T.onEvent?h.onEvent(T.onEvent):()=>{};if(!R.prepareCart(v))throw l(),new Error("createRuntime: failed to prepare cart");let x=!1,U={async start(){if(!x){if(G()&&R.isPrepared&&(R.init(),R.unloadCart(),!R.prepareCart(v)))throw new Error("createRuntime: failed to prepare cart");R.needsAudio&&(await R.unlockAudio(),x)||(H=!0,R.beginPlayback())}},pause(){x||(R.paused=!0)},resume(){x||(R.paused=!1)},dispatch(V){x||h.dispatch(V)},snapshot(){if(x)return{seed:"",pngDataUrl:""};let V=R.canvas;return{seed:R.tokenData.hash,metadata:v.metadata,pngDataUrl:V?V.toDataURL("image/png"):""}},destroy(){x||(x=!0,H=!1,l(),h.clearInbound(),R.unloadCart(),m===U&&(m=null))},reload(){if(!x){if(!H){if(R.isPrepared&&(R.unloadCart(),!R.prepareCart(v)))throw new Error("createRuntime: failed to prepare cart");return}R.reloadCart()}},reinit(V){if(!x){if(!H){G();return}R.reinit(V)}},getCartState(){return R.animation?.cartState},exportState(){return x?Promise.reject(new Error("Cart handle has been destroyed")):R.exportState()},exportStateJSON(){return x?Promise.reject(new Error("Cart handle has been destroyed")):R.exportStateJSON()},async importState(V,W){if(x)throw new Error("Cart handle has been destroyed");await R.importState(V,W)},peekExportedFramebuffer(){return x?null:R.peekExportedFramebuffer()},peekSeed(){if(!x)return R.peekSeed()},isGenerative(){return x?!1:R.isGenerative()},async step(V=1){if(x)throw new Error("Cart handle has been destroyed");await R.step(V)},async advance(V){if(x)throw new Error("Cart handle has been destroyed");await R.advance(V)},schedule(V){x||R.schedule(V)},getClock(){if(x)throw new Error("Cart handle has been destroyed");return R.getClock()},getRandomState(){if(x)throw new Error("Cart handle has been destroyed");return R.getRandomState()},getReplayMetadata(){return x?Promise.reject(new Error("Cart handle has been destroyed")):R.getReplayMetadata()},get canvas(){return R.canvas},get paused(){return R.paused},set paused(V){x||(R.paused=V)},get tokenData(){return R.tokenData},get isPrepared(){return R.isPrepared},get isLoopRunning(){return R.isLoopRunning},get needsAudio(){return R.needsAudio},get audioLibraries(){return R.audioLibraries}};return m=U,U},async unlockAudio(){await R.unlockAudio()},destroy(){b||(b=!0,m?.destroy(),m=null,K?.disconnect(),K=null,g?.dispose(),h.close(),R.destroy())}}}var wn="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==",An=320,En=180,Or="Headless harness has been destroyed",Cn=!1;function Qe(e={}){if(e.glyphAtlas&&ot(e.glyphAtlas),typeof globalThis.ImageData>"u"){class n{constructor(i,s,a){this.colorSpace="srgb";typeof i=="number"?(this.width=i,this.height=s??0,this.data=new Uint8ClampedArray(this.width*this.height*4)):(this.data=i,this.width=s??0,this.height=a??i.length/4/this.width)}}globalThis.ImageData=n}Gt();let t=HTMLCanvasElement.prototype;t.getContext=function(r,i){return String(r??"2d").toLowerCase()!=="2d"?null:ut(this,{alpha:i?.alpha!==!1,glyphAtlas:e.glyphAtlas})},t.toDataURL=function(r){if(r&&r!=="image/png")throw new j(`toDataURL(${r})`);return Ot(this)??wn},Cn=!0}function Lr(e,t){let n=document.createElement("div");return Object.defineProperty(n,"clientWidth",{value:e,configurable:!0}),Object.defineProperty(n,"clientHeight",{value:t,configurable:!0}),document.body.appendChild(n),n}function _r(e){let t=e.indexOf(","),n=t>=0?e.slice(t+1):e,r=globalThis.atob(n),i=new Uint8Array(r.length);for(let s=0;s<r.length;s++)i[s]=r.charCodeAt(s);return i}function Ur(){return typeof process<"u"&&!!process.versions?.node}async function Nr(e,t){if(!Ur())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(e,_r(t))}catch(r){let i=r instanceof Error?r.message:String(r);throw new Error(`captureFrame could not write ${e}: ${i}`)}}function Gr(e){Cn||Qe();let t=e.width??An,n=e.height??En,r=Lr(t,n),i=[],s=[],a=!1,c=e.onEvent,h=e.onError,g=Je({container:r,seed:e.seed,deterministic:{origin:e.origin,actions:e.actions??[]}});g.onError=(C,O)=>{s.push({error:C,info:O}),h?.(C,O)},Object.defineProperty(g,"onError",{configurable:!0,enumerable:!0,get(){return h},set(C){h=C}});let b=C=>{i.push(C),c?.(C)},m=g.mount(e.cart,{initialState:e.initialState,gameManager:e.gameManager,onEvent:b}),E=()=>{if(a)throw new Error(Or)};return{runtime:g,container:r,get events(){return i.slice()},get errors(){return s.slice()},get cart(){return m},async step(C=1){E(),await m.step(C)},async advance(C){E(),await m.advance(C)},schedule(C){E(),m.schedule(C)},dispatch(C){E(),m.dispatch(C)},start(){return E(),m.start()},pause(){E(),m.pause()},resume(){E(),m.resume()},get paused(){return m.paused},key(C){E(),m.schedule({type:"key",atFrame:m.getClock().framesElapsed,key:C})},click(C,O){E(),m.schedule({type:"pointer",atFrame:m.getClock().framesElapsed,pointer:{kind:"down",x:C,y:O}})},async inspect(){E();let C=await m.getReplayMetadata();return{state:C.state,events:i.slice(),errors:s.slice(),replay:C,clock:m.getClock()}},async captureFrame(C){E();let O=m.snapshot();return C&&await Nr(C,O.pngDataUrl),O},remount(C={}){return E(),i.length=0,s.length=0,"onEvent"in C&&(c=C.onEvent),m=g.mount(e.cart,{initialState:C.initialState??e.initialState,gameManager:C.gameManager??e.gameManager,onEvent:b}),m},destroy(){if(!a){a=!0;try{m.destroy()}finally{try{g.destroy()}finally{r.remove()}}}}}}var xn="CYBERART_UPDATE_GOLDEN";function Rn(e=typeof process<"u"?process.env:void 0){let t=e?.[xn];return t==="1"||t==="true"}function Rt(e){return ct(Ve(e))}function Sn(e,t,n={}){if(e.width!==t.width||e.height!==t.height){let b=Vr(e,t);return{match:!1,differingPixels:e.width*e.height,width:e.width,height:e.height,artifacts:b,updatedGolden:!1}}let r=n.tolerance??0,i=n.perceptualThreshold,s=n.maxDifferingPixels??0,a=new Uint8ClampedArray(e.width*e.height*4),c=0;for(let b=0;b<e.data.length;b+=4){let m=Math.abs(e.data[b]-t.data[b]),E=Math.abs(e.data[b+1]-t.data[b+1]),H=Math.abs(e.data[b+2]-t.data[b+2]),C=Math.abs(e.data[b+3]-t.data[b+3]),O=.299*m+.587*E+.114*H,R=n.alphaTolerance??r;(i!==void 0?O<=i&&C<=R:m<=r&&E<=r&&H<=r&&C<=R)?(a[b]=0,a[b+1]=0,a[b+2]=0,a[b+3]=255):(c+=1,a[b]=255,a[b+1]=0,a[b+2]=255,a[b+3]=255)}let h=St(t,e,he(a,e.width,e.height),c);return n.updateGolden===!0||Rn()?{match:!0,differingPixels:0,width:e.width,height:e.height,artifacts:St(e,e,he(a,e.width,e.height),0),updatedGolden:!0}:{match:c<=s,differingPixels:c,width:e.width,height:e.height,artifacts:h,updatedGolden:!1}}function kn(e,t,n={}){let r=Sn(e,t,n);if(!r.match){let i=new Error(`Visual assertion failed: ${r.differingPixels} differing pixels (${r.width}\xD7${r.height}). Review expected/actual/diff PNG buffers on the result.`);throw i.visual=r,i}return r}function Kr(e,t,n={}){return kn(Rt(e),Rt(t),n)}function St(e,t,n,r){let i=Ae(e.width,e.height,e.data),s=Ae(t.width,t.height,t.data),a=Ae(n.width,n.height,n.data);return{expectedPng:i,actualPng:s,diffPng:a,expectedDataUrl:Ee(e.width,e.height,e.data),actualDataUrl:Ee(t.width,t.height,t.data),diffDataUrl:Ee(n.width,n.height,n.data),differingPixels:r}}function Vr(e,t){let n=Math.max(e.width,t.width),r=Math.max(e.height,t.height),i=new Uint8ClampedArray(n*r*4);for(let s=0;s<i.length;s+=4)i[s]=255,i[s+1]=0,i[s+2]=255,i[s+3]=255;return St(t,e,he(i,n,r),n*r)}async function Wr(e,t,n={}){let{mkdir:r,writeFile:i}=await import("node:fs/promises"),{join:s}=await import("path");await r(e,{recursive:!0});let a=s(e,n.expected??"expected.png"),c=s(e,n.actual??"actual.png"),h=s(e,n.diff??"diff.png");return await i(a,t.expectedPng),await i(c,t.actualPng),await i(h,t.diffPng),{expectedPath:a,actualPath:c,diffPath:h}}var Tn="cyberart.state.save",In="cyberart.state.load";var Ze=1,_e="cyberart.diagnostic.rejected",kt=8,$r=new Set(["intent","state","diagnostic"]),Br=new Set([Tn,In]);function Pn(e){return typeof e=="string"&&$r.has(e)}function jr(e){if(e.kind!==void 0)return Pn(e.kind)?e.kind:void 0;if(!(typeof e.type!="string"||e.type.length===0)){if(Br.has(e.type))return"intent";for(let t of e.type.split("."))if(Pn(t))return t}}function zr(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 Te(e,t){for(let n of e)if(zr(n,t))return!0;return!1}function qr(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 Tt(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!==Ze)return{ok:!1,reason:"malformed",detail:`unsupported schemaVersion ${String(e.schemaVersion)}`};let n=jr(e);if(!n)return{ok:!1,reason:"malformed",detail:`cannot infer kind from type "${e.type}"`};let r=qr(e.payload);if(!r.ok)return{ok:!1,reason:"malformed",detail:"payload is not JSON-serializable"};let i=t.createId(),s=typeof e.correlationId=="string"&&e.correlationId.length>0?e.correlationId:i,a=typeof e.causationId=="string"&&e.causationId.length>0?e.causationId:t.causationId,c=typeof e.target=="string"&&e.target.length>0?e.target:void 0,h=t.maxHops??kt,g=t.parentHops===void 0?h:Math.max(0,t.parentHops-1),b=typeof e.idempotencyKey=="string"&&e.idempotencyKey.length>0?e.idempotencyKey:void 0,m={schemaVersion:Ze,type:e.type,kind:n,source:t.source,id:i,correlationId:s,seq:t.seq,hops:g};return c&&(m.target=c),a&&(m.causationId=a),b&&(m.idempotencyKey=b),r.value!==void 0&&(m.payload=r.value),{ok:!0,envelope:m}}var Yr=new Set(["rate-limited","storm-detected","hop-limit","loop-detected","not-subscribed"]),Xr=8,Jr=8,Qr=16,Zr=256,ei=256,ti=["*.intent.*"];function Dn(e={}){let t=e.hostSource??"host",n="router",r=e.maxPerTurn??Xr,i=e.maxCausationDepth??Jr,s=e.maxHops??kt,a=e.maxCorrelationPerTurn??Qr,c=e.maxIndex??Zr,h=e.maxDecisions??ei,g=e.maxPerWindow,b=e.windowMs??1e3,m=e.now??Date.now,E=0,H=e.createId??(()=>`evt-${++E}`),C=new Map,O=[],R=[],G=new Map,K=new Map,z=new Map,v=[],T=0,l=0,x=0;function U(u){try{return JSON.parse(JSON.stringify(u))}catch{return u}}function V(u){for(v.push(u);v.length>h;)v.shift();for(let y of R)try{y(U(u))}catch{}}function W(u,y){let k={outcome:y.outcome,source:y.source,type:u.type,kind:u.kind,envelopeId:u.id,deliveredTo:y.deliveredTo,hops:u.hops,seq:u.seq,correlationId:u.correlationId,schemaVersion:u.schemaVersion,turn:x,time:m()};return y.reason&&(k.reason=y.reason),y.detail&&(k.detail=y.detail),y.priorEnvelopeId&&(k.priorEnvelopeId=y.priorEnvelopeId),u.target&&(k.target=u.target),u.causationId&&(k.causationId=u.causationId),u.idempotencyKey&&(k.idempotencyKey=u.idempotencyKey),u.payload!==void 0&&(k.payload=U(u.payload)),k}let Q=[],ee=!1;function d(u,y,k){for(u.set(y,k);u.size>c;){let P=u.keys().next().value;if(P===void 0)break;u.delete(P)}}function F(u){d(G,u.id,{type:u.type,source:u.source,causationId:u.causationId,hops:u.hops,correlationId:u.correlationId,idempotencyKey:u.idempotencyKey})}function L(u,y){y&&(u.correlationId||(u.correlationId=y.correlationId),u.causationId||(u.causationId=y.id),!u.idempotencyKey&&y.idempotencyKey&&(u.idempotencyKey=`${y.idempotencyKey}::${u.type}`))}function $(u,y){if(u){let k=G.get(u);return k?k.hops:s}return y}function o(u,y){return`${u}\0${y}`}function p(u,y){u.idempotencyKey&&d(z,o(u.source,u.idempotencyKey),y)}function f(u,y){if(y)return z.get(o(u,y))}function A(u){return f(u.source,u.idempotencyKey)}function w(u){return u.seq+=1,u.seq}function S(u,y){if(!(typeof y.causationId=="string"&&y.causationId.length>0))return u.lastDelivered}function I(u){let y=new Set,k=new Set([`${u.type}\0${u.source}`]),P=u.causationId,D=0;for(;P;){if(D+=1,D>i||y.has(P))return!0;y.add(P);let N=G.get(P);if(!N)break;let oe=`${N.type}\0${N.source}`;if(k.has(oe))return!0;k.add(oe),P=N.causationId}return!1}function M(u){let y=(K.get(u)??0)+1;return K.set(u,y),y}function _(u,y){g!==void 0&&(u.emitTimestamps=u.emitTimestamps.filter(k=>y-k<b))}function B(u,y){return(y.kind==="state"||y.kind==="diagnostic")&&!u.authoritative?!1:Te(u.emit,y.type)}function X(u){for(let y of O)if(Te(y.patterns,u.type))try{y.listener(u)}catch{}}function q(u){let y=[];if(u.target){let k=C.get(u.target);return!k||!Te(k.subscribe,u.type)||(k.channel.dispatch(u),k.lastDelivered={id:u.id,hops:u.hops,correlationId:u.correlationId,idempotencyKey:u.idempotencyKey},y.push(k.id)),y}for(let k of C.values())Te(k.subscribe,u.type)&&(k.channel.dispatch(u),k.lastDelivered={id:u.id,hops:u.hops,correlationId:u.correlationId,idempotencyKey:u.idempotencyKey},y.push(k.id));return y}function re(u,y,k,P,D,N,oe){let ne={reason:P,eventType:y,source:k};D&&(ne.detail=D),l+=1;let ce=H(),fe={schemaVersion:Ze,type:_e,kind:"diagnostic",source:n,id:ce,correlationId:N??ce,seq:l,hops:0,payload:ne};oe&&(fe.causationId=oe),F(fe);let Ue=C.get(u);Ue&&Ue.channel.dispatch(fe),X(fe)}function J(u,y,k,P,D){if(re(u,D?.type??(typeof y.type=="string"?y.type:""),D?.source??u,k,P,D?.correlationId,D?.id),D?.idempotencyKey&&!Yr.has(k)&&p(D,{status:"rejected"}),D)V(W(D,{outcome:"rejected",reason:k,detail:P,source:u,deliveredTo:[]}));else{let N={outcome:"rejected",reason:k,source:u,type:typeof y.type=="string"?y.type:"",deliveredTo:[],turn:x,time:m()};P&&(N.detail=P),typeof y.idempotencyKey=="string"&&(N.idempotencyKey=y.idempotencyKey),V(N)}}function ae(u,y){F(u),p(u,{status:"accepted",envelope:u}),M(u.correlationId),X(u);let k=q(u);V(W(u,{outcome:"accepted",source:y,deliveredTo:k}))}function ie(u,y,k,P){let D=P?.type??(typeof y.type=="string"?y.type:""),N={outcome:"duplicate",reason:"duplicate",detail:k.status==="accepted"?"idempotent accepted":"idempotent rejected",source:u,type:D,deliveredTo:[],turn:x,time:m()};P?(N.kind=P.kind,N.envelopeId=P.id,N.hops=P.hops,N.seq=P.seq,N.correlationId=P.correlationId,N.schemaVersion=P.schemaVersion,P.target&&(N.target=P.target),P.causationId&&(N.causationId=P.causationId),P.idempotencyKey&&(N.idempotencyKey=P.idempotencyKey),P.payload!==void 0&&(N.payload=U(P.payload))):typeof y.idempotencyKey=="string"&&(N.idempotencyKey=y.idempotencyKey),k.status==="accepted"&&(N.priorEnvelopeId=k.envelope.id,N.envelopeId||(N.envelopeId=k.envelope.id)),V(N)}function Y(u,y,k,P){if(!k.ok){J(u,y,"malformed",k.detail);return}let D=k.envelope,N=A(D);if(N)return ie(u,y,N,D),N.status==="accepted"?N.envelope:void 0;if(D.hops<1){J(u,y,"hop-limit","no hops remaining",D);return}if(D.target&&D.target!==t){let oe=C.get(D.target);if(!oe){J(u,y,"unknown-target",`unknown target "${D.target}"`,D);return}if(!Te(oe.subscribe,D.type)){J(u,y,"not-subscribed",`target "${D.target}" does not subscribe to ${D.type}`,D);return}}if(P){if(!B(P,D)){J(u,y,"unauthorized","source may not emit this event",D);return}if(P.emitsThisTurn+=1,P.emitsThisTurn>r){J(u,y,"rate-limited","maxPerTurn exceeded",D);return}if(g!==void 0){let ne=m();if(_(P,ne),P.emitTimestamps.push(ne),P.emitTimestamps.length>g){J(u,y,"rate-limited","maxPerWindow exceeded",D);return}}if(I(D)){J(u,y,"loop-detected","causation chain cycle or depth exceeded",D);return}if((K.get(D.correlationId)??0)+1>a){J(u,y,"storm-detected","correlationId storm",D);return}if(e.validate){let ne;try{ne=e.validate(D)}catch(ce){let fe=ce instanceof Error?ce.message:"validate threw";J(u,y,"host-rejected",fe,D);return}if(ne!==!0){J(u,y,"host-rejected",ne.detail,D);return}}}else{if(I(D)){J(u,y,"loop-detected","causation chain cycle or depth exceeded",D);return}if((K.get(D.correlationId)??0)+1>a){J(u,y,"storm-detected","correlationId storm",D);return}}return ae(D,u),D}function te(u,y){let k=C.get(u);if(!k)return;let P={...y},D=S(k,P);L(P,D);let N=f(k.id,P.idempotencyKey);if(N){ie(u,P,N);return}let oe=w(k),ne=Tt(P,{source:k.id,createId:H,seq:oe,causationId:D?.id,maxHops:s,parentHops:$(P.causationId??D?.id,D?.hops)});Y(u,P,ne,k)}function ve(u,y){let k=y?.cause,P={...u};L(P,k);let D=f(t,P.idempotencyKey);if(D)return ie(t,P,D),D.status==="accepted"?D.envelope:void 0;T+=1;let N=Tt(P,{source:t,createId:H,seq:T,causationId:P.causationId,maxHops:s,parentHops:$(P.causationId,k?.hops)});return Y(t,P,N,void 0)}function ye(){if(!ee){ee=!0;try{for(;Q.length>0;){let u=Q.shift();u&&(u.kind==="cart"?te(u.participantId,u.event):u.result=ve(u.event,u.extras))}}finally{ee=!1}}}function me(u){Q.push(u),ye()}return{attach(u,y,k={}){if(u===t||u===n)throw new Error(`createEventRouter: "${u}" is a reserved participant id`);for(let N of C.values())if(N.channel===y&&N.id!==u)throw new Error(`createEventRouter: channel already attached as "${N.id}"`);C.get(u)?.unsubscribe();let D={id:u,channel:y,emit:k.emit??ti,subscribe:k.subscribe??[],authoritative:k.authoritative===!0,seq:0,emitsThisTurn:0,emitTimestamps:[],unsubscribe:()=>{}};D.unsubscribe=y.onEvent(N=>{me({kind:"cart",participantId:u,event:N})}),C.set(u,D)},detach(u){let y=C.get(u);y&&(y.unsubscribe(),C.delete(u))},publish(u,y){let k={kind:"publish",event:u,extras:y};return me(k),k.result},subscribe(u,y){let k={patterns:u,listener:y};return O.push(k),()=>{let P=O.indexOf(k);P>=0&&O.splice(P,1)}},subscribeDecision(u){return R.push(u),()=>{let y=R.indexOf(u);y>=0&&R.splice(y,1)}},inspectParticipants(){return[...C.values()].map(u=>({id:u.id,emit:u.emit.slice(),subscribe:u.subscribe.slice(),authoritative:u.authoritative}))},inspectDecisions(){return v.map(u=>U(u))},turn(){x+=1,K.clear();for(let u of C.values())u.emitsThisTurn=0,u.lastDelivered=void 0,g!==void 0&&_(u,m())}}}var ni=320,ri=180,ii=1024,si="Runtime group has been destroyed";function ai(e){let t="";for(let n=0;n<32;n++){let r=e.charCodeAt(n%Math.max(e.length,1))+n*17&255;t+=r.toString(16).padStart(2,"0")}return`0x${t}`}function oi(e,t){let n=document.createElement("div");return Object.defineProperty(n,"clientWidth",{value:e,configurable:!0}),Object.defineProperty(n,"clientHeight",{value:t,configurable:!0}),document.body.appendChild(n),n}function Hn(e){let t=e.capability,n={},r=e.emit??t?.emit,i=e.subscribe??t?.subscribe,s=e.authoritative??t?.authoritative;return r&&(n.emit=r),i&&(n.subscribe=i),s!==void 0&&(n.authoritative=s),n}function Mn(e){try{return JSON.parse(JSON.stringify(e))}catch{return e}}function ui(e){let t=new Set([_e,"*.*","*.*.*","*.*.*.*","*.*.*.*.*"]);for(let n of e){let r=Hn(n);for(let i of r.emit??[])t.add(i);for(let i of r.subscribe??[])t.add(i)}return[...t]}function Fn(e){if(!e.participants.length)throw new Error("createRuntimeGroup: at least one participant is required");let t=new Set;for(let l of e.participants){if(!l.id)throw new Error("createRuntimeGroup: participant id is required");if(t.has(l.id))throw new Error(`createRuntimeGroup: duplicate participant id "${l.id}"`);t.add(l.id)}let n=e.origin??0,r=e.width??ni,i=e.height??ri,s=e.maxTrace??ii,a=[...e.participants].sort((l,x)=>l.id.localeCompare(x.id)),c=[],h=new Map,g=0,b=e.createId??e.router?.createId??(()=>`evt-${++g}`),m=e.now??e.router?.now??(()=>{let l=c[0];if(!l)return n;try{return l.cart.getClock().now}catch{return n}}),E=Dn({...e.router,createId:b,now:m,validate:e.validate??e.router?.validate}),H=[],C=!1,O=!1,R=()=>{},G=l=>x=>{l.events.push(x),l.userOnEvent?.(x)},K=()=>{if(O)throw new Error(si)},z=()=>{R();for(let l of c){try{E.detach(l.id)}catch{}try{l.runtime.destroy()}catch{}l.ownsContainer&&l.container.remove()}c.length=0,h.clear()};try{for(let l of a){let x=l.width??r,U=l.height??i,V=!l.container,W=l.container??oi(x,U),Q=Je({container:W,seed:l.seed??ai(l.id),deterministic:{origin:n}}),ee={id:l.id,kind:l.kind??"render",cartDef:l.cart,initialState:l.initialState,gameManager:l.gameManager,userOnEvent:l.onEvent,runtime:Q,container:W,ownsContainer:V,cart:void 0,events:[],errors:[]};Q.onError=(d,F)=>{ee.errors.push({error:d,info:F})},E.attach(l.id,Q.hostChannel,Hn(l)),ee.cart=Q.mount(l.cart,{initialState:l.initialState,gameManager:l.gameManager,onEvent:G(ee)}),c.push(ee),h.set(ee.id,ee)}R=E.subscribe(ui(a),l=>{for(H.push(Mn(l));H.length>s;)H.shift()})}catch(l){throw z(),l}let v=l=>({id:l.id,kind:l.kind,runtime:l.runtime,container:l.container,get events(){return l.events.slice()},get errors(){return l.errors.slice()},get cart(){return l.cart}});return{router:E,origin:n,get paused(){return C},participant(l){K();let x=h.get(l);if(!x)throw new Error(`createRuntimeGroup: unknown participant "${l}"`);return v(x)},async step(l=1){if(K(),C)return;let x=Math.max(0,Math.floor(l));for(let U=0;U<x;U++){E.turn();for(let V of c)try{await V.cart.step(1)}catch(W){V.errors.push({error:W,info:{phase:"update",consecutive:V.errors.length+1,stopped:!1}})}}},pause(){K(),C=!0;for(let l of c)l.cart.pause()},resume(){K(),C=!1;for(let l of c)l.cart.resume()},reset(){K(),H.length=0;for(let l of c)l.events.length=0,l.errors.length=0,l.cart=l.runtime.mount(l.cartDef,{initialState:l.initialState,gameManager:l.gameManager,onEvent:G(l)});E.turn()},resize(l,x){K();let U=Math.max(1,l|0),V=Math.max(1,x|0);for(let W of c){Object.defineProperty(W.container,"clientWidth",{value:U,configurable:!0}),Object.defineProperty(W.container,"clientHeight",{value:V,configurable:!0});let Q=W.cart.canvas;Q&&(Q.width=U,Q.height=V)}},detach(l){K();let x=h.get(l);if(!x)throw new Error(`createRuntimeGroup: unknown participant "${l}"`);try{E.detach(x.id)}catch{}try{x.runtime.destroy()}catch{}x.ownsContainer&&x.container.remove();let U=c.indexOf(x);U>=0&&c.splice(U,1),h.delete(l)},dispatch(l,x){K();let U=h.get(l);if(!U)throw new Error(`createRuntimeGroup: unknown participant "${l}"`);U.cart.dispatch(x)},publish(l,x){return K(),E.publish(l,x)},inspectParticipants(){K();let l=new Map(c.map(x=>[x.id,x.kind]));return E.inspectParticipants().map(x=>({...x,kind:l.get(x.id)??"render"}))},async inspect(){K();let l={},x={},U=new Map(E.inspectParticipants().map(W=>[W.id,W]));for(let W of c){let Q=await W.cart.getReplayMetadata(),ee=W.cart.getClock();x[W.id]=ee;let d=U.get(W.id);l[W.id]={state:Q.state,events:W.events.slice(),errors:W.errors.slice(),kind:W.kind,clock:ee,emit:d?.emit.slice()??[],subscribe:d?.subscribe.slice()??[],authoritative:d?.authoritative===!0}}let V=H.map(W=>Mn(W));return{participants:l,trace:V,diagnostics:{paused:C,participantIds:c.map(W=>W.id),clocks:x,rejections:V.filter(W=>W.type===_e).map(W=>W.payload)}}},destroy(){if(!O){O=!0,C=!1;try{z()}finally{H.length=0}}}}}function ci(e){return Qe(),Fn(e)}var It=1,di=512,li="[REDACTED]",pi=new Set([He,Fe]);function se(e){try{return JSON.parse(JSON.stringify(e))}catch{return e}}function et(e,t){if(e==null)return e;if(Array.isArray(e))return e.map(i=>et(i,t));if(typeof e!="object")return e;let n=e,r={};for(let[i,s]of Object.entries(n))r[i]=t.has(i)?li:et(s,t);return r}function hi(e){return e instanceof Error&&typeof e.message=="string"?e.message:"error"}function mi(e,t){return t?!(t.types&&!t.types.includes(e.type)||t.sources&&!t.sources.includes(e.source)||t.outcomes&&!t.outcomes.includes(e.outcome)||t.correlationId&&e.correlationId!==t.correlationId):!0}function On(e){return JSON.stringify({outcome:e.outcome,reason:e.reason,source:e.source,target:e.target,type:e.type,kind:e.kind,envelopeId:e.envelopeId,priorEnvelopeId:e.priorEnvelopeId,correlationId:e.correlationId,causationId:e.causationId,hops:e.hops,seq:e.seq,idempotencyKey:e.idempotencyKey,deliveredTo:e.deliveredTo,payload:e.payload})}function fi(e,t){if(e.length!==t.length)return{ok:!1,detail:`record count ${t.length} !== ${e.length}`};for(let n=0;n<e.length;n++){let r=On(e[n]),i=On(t[n]);if(r!==i)return{ok:!1,detail:`record ${n} differs`}}return{ok:!0}}function Ln(e){let t=new Map,n=[];for(let s of e){if(s.outcome==="duplicate"){n.push(void 0);continue}let a={envelopeId:s.envelopeId,type:s.type,source:s.source,outcome:s.outcome,children:[]};s.reason&&(a.reason=s.reason),n.push(a),s.envelopeId&&!t.has(s.envelopeId)&&t.set(s.envelopeId,a)}let r=new Set;for(let s=0;s<e.length;s++){let a=e[s],c=n[s];if(!c)continue;let h=a.causationId?t.get(a.causationId):void 0;h&&h!==c&&(h.children.push(c),r.add(c))}let i=[];for(let s of n)s&&!r.has(s)&&i.push(s);return i}function _n(e,t){let n={id:e.id,emit:e.emit.slice(),subscribe:e.subscribe.slice(),authoritative:e.authoritative,errorCount:0};return t&&(n.kind=t),n}function gi(e,t,n){let r=t.errors[t.errors.length-1],i={id:e,kind:t.kind,emit:t.emit.slice(),subscribe:t.subscribe.slice(),authoritative:t.authoritative,clock:se(t.clock),state:et(t.state,n),errorCount:t.errors.length};return r&&(i.lastError=hi(r.error)),i}function Un(e={}){let t=new Set(e.redactedKeys??[]),n=e.maxRecords??di,r=e.registry,i=0,s=0,a=!1,c=[],h=[],g,b=[],m=0,E=[],H={},C=()=>{},O=()=>{if(a)throw new Error("Replay inspector has been destroyed")},R=v=>{let T=r?.get(v.type),l={index:s,turn:v.turn,time:v.time,outcome:v.outcome,source:v.source,type:v.type,deliveredTo:v.deliveredTo.slice(),payload:et(v.payload,t)};for(s+=1,v.reason&&(l.reason=v.reason),v.detail&&(l.detail=v.detail),v.target&&(l.target=v.target),v.kind&&(l.kind=v.kind),v.envelopeId&&(l.envelopeId=v.envelopeId),v.priorEnvelopeId&&(l.priorEnvelopeId=v.priorEnvelopeId),v.correlationId&&(l.correlationId=v.correlationId),v.causationId&&(l.causationId=v.causationId),v.hops!==void 0&&(l.hops=v.hops),v.seq!==void 0&&(l.seq=v.seq),v.idempotencyKey&&(l.idempotencyKey=v.idempotencyKey),v.schemaVersion!==void 0&&(l.schemaVersion=v.schemaVersion),T&&(l.payloadSchemaVersion=T.payloadSchema.version),c.push(l);c.length>n;)c.shift(),i+=1},G=v=>c.filter(T=>mi(T,v)).map(T=>se(T)),K=v=>v?v.inspectParticipants().map(T=>_n(T,T.kind)):E.map(T=>se(T)),z={watchRouter(v){if(O(),C(),E=v.inspectParticipants().map(l=>_n(l)),c.length===0)for(let l of v.inspectDecisions())R(l);let T=v.subscribeDecision(l=>R(l));return C=()=>{T(),C=()=>{}},h.push(C),C},bind(v){O(),g&&C(),g=v,m=v.origin,z.watchRouter(v.router),E=K(v);let T={publish(l,x){O();let U={kind:"publish",event:se(l)};return x?.cause&&(U.extras={cause:se(x.cause)}),b.push(U),v.publish(l,x)},dispatch(l,x){O();let U=se(x);typeof U.type=="string"&&pi.has(U.type)?b.push({kind:"asset",participantId:l,event:U}):b.push({kind:"dispatch",participantId:l,event:U}),v.dispatch(l,x)},async step(l=1){O(),b.push({kind:"step",frames:l}),await v.step(l)},async report(){O();let l=await v.inspect(),x=[];for(let U of Object.keys(l.participants).sort())x.push(gi(U,l.participants[U],t));E=x,H={};for(let U of x)H[U.id]=se(U.state);return z.report()},async exportTrace(l){return await T.report(),z.exportTrace(l)},unbind(){C(),g=void 0}};return T},importTrace(v){O();let T=typeof v=="string"?JSON.parse(v):v;if(T.schemaVersion!==It)throw new Error("Replay inspector: unsupported export schemaVersion");i=0,s=0,c.length=0,b=se(T.tape??[]),m=T.origin??0,E=se(T.participants??[]),H=se(T.snapshots??{});for(let l of T.records??[])R({outcome:l.outcome,reason:l.reason,detail:l.detail,source:l.source,type:l.type,kind:l.kind,envelopeId:l.envelopeId,priorEnvelopeId:l.priorEnvelopeId,target:l.target,deliveredTo:l.deliveredTo,hops:l.hops,seq:l.seq,correlationId:l.correlationId,causationId:l.causationId,idempotencyKey:l.idempotencyKey,schemaVersion:l.schemaVersion,payload:l.payload,turn:l.turn,time:l.time})},exportTrace(v){return O(),{schemaVersion:It,origin:m,redactedKeys:[...t],participants:se(E),tape:se(b),records:G(v),snapshots:se(H)}},report(v){O();let T=G(v);return{schemaVersion:It,participants:se(E),records:T,trees:Ln(T),dropped:i}},causationTree(v){O();let T=G(v?{correlationId:v}:void 0);return Ln(T)},records(){return O(),c.map(v=>se(v))},reset(){O(),c.length=0,b=[],i=0,s=0,H={},g&&(E=K(g))},destroy(){if(!a){for(a=!0,C();h.length>0;)h.pop()?.();c.length=0,b=[],E=[],H={},g=void 0}}};return z}async function bi(e,t,n={}){let r=Un({redactedKeys:n.redactedKeys??e.redactedKeys,maxRecords:n.maxRecords,registry:n.registry}),i=r.bind(t);try{for(let a of e.tape)a.kind==="publish"?i.publish(a.event,a.extras):a.kind==="dispatch"||a.kind==="asset"?i.dispatch(a.participantId,a.event):await i.step(a.frames);let s=await i.report();return{inspector:r,report:s}}catch(s){throw r.destroy(),s}}async function js(e,t){let n=e.captureComposedFrame();if(!t)return n;let{writeFile:r}=await import("node:fs/promises");return await r(t,Ve(n.pngDataUrl)),{...n,path:t}}export{En as DEFAULT_HEADLESS_HEIGHT,An as DEFAULT_HEADLESS_WIDTH,wn as HEADLESS_PNG_DATA_URL,j as HeadlessUnsupportedOperationError,xn as UPDATE_GOLDEN_ENV,kn as assertPixelsEqual,Kr as assertPngDataUrlsEqual,ut as attachHeadlessCanvas2D,Sn as compareImageData,fi as compareReplayTraces,Ut as createDefaultGlyphAtlas,Gr as createHeadlessHarness,ci as createHeadlessMultiCartHarness,Kn as createImageFixture,Un as createReplayInspector,ct as decodePng,Ae as encodePng,Ee as encodePngDataUrl,Vn as getHeadlessSurface,Rt as imageDataFromPngDataUrl,Qe as installHeadlessCanvas,he as makeImageData,bi as replayExportedTrace,ot as setDefaultGlyphAtlas,Rn as shouldUpdateGolden,js as writeComposedFrame,Wr as writeVisualArtifacts};
|